2 * Copyright 2020-2021 Niklas Ekström
3 * Based on a314d daemon for A314.
8 #include <linux/spi/spidev.h>
9 #include <linux/types.h>
11 #include <netinet/in.h>
12 #include <netinet/tcp.h>
14 #include <sys/epoll.h>
15 #include <sys/ioctl.h>
16 #include <sys/socket.h>
18 #include <sys/types.h>
38 // Silence stupid warning
40 #include "config_file/config_file.h"
42 extern "C" emulator_config *cfg;
44 #define LOGGER_TRACE 1
45 #define LOGGER_DEBUG 2
48 #define LOGGER_ERROR 5
50 #define LOGGER_SHOW LOGGER_INFO
52 #define logger_trace(...) do { if (LOGGER_TRACE >= LOGGER_SHOW) fprintf(stdout, __VA_ARGS__); } while (0)
53 #define logger_debug(...) do { if (LOGGER_DEBUG >= LOGGER_SHOW) fprintf(stdout, __VA_ARGS__); } while (0)
54 #define logger_info(...) do { if (LOGGER_INFO >= LOGGER_SHOW) fprintf(stdout, __VA_ARGS__); } while (0)
55 #define logger_warn(...) do { if (LOGGER_WARN >= LOGGER_SHOW) fprintf(stdout, __VA_ARGS__); } while (0)
56 #define logger_error(...) do { if (LOGGER_ERROR >= LOGGER_SHOW) fprintf(stderr, __VA_ARGS__); } while (0)
58 // Events that are communicated via IRQ from Amiga to Raspberry.
59 #define R_EVENT_A2R_TAIL 1
60 #define R_EVENT_R2A_HEAD 2
61 #define R_EVENT_STARTED 4
63 // Events that are communicated from Raspberry to Amiga.
64 #define A_EVENT_R2A_TAIL 1
65 #define A_EVENT_A2R_HEAD 2
67 // Offset relative to communication area for queue pointers.
68 #define A2R_TAIL_OFFSET 0
69 #define R2A_HEAD_OFFSET 1
70 #define R2A_TAIL_OFFSET 2
71 #define A2R_HEAD_OFFSET 3
73 // Packets that are communicated across physical channels (A2R and R2A).
75 #define PKT_CONNECT_RESPONSE 5
80 // Valid responses for PKT_CONNECT_RESPONSE.
82 #define CONNECT_UNKNOWN_SERVICE 3
84 // Messages that are communicated between driver and client.
85 #define MSG_REGISTER_REQ 1
86 #define MSG_REGISTER_RES 2
87 #define MSG_DEREGISTER_REQ 3
88 #define MSG_DEREGISTER_RES 4
89 #define MSG_READ_MEM_REQ 5
90 #define MSG_READ_MEM_RES 6
91 #define MSG_WRITE_MEM_REQ 7
92 #define MSG_WRITE_MEM_RES 8
94 #define MSG_CONNECT_RESPONSE 10
102 static sigset_t original_sigset;
104 static pthread_t thread_id;
105 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
107 static int server_socket = -1;
109 static int epfd = -1;
110 static int irq_fds[2];
112 extern "C" unsigned int ps_read_8(unsigned int address);
113 extern "C" void ps_write_8(unsigned int address, unsigned int value);
114 extern "C" void ps_write_16(unsigned int address, unsigned int value);
116 unsigned int a314_base;
117 int a314_base_configured;
124 uint8_t r_enable; // Unused.
134 uint8_t a2r_buffer[256];
135 uint8_t r2a_buffer[256];
140 static bool a314_device_started = false;
142 static uint8_t channel_status[4];
143 static uint8_t channel_status_updated = 0;
145 static uint8_t recv_buf[256];
146 static uint8_t send_buf[256];
148 struct LogicalChannel;
149 struct ClientConnection;
151 #pragma pack(push, 1)
157 }; //} __attribute__((packed));
163 std::vector<uint8_t> data;
166 struct RegisteredService
169 ClientConnection *cc;
175 std::vector<uint8_t> data;
178 struct ClientConnection
185 MessageHeader header;
186 std::vector<uint8_t> payload;
188 std::list<MessageBuffer> message_queue;
190 std::list<LogicalChannel*> associations;
193 struct LogicalChannel
197 ClientConnection *association;
200 bool got_eos_from_ami;
201 bool got_eos_from_client;
203 std::list<PacketBuffer> packet_queue;
206 static void remove_association(LogicalChannel *ch);
207 static void clear_packet_queue(LogicalChannel *ch);
208 static void create_and_enqueue_packet(LogicalChannel *ch, uint8_t type, uint8_t *data, uint8_t length);
210 static std::list<ClientConnection> connections;
211 static std::list<RegisteredService> services;
212 static std::list<LogicalChannel> channels;
213 static std::list<LogicalChannel*> send_queue;
217 std::string service_name;
219 std::vector<std::string> arguments;
222 std::vector<OnDemandStart> on_demand_services;
224 std::string a314_config_file = "./a314/files_pi/a314d.conf";
225 std::string home_env = "HOME=./";
227 static void load_config_file(const char *filename)
229 FILE *f = fopen(filename, "rt");
235 std::vector<char *> parts;
237 while (fgets(line, 256, f) != nullptr)
240 strcpy(org_line, line);
242 bool in_quotes = false;
245 for (int i = 0; i < 256; i++)
250 parts.push_back(&line[start]);
253 else if (line[i] == '"')
257 parts.push_back(&line[start]);
258 in_quotes = !in_quotes;
261 else if (isspace(line[i]) && !in_quotes)
265 parts.push_back(&line[start]);
270 if (parts.size() >= 2)
272 on_demand_services.emplace_back();
273 auto &e = on_demand_services.back();
274 e.service_name = parts[0];
275 e.program = parts[1];
276 for (int i = 1; i < parts.size(); i++)
277 e.arguments.push_back(std::string(parts[i]));
279 else if (parts.size() != 0)
280 logger_warn("Invalid number of columns in configuration file line: %s\n", org_line);
287 if (on_demand_services.empty())
288 logger_warn("No registered services\n");
291 static int init_server_socket()
293 server_socket = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
294 if (server_socket == -1)
296 logger_error("Failed to create server socket\n");
300 struct sockaddr_in address;
301 address.sin_family = AF_INET;
302 address.sin_addr.s_addr = INADDR_ANY;
303 address.sin_port = htons(7110);
305 int res = bind(server_socket, (struct sockaddr *)&address, sizeof(address));
308 logger_error("Bind to localhost:7110 failed\n");
312 listen(server_socket, 16);
317 static void shutdown_server_socket()
319 if (server_socket != -1)
320 close(server_socket);
324 void create_and_send_msg(ClientConnection *cc, int type, int stream_id, uint8_t *data, int length)
328 mb.data.resize(sizeof(MessageHeader) + length);
330 MessageHeader *mh = (MessageHeader *)&mb.data[0];
332 mh->stream_id = stream_id;
335 memcpy(&mb.data[sizeof(MessageHeader)], data, length);
337 if (!cc->message_queue.empty())
339 cc->message_queue.push_back(std::move(mb));
345 int left = mb.data.size() - mb.pos;
346 uint8_t *src = &mb.data[mb.pos];
347 ssize_t r = write(cc->fd, src, left);
350 if (errno == EAGAIN || errno == EWOULDBLOCK)
352 cc->message_queue.push_back(std::move(mb));
355 else if (errno == ECONNRESET)
357 // Do not close connection here; it will get done at some other place.
362 logger_error("Write failed unexpectedly with errno = %d\n", errno);
375 static void handle_msg_register_req(ClientConnection *cc)
377 uint8_t result = MSG_FAIL;
379 std::string service_name((char *)&cc->payload[0], cc->payload.size());
381 auto it = services.begin();
382 for (; it != services.end(); it++)
383 if (it->name == service_name)
386 if (it == services.end())
388 services.emplace_back();
390 RegisteredService &srv = services.back();
392 srv.name = std::move(service_name);
394 result = MSG_SUCCESS;
397 create_and_send_msg(cc, MSG_REGISTER_RES, 0, &result, 1);
400 static void handle_msg_deregister_req(ClientConnection *cc)
402 uint8_t result = MSG_FAIL;
404 std::string service_name((char *)&cc->payload[0], cc->payload.size());
406 for (auto it = services.begin(); it != services.end(); it++)
408 if (it->name == service_name && it->cc == cc)
411 result = MSG_SUCCESS;
416 create_and_send_msg(cc, MSG_DEREGISTER_RES, 0, &result, 1);
419 uint8_t manual_read_buf[64 * SIZE_KILO];
421 static void handle_msg_read_mem_req(ClientConnection *cc)
423 uint32_t address = *(uint32_t *)&(cc->payload[0]);
424 uint32_t length = *(uint32_t *)&(cc->payload[4]);
426 if (get_mapped_item_by_address(cfg, address) != -1) {
427 int32_t index = get_mapped_item_by_address(cfg, address);
428 uint8_t *map = &cfg->map_data[index][address - cfg->map_offset[index]];
429 create_and_send_msg(cc, MSG_READ_MEM_RES, 0, map, length);
431 // No idea if this actually works.
432 for (int i = 0; i < length; i++) {
433 manual_read_buf[i] = (unsigned char)ps_read_8(address + i);
435 create_and_send_msg(cc, MSG_READ_MEM_RES, 0, manual_read_buf, length);
440 static void handle_msg_write_mem_req(ClientConnection *cc)
442 uint32_t address = *(uint32_t *)&(cc->payload[0]);
443 uint32_t length = cc->payload.size() - 4;
445 if (get_mapped_item_by_address(cfg, address) != -1) {
446 int32_t index = get_mapped_item_by_address(cfg, address);
447 uint8_t *map = &cfg->map_data[index][address - cfg->map_offset[index]];
448 memcpy(map, &(cc->payload[4]), length);
450 // No idea if this actually works.
451 for (int i = 0; i < length; i++) {
452 ps_write_8(address + i, cc->payload[4 + i]);
456 create_and_send_msg(cc, MSG_WRITE_MEM_RES, 0, nullptr, 0);
459 static LogicalChannel *get_associated_channel_by_stream_id(ClientConnection *cc, int stream_id)
461 for (auto ch : cc->associations)
463 if (ch->stream_id == stream_id)
469 static void handle_msg_connect(ClientConnection *cc)
471 // We currently don't handle that a client tries to connect to a service on the Amiga.
474 static void handle_msg_connect_response(ClientConnection *cc)
476 LogicalChannel *ch = get_associated_channel_by_stream_id(cc, cc->header.stream_id);
480 create_and_enqueue_packet(ch, PKT_CONNECT_RESPONSE, &cc->payload[0], cc->payload.size());
482 if (cc->payload[0] != CONNECT_OK)
483 remove_association(ch);
486 static void handle_msg_data(ClientConnection *cc)
488 LogicalChannel *ch = get_associated_channel_by_stream_id(cc, cc->header.stream_id);
492 create_and_enqueue_packet(ch, PKT_DATA, &cc->payload[0], cc->header.length);
495 static void handle_msg_eos(ClientConnection *cc)
497 LogicalChannel *ch = get_associated_channel_by_stream_id(cc, cc->header.stream_id);
498 if (!ch || ch->got_eos_from_client)
501 ch->got_eos_from_client = true;
503 create_and_enqueue_packet(ch, PKT_EOS, nullptr, 0);
505 if (ch->got_eos_from_ami)
506 remove_association(ch);
509 static void handle_msg_reset(ClientConnection *cc)
511 LogicalChannel *ch = get_associated_channel_by_stream_id(cc, cc->header.stream_id);
515 remove_association(ch);
517 clear_packet_queue(ch);
518 create_and_enqueue_packet(ch, PKT_RESET, nullptr, 0);
521 static void handle_received_message(ClientConnection *cc)
523 switch (cc->header.type)
525 case MSG_REGISTER_REQ:
526 handle_msg_register_req(cc);
528 case MSG_DEREGISTER_REQ:
529 handle_msg_deregister_req(cc);
531 case MSG_READ_MEM_REQ:
532 handle_msg_read_mem_req(cc);
534 case MSG_WRITE_MEM_REQ:
535 handle_msg_write_mem_req(cc);
538 handle_msg_connect(cc);
540 case MSG_CONNECT_RESPONSE:
541 handle_msg_connect_response(cc);
550 handle_msg_reset(cc);
553 // This is bad, probably should disconnect from client.
554 logger_warn("Received a message of unknown type from client\n");
559 static void close_and_remove_connection(ClientConnection *cc)
561 shutdown(cc->fd, SHUT_WR);
565 auto it = services.begin();
566 while (it != services.end())
569 it = services.erase(it);
576 auto it = cc->associations.begin();
577 while (it != cc->associations.end())
581 clear_packet_queue(ch);
582 create_and_enqueue_packet(ch, PKT_RESET, nullptr, 0);
584 ch->association = nullptr;
587 it = cc->associations.erase(it);
591 for (auto it = connections.begin(); it != connections.end(); it++)
595 connections.erase(it);
601 static void remove_association(LogicalChannel *ch)
603 auto &ass = ch->association->associations;
604 ass.erase(std::find(ass.begin(), ass.end(), ch));
606 ch->association = nullptr;
610 static void clear_packet_queue(LogicalChannel *ch)
612 if (!ch->packet_queue.empty())
614 ch->packet_queue.clear();
615 send_queue.erase(std::find(send_queue.begin(), send_queue.end(), ch));
619 static void create_and_enqueue_packet(LogicalChannel *ch, uint8_t type, uint8_t *data, uint8_t length)
621 if (ch->packet_queue.empty())
622 send_queue.push_back(ch);
624 ch->packet_queue.emplace_back();
626 PacketBuffer &pb = ch->packet_queue.back();
628 pb.data.resize(length);
630 memcpy(&pb.data[0], data, length);
633 static void handle_pkt_connect(int channel_id, uint8_t *data, int plen)
635 for (auto &ch : channels)
637 if (ch.channel_id == channel_id)
639 // We should handle this in some constructive way.
640 // This signals that should reset all logical channels.
641 logger_error("Received a CONNECT packet on a channel that was believed to be previously allocated\n");
646 channels.emplace_back();
648 auto &ch = channels.back();
650 ch.channel_id = channel_id;
651 ch.association = nullptr;
653 ch.got_eos_from_ami = false;
654 ch.got_eos_from_client = false;
656 std::string service_name((char *)data, plen);
658 for (auto &srv : services)
660 if (srv.name == service_name)
662 ClientConnection *cc = srv.cc;
665 ch.stream_id = cc->next_stream_id;
667 cc->next_stream_id += 2;
668 cc->associations.push_back(&ch);
670 create_and_send_msg(ch.association, MSG_CONNECT, ch.stream_id, data, plen);
675 for (auto &on_demand : on_demand_services)
677 if (on_demand.service_name == service_name)
680 int status = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
683 logger_error("Unexpectedly not able to create socket pair.\n");
687 pid_t child = fork();
690 logger_error("Unexpectedly was not able to fork.\n");
698 // FIXE: The user should be configurable.
701 putenv((char *)home_env.c_str());
703 std::vector<std::string> args(on_demand.arguments);
704 args.push_back("-ondemand");
705 args.push_back(std::to_string(fd));
706 std::vector<const char *> args_arr;
707 for (auto &arg : args)
708 args_arr.push_back(arg.c_str());
709 args_arr.push_back(nullptr);
711 execvp(on_demand.program.c_str(), (char* const*) &args_arr[0]);
718 int status = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
721 logger_error("Unexpectedly unable to set close-on-exec flag on client socket descriptor; errno = %d\n", errno);
725 status = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
728 logger_error("Unexpectedly unable to set client socket to non blocking; errno = %d\n", errno);
733 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
735 connections.emplace_back();
737 ClientConnection &cc = connections.back();
739 cc.next_stream_id = 1;
742 struct epoll_event ev;
743 ev.events = EPOLLIN | EPOLLOUT | EPOLLET;
745 if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) != 0)
747 logger_error("epoll_ctl() failed unexpectedly with errno = %d\n", errno);
751 services.emplace_back();
753 RegisteredService &srv = services.back();
755 srv.name = std::move(service_name);
757 ch.association = &cc;
758 ch.stream_id = cc.next_stream_id;
760 cc.next_stream_id += 2;
761 cc.associations.push_back(&ch);
763 create_and_send_msg(ch.association, MSG_CONNECT, ch.stream_id, data, plen);
769 uint8_t response = CONNECT_UNKNOWN_SERVICE;
770 create_and_enqueue_packet(&ch, PKT_CONNECT_RESPONSE, &response, 1);
773 static void handle_pkt_data(int channel_id, uint8_t *data, int plen)
775 for (auto &ch : channels)
777 if (ch.channel_id == channel_id)
779 if (ch.association != nullptr && !ch.got_eos_from_ami)
780 create_and_send_msg(ch.association, MSG_DATA, ch.stream_id, data, plen);
787 static void handle_pkt_eos(int channel_id)
789 for (auto &ch : channels)
791 if (ch.channel_id == channel_id)
793 if (ch.association != nullptr && !ch.got_eos_from_ami)
795 ch.got_eos_from_ami = true;
797 create_and_send_msg(ch.association, MSG_EOS, ch.stream_id, nullptr, 0);
799 if (ch.got_eos_from_client)
800 remove_association(&ch);
807 static void handle_pkt_reset(int channel_id)
809 for (auto &ch : channels)
811 if (ch.channel_id == channel_id)
813 clear_packet_queue(&ch);
815 if (ch.association != nullptr)
817 create_and_send_msg(ch.association, MSG_RESET, ch.stream_id, nullptr, 0);
818 remove_association(&ch);
826 static void remove_channel_if_not_associated_and_empty_pq(int channel_id)
828 for (auto it = channels.begin(); it != channels.end(); it++)
830 if (it->channel_id == channel_id)
832 if (it->association == nullptr && it->packet_queue.empty())
840 static void handle_received_pkt(int ptype, int channel_id, uint8_t *data, int plen)
842 if (ptype == PKT_CONNECT)
843 handle_pkt_connect(channel_id, data, plen);
844 else if (ptype == PKT_DATA)
845 handle_pkt_data(channel_id, data, plen);
846 else if (ptype == PKT_EOS)
847 handle_pkt_eos(channel_id);
848 else if (ptype == PKT_RESET)
849 handle_pkt_reset(channel_id);
851 remove_channel_if_not_associated_and_empty_pq(channel_id);
854 static bool receive_from_a2r()
856 int head = channel_status[A2R_HEAD_OFFSET];
857 int tail = channel_status[A2R_TAIL_OFFSET];
858 int len = (tail - head) & 255;
864 memcpy(recv_buf, &ca.a2r_buffer[head], len);
868 memcpy(recv_buf, &ca.a2r_buffer[head], 256 - head);
872 memcpy(&recv_buf[len - tail], &ca.a2r_buffer[0], tail);
876 uint8_t *p = recv_buf;
877 while (p < recv_buf + len)
880 uint8_t ptype = *p++;
881 uint8_t channel_id = *p++;
882 handle_received_pkt(ptype, channel_id, p, plen);
886 channel_status[A2R_HEAD_OFFSET] = channel_status[A2R_TAIL_OFFSET];
887 channel_status_updated |= A_EVENT_A2R_HEAD;
891 static bool flush_send_queue()
893 int tail = channel_status[R2A_TAIL_OFFSET];
894 int head = channel_status[R2A_HEAD_OFFSET];
895 int len = (tail - head) & 255;
896 int left = 255 - len;
900 while (!send_queue.empty())
902 LogicalChannel *ch = send_queue.front();
903 PacketBuffer &pb = ch->packet_queue.front();
906 int plen = 3 + pb.data.size();
911 send_buf[pos++] = pb.data.size();
912 send_buf[pos++] = ptype;
913 send_buf[pos++] = ch->channel_id;
914 memcpy(&send_buf[pos], &pb.data[0], pb.data.size());
915 pos += pb.data.size();
917 ch->packet_queue.pop_front();
919 send_queue.pop_front();
921 if (!ch->packet_queue.empty())
922 send_queue.push_back(ch);
924 remove_channel_if_not_associated_and_empty_pq(ch->channel_id);
933 uint8_t *p = send_buf;
934 int at_end = 256 - tail;
935 if (at_end < to_write)
937 memcpy(&ca.r2a_buffer[tail], p, at_end);
943 memcpy(&ca.r2a_buffer[tail], p, to_write);
944 tail = (tail + to_write) & 255;
946 channel_status[R2A_TAIL_OFFSET] = tail;
947 channel_status_updated |= A_EVENT_R2A_TAIL;
951 static void read_channel_status()
953 channel_status[A2R_TAIL_OFFSET] = ca.a2r_tail;
954 channel_status[R2A_HEAD_OFFSET] = ca.r2a_head;
955 channel_status[R2A_TAIL_OFFSET] = ca.r2a_tail;
956 channel_status[A2R_HEAD_OFFSET] = ca.a2r_head;
957 channel_status_updated = 0;
960 static void write_channel_status()
962 if (channel_status_updated != 0)
964 ca.r2a_tail = channel_status[R2A_TAIL_OFFSET];
965 ca.a2r_head = channel_status[A2R_HEAD_OFFSET];
967 pthread_mutex_lock(&mutex);
968 ca.a_events |= channel_status_updated;
969 pthread_mutex_unlock(&mutex);
971 channel_status_updated = 0;
975 static void close_all_logical_channels()
979 auto it = channels.begin();
980 while (it != channels.end())
982 LogicalChannel &ch = *it;
984 if (ch.association != nullptr)
986 create_and_send_msg(ch.association, MSG_RESET, ch.stream_id, nullptr, 0);
987 remove_association(&ch);
990 it = channels.erase(it);
994 static void handle_a314_irq(uint8_t events)
999 if (events & R_EVENT_STARTED)
1001 if (!channels.empty())
1002 logger_info("Received STARTED event while logical channels are open -- closing channels\n");
1004 close_all_logical_channels();
1005 a314_device_started = true;
1008 if (!a314_device_started)
1011 read_channel_status();
1013 bool any_rcvd = receive_from_a2r();
1014 bool any_sent = flush_send_queue();
1016 if (any_rcvd || any_sent)
1017 write_channel_status();
1020 static void handle_client_connection_event(ClientConnection *cc, struct epoll_event *ev)
1022 if (ev->events & EPOLLERR)
1024 logger_warn("Received EPOLLERR for client connection\n");
1025 close_and_remove_connection(cc);
1029 if (ev->events & EPOLLIN)
1036 if (cc->payload.empty())
1038 left = sizeof(MessageHeader) - cc->bytes_read;
1039 dst = (uint8_t *)&(cc->header) + cc->bytes_read;
1043 left = cc->header.length - cc->bytes_read;
1044 dst = &cc->payload[cc->bytes_read];
1047 ssize_t r = read(cc->fd, dst, left);
1050 if (errno == EAGAIN || errno == EWOULDBLOCK)
1053 logger_error("Read failed unexpectedly with errno = %d\n", errno);
1059 logger_info("Received End-of-File on client connection\n");
1060 close_and_remove_connection(cc);
1065 cc->bytes_read += r;
1069 if (cc->payload.empty())
1071 if (cc->header.length == 0)
1073 logger_trace("header: length=%d, stream_id=%d, type=%d\n", cc->header.length, cc->header.stream_id, cc->header.type);
1074 handle_received_message(cc);
1078 cc->payload.resize(cc->header.length);
1083 logger_trace("header: length=%d, stream_id=%d, type=%d\n", cc->header.length, cc->header.stream_id, cc->header.type);
1084 handle_received_message(cc);
1085 cc->payload.clear();
1093 if (ev->events & EPOLLOUT)
1095 while (!cc->message_queue.empty())
1097 MessageBuffer &mb = cc->message_queue.front();
1099 int left = mb.data.size() - mb.pos;
1100 uint8_t *src = &mb.data[mb.pos];
1101 ssize_t r = write(cc->fd, src, left);
1104 if (errno == EAGAIN || errno == EWOULDBLOCK)
1106 else if (errno == ECONNRESET)
1108 close_and_remove_connection(cc);
1113 logger_error("Write failed unexpectedly with errno = %d\n", errno);
1120 cc->message_queue.pop_front();
1125 static void handle_server_socket_ready()
1127 struct sockaddr_in address;
1128 int alen = sizeof(struct sockaddr_in);
1130 int fd = accept(server_socket, (struct sockaddr *)&address, (socklen_t *)&alen);
1133 logger_error("Accept failed unexpectedly with errno = %d\n", errno);
1137 int status = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
1140 logger_error("Unexpectedly unable to set close-on-exec flag on client socket descriptor; errno = %d\n", errno);
1144 status = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
1147 logger_error("Unexpectedly unable to set client socket to non blocking; errno = %d\n", errno);
1152 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
1154 connections.emplace_back();
1156 ClientConnection &cc = connections.back();
1158 cc.next_stream_id = 1;
1161 struct epoll_event ev;
1162 ev.events = EPOLLIN | EPOLLOUT | EPOLLET;
1164 if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) != 0)
1166 logger_error("epoll_ctl() failed unexpectedly with errno = %d\n", errno);
1171 static void main_loop()
1173 bool shutting_down = false;
1178 struct epoll_event ev;
1179 int timeout = shutting_down ? 10000 : -1;
1180 int n = epoll_pwait(epfd, &ev, 1, timeout, &original_sigset);
1185 logger_info("Received SIGTERM\n");
1187 shutdown_server_socket();
1189 while (!connections.empty())
1190 close_and_remove_connection(&connections.front());
1192 if (flush_send_queue())
1193 write_channel_status();
1195 if (!channels.empty())
1196 shutting_down = true;
1202 logger_error("epoll_pwait failed with unexpected errno = %d\n", errno);
1212 logger_error("epoll_pwait returned 0 which is unexpected since no timeout was set\n");
1218 if (ev.data.fd == irq_fds[1])
1221 if (read(irq_fds[1], &events, 1) != 1)
1223 logger_error("Read from interrupt socket pair, and unexpectedly didn't return 1 byte\n");
1227 handle_a314_irq(events);
1229 else if (ev.data.fd == server_socket)
1231 logger_trace("Epoll event: server socket is ready, events = %d\n", ev.events);
1232 handle_server_socket_ready();
1236 logger_trace("Epoll event: client socket is ready, events = %d\n", ev.events);
1238 auto it = connections.begin();
1239 for (; it != connections.end(); it++)
1241 if (it->fd == ev.data.fd)
1245 if (it == connections.end())
1247 logger_error("Got notified about an event on a client connection that supposedly isn't currently open\n");
1251 ClientConnection *cc = &(*it);
1252 handle_client_connection_event(cc, &ev);
1254 if (flush_send_queue())
1255 write_channel_status();
1261 static int init_driver()
1263 if (init_server_socket() != 0)
1266 int err = socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, irq_fds);
1269 logger_error("Unable to create socket pair, errno = %d\n", errno);
1273 epfd = epoll_create1(EPOLL_CLOEXEC);
1277 struct epoll_event ev;
1278 ev.events = EPOLLIN;
1279 ev.data.fd = irq_fds[1];
1280 if (epoll_ctl(epfd, EPOLL_CTL_ADD, irq_fds[1], &ev) != 0)
1283 ev.events = EPOLLIN;
1284 ev.data.fd = server_socket;
1285 if (epoll_ctl(epfd, EPOLL_CTL_ADD, server_socket, &ev) != 0)
1291 static void shutdown_driver()
1296 shutdown_server_socket();
1299 static void *thread_start(void *arg)
1306 static void write_r_events(uint8_t events)
1308 if (write(irq_fds[0], &events, 1) != 1)
1309 logger_error("Write to interrupt socket pair did not return 1\n");
1314 load_config_file(a314_config_file.c_str());
1316 int err = init_driver();
1323 err = pthread_create(&thread_id, NULL, thread_start, NULL);
1326 logger_error("pthread_create failed with err = %d\n", err);
1333 void a314_set_mem_base_size(unsigned int base, unsigned int size)
1335 ca.mem_base = htobe32(base);
1336 ca.mem_size = htobe32(size);
1339 void a314_process_events()
1341 if (ca.a_events & ca.a_enable)
1343 ps_write_16(0xdff09c, 0x8008);
1348 unsigned int a314_read_memory_8(unsigned int address)
1350 if (address >= sizeof(ca))
1354 if (address == offsetof(ComArea, a_events))
1356 pthread_mutex_lock(&mutex);
1359 pthread_mutex_unlock(&mutex);
1363 uint8_t *p = (uint8_t *)&ca;
1370 unsigned int a314_read_memory_16(unsigned int address)
1372 if (address >= sizeof(ca))
1375 uint16_t *p = (uint16_t *)&ca;
1376 return be16toh(p[address >> 1]);
1379 unsigned int a314_read_memory_32(unsigned int address)
1381 if (address >= sizeof(ca))
1384 uint32_t *p = (uint32_t *)&ca;
1385 return be32toh(p[address >> 2]);
1388 void a314_write_memory_8(unsigned int address, unsigned int value)
1390 if (address >= sizeof(ca))
1395 case offsetof(ComArea, a_events):
1396 // a_events is not writable.
1399 case offsetof(ComArea, r_events):
1401 write_r_events((uint8_t)value);
1406 uint8_t *p = (uint8_t *)&ca;
1407 p[address] = (uint8_t)value;
1413 void a314_write_memory_16(unsigned int address, unsigned int value)
1418 void a314_write_memory_32(unsigned int address, unsigned int value)
1423 void a314_set_config_file(char *filename)
1425 printf ("[A314] Set A314 config filename to %s.\n", filename);
1426 a314_config_file = std::string(filename);