ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/main_unix.cpp
Revision: 1.44
Committed: 2002-02-07T16:10:55Z (22 years, 5 months ago) by cebix
Branch: MAIN
Changes since 1.43: +49 -11 lines
Log Message:
cleaned up pthread attributes [Brian Johnson]

File Contents

# Content
1 /*
2 * main_unix.cpp - Startup code for Unix
3 *
4 * Basilisk II (C) 1997-2002 Christian Bauer
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21 #include "sysdeps.h"
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <signal.h>
26 #include <errno.h>
27 #include <X11/Xlib.h>
28
29 #ifdef HAVE_PTHREADS
30 # include <pthread.h>
31 #endif
32
33 #if REAL_ADDRESSING || DIRECT_ADDRESSING
34 # include <sys/mman.h>
35 #endif
36
37 #if !EMULATED_68K && defined(__NetBSD__)
38 # include <m68k/sync_icache.h>
39 # include <m68k/frame.h>
40 # include <sys/param.h>
41 # include <sys/sysctl.h>
42 struct sigstate {
43 int ss_flags;
44 struct frame ss_frame;
45 struct fpframe ss_fpstate;
46 };
47 # define SS_FPSTATE 0x02
48 # define SS_USERREGS 0x04
49 #endif
50
51 #ifdef ENABLE_GTK
52 # include <gtk/gtk.h>
53 # include <gdk/gdk.h>
54 # ifdef HAVE_GNOMEUI
55 # include <gnome.h>
56 # endif
57 #endif
58
59 #ifdef ENABLE_XF86_DGA
60 # include <X11/Xutil.h>
61 # include <X11/extensions/xf86dga.h>
62 #endif
63
64 #include "cpu_emulation.h"
65 #include "sys.h"
66 #include "rom_patches.h"
67 #include "xpram.h"
68 #include "timer.h"
69 #include "video.h"
70 #include "emul_op.h"
71 #include "prefs.h"
72 #include "prefs_editor.h"
73 #include "macos_util.h"
74 #include "user_strings.h"
75 #include "version.h"
76 #include "main.h"
77 #include "vm_alloc.h"
78
79 #ifdef ENABLE_MON
80 # include "mon.h"
81 #endif
82
83 #define DEBUG 0
84 #include "debug.h"
85
86
87 // Constants
88 const char ROM_FILE_NAME[] = "ROM";
89 const int SIG_STACK_SIZE = SIGSTKSZ; // Size of signal stack
90 const int SCRATCH_MEM_SIZE = 0x10000; // Size of scratch memory area
91
92
93 #if !EMULATED_68K
94 // RAM and ROM pointers
95 uint32 RAMBaseMac; // RAM base (Mac address space)
96 uint8 *RAMBaseHost; // RAM base (host address space)
97 uint32 RAMSize; // Size of RAM
98 uint32 ROMBaseMac; // ROM base (Mac address space)
99 uint8 *ROMBaseHost; // ROM base (host address space)
100 uint32 ROMSize; // Size of ROM
101 #endif
102
103
104 // CPU and FPU type, addressing mode
105 int CPUType;
106 bool CPUIs68060;
107 int FPUType;
108 bool TwentyFourBitAddressing;
109
110
111 // Global variables
112 char *x_display_name = NULL; // X11 display name
113 Display *x_display = NULL; // X11 display handle
114
115 static uint8 last_xpram[XPRAM_SIZE]; // Buffer for monitoring XPRAM changes
116
117 #ifdef HAVE_PTHREADS
118 static pthread_t emul_thread; // Handle of MacOS emulation thread (main thread)
119
120 static bool xpram_thread_active = false; // Flag: XPRAM watchdog installed
121 static volatile bool xpram_thread_cancel = false; // Flag: Cancel XPRAM thread
122 static pthread_t xpram_thread; // XPRAM watchdog
123
124 static bool tick_thread_active = false; // Flag: 60Hz thread installed
125 static volatile bool tick_thread_cancel = false; // Flag: Cancel 60Hz thread
126 static pthread_t tick_thread; // 60Hz thread
127 static pthread_attr_t tick_thread_attr; // 60Hz thread attributes
128
129 static pthread_mutex_t intflag_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect InterruptFlags
130 #define LOCK_INTFLAGS pthread_mutex_lock(&intflag_lock)
131 #define UNLOCK_INTFLAGS pthread_mutex_unlock(&intflag_lock)
132
133 #else
134
135 #define LOCK_INTFLAGS
136 #define UNLOCK_INTFLAGS
137
138 #endif
139
140 #if !EMULATED_68K
141 #define SIG_IRQ SIGUSR1
142 static struct sigaction sigirq_sa; // Virtual 68k interrupt signal
143 static struct sigaction sigill_sa; // Illegal instruction
144 static void *sig_stack = NULL; // Stack for signal handlers
145 uint16 EmulatedSR; // Emulated bits of SR (supervisor bit and interrupt mask)
146 #endif
147
148 #if USE_SCRATCHMEM_SUBTERFUGE
149 uint8 *ScratchMem = NULL; // Scratch memory for Mac ROM writes
150 #endif
151
152 static struct sigaction timer_sa; // sigaction used for timer
153
154 #if defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
155 #define SIG_TIMER SIGRTMIN
156 static timer_t timer; // 60Hz timer
157 #endif
158
159 #ifdef ENABLE_MON
160 static struct sigaction sigint_sa; // sigaction for SIGINT handler
161 static void sigint_handler(...);
162 #endif
163
164 #if REAL_ADDRESSING
165 static bool lm_area_mapped = false; // Flag: Low Memory area mmap()ped
166 #endif
167
168
169 // Prototypes
170 static void *xpram_func(void *arg);
171 static void *tick_func(void *arg);
172 static void one_tick(...);
173 #if !EMULATED_68K
174 static void sigirq_handler(int sig, int code, struct sigcontext *scp);
175 static void sigill_handler(int sig, int code, struct sigcontext *scp);
176 extern "C" void EmulOpTrampoline(void);
177 #endif
178
179
180 /*
181 * Ersatz functions
182 */
183
184 extern "C" {
185
186 #ifndef HAVE_STRDUP
187 char *strdup(const char *s)
188 {
189 char *n = (char *)malloc(strlen(s) + 1);
190 strcpy(n, s);
191 return n;
192 }
193 #endif
194
195 }
196
197
198 /*
199 * Main program
200 */
201
202 static void usage(const char *prg_name)
203 {
204 printf("Usage: %s [OPTION...]\n", prg_name);
205 printf("\nUnix options:\n");
206 printf(" --display STRING\n X display to use\n");
207 printf(" --break ADDRESS\n set ROM breakpoint\n");
208 printf(" --rominfo\n dump ROM information\n");
209 PrefsPrintUsage();
210 exit(0);
211 }
212
213 int main(int argc, char **argv)
214 {
215 char str[256];
216
217 // Initialize variables
218 RAMBaseHost = NULL;
219 ROMBaseHost = NULL;
220 srand(time(NULL));
221 tzset();
222
223 // Print some info
224 printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
225 printf(" %s\n", GetString(STR_ABOUT_TEXT2));
226
227 #ifdef ENABLE_GTK
228 #ifdef HAVE_GNOMEUI
229 // Init GNOME/GTK
230 char version[16];
231 sprintf(version, "%d.%d", VERSION_MAJOR, VERSION_MINOR);
232 gnome_init("Basilisk II", version, argc, argv);
233 #else
234 // Init GTK
235 gtk_set_locale();
236 gtk_init(&argc, &argv);
237 #endif
238 x_display_name = gdk_get_display(); // gtk_init() handles and removes the "--display" argument
239 #endif
240
241 // Read preferences
242 PrefsInit(argc, argv);
243
244 // Parse command line arguments
245 for (int i=1; i<argc; i++) {
246 if (strcmp(argv[i], "--help") == 0) {
247 usage(argv[0]);
248 } else if (strcmp(argv[i], "--display") == 0) {
249 i++;
250 if (i < argc)
251 x_display_name = strdup(argv[i]);
252 } else if (strcmp(argv[i], "--break") == 0) {
253 i++;
254 if (i < argc)
255 ROMBreakpoint = strtol(argv[i], NULL, 0);
256 } else if (strcmp(argv[i], "--rominfo") == 0) {
257 PrintROMInfo = true;
258 } else if (argv[i][0] == '-') {
259 fprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
260 usage(argv[0]);
261 }
262 }
263
264 // Open display
265 x_display = XOpenDisplay(x_display_name);
266 if (x_display == NULL) {
267 char str[256];
268 sprintf(str, GetString(STR_NO_XSERVER_ERR), XDisplayName(x_display_name));
269 ErrorAlert(str);
270 QuitEmulator();
271 }
272
273 #if defined(ENABLE_XF86_DGA) && !defined(ENABLE_MON)
274 // Fork out, so we can return from fullscreen mode when things get ugly
275 XF86DGAForkApp(DefaultScreen(x_display));
276 #endif
277
278 // Init system routines
279 SysInit();
280
281 // Show preferences editor
282 if (!PrefsFindBool("nogui"))
283 if (!PrefsEditor())
284 QuitEmulator();
285
286 // Read RAM size
287 RAMSize = PrefsFindInt32("ramsize") & 0xfff00000; // Round down to 1MB boundary
288 if (RAMSize < 1024*1024) {
289 WarningAlert(GetString(STR_SMALL_RAM_WARN));
290 RAMSize = 1024*1024;
291 }
292
293 #if REAL_ADDRESSING || DIRECT_ADDRESSING
294 RAMSize = RAMSize & -getpagesize(); // Round down to page boundary
295 #endif
296
297 // Initialize VM system
298 vm_init();
299
300 #if REAL_ADDRESSING
301 // Flag: RAM and ROM are contigously allocated from address 0
302 bool memory_mapped_from_zero = false;
303
304 // Under Solaris/SPARC and NetBSD/m68k, Basilisk II is known to crash
305 // when trying to map a too big chunk of memory starting at address 0
306 #if defined(OS_solaris) || defined(OS_netbsd)
307 const bool can_map_all_memory = false;
308 #else
309 const bool can_map_all_memory = true;
310 #endif
311
312 // Try to allocate all memory from 0x0000, if it is not known to crash
313 if (can_map_all_memory && (vm_acquire_fixed(0, RAMSize + 0x100000) == 0)) {
314 D(bug("Could allocate RAM and ROM from 0x0000\n"));
315 memory_mapped_from_zero = true;
316 }
317
318 // Otherwise, just create the Low Memory area (0x0000..0x2000)
319 else if (vm_acquire_fixed(0, 0x2000) == 0) {
320 D(bug("Could allocate the Low Memory globals\n"));
321 lm_area_mapped = true;
322 }
323
324 // Exit on failure
325 else {
326 sprintf(str, GetString(STR_LOW_MEM_MMAP_ERR), strerror(errno));
327 ErrorAlert(str);
328 QuitEmulator();
329 }
330 #endif
331
332 // Create areas for Mac RAM and ROM
333 #if REAL_ADDRESSING
334 if (memory_mapped_from_zero) {
335 RAMBaseHost = (uint8 *)0;
336 ROMBaseHost = RAMBaseHost + RAMSize;
337 }
338 else
339 #endif
340 {
341 RAMBaseHost = (uint8 *)vm_acquire(RAMSize);
342 ROMBaseHost = (uint8 *)vm_acquire(0x100000);
343 if (RAMBaseHost == VM_MAP_FAILED || ROMBaseHost == VM_MAP_FAILED) {
344 ErrorAlert(STR_NO_MEM_ERR);
345 QuitEmulator();
346 }
347 }
348
349 #if USE_SCRATCHMEM_SUBTERFUGE
350 // Allocate scratch memory
351 ScratchMem = (uint8 *)vm_acquire(SCRATCH_MEM_SIZE);
352 if (ScratchMem == VM_MAP_FAILED) {
353 ErrorAlert(STR_NO_MEM_ERR);
354 QuitEmulator();
355 }
356 ScratchMem += SCRATCH_MEM_SIZE/2; // ScratchMem points to middle of block
357 #endif
358
359 #if DIRECT_ADDRESSING
360 // RAMBaseMac shall always be zero
361 MEMBaseDiff = (uintptr)RAMBaseHost;
362 RAMBaseMac = 0;
363 ROMBaseMac = Host2MacAddr(ROMBaseHost);
364 #endif
365 #if REAL_ADDRESSING
366 RAMBaseMac = (uint32)RAMBaseHost;
367 ROMBaseMac = (uint32)ROMBaseHost;
368 #endif
369 D(bug("Mac RAM starts at %p (%08x)\n", RAMBaseHost, RAMBaseMac));
370 D(bug("Mac ROM starts at %p (%08x)\n", ROMBaseHost, ROMBaseMac));
371
372 // Get rom file path from preferences
373 const char *rom_path = PrefsFindString("rom");
374
375 // Load Mac ROM
376 int rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME, O_RDONLY);
377 if (rom_fd < 0) {
378 ErrorAlert(STR_NO_ROM_FILE_ERR);
379 QuitEmulator();
380 }
381 printf(GetString(STR_READING_ROM_FILE));
382 ROMSize = lseek(rom_fd, 0, SEEK_END);
383 if (ROMSize != 64*1024 && ROMSize != 128*1024 && ROMSize != 256*1024 && ROMSize != 512*1024 && ROMSize != 1024*1024) {
384 ErrorAlert(STR_ROM_SIZE_ERR);
385 close(rom_fd);
386 QuitEmulator();
387 }
388 lseek(rom_fd, 0, SEEK_SET);
389 if (read(rom_fd, ROMBaseHost, ROMSize) != (ssize_t)ROMSize) {
390 ErrorAlert(STR_ROM_FILE_READ_ERR);
391 close(rom_fd);
392 QuitEmulator();
393 }
394
395 #if !EMULATED_68K
396 // Get CPU model
397 int mib[2] = {CTL_HW, HW_MODEL};
398 char *model;
399 size_t model_len;
400 sysctl(mib, 2, NULL, &model_len, NULL, 0);
401 model = (char *)malloc(model_len);
402 sysctl(mib, 2, model, &model_len, NULL, 0);
403 D(bug("Model: %s\n", model));
404
405 // Set CPU and FPU type
406 CPUIs68060 = false;
407 if (strstr(model, "020"))
408 CPUType = 2;
409 else if (strstr(model, "030"))
410 CPUType = 3;
411 else if (strstr(model, "040"))
412 CPUType = 4;
413 else if (strstr(model, "060")) {
414 CPUType = 4;
415 CPUIs68060 = true;
416 } else {
417 printf("WARNING: Cannot detect CPU type, assuming 68020\n");
418 CPUType = 2;
419 }
420 FPUType = 1; // NetBSD has an FPU emulation, so the FPU ought to be available at all times
421 TwentyFourBitAddressing = false;
422 #endif
423
424 // Initialize everything
425 if (!InitAll())
426 QuitEmulator();
427 D(bug("Initialization complete\n"));
428
429 #ifdef HAVE_PTHREADS
430 // Get handle of main thread
431 emul_thread = pthread_self();
432 #endif
433
434 #if !EMULATED_68K
435 // (Virtual) supervisor mode, disable interrupts
436 EmulatedSR = 0x2700;
437
438 // Create and install stack for signal handlers
439 sig_stack = malloc(SIG_STACK_SIZE);
440 D(bug("Signal stack at %p\n", sig_stack));
441 if (sig_stack == NULL) {
442 ErrorAlert(STR_NOT_ENOUGH_MEMORY_ERR);
443 QuitEmulator();
444 }
445 stack_t new_stack;
446 new_stack.ss_sp = sig_stack;
447 new_stack.ss_flags = 0;
448 new_stack.ss_size = SIG_STACK_SIZE;
449 if (sigaltstack(&new_stack, NULL) < 0) {
450 sprintf(str, GetString(STR_SIGALTSTACK_ERR), strerror(errno));
451 ErrorAlert(str);
452 QuitEmulator();
453 }
454
455 // Install SIGILL handler for emulating privileged instructions and
456 // executing A-Trap and EMUL_OP opcodes
457 sigemptyset(&sigill_sa.sa_mask); // Block virtual 68k interrupts during SIGILL handling
458 sigaddset(&sigill_sa.sa_mask, SIG_IRQ);
459 sigaddset(&sigill_sa.sa_mask, SIGALRM);
460 sigill_sa.sa_handler = (void (*)(int))sigill_handler;
461 sigill_sa.sa_flags = SA_ONSTACK;
462 if (sigaction(SIGILL, &sigill_sa, NULL) < 0) {
463 sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGILL", strerror(errno));
464 ErrorAlert(str);
465 QuitEmulator();
466 }
467
468 // Install virtual 68k interrupt signal handler
469 sigemptyset(&sigirq_sa.sa_mask);
470 sigaddset(&sigirq_sa.sa_mask, SIGALRM);
471 sigirq_sa.sa_handler = (void (*)(int))sigirq_handler;
472 sigirq_sa.sa_flags = SA_ONSTACK | SA_RESTART;
473 if (sigaction(SIG_IRQ, &sigirq_sa, NULL) < 0) {
474 sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIG_IRQ", strerror(errno));
475 ErrorAlert(str);
476 QuitEmulator();
477 }
478 #endif
479
480 #ifdef ENABLE_MON
481 // Setup SIGINT handler to enter mon
482 sigemptyset(&sigint_sa.sa_mask);
483 sigint_sa.sa_handler = (void (*)(int))sigint_handler;
484 sigint_sa.sa_flags = 0;
485 sigaction(SIGINT, &sigint_sa, NULL);
486 #endif
487
488 #if defined(HAVE_PTHREADS)
489
490 // POSIX threads available, start 60Hz thread
491 Set_pthread_attr(&tick_thread_attr, 0);
492 tick_thread_active = (pthread_create(&tick_thread, &tick_thread_attr, tick_func, NULL) == 0);
493 if (!tick_thread_active) {
494 sprintf(str, GetString(STR_TICK_THREAD_ERR), strerror(errno));
495 ErrorAlert(str);
496 QuitEmulator();
497 }
498 D(bug("60Hz thread started\n"));
499
500 #elif defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
501
502 // POSIX.4 timers and real-time signals available, start 60Hz timer
503 sigemptyset(&timer_sa.sa_mask);
504 timer_sa.sa_sigaction = (void (*)(int, siginfo_t *, void *))one_tick;
505 timer_sa.sa_flags = SA_SIGINFO | SA_RESTART;
506 if (sigaction(SIG_TIMER, &timer_sa, NULL) < 0) {
507 sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIG_TIMER", strerror(errno));
508 ErrorAlert(str);
509 QuitEmulator();
510 }
511 struct sigevent timer_event;
512 timer_event.sigev_notify = SIGEV_SIGNAL;
513 timer_event.sigev_signo = SIG_TIMER;
514 if (timer_create(CLOCK_REALTIME, &timer_event, &timer) < 0) {
515 sprintf(str, GetString(STR_TIMER_CREATE_ERR), strerror(errno));
516 ErrorAlert(str);
517 QuitEmulator();
518 }
519 struct itimerspec req;
520 req.it_value.tv_sec = 0;
521 req.it_value.tv_nsec = 16625000;
522 req.it_interval.tv_sec = 0;
523 req.it_interval.tv_nsec = 16625000;
524 if (timer_settime(timer, 0, &req, NULL) < 0) {
525 sprintf(str, GetString(STR_TIMER_SETTIME_ERR), strerror(errno));
526 ErrorAlert(str);
527 QuitEmulator();
528 }
529 D(bug("60Hz timer started\n"));
530
531 #else
532
533 // Start 60Hz timer
534 sigemptyset(&timer_sa.sa_mask); // Block virtual 68k interrupts during SIGARLM handling
535 sigaddset(&timer_sa.sa_mask, SIG_IRQ);
536 timer_sa.sa_handler = one_tick;
537 timer_sa.sa_flags = SA_ONSTACK | SA_RESTART;
538 if (sigaction(SIGALRM, &timer_sa, NULL) < 0) {
539 sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGALRM", strerror(errno));
540 ErrorAlert(str);
541 QuitEmulator();
542 }
543 struct itimerval req;
544 req.it_interval.tv_sec = req.it_value.tv_sec = 0;
545 req.it_interval.tv_usec = req.it_value.tv_usec = 16625;
546 setitimer(ITIMER_REAL, &req, NULL);
547
548 #endif
549
550 #ifdef HAVE_PTHREADS
551 // Start XPRAM watchdog thread
552 memcpy(last_xpram, XPRAM, XPRAM_SIZE);
553 xpram_thread_active = (pthread_create(&xpram_thread, NULL, xpram_func, NULL) == 0);
554 D(bug("XPRAM thread started\n"));
555 #endif
556
557 // Start 68k and jump to ROM boot routine
558 D(bug("Starting emulation...\n"));
559 Start680x0();
560
561 QuitEmulator();
562 return 0;
563 }
564
565
566 /*
567 * Quit emulator
568 */
569
570 void QuitEmulator(void)
571 {
572 D(bug("QuitEmulator\n"));
573
574 #if EMULATED_68K
575 // Exit 680x0 emulation
576 Exit680x0();
577 #endif
578
579 #if defined(HAVE_PTHREADS)
580 // Stop 60Hz thread
581 if (tick_thread_active) {
582 tick_thread_cancel = true;
583 #ifdef HAVE_PTHREAD_CANCEL
584 pthread_cancel(tick_thread);
585 #endif
586 pthread_join(tick_thread, NULL);
587 }
588 #elif defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
589 // Stop 60Hz timer
590 timer_delete(timer);
591 #else
592 struct itimerval req;
593 req.it_interval.tv_sec = req.it_value.tv_sec = 0;
594 req.it_interval.tv_usec = req.it_value.tv_usec = 0;
595 setitimer(ITIMER_REAL, &req, NULL);
596 #endif
597
598 #ifdef HAVE_PTHREADS
599 // Stop XPRAM watchdog thread
600 if (xpram_thread_active) {
601 xpram_thread_cancel = true;
602 #ifdef HAVE_PTHREAD_CANCEL
603 pthread_cancel(xpram_thread);
604 #endif
605 pthread_join(xpram_thread, NULL);
606 }
607 #endif
608
609 // Deinitialize everything
610 ExitAll();
611
612 // Free ROM/RAM areas
613 if (RAMBaseHost != VM_MAP_FAILED) {
614 vm_release(RAMBaseHost, RAMSize);
615 RAMBaseHost = NULL;
616 }
617 if (ROMBaseHost != VM_MAP_FAILED) {
618 vm_release(ROMBaseHost, 0x100000);
619 ROMBaseHost = NULL;
620 }
621
622 #if USE_SCRATCHMEM_SUBTERFUGE
623 // Delete scratch memory area
624 if (ScratchMem != (uint8 *)VM_MAP_FAILED) {
625 vm_release((void *)(ScratchMem - SCRATCH_MEM_SIZE/2), SCRATCH_MEM_SIZE);
626 ScratchMem = NULL;
627 }
628 #endif
629
630 #if REAL_ADDRESSING
631 // Delete Low Memory area
632 if (lm_area_mapped)
633 vm_release(0, 0x2000);
634 #endif
635
636 // Exit VM wrappers
637 vm_exit();
638
639 // Exit system routines
640 SysExit();
641
642 // Exit preferences
643 PrefsExit();
644
645 // Close X11 server connection
646 if (x_display)
647 XCloseDisplay(x_display);
648
649 exit(0);
650 }
651
652
653 /*
654 * Code was patched, flush caches if neccessary (i.e. when using a real 680x0
655 * or a dynamically recompiling emulator)
656 */
657
658 void FlushCodeCache(void *start, uint32 size)
659 {
660 #if !EMULATED_68K && defined(__NetBSD__)
661 m68k_sync_icache(start, size);
662 #endif
663 }
664
665
666 /*
667 * SIGINT handler, enters mon
668 */
669
670 #ifdef ENABLE_MON
671 static void sigint_handler(...)
672 {
673 #if EMULATED_68K
674 uaecptr nextpc;
675 extern void m68k_dumpstate(uaecptr *nextpc);
676 m68k_dumpstate(&nextpc);
677 #endif
678 VideoQuitFullScreen();
679 char *arg[4] = {"mon", "-m", "-r", NULL};
680 mon(3, arg);
681 QuitEmulator();
682 }
683 #endif
684
685
686 #ifdef HAVE_PTHREADS
687 /*
688 * Pthread configuration
689 */
690 void
691 Set_pthread_attr(pthread_attr_t *attr, int priority)
692 {
693 pthread_attr_init(attr);
694 #if defined(_POSIX_THREAD_PRIORITY_SCHEDULING)
695 // Some of these only work for superuser
696 if (geteuid() == 0) {
697 pthread_attr_setinheritsched(attr, PTHREAD_EXPLICIT_SCHED);
698 pthread_attr_setschedpolicy(attr, SCHED_FIFO);
699 struct sched_param fifo_param;
700 fifo_param.sched_priority = ((sched_get_priority_min(SCHED_FIFO) +
701 sched_get_priority_max(SCHED_FIFO)) / 2 +
702 priority);
703 pthread_attr_setschedparam(attr, &fifo_param);
704 }
705 if (pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM) != 0) {
706 #ifdef PTHREAD_SCOPE_BOUND_NP
707 // If system scope is not available (eg. we're not running
708 // with CAP_SCHED_MGT capability on an SGI box), try bound
709 // scope. It exposes pthread scheduling to the kernel,
710 // without setting realtime priority.
711 pthread_attr_setscope(attr, PTHREAD_SCOPE_BOUND_NP);
712 #endif
713 }
714 #endif
715 }
716 #endif // HAVE_PTHREADS
717
718
719 /*
720 * Mutexes
721 */
722
723 #ifdef HAVE_PTHREADS
724
725 struct B2_mutex {
726 B2_mutex() {
727 pthread_mutexattr_t attr;
728 pthread_mutexattr_init(&attr);
729 // Initialize the mutex for priority inheritance --
730 // required for accurate timing.
731 #ifdef HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL
732 pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
733 #endif
734 #if defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE) && defined(PTHREAD_MUTEX_NORMAL)
735 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
736 #endif
737 pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);
738 pthread_mutex_init(&m, &attr);
739 pthread_mutexattr_destroy(&attr);
740 }
741 ~B2_mutex() { pthread_mutex_unlock(&m); pthread_mutex_destroy(&m); }
742 pthread_mutex_t m;
743 };
744
745 B2_mutex *B2_create_mutex(void)
746 {
747 return new B2_mutex;
748 }
749
750 void B2_lock_mutex(B2_mutex *mutex)
751 {
752 pthread_mutex_lock(&mutex->m);
753 }
754
755 void B2_unlock_mutex(B2_mutex *mutex)
756 {
757 pthread_mutex_unlock(&mutex->m);
758 }
759
760 void B2_delete_mutex(B2_mutex *mutex)
761 {
762 delete mutex;
763 }
764
765 #else
766
767 struct B2_mutex {
768 int dummy;
769 };
770
771 B2_mutex *B2_create_mutex(void)
772 {
773 return new B2_mutex;
774 }
775
776 void B2_lock_mutex(B2_mutex *mutex)
777 {
778 }
779
780 void B2_unlock_mutex(B2_mutex *mutex)
781 {
782 }
783
784 void B2_delete_mutex(B2_mutex *mutex)
785 {
786 delete mutex;
787 }
788
789 #endif
790
791
792 /*
793 * Interrupt flags (must be handled atomically!)
794 */
795
796 uint32 InterruptFlags = 0;
797
798 #if EMULATED_68K
799 void SetInterruptFlag(uint32 flag)
800 {
801 LOCK_INTFLAGS;
802 InterruptFlags |= flag;
803 UNLOCK_INTFLAGS;
804 }
805
806 void ClearInterruptFlag(uint32 flag)
807 {
808 LOCK_INTFLAGS;
809 InterruptFlags &= ~flag;
810 UNLOCK_INTFLAGS;
811 }
812 #endif
813
814 #if !EMULATED_68K
815 void TriggerInterrupt(void)
816 {
817 #if defined(HAVE_PTHREADS)
818 pthread_kill(emul_thread, SIG_IRQ);
819 #else
820 raise(SIG_IRQ);
821 #endif
822 }
823
824 void TriggerNMI(void)
825 {
826 // not yet supported
827 }
828 #endif
829
830
831 /*
832 * XPRAM watchdog thread (saves XPRAM every minute)
833 */
834
835 static void xpram_watchdog(void)
836 {
837 if (memcmp(last_xpram, XPRAM, XPRAM_SIZE)) {
838 memcpy(last_xpram, XPRAM, XPRAM_SIZE);
839 SaveXPRAM();
840 }
841 }
842
843 #ifdef HAVE_PTHREADS
844 static void *xpram_func(void *arg)
845 {
846 while (!xpram_thread_cancel) {
847 for (int i=0; i<60 && !xpram_thread_cancel; i++)
848 Delay_usec(999999); // Only wait 1 second so we quit promptly when xpram_thread_cancel becomes true
849 xpram_watchdog();
850 }
851 return NULL;
852 }
853 #endif
854
855
856 /*
857 * 60Hz thread (really 60.15Hz)
858 */
859
860 static void one_second(void)
861 {
862 // Pseudo Mac 1Hz interrupt, update local time
863 WriteMacInt32(0x20c, TimerDateTime());
864
865 SetInterruptFlag(INTFLAG_1HZ);
866 TriggerInterrupt();
867
868 #ifndef HAVE_PTHREADS
869 static int second_counter = 0;
870 if (++second_counter > 60) {
871 second_counter = 0;
872 xpram_watchdog();
873 }
874 #endif
875 }
876
877 static void one_tick(...)
878 {
879 static int tick_counter = 0;
880 if (++tick_counter > 60) {
881 tick_counter = 0;
882 one_second();
883 }
884
885 #ifndef HAVE_PTHREADS
886 // No threads available, perform video refresh and networking from here
887 VideoRefresh();
888 SetInterruptFlag(INTFLAG_ETHER);
889 #endif
890
891 // Trigger 60Hz interrupt
892 if (ROMVersion != ROM_VERSION_CLASSIC || HasMacStarted()) {
893 SetInterruptFlag(INTFLAG_60HZ);
894 TriggerInterrupt();
895 }
896 }
897
898 #ifdef HAVE_PTHREADS
899 static void *tick_func(void *arg)
900 {
901 uint64 start = GetTicks_usec();
902 int64 ticks = 0;
903 uint64 next = GetTicks_usec();
904 while (!tick_thread_cancel) {
905 one_tick();
906 next += 16625;
907 int64 delay = next - GetTicks_usec();
908 if (delay > 0)
909 Delay_usec(delay);
910 else if (delay < -16625)
911 next = GetTicks_usec();
912 ticks++;
913 }
914 uint64 end = GetTicks_usec();
915 D(bug("%Ld ticks in %Ld usec = %f ticks/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
916 return NULL;
917 }
918 #endif
919
920
921 #if !EMULATED_68K
922 /*
923 * Virtual 68k interrupt handler
924 */
925
926 static void sigirq_handler(int sig, int code, struct sigcontext *scp)
927 {
928 // Interrupts disabled? Then do nothing
929 if (EmulatedSR & 0x0700)
930 return;
931
932 struct sigstate *state = (struct sigstate *)scp->sc_ap;
933 M68kRegisters *regs = (M68kRegisters *)&state->ss_frame;
934
935 // Set up interrupt frame on stack
936 uint32 a7 = regs->a[7];
937 a7 -= 2;
938 WriteMacInt16(a7, 0x64);
939 a7 -= 4;
940 WriteMacInt32(a7, scp->sc_pc);
941 a7 -= 2;
942 WriteMacInt16(a7, scp->sc_ps | EmulatedSR);
943 scp->sc_sp = regs->a[7] = a7;
944
945 // Set interrupt level
946 EmulatedSR |= 0x2100;
947
948 // Jump to MacOS interrupt handler on return
949 scp->sc_pc = ReadMacInt32(0x64);
950 }
951
952
953 /*
954 * SIGILL handler, for emulation of privileged instructions and executing
955 * A-Trap and EMUL_OP opcodes
956 */
957
958 static void sigill_handler(int sig, int code, struct sigcontext *scp)
959 {
960 struct sigstate *state = (struct sigstate *)scp->sc_ap;
961 uint16 *pc = (uint16 *)scp->sc_pc;
962 uint16 opcode = *pc;
963 M68kRegisters *regs = (M68kRegisters *)&state->ss_frame;
964
965 #define INC_PC(n) scp->sc_pc += (n)
966
967 #define GET_SR (scp->sc_ps | EmulatedSR)
968
969 #define STORE_SR(v) \
970 scp->sc_ps = (v) & 0xff; \
971 EmulatedSR = (v) & 0xe700; \
972 if (((v) & 0x0700) == 0 && InterruptFlags) \
973 TriggerInterrupt();
974
975 //printf("opcode %04x at %p, sr %04x, emul_sr %04x\n", opcode, pc, scp->sc_ps, EmulatedSR);
976
977 if ((opcode & 0xf000) == 0xa000) {
978
979 // A-Line instruction, set up A-Line trap frame on stack
980 uint32 a7 = regs->a[7];
981 a7 -= 2;
982 WriteMacInt16(a7, 0x28);
983 a7 -= 4;
984 WriteMacInt32(a7, (uint32)pc);
985 a7 -= 2;
986 WriteMacInt16(a7, GET_SR);
987 scp->sc_sp = regs->a[7] = a7;
988
989 // Jump to MacOS A-Line handler on return
990 scp->sc_pc = ReadMacInt32(0x28);
991
992 } else if ((opcode & 0xff00) == 0x7100) {
993
994 // Extended opcode, push registers on user stack
995 uint32 a7 = regs->a[7];
996 a7 -= 4;
997 WriteMacInt32(a7, (uint32)pc);
998 a7 -= 2;
999 WriteMacInt16(a7, scp->sc_ps);
1000 for (int i=7; i>=0; i--) {
1001 a7 -= 4;
1002 WriteMacInt32(a7, regs->a[i]);
1003 }
1004 for (int i=7; i>=0; i--) {
1005 a7 -= 4;
1006 WriteMacInt32(a7, regs->d[i]);
1007 }
1008 scp->sc_sp = regs->a[7] = a7;
1009
1010 // Jump to EmulOp trampoline code on return
1011 scp->sc_pc = (uint32)EmulOpTrampoline;
1012
1013 } else switch (opcode) { // Emulate privileged instructions
1014
1015 case 0x40e7: // move sr,-(sp)
1016 regs->a[7] -= 2;
1017 WriteMacInt16(regs->a[7], GET_SR);
1018 scp->sc_sp = regs->a[7];
1019 INC_PC(2);
1020 break;
1021
1022 case 0x46df: { // move (sp)+,sr
1023 uint16 sr = ReadMacInt16(regs->a[7]);
1024 STORE_SR(sr);
1025 regs->a[7] += 2;
1026 scp->sc_sp = regs->a[7];
1027 INC_PC(2);
1028 break;
1029 }
1030
1031 case 0x007c: { // ori #xxxx,sr
1032 uint16 sr = GET_SR | pc[1];
1033 scp->sc_ps = sr & 0xff; // oring bits into the sr can't enable interrupts, so we don't need to call STORE_SR
1034 EmulatedSR = sr & 0xe700;
1035 INC_PC(4);
1036 break;
1037 }
1038
1039 case 0x027c: { // andi #xxxx,sr
1040 uint16 sr = GET_SR & pc[1];
1041 STORE_SR(sr);
1042 INC_PC(4);
1043 break;
1044 }
1045
1046 case 0x46fc: // move #xxxx,sr
1047 STORE_SR(pc[1]);
1048 INC_PC(4);
1049 break;
1050
1051 case 0x46ef: { // move (xxxx,sp),sr
1052 uint16 sr = ReadMacInt16(regs->a[7] + (int32)(int16)pc[1]);
1053 STORE_SR(sr);
1054 INC_PC(4);
1055 break;
1056 }
1057
1058 case 0x46d8: // move (a0)+,sr
1059 case 0x46d9: { // move (a1)+,sr
1060 uint16 sr = ReadMacInt16(regs->a[opcode & 7]);
1061 STORE_SR(sr);
1062 regs->a[opcode & 7] += 2;
1063 INC_PC(2);
1064 break;
1065 }
1066
1067 case 0x40f8: // move sr,xxxx.w
1068 WriteMacInt16(pc[1], GET_SR);
1069 INC_PC(4);
1070 break;
1071
1072 case 0x40d0: // move sr,(a0)
1073 case 0x40d1: // move sr,(a1)
1074 case 0x40d2: // move sr,(a2)
1075 case 0x40d3: // move sr,(a3)
1076 case 0x40d4: // move sr,(a4)
1077 case 0x40d5: // move sr,(a5)
1078 case 0x40d6: // move sr,(a6)
1079 case 0x40d7: // move sr,(sp)
1080 WriteMacInt16(regs->a[opcode & 7], GET_SR);
1081 INC_PC(2);
1082 break;
1083
1084 case 0x40c0: // move sr,d0
1085 case 0x40c1: // move sr,d1
1086 case 0x40c2: // move sr,d2
1087 case 0x40c3: // move sr,d3
1088 case 0x40c4: // move sr,d4
1089 case 0x40c5: // move sr,d5
1090 case 0x40c6: // move sr,d6
1091 case 0x40c7: // move sr,d7
1092 regs->d[opcode & 7] = GET_SR;
1093 INC_PC(2);
1094 break;
1095
1096 case 0x46c0: // move d0,sr
1097 case 0x46c1: // move d1,sr
1098 case 0x46c2: // move d2,sr
1099 case 0x46c3: // move d3,sr
1100 case 0x46c4: // move d4,sr
1101 case 0x46c5: // move d5,sr
1102 case 0x46c6: // move d6,sr
1103 case 0x46c7: { // move d7,sr
1104 uint16 sr = regs->d[opcode & 7];
1105 STORE_SR(sr);
1106 INC_PC(2);
1107 break;
1108 }
1109
1110 case 0xf327: // fsave -(sp)
1111 regs->a[7] -= 4;
1112 WriteMacInt32(regs->a[7], 0x41000000); // Idle frame
1113 scp->sc_sp = regs->a[7];
1114 INC_PC(2);
1115 break;
1116
1117 case 0xf35f: // frestore (sp)+
1118 regs->a[7] += 4;
1119 scp->sc_sp = regs->a[7];
1120 INC_PC(2);
1121 break;
1122
1123 case 0x4e73: { // rte
1124 uint32 a7 = regs->a[7];
1125 uint16 sr = ReadMacInt16(a7);
1126 a7 += 2;
1127 scp->sc_ps = sr & 0xff;
1128 EmulatedSR = sr & 0xe700;
1129 scp->sc_pc = ReadMacInt32(a7);
1130 a7 += 4;
1131 uint16 format = ReadMacInt16(a7) >> 12;
1132 a7 += 2;
1133 static const int frame_adj[16] = {
1134 0, 0, 4, 4, 8, 0, 0, 52, 50, 12, 24, 84, 16, 0, 0, 0
1135 };
1136 scp->sc_sp = regs->a[7] = a7 + frame_adj[format];
1137 break;
1138 }
1139
1140 case 0x4e7a: // movec cr,x
1141 switch (pc[1]) {
1142 case 0x0002: // movec cacr,d0
1143 regs->d[0] = 0x3111;
1144 break;
1145 case 0x1002: // movec cacr,d1
1146 regs->d[1] = 0x3111;
1147 break;
1148 case 0x0003: // movec tc,d0
1149 case 0x0004: // movec itt0,d0
1150 case 0x0005: // movec itt1,d0
1151 case 0x0006: // movec dtt0,d0
1152 case 0x0007: // movec dtt1,d0
1153 case 0x0806: // movec urp,d0
1154 case 0x0807: // movec srp,d0
1155 regs->d[0] = 0;
1156 break;
1157 case 0x1000: // movec sfc,d1
1158 case 0x1001: // movec dfc,d1
1159 case 0x1003: // movec tc,d1
1160 case 0x1801: // movec vbr,d1
1161 regs->d[1] = 0;
1162 break;
1163 case 0x8801: // movec vbr,a0
1164 regs->a[0] = 0;
1165 break;
1166 case 0x9801: // movec vbr,a1
1167 regs->a[1] = 0;
1168 break;
1169 default:
1170 goto ill;
1171 }
1172 INC_PC(4);
1173 break;
1174
1175 case 0x4e7b: // movec x,cr
1176 switch (pc[1]) {
1177 case 0x1000: // movec d1,sfc
1178 case 0x1001: // movec d1,dfc
1179 case 0x0801: // movec d0,vbr
1180 case 0x1801: // movec d1,vbr
1181 break;
1182 case 0x0002: // movec d0,cacr
1183 case 0x1002: // movec d1,cacr
1184 FlushCodeCache(NULL, 0);
1185 break;
1186 default:
1187 goto ill;
1188 }
1189 INC_PC(4);
1190 break;
1191
1192 case 0xf478: // cpusha dc
1193 case 0xf4f8: // cpusha dc/ic
1194 FlushCodeCache(NULL, 0);
1195 INC_PC(2);
1196 break;
1197
1198 default:
1199 ill: printf("SIGILL num %d, code %d\n", sig, code);
1200 printf(" context %p:\n", scp);
1201 printf(" onstack %08x\n", scp->sc_onstack);
1202 printf(" sp %08x\n", scp->sc_sp);
1203 printf(" fp %08x\n", scp->sc_fp);
1204 printf(" pc %08x\n", scp->sc_pc);
1205 printf(" opcode %04x\n", opcode);
1206 printf(" sr %08x\n", scp->sc_ps);
1207 printf(" state %p:\n", state);
1208 printf(" flags %d\n", state->ss_flags);
1209 for (int i=0; i<8; i++)
1210 printf(" d%d %08x\n", i, state->ss_frame.f_regs[i]);
1211 for (int i=0; i<8; i++)
1212 printf(" a%d %08x\n", i, state->ss_frame.f_regs[i+8]);
1213
1214 VideoQuitFullScreen();
1215 #ifdef ENABLE_MON
1216 char *arg[4] = {"mon", "-m", "-r", NULL};
1217 mon(3, arg);
1218 #endif
1219 QuitEmulator();
1220 break;
1221 }
1222 }
1223 #endif
1224
1225
1226 /*
1227 * Display alert
1228 */
1229
1230 #ifdef ENABLE_GTK
1231 static void dl_destroyed(void)
1232 {
1233 gtk_main_quit();
1234 }
1235
1236 static void dl_quit(GtkWidget *dialog)
1237 {
1238 gtk_widget_destroy(dialog);
1239 }
1240
1241 void display_alert(int title_id, int prefix_id, int button_id, const char *text)
1242 {
1243 char str[256];
1244 sprintf(str, GetString(prefix_id), text);
1245
1246 GtkWidget *dialog = gtk_dialog_new();
1247 gtk_window_set_title(GTK_WINDOW(dialog), GetString(title_id));
1248 gtk_container_border_width(GTK_CONTAINER(dialog), 5);
1249 gtk_widget_set_uposition(GTK_WIDGET(dialog), 100, 150);
1250 gtk_signal_connect(GTK_OBJECT(dialog), "destroy", GTK_SIGNAL_FUNC(dl_destroyed), NULL);
1251
1252 GtkWidget *label = gtk_label_new(str);
1253 gtk_widget_show(label);
1254 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), label, TRUE, TRUE, 0);
1255
1256 GtkWidget *button = gtk_button_new_with_label(GetString(button_id));
1257 gtk_widget_show(button);
1258 gtk_signal_connect_object(GTK_OBJECT(button), "clicked", GTK_SIGNAL_FUNC(dl_quit), GTK_OBJECT(dialog));
1259 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area), button, FALSE, FALSE, 0);
1260 GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1261 gtk_widget_grab_default(button);
1262 gtk_widget_show(dialog);
1263
1264 gtk_main();
1265 }
1266 #endif
1267
1268
1269 /*
1270 * Display error alert
1271 */
1272
1273 void ErrorAlert(const char *text)
1274 {
1275 #ifdef ENABLE_GTK
1276 if (PrefsFindBool("nogui") || x_display == NULL) {
1277 printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1278 return;
1279 }
1280 VideoQuitFullScreen();
1281 display_alert(STR_ERROR_ALERT_TITLE, STR_GUI_ERROR_PREFIX, STR_QUIT_BUTTON, text);
1282 #else
1283 printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1284 #endif
1285 }
1286
1287
1288 /*
1289 * Display warning alert
1290 */
1291
1292 void WarningAlert(const char *text)
1293 {
1294 #ifdef ENABLE_GTK
1295 if (PrefsFindBool("nogui") || x_display == NULL) {
1296 printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1297 return;
1298 }
1299 display_alert(STR_WARNING_ALERT_TITLE, STR_GUI_WARNING_PREFIX, STR_OK_BUTTON, text);
1300 #else
1301 printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1302 #endif
1303 }
1304
1305
1306 /*
1307 * Display choice alert
1308 */
1309
1310 bool ChoiceAlert(const char *text, const char *pos, const char *neg)
1311 {
1312 printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1313 return false; //!!
1314 }