4 * (c) 2010 Martin Mares <mj@ucw.cz>
9 * - we probably have to disable NOP
13 * Things that are not implemented:
16 * - exact behavior of accumulator/R1/R2 (the manual lacks details)
17 * - exact behavior of negative zero
18 * - I/O instructions for devices that are not emulated (paper tape
19 * reader and puncher, card reader and puncher, magnetic tape unit)
33 static int cpu_quota = -1;
34 static int print_quota = -1;
35 static void (*error_hook)(char *msg);
37 // Minsk-2 has 37-bit words in sign-magnitude representation (bit 36 = sign)
38 typedef unsigned long long int word;
40 #define WORD_MASK 01777777777777ULL
41 #define SIGN_MASK 01000000000000ULL
42 #define VAL_MASK 00777777777777ULL
44 static int wsign(word w)
46 return (w & SIGN_MASK) ? -1 : 1;
49 static word wabs(word w)
54 #define WF(w) (wsign(w) < 0 ? '-' : '+'), wabs(w)
56 static long long wtoll(word w)
64 static word wfromll(long long x)
66 word w = ((x < 0) ? -x : x) & VAL_MASK;
72 static double wtofrac(word w)
74 return (double)wtoll(w) / (double)(1ULL << 36);
77 static word wfromfrac(double d)
79 return wfromll((long long)(d * (double)(1ULL << 36)));
82 static int int_in_range(long long x)
84 return (x >= -(long long)VAL_MASK && x <= (long long)VAL_MASK);
87 static int frac_in_range(double d)
89 return (d > -1. && d < 1.);
92 static int wexp(word w)
95 return (w & 0100 ? -exp : exp);
98 static word wputexp(word w, int exp)
100 return ((w & ~(word)0177) | ((exp < 0) ? 0100 | (-exp) : exp));
103 static int wmanti(word w)
105 return ((w >> 8) & ((1 << 28) - 1));
108 static double wtofloat(word w)
110 double x = wmanti(w);
111 return ldexp(x, wexp(w) - 28);
114 static int float_in_range(double x)
117 return (x <= ldexp((1 << 28) - 1, 63 - 28));
120 static word wfromfloat(double x, int normalized)
129 double m = frexp(x, &exp);
130 word mm = (word) ldexp(m, 28);
135 if (normalized || exp < -91)
153 static word mem[4096];
155 static word rd(int addr)
157 word val = addr ? mem[addr] : 0;
159 printf("\tRD %04o = %c%012llo\n", addr, WF(val));
163 static void wr(int addr, word val)
165 assert(!(val & ~(WORD_MASK)));
167 printf("\tWR %04o = %c%012llo\n", addr, WF(val));
173 static void parse_error(char *msg)
176 error_hook("Parse error");
177 printf("Ошибка входа (стр. %d): %s\n", lino, msg);
181 static void parse_in(void)
186 while (fgets(line, sizeof(line), stdin))
189 char *eol = strchr(line, '\n');
191 parse_error("Строка слишком долгая");
195 if (!c[0] || c[0] == ';')
197 if (!strncmp(c, ";daji_zor_i_litva=", 18))
201 error_hook("Secret tracing switch flipped");
210 for (int i=0; i<4; i++)
214 if (*c >= '0' && *c <= '7')
215 addr = 8*addr + *c++ - '0';
217 parse_error("Плохая цифра");
222 parse_error("Адрес слишком долгий");
230 parse_error("Плохой знак");
232 for (int i=0; i<12; i++)
236 if (*c >= '0' && *c <= '7')
237 w = 8*w + *c++ - '0';
239 parse_error("Плохая цифра");
244 parse_error("Номер слишком долгий");
251 static word r1, r2, current_ins;
252 static int ip = 00050; // Standard program start location
255 static void stop(char *reason, char *notice)
259 printf("Машина остановлена -- %s\n", reason);
260 printf("СчАК:%04o См:%c%012llo Р1:%c%012llo Р2:%c%012llo\n", prev_ip, WF(acc), WF(r1), WF(r2));
264 static void over(void)
266 stop("Аварийный останов", "Overflow");
269 static void notimp(void)
272 stop("Устройство разбитое", "Not implemented");
275 static void noins(void)
278 stop("Эту команду не знаю", "Illegal instruction");
281 static uint16_t linebuf[128];
283 static uint16_t russian_chars[64] = {
284 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
285 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
286 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
287 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
288 0x410, 0x411, 0x412, 0x413, 0x414, 0x415, 0x416, 0x417, // 4x
289 0x418, 0x419, 0x41a, 0x41b, 0x41c, 0x41d, 0x41e, 0x41f, // 5x
290 0x420, 0x421, 0x422, 0x423, 0x424, 0x425, 0x426, 0x427, // 6x
291 0x428, 0x429, 0x42b, 0x42c, 0x42d, 0x42e, 0x42f, 0x2013 // 7x
294 static uint16_t latin_chars[64] = {
295 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
296 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
297 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
298 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
299 'A', 'B', 'W', 'G', 'D', 'E', 'V', 'Z', // 4x
300 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 5x
301 'R', 'S', 'T', 'U', 'F', 'H', 'C', ' ', // 6x
302 ' ', ' ', 'Y', 'X', ' ', ' ', 'Q', 0x2013 // 7x
305 static void print_line(int r)
308 * Meaning of bits of r:
309 * 0 = perform line feed
315 if (print_quota > 0 && !--print_quota)
316 stop("Бумага дошла - нужно ехать в Сибирь про новую", "Out of paper");
317 for (int i=0; i<128; i++)
326 putchar(0xc0 | (ch >> 6));
327 putchar(0x80 | (ch & 0x3f));
331 putchar(0xe0 | (ch >> 12));
332 putchar(0x80 | ((ch >> 6) & 0x3f));
333 putchar(0x80 | (ch & 0x3f));
338 memset(linebuf, 0, sizeof(linebuf));
346 static void print_ins(int x, int y)
350 int r = (x >> 9) & 7;
363 case 0: // Decimal float
364 fmt = "+dddddddx+xbd";
366 case 1: // Octal number
367 fmt = "+oooooooooooo";
369 case 2: // Decimal fixed
372 case 3: // Decimal unsigned
376 case 4: // One Russian symbol
380 case 5: // Russian text
383 case 6: // One Latin symbol
387 default: // Latin text
404 ch = (yy & (1ULL << bit)) ? '-' : '+';
408 ch = '0' + ((yy >> bit) & 1);
412 ch = '0' + ((yy >> bit) & 7);
416 ch = '0' + ((yy >> bit) & 15);
422 ch = russian_chars[(yy >> bit) & 077];
426 ch = latin_chars[(yy >> bit) & 077];
434 if (ch == '0' || ch == ' ')
440 pos = (pos+1) & 0177;
445 static void run(void)
454 int op = (w >> 30) & 0177; // Operation code
455 int ax = (w >> 28) & 3; // Address extensions not supported
456 int ix = (w >> 24) & 15; // Indexing
457 int x = (w >> 12) & 07777; // Operands (original form)
459 int xi=x, yi=y; // (indexed form)
461 printf("@%04o %c%02o %02o %04o %04o\n",
463 (w & SIGN_MASK) ? '-' : '+',
464 (int)((w >> 30) & 077),
465 (int)((w >> 24) & 077),
473 xi = (xi + (int)((i >> 12) & 07777)) & 07777;
474 yi = (yi + (int)(i & 07777)) & 07777;
476 printf("\tIndexing -> %04o %04o\n", xi, yi);
481 if (cpu_quota > 0 && !--cpu_quota)
482 stop("Тайм-аут", "CPU quota exceeded");
484 /* Arithmetic operations */
487 long long aa, bb, cc;
491 auto void afetch(void);
501 auto void astore(word result);
502 void astore(word result)
509 auto void astore_int(long long x);
510 void astore_int(long long x)
512 if (!int_in_range(x))
517 auto void astore_frac(double f);
518 void astore_frac(double f)
520 if (!frac_in_range(f))
522 astore(wfromfrac(f));
525 auto void astore_float(double f);
526 void astore_float(double f)
528 if (!float_in_range(f))
530 astore(wfromfloat(f, 0));
539 case 004 ... 007: // XOR
543 case 010 ... 013: // FIX addition
545 astore_int(wtoll(a) + wtoll(b));
547 case 014 ... 017: // FP addition
549 astore_float(wtofloat(a) + wtofloat(b));
551 case 020 ... 023: // FIX subtraction
553 astore_int(wtoll(a) - wtoll(b));
555 case 024 ... 027: // FP subtraction
557 astore_float(wtofloat(a) - wtofloat(b));
559 case 030 ... 033: // FIX multiplication
561 astore_frac(wtofrac(a) * wtofrac(b));
563 case 034 ... 037: // FP multiplication
565 astore_float(wtofloat(a) * wtofloat(b));
567 case 040 ... 043: // FIX division
573 astore_frac(ad / bd);
575 case 044 ... 047: // FP division
579 if (!bd || wexp(b) < -63)
581 astore_float(ad / bd);
583 case 050 ... 053: // FIX subtraction of abs values
585 astore_int(wabs(a) - wabs(b));
587 case 054 ... 057: // FP subtraction of abs values
589 astore_float(fabs(wtofloat(a)) - fabs(wtofloat(b)));
591 case 060 ... 063: // Shift logical
594 if (i <= -37 || i >= 37)
597 astore((a << i) & WORD_MASK);
601 case 064 ... 067: // Shift arithmetical
605 if (i <= -36 || i >= 36)
608 cc = (aa << i) & VAL_MASK;
611 astore((a & SIGN_MASK) | wfromll(cc));
613 case 070 ... 073: // And
617 case 074 ... 077: // Or
625 stop("Останов машины", "Halted");
626 case 0103: // I/O magtape
628 case 0104: // Disable rounding
630 case 0105: // Enable rounding
632 case 0106: // Interrupt control
634 case 0107: // Reverse tape
637 wr(yi, r1 = acc = rd(xi));
639 case 0111: // Move negative
640 wr(yi, acc = (r1 = rd(xi)) ^ SIGN_MASK);
642 case 0112: // Move absolute value
643 wr(yi, acc = (r1 = rd(xi)) & VAL_MASK);
645 case 0113: // Read from keyboard
647 case 0114: // Copy sign
648 wr(yi, acc = rd(yi) ^ ((r1 = rd(xi)) & SIGN_MASK));
650 case 0115: // Read code from R1 (obscure)
652 case 0116: // Copy exponent
653 wr(yi, acc = wputexp(rd(yi), wexp(r1 = rd(xi))));
655 case 0117: // I/O teletype
661 aa = (a >> 24) & 017777;
664 b = rd(y); // (a mountain range near Prague)
665 acc = ((aa-1) << 24) |
666 (((((a >> 12) & 07777) + (b >> 12) & 07777) & 07777) << 12) |
667 (((a & 07777) + (b & 07777)) & 07777);
675 case 0131: // Jump to subroutine
676 wr(y, acc = ((030ULL << 30) | ((ip & 07777ULL) << 12)));
679 case 0132: // Jump if positive
685 case 0133: // Jump if overflow
686 // Since we always trap on overflow, this instruction always jumps to the 1st address
689 case 0134: // Jump if zero
695 case 0135: // Jump if key pressed
696 // No keys are ever pressed, so always jump to 2nd
699 case 0136: // Interrupt masking
701 case 0137: // Used only when reading from tape
703 case 0140 ... 0147: // I/O
705 case 0150 ... 0154: // I/O
707 case 0160 ... 0161: // I/O
709 case 0162: // Printing
714 case 0170: // FIX multiplication, bottom part
716 if (wtofrac(a) * wtofrac(b) >= .1/(1ULL << 32))
718 acc = wfromll(((unsigned long long)wabs(a) * (unsigned long long)wabs(b)) & VAL_MASK);
719 // XXX: What should be the sign? The book does not define that.
732 case 0172: // Add exponents
735 i = wexp(a) + wexp(b);
736 if (i < -63 || i > 63)
741 case 0173: // Sub exponents
744 i = wexp(b) - wexp(a);
745 if (i < -63 || i > 63)
750 case 0174: // Addition in one's complement
757 // XXX: The effect on the accumulator is undocumented, but likely to be as follows:
760 case 0175: // Normalization
765 wr((yi+1) & 07777, 0);
773 while (!(a & (SIGN_MASK >> 1)))
780 wr((yi+1) & 07777, i);
783 case 0176: // Population count
786 for (int i=0; i<36; i++)
789 // XXX: Guessing that acc gets a copy of the result
798 printf("\tACC:%c%012llo R1:%c%012llo R2:%c%012llo\n", WF(acc), WF(r1), WF(r2));
802 /*** Daemon interface ***/
808 #include <sys/signal.h>
809 #include <sys/wait.h>
810 #include <sys/poll.h>
811 #include <sys/socket.h>
812 #include <netinet/in.h>
813 #include <arpa/inet.h>
816 #define DTRACE(msg, args...) fprintf(stderr, msg "\n", ##args)
817 #define DLOG(msg, args...) fprintf(stderr, msg "\n", ##args)
819 #define DTRACE(msg, args...) do { } while(0)
820 #define DLOG(msg, args...) syslog(LOG_INFO, msg, ##args)
823 #define MAX_CONNECTIONS 50 // Per daemon
824 #define MAX_CONNS_PER_IP 1 // Per IP
825 #define MAX_TRACKERS 200 // IP address trackers
826 #define TBF_MAX 5 // Max number of tokens in the bucket
827 #define TBF_REFILL_PER_SEC 0.2 // Bucket refill rate (buckets/sec)
829 #define PID_FILE "/var/run/minsk.pid"
833 static void die(char *msg)
835 fprintf(stderr, "minsk: ");
836 fprintf(stderr, msg);
841 static char **spt_argv;
842 static char *spt_start, *spt_end;
844 static void setproctitle_init(int argc, char **argv)
847 char **env, **oldenv, *t;
851 /* Create a backup copy of environment */
854 for (i=0; oldenv[i]; i++)
855 len += strlen(oldenv[i]) + 1;
856 __environ = env = malloc(sizeof(char *)*(i+1));
858 if (!__environ || !t)
859 die("malloc failed");
860 for (i=0; oldenv[i]; i++)
863 len = strlen(oldenv[i]) + 1;
864 memcpy(t, oldenv[i], len);
869 /* Scan for consecutive free space */
870 spt_start = spt_end = argv[0];
871 for (i=0; i<argc; i++)
872 if (!i || spt_end+1 == argv[i])
873 spt_end = argv[i] + strlen(argv[i]);
874 for (i=0; oldenv[i]; i++)
875 if (spt_end+1 == oldenv[i])
876 spt_end = oldenv[i] + strlen(oldenv[i]);
880 setproctitle(const char *msg, ...)
887 if (spt_end > spt_start)
889 n = vsnprintf(buf, sizeof(buf), msg, args);
890 if (n >= (int) sizeof(buf) || n < 0)
891 sprintf(buf, "<too-long>");
892 n = spt_end - spt_start;
893 strncpy(spt_start, buf, n);
895 spt_argv[0] = spt_start;
901 static void sigchld_handler(int sig __attribute__((unused)))
905 static void sigalrm_handler(int sig __attribute__((unused)))
907 const char err[] = "--- Timed out. Time machine disconnected. ---\n";
908 write(1, err, sizeof(err));
909 DLOG("Connection timed out");
913 static void child_error_hook(char *err)
915 DLOG("Stopped: %s", err);
918 static void child(int sk2)
924 struct sigaction sact = {
925 .sa_handler = sigalrm_handler,
927 if (sigaction(SIGALRM, &sact, NULL) < 0)
928 die("sigaction: %m");
935 const char welcome[] = "+++ Welcome to our computer museum. +++\n+++ Our time machine will connect you to one of our exhibits. +++\n\n";
936 write(1, welcome, sizeof(welcome));
938 error_hook = child_error_hook;
948 struct tracker *tracker;
951 static struct conn connections[MAX_CONNECTIONS];
953 static struct conn *get_conn(struct in_addr *a)
955 for (int i=0; i<MAX_CONNECTIONS; i++)
957 struct conn *c = &connections[i];
960 memcpy(&c->addr, a, sizeof(struct in_addr));
967 static struct conn *pid_to_conn(pid_t pid)
969 for (int i=0; i<MAX_CONNECTIONS; i++)
971 struct conn *c = &connections[i];
978 static void put_conn(struct conn *c)
991 static struct tracker trackers[MAX_TRACKERS];
993 static int get_tracker(struct conn *c)
996 time_t now = time(NULL);
999 for (i=0; i<MAX_TRACKERS; i++)
1002 if (!memcmp(&t->addr, &c->addr, sizeof(struct in_addr)))
1005 if (i < MAX_TRACKERS)
1007 if (now > t->last_access)
1009 t->tokens += (now - t->last_access) * (double) TBF_REFILL_PER_SEC;
1010 t->last_access = now;
1011 if (t->tokens > TBF_MAX)
1012 t->tokens = TBF_MAX;
1014 DTRACE("TBF: Using tracker %d (%.3f tokens)", i, t->tokens);
1019 for (int i=0; i<MAX_TRACKERS; i++)
1022 if (!t->active_conns && (min_i < 0 || t->last_access < trackers[min_i].last_access))
1027 DLOG("TBF: Out of trackers!");
1030 t = &trackers[min_i];
1032 DTRACE("TBF: Recycling tracker %d", min_i);
1034 DTRACE("TBF: Creating tracker %d", min_i);
1035 memset(t, 0, sizeof(*t));
1037 t->last_access = now;
1038 t->tokens = TBF_MAX;
1041 if (t->active_conns >= MAX_CONNS_PER_IP)
1043 DTRACE("TBF: Too many conns per IP");
1047 if (t->tokens >= 0.999)
1052 DTRACE("TBF: Passed (%d conns)", t->active_conns);
1057 DTRACE("TBF: Failed");
1063 static void put_tracker(struct conn *c)
1065 struct tracker *t = c->tracker;
1068 DLOG("put_tracker: no tracker?");
1072 if (t->active_conns <= 0)
1074 DLOG("put_tracker: no counter?");
1079 DTRACE("TBF: Put tracker (%d conns remain)", t->active_conns);
1082 static void run_as_daemon(int do_fork)
1084 int sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1089 if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
1090 die("setsockopt: %m");
1092 struct sockaddr_in sa = {
1093 .sin_family = AF_INET,
1094 .sin_port = ntohs(1969),
1095 .sin_addr.s_addr = INADDR_ANY,
1097 if (bind(sk, (struct sockaddr *) &sa, sizeof(sa)) < 0)
1099 if (listen(sk, 128) < 0)
1101 // if (fcntl(sk, F_SETFL, O_NONBLOCK) < 0)
1102 // die("fcntl: %m");
1111 FILE *f = fopen(PID_FILE, "w");
1114 fprintf(f, "%d\n", pid);
1121 setresgid(GID, GID, GID);
1122 setresuid(UID, UID, UID);
1126 struct sigaction sact = {
1127 .sa_handler = sigchld_handler,
1128 .sa_flags = SA_RESTART,
1130 if (sigaction(SIGCHLD, &sact, NULL) < 0)
1131 die("sigaction: %m");
1133 DLOG("Daemon ready");
1134 setproctitle("minsk: Listening");
1135 openlog("minsk", LOG_PID, LOG_LOCAL7);
1139 struct pollfd pfd[1] = {
1140 { .fd = sk, .events = POLLIN },
1143 int nfds = poll(pfd, 1, 60000);
1144 if (nfds < 0 && errno != EINTR)
1153 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1155 if (!WIFEXITED(status) || WEXITSTATUS(status))
1156 DLOG("Process %d exited with strange status %x", pid, status);
1158 struct conn *conn = pid_to_conn(pid);
1161 DTRACE("Connection with PID %d exited", pid);
1166 DTRACE("PID %d exited, matching no connection", pid);
1169 if (!(pfd[0].revents & POLLIN))
1172 socklen_t salen = sizeof(sa);
1173 int sk2 = accept(sk, (struct sockaddr *) &sa, &salen);
1183 DTRACE("Got connection: fd=%d", sk2);
1185 struct conn *conn = get_conn(&sa.sin_addr);
1186 const char *reason = NULL;
1189 if (!get_tracker(conn))
1191 DLOG("Connection from %s dropped: Throttling", inet_ntoa(sa.sin_addr));
1194 reason = "--- Sorry, but you are sending too many requests. Please slow down. ---\n";
1199 DLOG("Connection from %s dropped: Too many connections", inet_ntoa(sa.sin_addr));
1200 reason = "--- Sorry, maximum number of connections exceeded. Please come later. ---\n";
1206 DLOG("fork failed: %m");
1215 DLOG("Accepted connection from %s", inet_ntoa(sa.sin_addr));
1216 setproctitle("minsk: %s", inet_ntoa(sa.sin_addr));
1221 DLOG("Sending error message to %s", inet_ntoa(sa.sin_addr));
1222 setproctitle("minsk: %s ERR", inet_ntoa(sa.sin_addr));
1223 write(sk2, reason, strlen(reason));
1228 DTRACE("Created process %d", pid);
1235 int main(int argc, char **argv)
1239 setproctitle_init(argc, argv);
1240 if (!strcmp(argv[1], "--daemon"))
1242 else if (!strcmp(argv[1], "--net"))
1245 die("Usage: minsk [--daemon | --net]");