]> git.sesse.net Git - pistorm/blob - emulator.c
8a796670e27b6bb890a116e1f84fda312a3f8d0c
[pistorm] / emulator.c
1 // SPDX-License-Identifier: MIT
2
3 #include "m68k.h"
4 #include "emulator.h"
5 #include "platforms/platforms.h"
6 #include "input/input.h"
7 #include "m68kcpu.h"
8
9 #include "platforms/amiga/Gayle.h"
10 #include "platforms/amiga/amiga-registers.h"
11 #include "platforms/amiga/rtg/rtg.h"
12 #include "platforms/amiga/hunk-reloc.h"
13 #include "platforms/amiga/piscsi/piscsi.h"
14 #include "platforms/amiga/piscsi/piscsi-enums.h"
15 #include "platforms/amiga/net/pi-net.h"
16 #include "platforms/amiga/net/pi-net-enums.h"
17 #include "platforms/amiga/pistorm-dev/pistorm-dev.h"
18 #include "platforms/amiga/pistorm-dev/pistorm-dev-enums.h"
19 #include "gpio/ps_protocol.h"
20
21 #include <assert.h>
22 #include <dirent.h>
23 #include <endian.h>
24 #include <fcntl.h>
25 #include <poll.h>
26 #include <pthread.h>
27 #include <sched.h>
28 #include <signal.h>
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/ioctl.h>
34 #include <sys/mman.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <unistd.h>
38
39 #define KEY_POLL_INTERVAL_MSEC 5000
40
41 int kb_hook_enabled = 0;
42 int mouse_hook_enabled = 0;
43 int cpu_emulation_running = 1;
44
45 uint8_t mouse_dx = 0, mouse_dy = 0;
46 uint8_t mouse_buttons = 0;
47 uint8_t mouse_extra = 0;
48
49 extern uint8_t gayle_int;
50 extern uint8_t gayle_ide_enabled;
51 extern uint8_t gayle_emulation_enabled;
52 extern uint8_t gayle_a4k_int;
53 extern volatile unsigned int *gpio;
54 extern volatile uint16_t srdata;
55 extern uint8_t realtime_graphics_debug, emulator_exiting;
56 extern uint8_t rtg_on;
57 uint8_t realtime_disassembly, int2_enabled = 0;
58 uint32_t do_disasm = 0, old_level;
59 uint32_t last_irq = 8, last_last_irq = 8;
60
61 uint8_t end_signal = 0, load_new_config = 0;
62
63 char disasm_buf[4096];
64
65 #define KICKBASE 0xF80000
66 #define KICKSIZE 0x7FFFF
67
68 int mem_fd, mouse_fd = -1, keyboard_fd = -1;
69 int mem_fd_gpclk;
70 int irq;
71 int gayleirq;
72
73 #define MUSASHI_HAX
74
75 #ifdef MUSASHI_HAX
76 #include "m68kcpu.h"
77 extern m68ki_cpu_core m68ki_cpu;
78 extern int m68ki_initial_cycles;
79 extern int m68ki_remaining_cycles;
80
81 #define M68K_SET_IRQ(i) old_level = CPU_INT_LEVEL; \
82         CPU_INT_LEVEL = (i << 8); \
83         if(old_level != 0x0700 && CPU_INT_LEVEL == 0x0700) \
84                 m68ki_cpu.nmi_pending = TRUE;
85 #define M68K_END_TIMESLICE      m68ki_initial_cycles = GET_CYCLES(); \
86         SET_CYCLES(0);
87 #else
88 #define M68K_SET_IRQ m68k_set_irq
89 #define M68K_END_TIMESLICE m68k_end_timeslice()
90 #endif
91
92 #define NOP asm("nop"); asm("nop"); asm("nop"); asm("nop");
93
94 #define DEBUG_EMULATOR
95 #ifdef DEBUG_EMULATOR
96 #define DEBUG printf
97 #else
98 #define DEBUG(...)
99 #endif
100
101 // Configurable emulator options
102 unsigned int cpu_type = M68K_CPU_TYPE_68000;
103 unsigned int loop_cycles = 300, irq_status = 0;
104 struct emulator_config *cfg = NULL;
105 char keyboard_file[256] = "/dev/input/event1";
106
107 uint64_t trig_irq = 0, serv_irq = 0;
108 uint16_t irq_delay = 0;
109 unsigned int amiga_reset=0, amiga_reset_last=0;
110 unsigned int do_reset=0;
111
112 void *ipl_task(void *args) {
113   printf("IPL thread running\n");
114   uint16_t old_irq = 0;
115   uint32_t value;
116
117   while (1) {
118     value = *(gpio + 13);
119     if (value & (1 << PIN_TXN_IN_PROGRESS))
120       goto noppers;
121
122     if (!(value & (1 << PIN_IPL_ZERO))) {
123       old_irq = irq_delay;
124       //NOP
125       if (!irq) {
126         M68K_END_TIMESLICE;
127         NOP
128         irq = 1;
129       }
130       //usleep(0);
131     }
132     else {
133       if (irq) {
134         if (old_irq) {
135           old_irq--;
136         }
137         else {
138           irq = 0;
139         }
140         M68K_END_TIMESLICE;
141         NOP
142         //usleep(0);
143       }
144     }
145     if(do_reset==0)
146     {
147       amiga_reset=(value & (1 << PIN_RESET));
148       if(amiga_reset!=amiga_reset_last)
149       {
150         amiga_reset_last=amiga_reset;
151         if(amiga_reset==0)
152         {
153           printf("Amiga Reset is down...\n");
154           do_reset=1;
155           M68K_END_TIMESLICE;
156         }
157         else
158         {
159           printf("Amiga Reset is up...\n");
160         }
161       }
162     }
163
164     /*if (gayle_ide_enabled) {
165       if (((gayle_int & 0x80) || gayle_a4k_int) && (get_ide(0)->drive[0].intrq || get_ide(0)->drive[1].intrq)) {
166         //get_ide(0)->drive[0].intrq = 0;
167         gayleirq = 1;
168         M68K_END_TIMESLICE;
169       }
170       else
171         gayleirq = 0;
172     }*/
173     //usleep(0);
174     //NOP NOP
175 noppers:
176     NOP NOP NOP NOP NOP NOP NOP NOP
177     //NOP NOP NOP NOP NOP NOP NOP NOP
178     //NOP NOP NOP NOP NOP NOP NOP NOP
179     /*NOP NOP NOP NOP NOP NOP NOP NOP
180     NOP NOP NOP NOP NOP NOP NOP NOP
181     NOP NOP NOP NOP NOP NOP NOP NOP*/
182   }
183   return args;
184 }
185
186 static inline unsigned int inline_read_status_reg() {
187   *(gpio + 7) = (REG_STATUS << PIN_A0);
188   *(gpio + 7) = 1 << PIN_RD;
189   *(gpio + 7) = 1 << PIN_RD;
190   *(gpio + 7) = 1 << PIN_RD;
191   *(gpio + 7) = 1 << PIN_RD;
192
193   unsigned int value = *(gpio + 13);
194
195   *(gpio + 10) = 0xffffec;
196
197   return (value >> 8) & 0xffff;
198 }
199
200 void *cpu_task() {
201         m68ki_cpu_core *state = &m68ki_cpu;
202         m68k_pulse_reset(state);
203
204 cpu_loop:
205   if (mouse_hook_enabled) {
206     get_mouse_status(&mouse_dx, &mouse_dy, &mouse_buttons, &mouse_extra);
207   }
208
209   if (realtime_disassembly && (do_disasm || cpu_emulation_running)) {
210     m68k_disassemble(disasm_buf, m68k_get_reg(NULL, M68K_REG_PC), cpu_type);
211     printf("REGA: 0:$%.8X 1:$%.8X 2:$%.8X 3:$%.8X 4:$%.8X 5:$%.8X 6:$%.8X 7:$%.8X\n", m68k_get_reg(NULL, M68K_REG_A0), m68k_get_reg(NULL, M68K_REG_A1), m68k_get_reg(NULL, M68K_REG_A2), m68k_get_reg(NULL, M68K_REG_A3), \
212             m68k_get_reg(NULL, M68K_REG_A4), m68k_get_reg(NULL, M68K_REG_A5), m68k_get_reg(NULL, M68K_REG_A6), m68k_get_reg(NULL, M68K_REG_A7));
213     printf("REGD: 0:$%.8X 1:$%.8X 2:$%.8X 3:$%.8X 4:$%.8X 5:$%.8X 6:$%.8X 7:$%.8X\n", m68k_get_reg(NULL, M68K_REG_D0), m68k_get_reg(NULL, M68K_REG_D1), m68k_get_reg(NULL, M68K_REG_D2), m68k_get_reg(NULL, M68K_REG_D3), \
214             m68k_get_reg(NULL, M68K_REG_D4), m68k_get_reg(NULL, M68K_REG_D5), m68k_get_reg(NULL, M68K_REG_D6), m68k_get_reg(NULL, M68K_REG_D7));
215     printf("%.8X (%.8X)]] %s\n", m68k_get_reg(NULL, M68K_REG_PC), (m68k_get_reg(NULL, M68K_REG_PC) & 0xFFFFFF), disasm_buf);
216     if (do_disasm)
217       do_disasm--;
218           m68k_execute(state, 1);
219   }
220   else {
221     if (cpu_emulation_running) {
222                 if (irq)
223                         m68k_execute(state, 5);
224                 else
225                         m68k_execute(state, loop_cycles);
226     }
227   }
228
229   while (irq) {
230       last_irq = ((inline_read_status_reg() & 0xe000) >> 13);
231       if (last_irq != last_last_irq) {
232         last_last_irq = last_irq;
233         M68K_SET_IRQ(last_irq);
234       }
235       m68k_execute(state, 50);
236   }
237   if (!irq && last_last_irq != 0) {
238     M68K_SET_IRQ(0);
239     last_last_irq = 0;
240   }
241
242   if (do_reset) {
243     cpu_pulse_reset();
244     do_reset=0;
245     usleep(1000000); // 1sec
246     rtg_on=0;
247 //    while(amiga_reset==0);
248 //    printf("CPU emulation reset.\n");
249   }
250
251   if (mouse_hook_enabled && (mouse_extra != 0x00)) {
252     // mouse wheel events have occurred; unlike l/m/r buttons, these are queued as keypresses, so add to end of buffer
253     switch (mouse_extra) {
254       case 0xff:
255         // wheel up
256         queue_keypress(0xfe, KEYPRESS_PRESS, PLATFORM_AMIGA);
257         break;
258       case 0x01:
259         // wheel down
260         queue_keypress(0xff, KEYPRESS_PRESS, PLATFORM_AMIGA);
261         break;
262     }
263
264     // dampen the scroll wheel until next while loop iteration
265     mouse_extra = 0x00;
266   }
267
268   if (load_new_config) {
269     printf("[CPU] Loading new config file.\n");
270     goto stop_cpu_emulation;
271   }
272
273   if (end_signal)
274           goto stop_cpu_emulation;
275
276   goto cpu_loop;
277
278 stop_cpu_emulation:
279   printf("[CPU] End of CPU thread\n");
280   return (void *)NULL;
281 }
282
283 void *keyboard_task() {
284   struct pollfd kbdpoll[1];
285   int kpollrc;
286   char c = 0, c_code = 0, c_type = 0;
287   char grab_message[] = "[KBD] Grabbing keyboard from input layer\n",
288        ungrab_message[] = "[KBD] Ungrabbing keyboard\n";
289
290   printf("[KBD] Keyboard thread started\n");
291
292   // because we permit the keyboard to be grabbed on startup, quickly check if we need to grab it
293   if (kb_hook_enabled && cfg->keyboard_grab) {
294     printf(grab_message);
295     grab_device(keyboard_fd);
296   }
297
298   kbdpoll[0].fd = keyboard_fd;
299   kbdpoll[0].events = POLLIN;
300
301 key_loop:
302   kpollrc = poll(kbdpoll, 1, KEY_POLL_INTERVAL_MSEC);
303   if ((kpollrc > 0) && (kbdpoll[0].revents & POLLHUP)) {
304     // in the event that a keyboard is unplugged, keyboard_task will whiz up to 100% utilisation
305     // this is undesired, so if the keyboard HUPs, end the thread without ending the emulation
306     printf("[KBD] Keyboard node returned HUP (unplugged?)\n");
307     goto key_end;
308   }
309
310   // if kpollrc > 0 then it contains number of events to pull, also check if POLLIN is set in revents
311   if ((kpollrc <= 0) || !(kbdpoll[0].revents & POLLIN)) {
312     goto key_loop;
313   }
314
315   while (get_key_char(&c, &c_code, &c_type)) {
316     if (c && c == cfg->keyboard_toggle_key && !kb_hook_enabled) {
317       kb_hook_enabled = 1;
318       printf("[KBD] Keyboard hook enabled.\n");
319       if (cfg->keyboard_grab) {
320         grab_device(keyboard_fd);
321         printf(grab_message);
322       }
323     } else if (kb_hook_enabled) {
324       if (c == 0x1B && c_type) {
325         kb_hook_enabled = 0;
326         printf("[KBD] Keyboard hook disabled.\n");
327         if (cfg->keyboard_grab) {
328           release_device(keyboard_fd);
329           printf(ungrab_message);
330         }
331       } else {
332         if (queue_keypress(c_code, c_type, cfg->platform->id) && int2_enabled && last_irq != 2) {
333           //last_irq = 0;
334           //M68K_SET_IRQ(2);
335         }
336       }
337     }
338
339     // pause pressed; trigger nmi (int level 7)
340     if (c == 0x01 && c_type) {
341       printf("[INT] Sending NMI\n");
342       M68K_SET_IRQ(7);
343     }
344
345     if (!kb_hook_enabled && c_type) {
346       if (c && c == cfg->mouse_toggle_key) {
347         mouse_hook_enabled ^= 1;
348         printf("Mouse hook %s.\n", mouse_hook_enabled ? "enabled" : "disabled");
349         mouse_dx = mouse_dy = mouse_buttons = mouse_extra = 0;
350       }
351       if (c == 'r') {
352         cpu_emulation_running ^= 1;
353         printf("CPU emulation is now %s\n", cpu_emulation_running ? "running" : "stopped");
354       }
355       if (c == 'g') {
356         realtime_graphics_debug ^= 1;
357         printf("Real time graphics debug is now %s\n", realtime_graphics_debug ? "on" : "off");
358       }
359       if (c == 'R') {
360         cpu_pulse_reset();
361         //m68k_pulse_reset();
362         printf("CPU emulation reset.\n");
363       }
364       if (c == 'q') {
365         printf("Quitting and exiting emulator.\n");
366               end_signal = 1;
367         goto key_end;
368       }
369       if (c == 'd') {
370         realtime_disassembly ^= 1;
371         do_disasm = 1;
372         printf("Real time disassembly is now %s\n", realtime_disassembly ? "on" : "off");
373       }
374       if (c == 'D') {
375         int r = get_mapped_item_by_address(cfg, 0x08000000);
376         if (r != -1) {
377           printf("Dumping first 16MB of mapped range %d.\n", r);
378           FILE *dmp = fopen("./memdmp.bin", "wb+");
379           fwrite(cfg->map_data[r], 16 * SIZE_MEGA, 1, dmp);
380           fclose(dmp);
381         }
382       }
383       if (c == 's' && realtime_disassembly) {
384         do_disasm = 1;
385       }
386       if (c == 'S' && realtime_disassembly) {
387         do_disasm = 128;
388       }
389     }
390   }
391
392   goto key_loop;
393
394 key_end:
395   printf("[KBD] Keyboard thread ending\n");
396   if (cfg->keyboard_grab) {
397     printf(ungrab_message);
398     release_device(keyboard_fd);
399   }
400   return (void*)NULL;
401 }
402
403 void stop_cpu_emulation(uint8_t disasm_cur) {
404   M68K_END_TIMESLICE;
405   if (disasm_cur) {
406     m68k_disassemble(disasm_buf, m68k_get_reg(NULL, M68K_REG_PC), cpu_type);
407     printf("REGA: 0:$%.8X 1:$%.8X 2:$%.8X 3:$%.8X 4:$%.8X 5:$%.8X 6:$%.8X 7:$%.8X\n", m68k_get_reg(NULL, M68K_REG_A0), m68k_get_reg(NULL, M68K_REG_A1), m68k_get_reg(NULL, M68K_REG_A2), m68k_get_reg(NULL, M68K_REG_A3), \
408             m68k_get_reg(NULL, M68K_REG_A4), m68k_get_reg(NULL, M68K_REG_A5), m68k_get_reg(NULL, M68K_REG_A6), m68k_get_reg(NULL, M68K_REG_A7));
409     printf("REGD: 0:$%.8X 1:$%.8X 2:$%.8X 3:$%.8X 4:$%.8X 5:$%.8X 6:$%.8X 7:$%.8X\n", m68k_get_reg(NULL, M68K_REG_D0), m68k_get_reg(NULL, M68K_REG_D1), m68k_get_reg(NULL, M68K_REG_D2), m68k_get_reg(NULL, M68K_REG_D3), \
410             m68k_get_reg(NULL, M68K_REG_D4), m68k_get_reg(NULL, M68K_REG_D5), m68k_get_reg(NULL, M68K_REG_D6), m68k_get_reg(NULL, M68K_REG_D7));
411     printf("%.8X (%.8X)]] %s\n", m68k_get_reg(NULL, M68K_REG_PC), (m68k_get_reg(NULL, M68K_REG_PC) & 0xFFFFFF), disasm_buf);
412     realtime_disassembly = 1;
413   }
414
415   cpu_emulation_running = 0;
416   do_disasm = 0;
417 }
418
419 unsigned int ovl;
420 static volatile unsigned char maprom;
421
422 void sigint_handler(int sig_num) {
423   //if (sig_num) { }
424   //cpu_emulation_running = 0;
425
426   //return;
427   printf("Received sigint %d, exiting.\n", sig_num);
428   if (mouse_fd != -1)
429     close(mouse_fd);
430   if (mem_fd)
431     close(mem_fd);
432
433   if (cfg->platform->shutdown) {
434     cfg->platform->shutdown(cfg);
435   }
436
437   while (!emulator_exiting) {
438     emulator_exiting = 1;
439     usleep(0);
440   }
441
442   printf("IRQs triggered: %lld\n", trig_irq);
443   printf("IRQs serviced: %lld\n", serv_irq);
444
445   exit(0);
446 }
447
448 int main(int argc, char *argv[]) {
449   int g;
450
451   ps_setup_protocol();
452
453   //const struct sched_param priority = {99};
454
455   // Some command line switch stuffles
456   for (g = 1; g < argc; g++) {
457     if (strcmp(argv[g], "--cpu_type") == 0 || strcmp(argv[g], "--cpu") == 0) {
458       if (g + 1 >= argc) {
459         printf("%s switch found, but no CPU type specified.\n", argv[g]);
460       } else {
461         g++;
462         cpu_type = get_m68k_cpu_type(argv[g]);
463       }
464     }
465     else if (strcmp(argv[g], "--config-file") == 0 || strcmp(argv[g], "--config") == 0) {
466       if (g + 1 >= argc) {
467         printf("%s switch found, but no config filename specified.\n", argv[g]);
468       } else {
469         g++;
470         FILE *chk = fopen(argv[g], "rb");
471         if (chk == NULL) {
472           printf("Config file %s does not exist, please check that you've specified the path correctly.\n", argv[g]);
473         } else {
474           fclose(chk);
475           load_new_config = 1;
476           set_pistorm_devcfg_filename(argv[g]);
477         }
478       }
479     }
480     else if (strcmp(argv[g], "--keyboard-file") == 0 || strcmp(argv[g], "--kbfile") == 0) {
481       if (g + 1 >= argc) {
482         printf("%s switch found, but no keyboard device path specified.\n", argv[g]);
483       } else {
484         g++;
485         strcpy(keyboard_file, argv[g]);
486       }
487     }
488   }
489
490 switch_config:
491   srand(clock());
492
493   ps_reset_state_machine();
494   ps_pulse_reset();
495   usleep(1500);
496
497   if (load_new_config != 0) {
498     uint8_t config_action = load_new_config - 1;
499     load_new_config = 0;
500     if (cfg) {
501       free_config_file(cfg);
502       free(cfg);
503       cfg = NULL;
504     }
505
506     switch(config_action) {
507       case PICFG_LOAD:
508       case PICFG_RELOAD:
509         cfg = load_config_file(get_pistorm_devcfg_filename());
510         break;
511       case PICFG_DEFAULT:
512         cfg = load_config_file("default.cfg");
513         break;
514     }
515   }
516
517   if (!cfg) {
518     printf("No config file specified. Trying to load default.cfg...\n");
519     cfg = load_config_file("default.cfg");
520     if (!cfg) {
521       printf("Couldn't load default.cfg, empty emulator config will be used.\n");
522       cfg = (struct emulator_config *)calloc(1, sizeof(struct emulator_config));
523       if (!cfg) {
524         printf("Failed to allocate memory for emulator config!\n");
525         return 1;
526       }
527       memset(cfg, 0x00, sizeof(struct emulator_config));
528     }
529   }
530
531   if (cfg) {
532     if (cfg->cpu_type) cpu_type = cfg->cpu_type;
533     if (cfg->loop_cycles) loop_cycles = cfg->loop_cycles;
534
535     if (!cfg->platform)
536       cfg->platform = make_platform_config("none", "generic");
537     cfg->platform->platform_initial_setup(cfg);
538   }
539
540   if (cfg->mouse_enabled) {
541     mouse_fd = open(cfg->mouse_file, O_RDWR | O_NONBLOCK);
542     if (mouse_fd == -1) {
543       printf("Failed to open %s, can't enable mouse hook.\n", cfg->mouse_file);
544       cfg->mouse_enabled = 0;
545     } else {
546       /**
547        * *-*-*-* magic numbers! *-*-*-*
548        * great, so waaaay back in the history of the pc, the ps/2 protocol set the standard for mice
549        * and in the process, the mouse sample rate was defined as a way of putting mice into vendor-specific modes.
550        * as the ancient gpm command explains, almost everything except incredibly old mice talk the IntelliMouse
551        * protocol, which reports four bytes. by default, every mouse starts in 3-byte mode (don't report wheel or
552        * additional buttons) until imps2 magic is sent. so, command $f3 is "set sample rate", followed by a byte.
553        */
554       uint8_t mouse_init[] = { 0xf4, 0xf3, 0x64 }; // enable, then set sample rate 100
555       uint8_t imps2_init[] = { 0xf3, 0xc8, 0xf3, 0x64, 0xf3, 0x50 }; // magic sequence; set sample 200, 100, 80
556       if (write(mouse_fd, mouse_init, sizeof(mouse_init)) != -1) {
557         if (write(mouse_fd, imps2_init, sizeof(imps2_init)) == -1)
558           printf("[MOUSE] Couldn't enable scroll wheel events; is this mouse from the 1980s?\n");
559       } else
560         printf("[MOUSE] Mouse didn't respond to normal PS/2 init; have you plugged a brick in by mistake?\n");
561     }
562   }
563
564   if (cfg->keyboard_file)
565     keyboard_fd = open(cfg->keyboard_file, O_RDONLY | O_NONBLOCK);
566   else
567     keyboard_fd = open(keyboard_file, O_RDONLY | O_NONBLOCK);
568
569   if (keyboard_fd == -1) {
570     printf("Failed to open keyboard event source.\n");
571   }
572
573   if (cfg->mouse_autoconnect)
574     mouse_hook_enabled = 1;
575
576   if (cfg->keyboard_autoconnect)
577     kb_hook_enabled = 1;
578
579   InitGayle();
580
581   signal(SIGINT, sigint_handler);
582
583   ps_reset_state_machine();
584   ps_pulse_reset();
585   usleep(1500);
586
587   m68k_init();
588   printf("Setting CPU type to %d.\n", cpu_type);
589         m68k_set_cpu_type(&m68ki_cpu, cpu_type);
590   cpu_pulse_reset();
591
592   pthread_t ipl_tid = 0, cpu_tid, kbd_tid;
593   int err;
594   if (ipl_tid == 0) {
595     err = pthread_create(&ipl_tid, NULL, &ipl_task, NULL);
596     if (err != 0)
597       printf("[ERROR] Cannot create IPL thread: [%s]", strerror(err));
598     else {
599       pthread_setname_np(ipl_tid, "pistorm: ipl");
600       printf("IPL thread created successfully\n");
601     }
602   }
603
604   // create keyboard task
605   err = pthread_create(&kbd_tid, NULL, &keyboard_task, NULL);
606   if (err != 0)
607     printf("[ERROR] Cannot create keyboard thread: [%s]", strerror(err));
608   else {
609     pthread_setname_np(kbd_tid, "pistorm: kbd");
610     printf("[MAIN] Keyboard thread created successfully\n");
611   }
612
613   // create cpu task
614   err = pthread_create(&cpu_tid, NULL, &cpu_task, NULL);
615   if (err != 0)
616     printf("[ERROR] Cannot create CPU thread: [%s]", strerror(err));
617   else {
618     pthread_setname_np(cpu_tid, "pistorm: cpu");
619     printf("[MAIN] CPU thread created successfully\n");
620   }
621
622   // wait for cpu task to end before closing up and finishing
623   pthread_join(cpu_tid, NULL);
624
625   while (!emulator_exiting) {
626     emulator_exiting = 1;
627     usleep(0);
628   }
629
630   if (load_new_config == 0)
631     printf("[MAIN] All threads appear to have concluded; ending process\n");
632
633   if (mouse_fd != -1)
634     close(mouse_fd);
635   if (mem_fd)
636     close(mem_fd);
637
638   if (load_new_config != 0)
639     goto switch_config;
640
641   if (cfg->platform->shutdown) {
642     cfg->platform->shutdown(cfg);
643   }
644
645   return 0;
646 }
647
648 void cpu_pulse_reset(void) {
649         m68ki_cpu_core *state = &m68ki_cpu;
650   ps_pulse_reset();
651
652   ovl = 1;
653   if (cfg->platform->handle_reset)
654     cfg->platform->handle_reset(cfg);
655
656         m68k_pulse_reset(state);
657 }
658
659 int cpu_irq_ack(int level) {
660   printf("cpu irq ack\n");
661   return level;
662 }
663
664 static unsigned int target = 0;
665 static uint8_t send_keypress = 0;
666 static uint32_t platform_res, rres;
667
668 uint8_t cdtv_dmac_reg_idx_read();
669 void cdtv_dmac_reg_idx_write(uint8_t value);
670 uint32_t cdtv_dmac_read(uint32_t address, uint8_t type);
671 void cdtv_dmac_write(uint32_t address, uint32_t value, uint8_t type);
672
673 static inline void inline_write_16(unsigned int address, unsigned int data) {
674   *(gpio + 0) = GPFSEL0_OUTPUT;
675   *(gpio + 1) = GPFSEL1_OUTPUT;
676   *(gpio + 2) = GPFSEL2_OUTPUT;
677
678   *(gpio + 7) = ((data & 0xffff) << 8) | (REG_DATA << PIN_A0);
679   *(gpio + 7) = 1 << PIN_WR;
680   *(gpio + 10) = 1 << PIN_WR;
681   *(gpio + 10) = 0xffffec;
682
683   *(gpio + 7) = ((address & 0xffff) << 8) | (REG_ADDR_LO << PIN_A0);
684   *(gpio + 7) = 1 << PIN_WR;
685   *(gpio + 10) = 1 << PIN_WR;
686   *(gpio + 10) = 0xffffec;
687
688   *(gpio + 7) = ((0x0000 | (address >> 16)) << 8) | (REG_ADDR_HI << PIN_A0);
689   *(gpio + 7) = 1 << PIN_WR;
690   *(gpio + 10) = 1 << PIN_WR;
691   *(gpio + 10) = 0xffffec;
692
693   *(gpio + 0) = GPFSEL0_INPUT;
694   *(gpio + 1) = GPFSEL1_INPUT;
695   *(gpio + 2) = GPFSEL2_INPUT;
696
697   while (*(gpio + 13) & (1 << PIN_TXN_IN_PROGRESS)) {}
698 }
699
700 static inline void inline_write_8(unsigned int address, unsigned int data) {
701   if ((address & 1) == 0)
702     data = data + (data << 8);  // EVEN, A0=0,UDS
703   else
704     data = data & 0xff;  // ODD , A0=1,LDS
705
706   *(gpio + 0) = GPFSEL0_OUTPUT;
707   *(gpio + 1) = GPFSEL1_OUTPUT;
708   *(gpio + 2) = GPFSEL2_OUTPUT;
709
710   *(gpio + 7) = ((data & 0xffff) << 8) | (REG_DATA << PIN_A0);
711   *(gpio + 7) = 1 << PIN_WR;
712   *(gpio + 10) = 1 << PIN_WR;
713   *(gpio + 10) = 0xffffec;
714
715   *(gpio + 7) = ((address & 0xffff) << 8) | (REG_ADDR_LO << PIN_A0);
716   *(gpio + 7) = 1 << PIN_WR;
717   *(gpio + 10) = 1 << PIN_WR;
718   *(gpio + 10) = 0xffffec;
719
720   *(gpio + 7) = ((0x0100 | (address >> 16)) << 8) | (REG_ADDR_HI << PIN_A0);
721   *(gpio + 7) = 1 << PIN_WR;
722   *(gpio + 10) = 1 << PIN_WR;
723   *(gpio + 10) = 0xffffec;
724
725   *(gpio + 0) = GPFSEL0_INPUT;
726   *(gpio + 1) = GPFSEL1_INPUT;
727   *(gpio + 2) = GPFSEL2_INPUT;
728
729   while (*(gpio + 13) & (1 << PIN_TXN_IN_PROGRESS)) {}
730 }
731
732 static inline void inline_write_32(unsigned int address, unsigned int value) {
733   inline_write_16(address, value >> 16);
734   inline_write_16(address + 2, value);
735 }
736
737 static inline unsigned int inline_read_16(unsigned int address) {
738   *(gpio + 0) = GPFSEL0_OUTPUT;
739   *(gpio + 1) = GPFSEL1_OUTPUT;
740   *(gpio + 2) = GPFSEL2_OUTPUT;
741
742   *(gpio + 7) = ((address & 0xffff) << 8) | (REG_ADDR_LO << PIN_A0);
743   *(gpio + 7) = 1 << PIN_WR;
744   *(gpio + 10) = 1 << PIN_WR;
745   *(gpio + 10) = 0xffffec;
746
747   *(gpio + 7) = ((0x0200 | (address >> 16)) << 8) | (REG_ADDR_HI << PIN_A0);
748   *(gpio + 7) = 1 << PIN_WR;
749   *(gpio + 10) = 1 << PIN_WR;
750   *(gpio + 10) = 0xffffec;
751
752   *(gpio + 0) = GPFSEL0_INPUT;
753   *(gpio + 1) = GPFSEL1_INPUT;
754   *(gpio + 2) = GPFSEL2_INPUT;
755
756   *(gpio + 7) = (REG_DATA << PIN_A0);
757   *(gpio + 7) = 1 << PIN_RD;
758
759   while (*(gpio + 13) & (1 << PIN_TXN_IN_PROGRESS)) {}
760   unsigned int value = *(gpio + 13);
761
762   *(gpio + 10) = 0xffffec;
763
764   return (value >> 8) & 0xffff;
765 }
766
767 static inline unsigned int inline_read_8(unsigned int address) {
768   *(gpio + 0) = GPFSEL0_OUTPUT;
769   *(gpio + 1) = GPFSEL1_OUTPUT;
770   *(gpio + 2) = GPFSEL2_OUTPUT;
771
772   *(gpio + 7) = ((address & 0xffff) << 8) | (REG_ADDR_LO << PIN_A0);
773   *(gpio + 7) = 1 << PIN_WR;
774   *(gpio + 10) = 1 << PIN_WR;
775   *(gpio + 10) = 0xffffec;
776
777   *(gpio + 7) = ((0x0300 | (address >> 16)) << 8) | (REG_ADDR_HI << PIN_A0);
778   *(gpio + 7) = 1 << PIN_WR;
779   *(gpio + 10) = 1 << PIN_WR;
780   *(gpio + 10) = 0xffffec;
781
782   *(gpio + 0) = GPFSEL0_INPUT;
783   *(gpio + 1) = GPFSEL1_INPUT;
784   *(gpio + 2) = GPFSEL2_INPUT;
785
786   *(gpio + 7) = (REG_DATA << PIN_A0);
787   *(gpio + 7) = 1 << PIN_RD;
788
789   while (*(gpio + 13) & (1 << PIN_TXN_IN_PROGRESS)) {}
790   unsigned int value = *(gpio + 13);
791
792   *(gpio + 10) = 0xffffec;
793
794   value = (value >> 8) & 0xffff;
795
796   if ((address & 1) == 0)
797     return (value >> 8) & 0xff;  // EVEN, A0=0,UDS
798   else
799     return value & 0xff;  // ODD , A0=1,LDS
800 }
801
802 static inline unsigned int inline_read_32(unsigned int address) {
803   unsigned int a = inline_read_16(address);
804   unsigned int b = inline_read_16(address + 2);
805   return (a << 16) | b;
806 }
807
808 static inline uint32_t ps_read(uint8_t type, uint32_t addr) {
809   switch (type) {
810     case OP_TYPE_BYTE:
811       return inline_read_8(addr);
812     case OP_TYPE_WORD:
813       return inline_read_16(addr);
814     case OP_TYPE_LONGWORD:
815       return inline_read_32(addr);
816   }
817   // This shouldn't actually happen.
818   return 0;
819 }
820
821 static inline int32_t platform_read_check(uint8_t type, uint32_t addr, uint32_t *res) {
822   switch (cfg->platform->id) {
823     case PLATFORM_AMIGA:
824       switch (addr) {
825         case CIAAPRA:
826           if (mouse_hook_enabled && (mouse_buttons & 0x01)) {
827             rres = (uint32_t)ps_read(type, addr);
828             *res = (rres ^ 0x40);
829             return 1;
830           }
831           return 0;
832           break;
833         case CIAAICR:
834           if (kb_hook_enabled) {
835             rres = (uint32_t)ps_read(type, addr);
836             if (get_num_kb_queued() && (!send_keypress || send_keypress == 1)) {
837               rres |= 0x08;
838               if (!send_keypress)
839                 send_keypress = 1;
840             }
841             if (send_keypress == 2) {
842               send_keypress = 0;
843             }
844             *res = rres;
845             return 1;
846           }
847           return 0;
848           break;
849         case CIAADAT:
850           if (kb_hook_enabled) {
851             rres = (uint32_t)ps_read(type, addr);
852             uint8_t c = 0, t = 0;
853             pop_queued_key(&c, &t);
854             t ^= 0x01;
855             rres = ((c << 1) | t) ^ 0xFF;
856             send_keypress = 2;
857             *res = rres;
858             return 1;
859           }
860           return 0;
861           break;
862         case JOY0DAT:
863           if (mouse_hook_enabled) {
864             unsigned short result = (mouse_dy << 8) | (mouse_dx);
865             *res = (unsigned int)result;
866             return 1;
867           }
868           return 0;
869           break;
870         case POTGOR:
871           if (mouse_hook_enabled) {
872             unsigned short result = (unsigned short)ps_read(type, addr);
873             // bit 1 rmb, bit 2 mmb
874             if (mouse_buttons & 0x06) {
875               *res = (unsigned int)((result ^ ((mouse_buttons & 0x02) << 9))   // move rmb to bit 10
876                                   & (result ^ ((mouse_buttons & 0x04) << 6))); // move mmb to bit 8
877               return 1;
878             }
879             *res = (unsigned int)(result & 0xfffd);
880             return 1;
881           }
882           return 0;
883           break;
884         default:
885           break;
886       }
887
888       if (addr >= cfg->custom_low && addr < cfg->custom_high) {
889         if (addr >= PISCSI_OFFSET && addr < PISCSI_UPPER) {
890           *res = handle_piscsi_read(addr, type);
891           return 1;
892         }
893         if (addr >= PINET_OFFSET && addr < PINET_UPPER) {
894           *res = handle_pinet_read(addr, type);
895           return 1;
896         }
897         if (addr >= PIGFX_RTG_BASE && addr < PIGFX_UPPER) {
898           *res = rtg_read((addr & 0x0FFFFFFF), type);
899           return 1;
900         }
901         if (custom_read_amiga(cfg, addr, &target, type) != -1) {
902           *res = target;
903           return 1;
904         }
905       }
906       break;
907     default:
908       break;
909   }
910
911   if (ovl || (addr >= cfg->mapped_low && addr < cfg->mapped_high)) {
912     if (handle_mapped_read(cfg, addr, &target, type) != -1) {
913       *res = target;
914       return 1;
915     }
916   }
917
918   return 0;
919 }
920
921 unsigned int m68k_read_memory_8(unsigned int address) {
922   if (platform_read_check(OP_TYPE_BYTE, address, &platform_res)) {
923     return platform_res;
924   }
925
926   if (address & 0xFF000000)
927     return 0;
928
929   return (unsigned int)inline_read_8((uint32_t)address);
930 }
931
932 unsigned int m68k_read_memory_16(unsigned int address) {
933   if (platform_read_check(OP_TYPE_WORD, address, &platform_res)) {
934     return platform_res;
935   }
936
937   if (address & 0xFF000000)
938     return 0;
939
940   if (address & 0x01) {
941     return ((inline_read_8(address) << 8) | inline_read_8(address + 1));
942   }
943   return (unsigned int)inline_read_16((uint32_t)address);
944 }
945
946 unsigned int m68k_read_memory_32(unsigned int address) {
947   if (platform_read_check(OP_TYPE_LONGWORD, address, &platform_res)) {
948     return platform_res;
949   }
950
951   if (address & 0xFF000000)
952     return 0;
953
954   if (address & 0x01) {
955     uint32_t c = inline_read_8(address);
956     c |= (be16toh(inline_read_16(address+1)) << 8);
957     c |= (inline_read_8(address + 3) << 24);
958     return htobe32(c);
959   }
960   uint16_t a = inline_read_16(address);
961   uint16_t b = inline_read_16(address + 2);
962   return (a << 16) | b;
963 }
964
965 static inline int32_t platform_write_check(uint8_t type, uint32_t addr, uint32_t val) {
966   switch (cfg->platform->id) {
967     case PLATFORM_MAC:
968       switch (addr) {
969         case 0xEFFFFE: // VIA1?
970           if (val & 0x10 && !ovl) {
971               ovl = 1;
972               printf("[MAC] OVL on.\n");
973               handle_ovl_mappings_mac68k(cfg);
974           } else if (ovl) {
975             ovl = 0;
976             printf("[MAC] OVL off.\n");
977             handle_ovl_mappings_mac68k(cfg);
978           }
979           break;
980       }
981       break;
982     case PLATFORM_AMIGA:
983       switch (addr) {
984         case CIAAPRA:
985           if (ovl != (val & (1 << 0))) {
986             ovl = (val & (1 << 0));
987             printf("OVL:%x\n", ovl);
988           }
989           return 0;
990           break;
991         case SERDAT: {
992           char *serdat = (char *)&val;
993           // SERDAT word. see amiga dev docs appendix a; upper byte is control codes, and bit 0 is always 1.
994           // ignore this upper byte as it's not viewable data, only display lower byte.
995           printf("%c", serdat[0]);
996           return 0;
997           break;
998         }
999         case INTENA:
1000           // This code is kind of strange and should probably be reworked/revoked.
1001           if (!(val & 0x8000)) {
1002             if (val & 0x04) {
1003               int2_enabled = 0;
1004             }
1005           }
1006           else if (val & 0x04) {
1007             int2_enabled = 1;
1008           }
1009           return 0;
1010           break;
1011         default:
1012           break;
1013       }
1014
1015       if (addr >= cfg->custom_low && addr < cfg->custom_high) {
1016         if (addr >= PISCSI_OFFSET && addr < PISCSI_UPPER) {
1017           handle_piscsi_write(addr, val, type);
1018           return 1;
1019         }
1020         if (addr >= PINET_OFFSET && addr < PINET_UPPER) {
1021           handle_pinet_write(addr, val, type);
1022           return 1;
1023         }
1024         if (addr >= PIGFX_RTG_BASE && addr < PIGFX_UPPER) {
1025           rtg_write((addr & 0x0FFFFFFF), val, type);
1026           return 1;
1027         }
1028         if (custom_write_amiga(cfg, addr, val, type) != -1) {
1029           return 1;
1030         }
1031       }
1032       break;
1033     default:
1034       break;
1035   }
1036
1037   if (ovl || (addr >= cfg->mapped_low && addr < cfg->mapped_high)) {
1038     if (handle_mapped_write(cfg, addr, val, type) != -1) {
1039       return 1;
1040     }
1041   }
1042
1043   return 0;
1044 }
1045
1046 void m68k_write_memory_8(unsigned int address, unsigned int value) {
1047   if (platform_write_check(OP_TYPE_BYTE, address, value))
1048     return;
1049
1050   if (address & 0xFF000000)
1051     return;
1052
1053   inline_write_8((uint32_t)address, value);
1054   return;
1055 }
1056
1057 void m68k_write_memory_16(unsigned int address, unsigned int value) {
1058   if (platform_write_check(OP_TYPE_WORD, address, value))
1059     return;
1060
1061   if (address & 0xFF000000)
1062     return;
1063
1064   if (address & 0x01) {
1065     inline_write_8(value & 0xFF, address);
1066     inline_write_8((value >> 8) & 0xFF, address + 1);
1067     return;
1068   }
1069
1070   inline_write_16((uint32_t)address, value);
1071   return;
1072 }
1073
1074 void m68k_write_memory_32(unsigned int address, unsigned int value) {
1075   if (platform_write_check(OP_TYPE_LONGWORD, address, value))
1076     return;
1077
1078   if (address & 0xFF000000)
1079     return;
1080
1081   if (address & 0x01) {
1082     inline_write_8(value & 0xFF, address);
1083     inline_write_16(htobe16(((value >> 8) & 0xFFFF)), address + 1);
1084     inline_write_8((value >> 24), address + 3);
1085     return;
1086   }
1087
1088   inline_write_16(address, value >> 16);
1089   inline_write_16(address + 2, value);
1090   return;
1091 }