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] == ';')
201 for (int i=0; i<4; i++)
205 if (*c >= '0' && *c <= '7')
206 addr = 8*addr + *c++ - '0';
208 parse_error("Плохая цифра");
213 parse_error("Адрес слишком долгий");
221 parse_error("Плохой знак");
223 for (int i=0; i<12; i++)
227 if (*c >= '0' && *c <= '7')
228 w = 8*w + *c++ - '0';
230 parse_error("Плохая цифра");
235 parse_error("Номер слишком долгий");
242 static word r1, r2, current_ins;
243 static int ip = 00050; // Standard program start location
246 static void stop(char *reason, char *notice)
250 printf("Машина остановлена -- %s\n", reason);
251 printf("СчАК:%04o См:%c%012llo Р1:%c%012llo Р2:%c%012llo\n", prev_ip, WF(acc), WF(r1), WF(r2));
255 static void over(void)
257 stop("Аварийный останов", "Overflow");
260 static void notimp(void)
263 stop("Устройство разбитое", "Not implemented");
266 static void noins(void)
269 stop("Эту команду не знаю", "Illegal instruction");
272 static uint16_t linebuf[128];
274 static uint16_t russian_chars[64] = {
275 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
276 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
277 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
278 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
279 0x410, 0x411, 0x412, 0x413, 0x414, 0x415, 0x416, 0x417, // 4x
280 0x418, 0x419, 0x41a, 0x41b, 0x41c, 0x41d, 0x41e, 0x41f, // 5x
281 0x420, 0x421, 0x422, 0x423, 0x424, 0x425, 0x426, 0x427, // 6x
282 0x428, 0x429, 0x42b, 0x42c, 0x42d, 0x42e, 0x42f, 0x2013 // 7x
285 static uint16_t latin_chars[64] = {
286 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
287 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
288 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
289 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
290 'A', 'B', 'W', 'G', 'D', 'E', 'V', 'Z', // 4x
291 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 5x
292 'R', 'S', 'T', 'U', 'F', 'H', 'C', ' ', // 6x
293 ' ', ' ', 'Y', 'X', ' ', ' ', 'Q', 0x2013 // 7x
296 static void print_line(int r)
299 * Meaning of bits of r:
300 * 0 = perform line feed
306 if (print_quota > 0 && !--print_quota)
307 stop("Бумага дошла - нужно ехать в Сибирь про новую", "Out of paper");
308 for (int i=0; i<128; i++)
317 putchar(0xc0 | (ch >> 6));
318 putchar(0x80 | (ch & 0x3f));
322 putchar(0xe0 | (ch >> 12));
323 putchar(0x80 | ((ch >> 6) & 0x3f));
324 putchar(0x80 | (ch & 0x3f));
329 memset(linebuf, 0, sizeof(linebuf));
337 static void print_ins(int x, int y)
341 int r = (x >> 9) & 7;
354 case 0: // Decimal float
355 fmt = "+dddddddx+xbd";
357 case 1: // Octal number
358 fmt = "+oooooooooooo";
360 case 2: // Decimal fixed
363 case 3: // Decimal unsigned
367 case 4: // One Russian symbol
371 case 5: // Russian text
374 case 6: // One Latin symbol
378 default: // Latin text
395 ch = (yy & (1ULL << bit)) ? '-' : '+';
399 ch = '0' + ((yy >> bit) & 1);
403 ch = '0' + ((yy >> bit) & 7);
407 ch = '0' + ((yy >> bit) & 15);
413 ch = russian_chars[(yy >> bit) & 077];
417 ch = latin_chars[(yy >> bit) & 077];
425 if (ch == '0' || ch == ' ')
431 pos = (pos+1) & 0177;
436 static void run(void)
445 int op = (w >> 30) & 0177; // Operation code
446 int ax = (w >> 28) & 3; // Address extensions not supported
447 int ix = (w >> 24) & 15; // Indexing
448 int x = (w >> 12) & 07777; // Operands (original form)
450 int xi=x, yi=y; // (indexed form)
452 printf("@%04o %c%02o %02o %04o %04o\n",
454 (w & SIGN_MASK) ? '-' : '+',
455 (int)((w >> 30) & 077),
456 (int)((w >> 24) & 077),
464 xi = (xi + (int)((i >> 12) & 07777)) & 07777;
465 yi = (yi + (int)(i & 07777)) & 07777;
467 printf("\tIndexing -> %04o %04o\n", xi, yi);
472 if (cpu_quota > 0 && !--cpu_quota)
473 stop("Тайм-аут", "CPU quota exceeded");
475 /* Arithmetic operations */
478 long long aa, bb, cc;
482 auto void afetch(void);
492 auto void astore(word result);
493 void astore(word result)
500 auto void astore_int(long long x);
501 void astore_int(long long x)
503 if (!int_in_range(x))
508 auto void astore_frac(double f);
509 void astore_frac(double f)
511 if (!frac_in_range(f))
513 astore(wfromfrac(f));
516 auto void astore_float(double f);
517 void astore_float(double f)
519 if (!float_in_range(f))
521 astore(wfromfloat(f, 0));
530 case 004 ... 007: // XOR
534 case 010 ... 013: // FIX addition
536 astore_int(wtoll(a) + wtoll(b));
538 case 014 ... 017: // FP addition
540 astore_float(wtofloat(a) + wtofloat(b));
542 case 020 ... 023: // FIX subtraction
544 astore_int(wtoll(a) - wtoll(b));
546 case 024 ... 027: // FP subtraction
548 astore_float(wtofloat(a) - wtofloat(b));
550 case 030 ... 033: // FIX multiplication
552 astore_frac(wtofrac(a) * wtofrac(b));
554 case 034 ... 037: // FP multiplication
556 astore_float(wtofloat(a) * wtofloat(b));
558 case 040 ... 043: // FIX division
564 astore_frac(ad / bd);
566 case 044 ... 047: // FP division
570 if (!bd || wexp(b) < -63)
572 astore_float(ad / bd);
574 case 050 ... 053: // FIX subtraction of abs values
576 astore_int(wabs(a) - wabs(b));
578 case 054 ... 057: // FP subtraction of abs values
580 astore_float(fabs(wtofloat(a)) - fabs(wtofloat(b)));
582 case 060 ... 063: // Shift logical
585 if (i <= -37 || i >= 37)
588 astore((a << i) & WORD_MASK);
592 case 064 ... 067: // Shift arithmetical
596 if (i <= -36 || i >= 36)
599 cc = (aa << i) & VAL_MASK;
602 astore((a & SIGN_MASK) | wfromll(cc));
604 case 070 ... 073: // And
608 case 074 ... 077: // Or
616 stop("Останов машины", "Halted");
617 case 0103: // I/O magtape
619 case 0104: // Disable rounding
621 case 0105: // Enable rounding
623 case 0106: // Interrupt control
625 case 0107: // Reverse tape
628 wr(yi, r1 = acc = rd(xi));
630 case 0111: // Move negative
631 wr(yi, acc = (r1 = rd(xi)) ^ SIGN_MASK);
633 case 0112: // Move absolute value
634 wr(yi, acc = (r1 = rd(xi)) & VAL_MASK);
636 case 0113: // Read from keyboard
638 case 0114: // Copy sign
639 wr(yi, acc = rd(yi) ^ ((r1 = rd(xi)) & SIGN_MASK));
641 case 0115: // Read code from R1 (obscure)
643 case 0116: // Copy exponent
644 wr(yi, acc = wputexp(rd(yi), wexp(r1 = rd(xi))));
646 case 0117: // I/O teletype
652 aa = (a >> 24) & 017777;
655 b = rd(y); // (a mountain range near Prague)
656 acc = ((aa-1) << 24) |
657 (((((a >> 12) & 07777) + (b >> 12) & 07777) & 07777) << 12) |
658 (((a & 07777) + (b & 07777)) & 07777);
666 case 0131: // Jump to subroutine
667 wr(y, acc = ((030ULL << 30) | ((ip & 07777ULL) << 12)));
670 case 0132: // Jump if positive
676 case 0133: // Jump if overflow
677 // Since we always trap on overflow, this instruction always jumps to the 1st address
680 case 0134: // Jump if zero
686 case 0135: // Jump if key pressed
687 // No keys are ever pressed, so always jump to 2nd
690 case 0136: // Interrupt masking
692 case 0137: // Used only when reading from tape
694 case 0140 ... 0147: // I/O
696 case 0150 ... 0154: // I/O
698 case 0160 ... 0161: // I/O
700 case 0162: // Printing
705 case 0170: // FIX multiplication, bottom part
707 if (wtofrac(a) * wtofrac(b) >= .1/(1ULL << 32))
709 acc = wfromll(((unsigned long long)wabs(a) * (unsigned long long)wabs(b)) & VAL_MASK);
710 // XXX: What should be the sign? The book does not define that.
723 case 0172: // Add exponents
726 i = wexp(a) + wexp(b);
727 if (i < -63 || i > 63)
732 case 0173: // Sub exponents
735 i = wexp(b) - wexp(a);
736 if (i < -63 || i > 63)
741 case 0174: // Addition in one's complement
748 // XXX: The effect on the accumulator is undocumented, but likely to be as follows:
751 case 0175: // Normalization
756 wr((yi+1) & 07777, 0);
764 while (!(a & (SIGN_MASK >> 1)))
771 wr((yi+1) & 07777, i);
774 case 0176: // Population count
777 for (int i=0; i<36; i++)
780 // XXX: Guessing that acc gets a copy of the result
789 printf("\tACC:%c%012llo R1:%c%012llo R2:%c%012llo\n", WF(acc), WF(r1), WF(r2));
793 /*** Daemon interface ***/
799 #include <sys/signal.h>
800 #include <sys/wait.h>
801 #include <sys/poll.h>
802 #include <sys/socket.h>
803 #include <netinet/in.h>
804 #include <arpa/inet.h>
807 #define DTRACE(msg, args...) fprintf(stderr, msg "\n", ##args)
808 #define DLOG(msg, args...) fprintf(stderr, msg "\n", ##args)
810 #define DTRACE(msg, args...) do { } while(0)
811 #define DLOG(msg, args...) syslog(LOG_INFO, msg, ##args)
814 #define MAX_CONNECTIONS 50 // Per daemon
815 #define MAX_CONNS_PER_IP 1 // Per IP
816 #define MAX_TRACKERS 200 // IP address trackers
817 #define TBF_MAX 5 // Max number of tokens in the bucket
818 #define TBF_REFILL_PER_SEC 0.2 // Bucket refill rate (buckets/sec)
820 #define PID_FILE "/var/run/minsk.pid"
824 static void die(char *msg)
826 fprintf(stderr, "minsk: ");
827 fprintf(stderr, msg);
832 static char **spt_argv;
833 static char *spt_start, *spt_end;
835 static void setproctitle_init(int argc, char **argv)
838 char **env, **oldenv, *t;
842 /* Create a backup copy of environment */
845 for (i=0; oldenv[i]; i++)
846 len += strlen(oldenv[i]) + 1;
847 __environ = env = malloc(sizeof(char *)*(i+1));
849 if (!__environ || !t)
850 die("malloc failed");
851 for (i=0; oldenv[i]; i++)
854 len = strlen(oldenv[i]) + 1;
855 memcpy(t, oldenv[i], len);
860 /* Scan for consecutive free space */
861 spt_start = spt_end = argv[0];
862 for (i=0; i<argc; i++)
863 if (!i || spt_end+1 == argv[i])
864 spt_end = argv[i] + strlen(argv[i]);
865 for (i=0; oldenv[i]; i++)
866 if (spt_end+1 == oldenv[i])
867 spt_end = oldenv[i] + strlen(oldenv[i]);
871 setproctitle(const char *msg, ...)
878 if (spt_end > spt_start)
880 n = vsnprintf(buf, sizeof(buf), msg, args);
881 if (n >= (int) sizeof(buf) || n < 0)
882 sprintf(buf, "<too-long>");
883 n = spt_end - spt_start;
884 strncpy(spt_start, buf, n);
886 spt_argv[0] = spt_start;
892 static void sigchld_handler(int sig __attribute__((unused)))
896 static void sigalrm_handler(int sig __attribute__((unused)))
898 const char err[] = "--- Timed out. Time machine disconnected. ---\n";
899 write(1, err, sizeof(err));
900 DLOG("Connection timed out");
904 static void child_error_hook(char *err)
906 DLOG("Stopped: %s", err);
909 static void child(int sk2)
915 struct sigaction sact = {
916 .sa_handler = sigalrm_handler,
918 if (sigaction(SIGALRM, &sact, NULL) < 0)
919 die("sigaction: %m");
926 const char welcome[] = "+++ Welcome to our computer museum. +++\n+++ Our time machine will connect you to one of our exhibits. +++\n\n";
927 write(1, welcome, sizeof(welcome));
929 error_hook = child_error_hook;
939 struct tracker *tracker;
942 static struct conn connections[MAX_CONNECTIONS];
944 static struct conn *get_conn(struct in_addr *a)
946 for (int i=0; i<MAX_CONNECTIONS; i++)
948 struct conn *c = &connections[i];
951 memcpy(&c->addr, a, sizeof(struct in_addr));
958 static struct conn *pid_to_conn(pid_t pid)
960 for (int i=0; i<MAX_CONNECTIONS; i++)
962 struct conn *c = &connections[i];
969 static void put_conn(struct conn *c)
982 static struct tracker trackers[MAX_TRACKERS];
984 static int get_tracker(struct conn *c)
987 time_t now = time(NULL);
990 for (i=0; i<MAX_TRACKERS; i++)
993 if (!memcmp(&t->addr, &c->addr, sizeof(struct in_addr)))
996 if (i < MAX_TRACKERS)
998 if (now > t->last_access)
1000 t->tokens += (now - t->last_access) * (double) TBF_REFILL_PER_SEC;
1001 t->last_access = now;
1002 if (t->tokens > TBF_MAX)
1003 t->tokens = TBF_MAX;
1005 DTRACE("TBF: Using tracker %d (%.3f tokens)", i, t->tokens);
1010 for (int i=0; i<MAX_TRACKERS; i++)
1013 if (!t->active_conns && (min_i < 0 || t->last_access < trackers[min_i].last_access))
1018 DLOG("TBF: Out of trackers!");
1021 t = &trackers[min_i];
1023 DTRACE("TBF: Recycling tracker %d", min_i);
1025 DTRACE("TBF: Creating tracker %d", min_i);
1026 memset(t, 0, sizeof(*t));
1028 t->last_access = now;
1029 t->tokens = TBF_MAX;
1032 if (t->active_conns >= MAX_CONNS_PER_IP)
1034 DTRACE("TBF: Too many conns per IP");
1038 if (t->tokens >= 0.999)
1043 DTRACE("TBF: Passed (%d conns)", t->active_conns);
1048 DTRACE("TBF: Failed");
1054 static void put_tracker(struct conn *c)
1056 struct tracker *t = c->tracker;
1059 DLOG("put_tracker: no tracker?");
1063 if (t->active_conns <= 0)
1065 DLOG("put_tracker: no counter?");
1070 DTRACE("TBF: Put tracker (%d conns remain)", t->active_conns);
1073 static void run_as_daemon(int do_fork)
1075 int sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1080 if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
1081 die("setsockopt: %m");
1083 struct sockaddr_in sa = {
1084 .sin_family = AF_INET,
1085 .sin_port = ntohs(1969),
1086 .sin_addr.s_addr = INADDR_ANY,
1088 if (bind(sk, (struct sockaddr *) &sa, sizeof(sa)) < 0)
1090 if (listen(sk, 128) < 0)
1092 // if (fcntl(sk, F_SETFL, O_NONBLOCK) < 0)
1093 // die("fcntl: %m");
1102 FILE *f = fopen(PID_FILE, "w");
1105 fprintf(f, "%d\n", pid);
1112 setresgid(GID, GID, GID);
1113 setresuid(UID, UID, UID);
1117 struct sigaction sact = {
1118 .sa_handler = sigchld_handler,
1119 .sa_flags = SA_RESTART,
1121 if (sigaction(SIGCHLD, &sact, NULL) < 0)
1122 die("sigaction: %m");
1124 DLOG("Daemon ready");
1125 setproctitle("minsk: Listening");
1126 openlog("minsk", LOG_PID, LOG_LOCAL7);
1130 struct pollfd pfd[1] = {
1131 { .fd = sk, .events = POLLIN },
1134 int nfds = poll(pfd, 1, 60000);
1135 if (nfds < 0 && errno != EINTR)
1144 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1146 if (!WIFEXITED(status) || WEXITSTATUS(status))
1147 DLOG("Process %d exited with strange status %x", pid, status);
1149 struct conn *conn = pid_to_conn(pid);
1152 DTRACE("Connection with PID %d exited", pid);
1157 DTRACE("PID %d exited, matching no connection", pid);
1160 if (!(pfd[0].revents & POLLIN))
1163 socklen_t salen = sizeof(sa);
1164 int sk2 = accept(sk, (struct sockaddr *) &sa, &salen);
1174 DTRACE("Got connection: fd=%d", sk2);
1176 struct conn *conn = get_conn(&sa.sin_addr);
1177 const char *reason = NULL;
1180 if (!get_tracker(conn))
1182 DLOG("Connection from %s dropped: Throttling", inet_ntoa(sa.sin_addr));
1185 reason = "--- Sorry, but you are sending too many requests. Please slow down. ---\n";
1190 DLOG("Connection from %s dropped: Too many connections", inet_ntoa(sa.sin_addr));
1191 reason = "--- Sorry, maximum number of connections exceeded. Please come later. ---\n";
1197 DLOG("fork failed: %m");
1206 DLOG("Accepted connection from %s", inet_ntoa(sa.sin_addr));
1207 setproctitle("minsk: %s", inet_ntoa(sa.sin_addr));
1212 DLOG("Sending error message to %s", inet_ntoa(sa.sin_addr));
1213 setproctitle("minsk: %s ERR", inet_ntoa(sa.sin_addr));
1214 write(sk2, reason, strlen(reason));
1219 DTRACE("Created process %d", pid);
1226 int main(int argc, char **argv)
1230 setproctitle_init(argc, argv);
1231 if (!strcmp(argv[1], "--daemon"))
1233 else if (!strcmp(argv[1], "--net"))
1236 die("Usage: minsk [--daemon | --net]");