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