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" void ps_write_16(unsigned int address, unsigned int value);
114 unsigned int a314_base;
115 int a314_base_configured;
122 uint8_t r_enable; // Unused.
132 uint8_t a2r_buffer[256];
133 uint8_t r2a_buffer[256];
138 static bool a314_device_started = false;
140 static uint8_t channel_status[4];
141 static uint8_t channel_status_updated = 0;
143 static uint8_t recv_buf[256];
144 static uint8_t send_buf[256];
146 struct LogicalChannel;
147 struct ClientConnection;
149 #pragma pack(push, 1)
155 }; //} __attribute__((packed));
161 std::vector<uint8_t> data;
164 struct RegisteredService
167 ClientConnection *cc;
173 std::vector<uint8_t> data;
176 struct ClientConnection
183 MessageHeader header;
184 std::vector<uint8_t> payload;
186 std::list<MessageBuffer> message_queue;
188 std::list<LogicalChannel*> associations;
191 struct LogicalChannel
195 ClientConnection *association;
198 bool got_eos_from_ami;
199 bool got_eos_from_client;
201 std::list<PacketBuffer> packet_queue;
204 static void remove_association(LogicalChannel *ch);
205 static void clear_packet_queue(LogicalChannel *ch);
206 static void create_and_enqueue_packet(LogicalChannel *ch, uint8_t type, uint8_t *data, uint8_t length);
208 static std::list<ClientConnection> connections;
209 static std::list<RegisteredService> services;
210 static std::list<LogicalChannel> channels;
211 static std::list<LogicalChannel*> send_queue;
215 std::string service_name;
217 std::vector<std::string> arguments;
220 std::vector<OnDemandStart> on_demand_services;
222 std::string a314_config_file = "/etc/opt/a314/a314d.conf";
223 std::string home_env = "HOME=/home/pi";
225 static void load_config_file(const char *filename)
227 FILE *f = fopen(filename, "rt");
232 std::vector<char *> parts;
234 while (fgets(line, 256, f) != nullptr)
237 strcpy(org_line, line);
239 bool in_quotes = false;
242 for (int i = 0; i < 256; i++)
247 parts.push_back(&line[start]);
250 else if (line[i] == '"')
254 parts.push_back(&line[start]);
255 in_quotes = !in_quotes;
258 else if (isspace(line[i]) && !in_quotes)
262 parts.push_back(&line[start]);
267 if (parts.size() >= 2)
269 on_demand_services.emplace_back();
270 auto &e = on_demand_services.back();
271 e.service_name = parts[0];
272 e.program = parts[1];
273 for (int i = 1; i < parts.size(); i++)
274 e.arguments.push_back(std::string(parts[i]));
276 else if (parts.size() != 0)
277 logger_warn("Invalid number of columns in configuration file line: %s\n", org_line);
284 if (on_demand_services.empty())
285 logger_warn("No registered services\n");
288 static int init_server_socket()
290 server_socket = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
291 if (server_socket == -1)
293 logger_error("Failed to create server socket\n");
297 struct sockaddr_in address;
298 address.sin_family = AF_INET;
299 address.sin_addr.s_addr = INADDR_ANY;
300 address.sin_port = htons(7110);
302 int res = bind(server_socket, (struct sockaddr *)&address, sizeof(address));
305 logger_error("Bind to localhost:7110 failed\n");
309 listen(server_socket, 16);
314 static void shutdown_server_socket()
316 if (server_socket != -1)
317 close(server_socket);
321 void create_and_send_msg(ClientConnection *cc, int type, int stream_id, uint8_t *data, int length)
325 mb.data.resize(sizeof(MessageHeader) + length);
327 MessageHeader *mh = (MessageHeader *)&mb.data[0];
329 mh->stream_id = stream_id;
332 memcpy(&mb.data[sizeof(MessageHeader)], data, length);
334 if (!cc->message_queue.empty())
336 cc->message_queue.push_back(std::move(mb));
342 int left = mb.data.size() - mb.pos;
343 uint8_t *src = &mb.data[mb.pos];
344 ssize_t r = write(cc->fd, src, left);
347 if (errno == EAGAIN || errno == EWOULDBLOCK)
349 cc->message_queue.push_back(std::move(mb));
352 else if (errno == ECONNRESET)
354 // Do not close connection here; it will get done at some other place.
359 logger_error("Write failed unexpectedly with errno = %d\n", errno);
372 static void handle_msg_register_req(ClientConnection *cc)
374 uint8_t result = MSG_FAIL;
376 std::string service_name((char *)&cc->payload[0], cc->payload.size());
378 auto it = services.begin();
379 for (; it != services.end(); it++)
380 if (it->name == service_name)
383 if (it == services.end())
385 services.emplace_back();
387 RegisteredService &srv = services.back();
389 srv.name = std::move(service_name);
391 result = MSG_SUCCESS;
394 create_and_send_msg(cc, MSG_REGISTER_RES, 0, &result, 1);
397 static void handle_msg_deregister_req(ClientConnection *cc)
399 uint8_t result = MSG_FAIL;
401 std::string service_name((char *)&cc->payload[0], cc->payload.size());
403 for (auto it = services.begin(); it != services.end(); it++)
405 if (it->name == service_name && it->cc == cc)
408 result = MSG_SUCCESS;
413 create_and_send_msg(cc, MSG_DEREGISTER_RES, 0, &result, 1);
416 static void handle_msg_read_mem_req(ClientConnection *cc)
418 uint32_t address = *(uint32_t *)&(cc->payload[0]);
419 uint32_t length = *(uint32_t *)&(cc->payload[4]);
421 if (get_mapped_item_by_address(cfg, address) != -1) {
422 int32_t index = get_mapped_item_by_address(cfg, address);
423 uint8_t *map = &cfg->map_data[index][address - cfg->map_offset[index]];
424 create_and_send_msg(cc, MSG_READ_MEM_RES, 0, map, length);
430 static void handle_msg_write_mem_req(ClientConnection *cc)
432 uint32_t address = *(uint32_t *)&(cc->payload[0]);
433 uint32_t length = cc->payload.size() - 4;
436 if (get_mapped_item_by_address(cfg, address) != -1) {
437 int32_t index = get_mapped_item_by_address(cfg, address);
438 uint8_t *map = &cfg->map_data[index][address - cfg->map_offset[index]];
439 memcpy(map, &(cc->payload[4]), length);
444 create_and_send_msg(cc, MSG_WRITE_MEM_RES, 0, nullptr, 0);
447 static LogicalChannel *get_associated_channel_by_stream_id(ClientConnection *cc, int stream_id)
449 for (auto ch : cc->associations)
451 if (ch->stream_id == stream_id)
457 static void handle_msg_connect(ClientConnection *cc)
459 // We currently don't handle that a client tries to connect to a service on the Amiga.
462 static void handle_msg_connect_response(ClientConnection *cc)
464 LogicalChannel *ch = get_associated_channel_by_stream_id(cc, cc->header.stream_id);
468 create_and_enqueue_packet(ch, PKT_CONNECT_RESPONSE, &cc->payload[0], cc->payload.size());
470 if (cc->payload[0] != CONNECT_OK)
471 remove_association(ch);
474 static void handle_msg_data(ClientConnection *cc)
476 LogicalChannel *ch = get_associated_channel_by_stream_id(cc, cc->header.stream_id);
480 create_and_enqueue_packet(ch, PKT_DATA, &cc->payload[0], cc->header.length);
483 static void handle_msg_eos(ClientConnection *cc)
485 LogicalChannel *ch = get_associated_channel_by_stream_id(cc, cc->header.stream_id);
486 if (!ch || ch->got_eos_from_client)
489 ch->got_eos_from_client = true;
491 create_and_enqueue_packet(ch, PKT_EOS, nullptr, 0);
493 if (ch->got_eos_from_ami)
494 remove_association(ch);
497 static void handle_msg_reset(ClientConnection *cc)
499 LogicalChannel *ch = get_associated_channel_by_stream_id(cc, cc->header.stream_id);
503 remove_association(ch);
505 clear_packet_queue(ch);
506 create_and_enqueue_packet(ch, PKT_RESET, nullptr, 0);
509 static void handle_received_message(ClientConnection *cc)
511 switch (cc->header.type)
513 case MSG_REGISTER_REQ:
514 handle_msg_register_req(cc);
516 case MSG_DEREGISTER_REQ:
517 handle_msg_deregister_req(cc);
519 case MSG_READ_MEM_REQ:
520 handle_msg_read_mem_req(cc);
522 case MSG_WRITE_MEM_REQ:
523 handle_msg_write_mem_req(cc);
526 handle_msg_connect(cc);
528 case MSG_CONNECT_RESPONSE:
529 handle_msg_connect_response(cc);
538 handle_msg_reset(cc);
541 // This is bad, probably should disconnect from client.
542 logger_warn("Received a message of unknown type from client\n");
547 static void close_and_remove_connection(ClientConnection *cc)
549 shutdown(cc->fd, SHUT_WR);
553 auto it = services.begin();
554 while (it != services.end())
557 it = services.erase(it);
564 auto it = cc->associations.begin();
565 while (it != cc->associations.end())
569 clear_packet_queue(ch);
570 create_and_enqueue_packet(ch, PKT_RESET, nullptr, 0);
572 ch->association = nullptr;
575 it = cc->associations.erase(it);
579 for (auto it = connections.begin(); it != connections.end(); it++)
583 connections.erase(it);
589 static void remove_association(LogicalChannel *ch)
591 auto &ass = ch->association->associations;
592 ass.erase(std::find(ass.begin(), ass.end(), ch));
594 ch->association = nullptr;
598 static void clear_packet_queue(LogicalChannel *ch)
600 if (!ch->packet_queue.empty())
602 ch->packet_queue.clear();
603 send_queue.erase(std::find(send_queue.begin(), send_queue.end(), ch));
607 static void create_and_enqueue_packet(LogicalChannel *ch, uint8_t type, uint8_t *data, uint8_t length)
609 if (ch->packet_queue.empty())
610 send_queue.push_back(ch);
612 ch->packet_queue.emplace_back();
614 PacketBuffer &pb = ch->packet_queue.back();
616 pb.data.resize(length);
618 memcpy(&pb.data[0], data, length);
621 static void handle_pkt_connect(int channel_id, uint8_t *data, int plen)
623 for (auto &ch : channels)
625 if (ch.channel_id == channel_id)
627 // We should handle this in some constructive way.
628 // This signals that should reset all logical channels.
629 logger_error("Received a CONNECT packet on a channel that was believed to be previously allocated\n");
634 channels.emplace_back();
636 auto &ch = channels.back();
638 ch.channel_id = channel_id;
639 ch.association = nullptr;
641 ch.got_eos_from_ami = false;
642 ch.got_eos_from_client = false;
644 std::string service_name((char *)data, plen);
646 for (auto &srv : services)
648 if (srv.name == service_name)
650 ClientConnection *cc = srv.cc;
653 ch.stream_id = cc->next_stream_id;
655 cc->next_stream_id += 2;
656 cc->associations.push_back(&ch);
658 create_and_send_msg(ch.association, MSG_CONNECT, ch.stream_id, data, plen);
663 for (auto &on_demand : on_demand_services)
665 if (on_demand.service_name == service_name)
668 int status = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
671 logger_error("Unexpectedly not able to create socket pair.\n");
675 pid_t child = fork();
678 logger_error("Unexpectedly was not able to fork.\n");
686 // FIXE: The user should be configurable.
689 putenv((char *)home_env.c_str());
691 std::vector<std::string> args(on_demand.arguments);
692 args.push_back("-ondemand");
693 args.push_back(std::to_string(fd));
694 std::vector<const char *> args_arr;
695 for (auto &arg : args)
696 args_arr.push_back(arg.c_str());
697 args_arr.push_back(nullptr);
699 execvp(on_demand.program.c_str(), (char* const*) &args_arr[0]);
706 int status = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
709 logger_error("Unexpectedly unable to set close-on-exec flag on client socket descriptor; errno = %d\n", errno);
713 status = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
716 logger_error("Unexpectedly unable to set client socket to non blocking; errno = %d\n", errno);
721 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
723 connections.emplace_back();
725 ClientConnection &cc = connections.back();
727 cc.next_stream_id = 1;
730 struct epoll_event ev;
731 ev.events = EPOLLIN | EPOLLOUT | EPOLLET;
733 if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) != 0)
735 logger_error("epoll_ctl() failed unexpectedly with errno = %d\n", errno);
739 services.emplace_back();
741 RegisteredService &srv = services.back();
743 srv.name = std::move(service_name);
745 ch.association = &cc;
746 ch.stream_id = cc.next_stream_id;
748 cc.next_stream_id += 2;
749 cc.associations.push_back(&ch);
751 create_and_send_msg(ch.association, MSG_CONNECT, ch.stream_id, data, plen);
757 uint8_t response = CONNECT_UNKNOWN_SERVICE;
758 create_and_enqueue_packet(&ch, PKT_CONNECT_RESPONSE, &response, 1);
761 static void handle_pkt_data(int channel_id, uint8_t *data, int plen)
763 for (auto &ch : channels)
765 if (ch.channel_id == channel_id)
767 if (ch.association != nullptr && !ch.got_eos_from_ami)
768 create_and_send_msg(ch.association, MSG_DATA, ch.stream_id, data, plen);
775 static void handle_pkt_eos(int channel_id)
777 for (auto &ch : channels)
779 if (ch.channel_id == channel_id)
781 if (ch.association != nullptr && !ch.got_eos_from_ami)
783 ch.got_eos_from_ami = true;
785 create_and_send_msg(ch.association, MSG_EOS, ch.stream_id, nullptr, 0);
787 if (ch.got_eos_from_client)
788 remove_association(&ch);
795 static void handle_pkt_reset(int channel_id)
797 for (auto &ch : channels)
799 if (ch.channel_id == channel_id)
801 clear_packet_queue(&ch);
803 if (ch.association != nullptr)
805 create_and_send_msg(ch.association, MSG_RESET, ch.stream_id, nullptr, 0);
806 remove_association(&ch);
814 static void remove_channel_if_not_associated_and_empty_pq(int channel_id)
816 for (auto it = channels.begin(); it != channels.end(); it++)
818 if (it->channel_id == channel_id)
820 if (it->association == nullptr && it->packet_queue.empty())
828 static void handle_received_pkt(int ptype, int channel_id, uint8_t *data, int plen)
830 if (ptype == PKT_CONNECT)
831 handle_pkt_connect(channel_id, data, plen);
832 else if (ptype == PKT_DATA)
833 handle_pkt_data(channel_id, data, plen);
834 else if (ptype == PKT_EOS)
835 handle_pkt_eos(channel_id);
836 else if (ptype == PKT_RESET)
837 handle_pkt_reset(channel_id);
839 remove_channel_if_not_associated_and_empty_pq(channel_id);
842 static bool receive_from_a2r()
844 int head = channel_status[A2R_HEAD_OFFSET];
845 int tail = channel_status[A2R_TAIL_OFFSET];
846 int len = (tail - head) & 255;
852 memcpy(recv_buf, &ca.a2r_buffer[head], len);
856 memcpy(recv_buf, &ca.a2r_buffer[head], 256 - head);
860 memcpy(&recv_buf[len - tail], &ca.a2r_buffer[0], tail);
864 uint8_t *p = recv_buf;
865 while (p < recv_buf + len)
868 uint8_t ptype = *p++;
869 uint8_t channel_id = *p++;
870 handle_received_pkt(ptype, channel_id, p, plen);
874 channel_status[A2R_HEAD_OFFSET] = channel_status[A2R_TAIL_OFFSET];
875 channel_status_updated |= A_EVENT_A2R_HEAD;
879 static bool flush_send_queue()
881 int tail = channel_status[R2A_TAIL_OFFSET];
882 int head = channel_status[R2A_HEAD_OFFSET];
883 int len = (tail - head) & 255;
884 int left = 255 - len;
888 while (!send_queue.empty())
890 LogicalChannel *ch = send_queue.front();
891 PacketBuffer &pb = ch->packet_queue.front();
894 int plen = 3 + pb.data.size();
899 send_buf[pos++] = pb.data.size();
900 send_buf[pos++] = ptype;
901 send_buf[pos++] = ch->channel_id;
902 memcpy(&send_buf[pos], &pb.data[0], pb.data.size());
903 pos += pb.data.size();
905 ch->packet_queue.pop_front();
907 send_queue.pop_front();
909 if (!ch->packet_queue.empty())
910 send_queue.push_back(ch);
912 remove_channel_if_not_associated_and_empty_pq(ch->channel_id);
921 uint8_t *p = send_buf;
922 int at_end = 256 - tail;
923 if (at_end < to_write)
925 memcpy(&ca.r2a_buffer[tail], p, at_end);
931 memcpy(&ca.r2a_buffer[tail], p, to_write);
932 tail = (tail + to_write) & 255;
934 channel_status[R2A_TAIL_OFFSET] = tail;
935 channel_status_updated |= A_EVENT_R2A_TAIL;
939 static void read_channel_status()
941 channel_status[A2R_TAIL_OFFSET] = ca.a2r_tail;
942 channel_status[R2A_HEAD_OFFSET] = ca.r2a_head;
943 channel_status[R2A_TAIL_OFFSET] = ca.r2a_tail;
944 channel_status[A2R_HEAD_OFFSET] = ca.a2r_head;
945 channel_status_updated = 0;
948 static void write_channel_status()
950 if (channel_status_updated != 0)
952 ca.r2a_tail = channel_status[R2A_TAIL_OFFSET];
953 ca.a2r_head = channel_status[A2R_HEAD_OFFSET];
955 pthread_mutex_lock(&mutex);
956 ca.a_events |= channel_status_updated;
957 pthread_mutex_unlock(&mutex);
959 channel_status_updated = 0;
963 static void close_all_logical_channels()
967 auto it = channels.begin();
968 while (it != channels.end())
970 LogicalChannel &ch = *it;
972 if (ch.association != nullptr)
974 create_and_send_msg(ch.association, MSG_RESET, ch.stream_id, nullptr, 0);
975 remove_association(&ch);
978 it = channels.erase(it);
982 static void handle_a314_irq(uint8_t events)
987 if (events & R_EVENT_STARTED)
989 if (!channels.empty())
990 logger_info("Received STARTED event while logical channels are open -- closing channels\n");
992 close_all_logical_channels();
993 a314_device_started = true;
996 if (!a314_device_started)
999 read_channel_status();
1001 bool any_rcvd = receive_from_a2r();
1002 bool any_sent = flush_send_queue();
1004 if (any_rcvd || any_sent)
1005 write_channel_status();
1008 static void handle_client_connection_event(ClientConnection *cc, struct epoll_event *ev)
1010 if (ev->events & EPOLLERR)
1012 logger_warn("Received EPOLLERR for client connection\n");
1013 close_and_remove_connection(cc);
1017 if (ev->events & EPOLLIN)
1024 if (cc->payload.empty())
1026 left = sizeof(MessageHeader) - cc->bytes_read;
1027 dst = (uint8_t *)&(cc->header) + cc->bytes_read;
1031 left = cc->header.length - cc->bytes_read;
1032 dst = &cc->payload[cc->bytes_read];
1035 ssize_t r = read(cc->fd, dst, left);
1038 if (errno == EAGAIN || errno == EWOULDBLOCK)
1041 logger_error("Read failed unexpectedly with errno = %d\n", errno);
1047 logger_info("Received End-of-File on client connection\n");
1048 close_and_remove_connection(cc);
1053 cc->bytes_read += r;
1057 if (cc->payload.empty())
1059 if (cc->header.length == 0)
1061 logger_trace("header: length=%d, stream_id=%d, type=%d\n", cc->header.length, cc->header.stream_id, cc->header.type);
1062 handle_received_message(cc);
1066 cc->payload.resize(cc->header.length);
1071 logger_trace("header: length=%d, stream_id=%d, type=%d\n", cc->header.length, cc->header.stream_id, cc->header.type);
1072 handle_received_message(cc);
1073 cc->payload.clear();
1081 if (ev->events & EPOLLOUT)
1083 while (!cc->message_queue.empty())
1085 MessageBuffer &mb = cc->message_queue.front();
1087 int left = mb.data.size() - mb.pos;
1088 uint8_t *src = &mb.data[mb.pos];
1089 ssize_t r = write(cc->fd, src, left);
1092 if (errno == EAGAIN || errno == EWOULDBLOCK)
1094 else if (errno == ECONNRESET)
1096 close_and_remove_connection(cc);
1101 logger_error("Write failed unexpectedly with errno = %d\n", errno);
1108 cc->message_queue.pop_front();
1113 static void handle_server_socket_ready()
1115 struct sockaddr_in address;
1116 int alen = sizeof(struct sockaddr_in);
1118 int fd = accept(server_socket, (struct sockaddr *)&address, (socklen_t *)&alen);
1121 logger_error("Accept failed unexpectedly with errno = %d\n", errno);
1125 int status = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
1128 logger_error("Unexpectedly unable to set close-on-exec flag on client socket descriptor; errno = %d\n", errno);
1132 status = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
1135 logger_error("Unexpectedly unable to set client socket to non blocking; errno = %d\n", errno);
1140 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
1142 connections.emplace_back();
1144 ClientConnection &cc = connections.back();
1146 cc.next_stream_id = 1;
1149 struct epoll_event ev;
1150 ev.events = EPOLLIN | EPOLLOUT | EPOLLET;
1152 if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) != 0)
1154 logger_error("epoll_ctl() failed unexpectedly with errno = %d\n", errno);
1159 static void main_loop()
1161 bool shutting_down = false;
1166 struct epoll_event ev;
1167 int timeout = shutting_down ? 10000 : -1;
1168 int n = epoll_pwait(epfd, &ev, 1, timeout, &original_sigset);
1173 logger_info("Received SIGTERM\n");
1175 shutdown_server_socket();
1177 while (!connections.empty())
1178 close_and_remove_connection(&connections.front());
1180 if (flush_send_queue())
1181 write_channel_status();
1183 if (!channels.empty())
1184 shutting_down = true;
1190 logger_error("epoll_pwait failed with unexpected errno = %d\n", errno);
1200 logger_error("epoll_pwait returned 0 which is unexpected since no timeout was set\n");
1206 if (ev.data.fd == irq_fds[1])
1209 if (read(irq_fds[1], &events, 1) != 1)
1211 logger_error("Read from interrupt socket pair, and unexpectedly didn't return 1 byte\n");
1215 handle_a314_irq(events);
1217 else if (ev.data.fd == server_socket)
1219 logger_trace("Epoll event: server socket is ready, events = %d\n", ev.events);
1220 handle_server_socket_ready();
1224 logger_trace("Epoll event: client socket is ready, events = %d\n", ev.events);
1226 auto it = connections.begin();
1227 for (; it != connections.end(); it++)
1229 if (it->fd == ev.data.fd)
1233 if (it == connections.end())
1235 logger_error("Got notified about an event on a client connection that supposedly isn't currently open\n");
1239 ClientConnection *cc = &(*it);
1240 handle_client_connection_event(cc, &ev);
1242 if (flush_send_queue())
1243 write_channel_status();
1249 static int init_driver()
1251 if (init_server_socket() != 0)
1254 int err = socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, irq_fds);
1257 logger_error("Unable to create socket pair, errno = %d\n", errno);
1261 epfd = epoll_create1(EPOLL_CLOEXEC);
1265 struct epoll_event ev;
1266 ev.events = EPOLLIN;
1267 ev.data.fd = irq_fds[1];
1268 if (epoll_ctl(epfd, EPOLL_CTL_ADD, irq_fds[1], &ev) != 0)
1271 ev.events = EPOLLIN;
1272 ev.data.fd = server_socket;
1273 if (epoll_ctl(epfd, EPOLL_CTL_ADD, server_socket, &ev) != 0)
1279 static void shutdown_driver()
1284 shutdown_server_socket();
1287 static void *thread_start(void *arg)
1294 static void write_r_events(uint8_t events)
1296 if (write(irq_fds[0], &events, 1) != 1)
1297 logger_error("Write to interrupt socket pair did not return 1\n");
1302 load_config_file(a314_config_file.c_str());
1304 int err = init_driver();
1311 err = pthread_create(&thread_id, NULL, thread_start, NULL);
1314 logger_error("pthread_create failed with err = %d\n", err);
1321 void a314_set_mem_base_size(unsigned int base, unsigned int size)
1323 ca.mem_base = htobe32(base);
1324 ca.mem_size = htobe32(size);
1327 void a314_process_events()
1329 if (ca.a_events & ca.a_enable)
1331 ps_write_16(0xdff09c, 0x8008);
1336 unsigned int a314_read_memory_8(unsigned int address)
1338 if (address >= sizeof(ca))
1342 if (address == offsetof(ComArea, a_events))
1344 pthread_mutex_lock(&mutex);
1347 pthread_mutex_unlock(&mutex);
1351 uint8_t *p = (uint8_t *)&ca;
1358 unsigned int a314_read_memory_16(unsigned int address)
1360 if (address >= sizeof(ca))
1363 uint16_t *p = (uint16_t *)&ca;
1364 return be16toh(p[address >> 1]);
1367 unsigned int a314_read_memory_32(unsigned int address)
1369 if (address >= sizeof(ca))
1372 uint32_t *p = (uint32_t *)&ca;
1373 return be32toh(p[address >> 2]);
1376 void a314_write_memory_8(unsigned int address, unsigned int value)
1378 if (address >= sizeof(ca))
1383 case offsetof(ComArea, a_events):
1384 // a_events is not writable.
1387 case offsetof(ComArea, r_events):
1389 write_r_events((uint8_t)value);
1394 uint8_t *p = (uint8_t *)&ca;
1395 p[address] = (uint8_t)value;
1401 void a314_write_memory_16(unsigned int address, unsigned int value)
1406 void a314_write_memory_32(unsigned int address, unsigned int value)
1411 void a314_set_config_file(char *filename)
1413 printf ("[A314] Set A314 config filename to %s.\n", filename);
1414 a314_config_file = std::string(filename);