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