ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/main_unix.cpp
Revision: 1.71
Committed: 2006-02-27T00:15:39Z (18 years, 8 months ago) by gbeauche
Branch: MAIN
Changes since 1.70: +29 -15 lines
Log Message:
Fix vm_acquire_mac() fallback to non 33-bit addressing mode. Support 33-bit
addressing in REAL_ADDRESSING mode. Only support platforms with proper
linker scripts to map the whole Mac memory from address 0. Warning fix.

NOTE: when compiled with --enable-addressing=real on Linux {x86,x86_64},
you can not address up to 1.5 GB in Basilisk II.

File Contents

# User Rev Content
1 cebix 1.1 /*
2     * main_unix.cpp - Startup code for Unix
3     *
4 gbeauche 1.65 * Basilisk II (C) 1997-2005 Christian Bauer
5 cebix 1.1 *
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 cebix 1.12 #include <errno.h>
27 gbeauche 1.59
28     #ifdef USE_SDL
29     # include <SDL.h>
30     #endif
31    
32     #ifndef USE_SDL_VIDEO
33     # include <X11/Xlib.h>
34     #endif
35 cebix 1.12
36     #ifdef HAVE_PTHREADS
37     # include <pthread.h>
38     #endif
39    
40 cebix 1.27 #if REAL_ADDRESSING || DIRECT_ADDRESSING
41 cebix 1.12 # include <sys/mman.h>
42     #endif
43    
44     #if !EMULATED_68K && defined(__NetBSD__)
45     # include <m68k/sync_icache.h>
46     # include <m68k/frame.h>
47     # include <sys/param.h>
48     # include <sys/sysctl.h>
49     struct sigstate {
50     int ss_flags;
51     struct frame ss_frame;
52     struct fpframe ss_fpstate;
53     };
54     # define SS_FPSTATE 0x02
55     # define SS_USERREGS 0x04
56     #endif
57    
58     #ifdef ENABLE_GTK
59     # include <gtk/gtk.h>
60 cebix 1.28 # include <gdk/gdk.h>
61 cebix 1.43 # ifdef HAVE_GNOMEUI
62     # include <gnome.h>
63     # endif
64 cebix 1.12 #endif
65    
66     #ifdef ENABLE_XF86_DGA
67     # include <X11/Xutil.h>
68     # include <X11/extensions/xf86dga.h>
69     #endif
70 cebix 1.1
71 cebix 1.48 #include <string>
72     using std::string;
73    
74 cebix 1.1 #include "cpu_emulation.h"
75     #include "sys.h"
76 cebix 1.3 #include "rom_patches.h"
77 cebix 1.1 #include "xpram.h"
78     #include "timer.h"
79     #include "video.h"
80 cebix 1.12 #include "emul_op.h"
81 cebix 1.1 #include "prefs.h"
82     #include "prefs_editor.h"
83     #include "macos_util.h"
84     #include "user_strings.h"
85     #include "version.h"
86     #include "main.h"
87 gbeauche 1.33 #include "vm_alloc.h"
88 gbeauche 1.46 #include "sigsegv.h"
89 cebix 1.1
90 gbeauche 1.50 #if USE_JIT
91 gbeauche 1.57 extern void flush_icache_range(uint32 start, uint32 size); // from compemu_support.cpp
92 gbeauche 1.50 #endif
93    
94 cebix 1.12 #ifdef ENABLE_MON
95     # include "mon.h"
96     #endif
97    
98 cebix 1.13 #define DEBUG 0
99 cebix 1.1 #include "debug.h"
100    
101    
102 cebix 1.12 // Constants
103     const char ROM_FILE_NAME[] = "ROM";
104 gbeauche 1.51 #if !EMULATED_68K
105 cebix 1.12 const int SIG_STACK_SIZE = SIGSTKSZ; // Size of signal stack
106 gbeauche 1.51 #endif
107 cebix 1.12 const int SCRATCH_MEM_SIZE = 0x10000; // Size of scratch memory area
108 cebix 1.1
109 cebix 1.4
110 cebix 1.12 #if !EMULATED_68K
111     // RAM and ROM pointers
112     uint32 RAMBaseMac; // RAM base (Mac address space)
113     uint8 *RAMBaseHost; // RAM base (host address space)
114     uint32 RAMSize; // Size of RAM
115     uint32 ROMBaseMac; // ROM base (Mac address space)
116     uint8 *ROMBaseHost; // ROM base (host address space)
117     uint32 ROMSize; // Size of ROM
118 cebix 1.9 #endif
119    
120 cebix 1.1
121     // CPU and FPU type, addressing mode
122     int CPUType;
123     bool CPUIs68060;
124     int FPUType;
125     bool TwentyFourBitAddressing;
126 gbeauche 1.62 bool ThirtyThreeBitAddressing = false;
127 cebix 1.1
128    
129     // Global variables
130 gbeauche 1.59 #ifndef USE_SDL_VIDEO
131     extern char *x_display_name; // X11 display name
132     extern Display *x_display; // X11 display handle
133 gbeauche 1.64 #ifdef X11_LOCK_TYPE
134     X11_LOCK_TYPE x_display_lock = X11_LOCK_INIT; // X11 display lock
135     #endif
136 gbeauche 1.59 #endif
137 cebix 1.1
138 cebix 1.41 static uint8 last_xpram[XPRAM_SIZE]; // Buffer for monitoring XPRAM changes
139 cebix 1.12
140     #ifdef HAVE_PTHREADS
141 gbeauche 1.51 #if !EMULATED_68K
142 cebix 1.12 static pthread_t emul_thread; // Handle of MacOS emulation thread (main thread)
143 gbeauche 1.51 #endif
144 cebix 1.12
145 cebix 1.1 static bool xpram_thread_active = false; // Flag: XPRAM watchdog installed
146     static volatile bool xpram_thread_cancel = false; // Flag: Cancel XPRAM thread
147     static pthread_t xpram_thread; // XPRAM watchdog
148    
149     static bool tick_thread_active = false; // Flag: 60Hz thread installed
150     static volatile bool tick_thread_cancel = false; // Flag: Cancel 60Hz thread
151     static pthread_t tick_thread; // 60Hz thread
152     static pthread_attr_t tick_thread_attr; // 60Hz thread attributes
153    
154     static pthread_mutex_t intflag_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect InterruptFlags
155 cebix 1.37 #define LOCK_INTFLAGS pthread_mutex_lock(&intflag_lock)
156     #define UNLOCK_INTFLAGS pthread_mutex_unlock(&intflag_lock)
157    
158     #else
159    
160     #define LOCK_INTFLAGS
161     #define UNLOCK_INTFLAGS
162    
163 cebix 1.12 #endif
164    
165     #if !EMULATED_68K
166     #define SIG_IRQ SIGUSR1
167     static struct sigaction sigirq_sa; // Virtual 68k interrupt signal
168     static struct sigaction sigill_sa; // Illegal instruction
169     static void *sig_stack = NULL; // Stack for signal handlers
170     uint16 EmulatedSR; // Emulated bits of SR (supervisor bit and interrupt mask)
171 gbeauche 1.20 #endif
172    
173     #if USE_SCRATCHMEM_SUBTERFUGE
174 cebix 1.22 uint8 *ScratchMem = NULL; // Scratch memory for Mac ROM writes
175 cebix 1.12 #endif
176    
177 gbeauche 1.51 #if !defined(HAVE_PTHREADS)
178 cebix 1.12 static struct sigaction timer_sa; // sigaction used for timer
179 cebix 1.1
180     #if defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
181     #define SIG_TIMER SIGRTMIN
182 cebix 1.12 static timer_t timer; // 60Hz timer
183 cebix 1.1 #endif
184 gbeauche 1.51 #endif // !HAVE_PTHREADS
185 cebix 1.1
186 cebix 1.12 #ifdef ENABLE_MON
187     static struct sigaction sigint_sa; // sigaction for SIGINT handler
188 cebix 1.4 static void sigint_handler(...);
189 cebix 1.15 #endif
190    
191     #if REAL_ADDRESSING
192     static bool lm_area_mapped = false; // Flag: Low Memory area mmap()ped
193 cebix 1.22 #endif
194    
195 cebix 1.1
196     // Prototypes
197     static void *xpram_func(void *arg);
198     static void *tick_func(void *arg);
199     static void one_tick(...);
200 cebix 1.12 #if !EMULATED_68K
201     static void sigirq_handler(int sig, int code, struct sigcontext *scp);
202     static void sigill_handler(int sig, int code, struct sigcontext *scp);
203     extern "C" void EmulOpTrampoline(void);
204     #endif
205 cebix 1.1
206    
207     /*
208     * Ersatz functions
209     */
210    
211     extern "C" {
212    
213     #ifndef HAVE_STRDUP
214     char *strdup(const char *s)
215     {
216     char *n = (char *)malloc(strlen(s) + 1);
217     strcpy(n, s);
218     return n;
219     }
220     #endif
221    
222     }
223    
224    
225     /*
226 gbeauche 1.62 * Map memory that can be accessed from the Mac side
227     */
228    
229     void *vm_acquire_mac(size_t size)
230     {
231     void *m = vm_acquire(size, VM_MAP_DEFAULT | VM_MAP_33BIT);
232 gbeauche 1.71 if (m == VM_MAP_FAILED) {
233     printf("WARNING: Cannot acquire memory in 33-bit address space (%s)\n", strerror(errno));
234 gbeauche 1.62 ThirtyThreeBitAddressing = false;
235     m = vm_acquire(size);
236     }
237     return m;
238     }
239    
240 gbeauche 1.71 static int vm_acquire_mac_fixed(void *addr, size_t size)
241     {
242     int ret = vm_acquire_fixed(addr, size, VM_MAP_DEFAULT | VM_MAP_33BIT);
243     if (ret < 0) {
244     printf("WARNING: Cannot acquire fixed memory in 33-bit address space (%s)\n", strerror(errno));
245     ThirtyThreeBitAddressing = false;
246     ret = vm_acquire_fixed(addr, size);
247     }
248     return ret;
249     }
250    
251 gbeauche 1.62
252     /*
253 gbeauche 1.54 * SIGSEGV handler
254     */
255    
256     static sigsegv_return_t sigsegv_handler(sigsegv_address_t fault_address, sigsegv_address_t fault_instruction)
257     {
258     #if ENABLE_VOSF
259     // Handle screen fault
260     extern bool Screen_fault_handler(sigsegv_address_t, sigsegv_address_t);
261     if (Screen_fault_handler(fault_address, fault_instruction))
262     return SIGSEGV_RETURN_SUCCESS;
263     #endif
264    
265     #ifdef HAVE_SIGSEGV_SKIP_INSTRUCTION
266     // Ignore writes to ROM
267     if (((uintptr)fault_address - (uintptr)ROMBaseHost) < ROMSize)
268     return SIGSEGV_RETURN_SKIP_INSTRUCTION;
269    
270     // Ignore all other faults, if requested
271     if (PrefsFindBool("ignoresegv"))
272     return SIGSEGV_RETURN_SKIP_INSTRUCTION;
273     #endif
274    
275     return SIGSEGV_RETURN_FAILURE;
276     }
277    
278     /*
279 gbeauche 1.47 * Dump state when everything went wrong after a SEGV
280     */
281    
282     static void sigsegv_dump_state(sigsegv_address_t fault_address, sigsegv_address_t fault_instruction)
283     {
284 gbeauche 1.50 fprintf(stderr, "Caught SIGSEGV at address %p", fault_address);
285 gbeauche 1.47 if (fault_instruction != SIGSEGV_INVALID_PC)
286     fprintf(stderr, " [IP=%p]", fault_instruction);
287     fprintf(stderr, "\n");
288     #if EMULATED_68K
289     uaecptr nextpc;
290     extern void m68k_dumpstate(uaecptr *nextpc);
291     m68k_dumpstate(&nextpc);
292     #endif
293 gbeauche 1.50 #if USE_JIT && JIT_DEBUG
294     extern void compiler_dumpstate(void);
295     compiler_dumpstate();
296     #endif
297 gbeauche 1.47 VideoQuitFullScreen();
298     #ifdef ENABLE_MON
299     char *arg[4] = {"mon", "-m", "-r", NULL};
300     mon(3, arg);
301 gbeauche 1.66 #endif
302 gbeauche 1.47 QuitEmulator();
303     }
304    
305    
306     /*
307 gbeauche 1.67 * Update virtual clock and trigger interrupts if necessary
308     */
309    
310     #ifdef USE_CPU_EMUL_SERVICES
311     static uint64 n_check_ticks = 0;
312     static uint64 emulated_ticks_start = 0;
313     static uint64 emulated_ticks_count = 0;
314     static int64 emulated_ticks_current = 0;
315     static int32 emulated_ticks_quantum = 1000;
316     int32 emulated_ticks = emulated_ticks_quantum;
317    
318     void cpu_do_check_ticks(void)
319     {
320     #if DEBUG
321     n_check_ticks++;
322     #endif
323    
324     uint64 now;
325     static uint64 next = 0;
326     if (next == 0)
327     next = emulated_ticks_start = GetTicks_usec();
328    
329     // Update total instructions count
330     if (emulated_ticks <= 0) {
331     emulated_ticks_current += (emulated_ticks_quantum - emulated_ticks);
332     // XXX: can you really have a machine fast enough to overflow
333     // a 63-bit m68k instruction counter within 16 ms?
334     if (emulated_ticks_current < 0) {
335     printf("WARNING: Overflowed 63-bit m68k instruction counter in less than 16 ms!\n");
336     goto recalibrate_quantum;
337     }
338     }
339    
340     // Check for interrupt opportunity
341     now = GetTicks_usec();
342     if (next < now) {
343     one_tick();
344     do {
345     next += 16625;
346     } while (next < now);
347     emulated_ticks_count++;
348    
349     // Recalibrate 1000 Hz quantum every 10 ticks
350     static uint64 last = 0;
351     if (last == 0)
352     last = now;
353     else if (now - last > 166250) {
354     recalibrate_quantum:
355     emulated_ticks_quantum = ((uint64)emulated_ticks_current * 1000) / (now - last);
356     emulated_ticks_current = 0;
357     last = now;
358     }
359     }
360    
361     // Update countdown
362     if (emulated_ticks <= 0)
363     emulated_ticks += emulated_ticks_quantum;
364     }
365     #endif
366    
367    
368     /*
369 cebix 1.1 * Main program
370     */
371    
372 cebix 1.32 static void usage(const char *prg_name)
373     {
374 cebix 1.48 printf(
375     "Usage: %s [OPTION...]\n"
376     "\nUnix options:\n"
377     " --config FILE\n read/write configuration from/to FILE\n"
378     " --display STRING\n X display to use\n"
379     " --break ADDRESS\n set ROM breakpoint\n"
380     " --rominfo\n dump ROM information\n", prg_name
381     );
382     LoadPrefs(); // read the prefs file so PrefsPrintUsage() will print the correct default values
383 cebix 1.32 PrefsPrintUsage();
384     exit(0);
385     }
386    
387 cebix 1.1 int main(int argc, char **argv)
388     {
389 cebix 1.12 char str[256];
390    
391 cebix 1.1 // Initialize variables
392     RAMBaseHost = NULL;
393     ROMBaseHost = NULL;
394     srand(time(NULL));
395     tzset();
396    
397     // Print some info
398     printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
399     printf(" %s\n", GetString(STR_ABOUT_TEXT2));
400    
401 cebix 1.48 // Parse command line arguments
402     for (int i=1; i<argc; i++) {
403     if (strcmp(argv[i], "--help") == 0) {
404     usage(argv[0]);
405 gbeauche 1.59 #ifndef USE_SDL_VIDEO
406 cebix 1.48 } else if (strcmp(argv[i], "--display") == 0) {
407     i++; // don't remove the argument, gtk_init() needs it too
408     if (i < argc)
409     x_display_name = strdup(argv[i]);
410 gbeauche 1.59 #endif
411 cebix 1.48 } else if (strcmp(argv[i], "--break") == 0) {
412     argv[i++] = NULL;
413     if (i < argc) {
414     ROMBreakpoint = strtol(argv[i], NULL, 0);
415     argv[i] = NULL;
416     }
417     } else if (strcmp(argv[i], "--config") == 0) {
418     argv[i++] = NULL;
419     if (i < argc) {
420     extern string UserPrefsPath; // from prefs_unix.cpp
421     UserPrefsPath = argv[i];
422     argv[i] = NULL;
423     }
424     } else if (strcmp(argv[i], "--rominfo") == 0) {
425     argv[i] = NULL;
426     PrintROMInfo = true;
427     }
428     }
429    
430     // Remove processed arguments
431     for (int i=1; i<argc; i++) {
432     int k;
433     for (k=i; k<argc; k++)
434     if (argv[k] != NULL)
435     break;
436     if (k > i) {
437     k -= i;
438     for (int j=i+k; j<argc; j++)
439     argv[j-k] = argv[j];
440     argc -= k;
441     }
442     }
443    
444 cebix 1.28 #ifdef ENABLE_GTK
445 cebix 1.43 #ifdef HAVE_GNOMEUI
446     // Init GNOME/GTK
447     char version[16];
448     sprintf(version, "%d.%d", VERSION_MAJOR, VERSION_MINOR);
449     gnome_init("Basilisk II", version, argc, argv);
450     #else
451 cebix 1.28 // Init GTK
452     gtk_set_locale();
453     gtk_init(&argc, &argv);
454 cebix 1.43 #endif
455 cebix 1.28 #endif
456    
457 cebix 1.32 // Read preferences
458     PrefsInit(argc, argv);
459    
460 cebix 1.48 // Any command line arguments left?
461 cebix 1.1 for (int i=1; i<argc; i++) {
462 cebix 1.48 if (argv[i][0] == '-') {
463 cebix 1.32 fprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
464     usage(argv[0]);
465 cebix 1.28 }
466 cebix 1.1 }
467    
468 gbeauche 1.59 #ifndef USE_SDL_VIDEO
469 cebix 1.1 // Open display
470     x_display = XOpenDisplay(x_display_name);
471     if (x_display == NULL) {
472     char str[256];
473     sprintf(str, GetString(STR_NO_XSERVER_ERR), XDisplayName(x_display_name));
474     ErrorAlert(str);
475     QuitEmulator();
476     }
477    
478 cebix 1.12 #if defined(ENABLE_XF86_DGA) && !defined(ENABLE_MON)
479 cebix 1.1 // Fork out, so we can return from fullscreen mode when things get ugly
480 cebix 1.2 XF86DGAForkApp(DefaultScreen(x_display));
481 cebix 1.1 #endif
482 gbeauche 1.59 #endif
483    
484     #ifdef USE_SDL
485     // Initialize SDL system
486     int sdl_flags = 0;
487     #ifdef USE_SDL_VIDEO
488     sdl_flags |= SDL_INIT_VIDEO;
489     #endif
490 gbeauche 1.61 #ifdef USE_SDL_AUDIO
491     sdl_flags |= SDL_INIT_AUDIO;
492     #endif
493 gbeauche 1.59 assert(sdl_flags != 0);
494     if (SDL_Init(sdl_flags) == -1) {
495     char str[256];
496     sprintf(str, "Could not initialize SDL: %s.\n", SDL_GetError());
497     ErrorAlert(str);
498     QuitEmulator();
499     }
500 gbeauche 1.60 atexit(SDL_Quit);
501 gbeauche 1.59 #endif
502 cebix 1.1
503     // Init system routines
504     SysInit();
505    
506     // Show preferences editor
507     if (!PrefsFindBool("nogui"))
508     if (!PrefsEditor())
509     QuitEmulator();
510 gbeauche 1.46
511 gbeauche 1.54 // Install the handler for SIGSEGV
512 gbeauche 1.55 if (!sigsegv_install_handler(sigsegv_handler)) {
513     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGSEGV", strerror(errno));
514     ErrorAlert(str);
515     QuitEmulator();
516     }
517 gbeauche 1.54
518 gbeauche 1.47 // Register dump state function when we got mad after a segfault
519     sigsegv_set_dump_state(sigsegv_dump_state);
520 cebix 1.1
521 cebix 1.9 // Read RAM size
522 cebix 1.1 RAMSize = PrefsFindInt32("ramsize") & 0xfff00000; // Round down to 1MB boundary
523     if (RAMSize < 1024*1024) {
524     WarningAlert(GetString(STR_SMALL_RAM_WARN));
525     RAMSize = 1024*1024;
526     }
527 cebix 1.9
528 gbeauche 1.20 #if REAL_ADDRESSING || DIRECT_ADDRESSING
529 gbeauche 1.33 RAMSize = RAMSize & -getpagesize(); // Round down to page boundary
530 gbeauche 1.20 #endif
531 gbeauche 1.33
532     // Initialize VM system
533     vm_init();
534 gbeauche 1.20
535 gbeauche 1.71 #ifdef USE_33BIT_ADDRESSING
536     // Speculatively enables 33-bit addressing
537     ThirtyThreeBitAddressing = true;
538     #endif
539    
540 cebix 1.12 #if REAL_ADDRESSING
541 gbeauche 1.33 // Flag: RAM and ROM are contigously allocated from address 0
542     bool memory_mapped_from_zero = false;
543 gbeauche 1.71
544     // Make sure to map RAM & ROM at address 0 only on platforms that
545     // supports linker scripts to relocate the Basilisk II executable
546     // above 0x70000000
547     #if HAVE_LINKER_SCRIPT
548     const bool can_map_all_memory = true;
549     #else
550 gbeauche 1.33 const bool can_map_all_memory = false;
551 gbeauche 1.20 #endif
552 gbeauche 1.33
553     // Try to allocate all memory from 0x0000, if it is not known to crash
554 gbeauche 1.71 if (can_map_all_memory && (vm_acquire_mac_fixed(0, RAMSize + 0x100000) == 0)) {
555 gbeauche 1.20 D(bug("Could allocate RAM and ROM from 0x0000\n"));
556     memory_mapped_from_zero = true;
557     }
558 gbeauche 1.33
559 gbeauche 1.56 #ifndef PAGEZERO_HACK
560 gbeauche 1.33 // Otherwise, just create the Low Memory area (0x0000..0x2000)
561 gbeauche 1.71 else if (vm_acquire_mac_fixed(0, 0x2000) == 0) {
562 gbeauche 1.20 D(bug("Could allocate the Low Memory globals\n"));
563     lm_area_mapped = true;
564     }
565 gbeauche 1.33
566     // Exit on failure
567 gbeauche 1.20 else {
568 cebix 1.12 sprintf(str, GetString(STR_LOW_MEM_MMAP_ERR), strerror(errno));
569     ErrorAlert(str);
570     QuitEmulator();
571     }
572     #endif
573 gbeauche 1.56 #endif /* REAL_ADDRESSING */
574 cebix 1.12
575 cebix 1.9 // Create areas for Mac RAM and ROM
576 gbeauche 1.20 #if REAL_ADDRESSING
577     if (memory_mapped_from_zero) {
578     RAMBaseHost = (uint8 *)0;
579 gbeauche 1.33 ROMBaseHost = RAMBaseHost + RAMSize;
580 gbeauche 1.20 }
581     else
582     #endif
583     {
584 gbeauche 1.69 uint8 *ram_rom_area = (uint8 *)vm_acquire_mac(RAMSize + 0x100000);
585     if (ram_rom_area == VM_MAP_FAILED) {
586 cebix 1.36 ErrorAlert(STR_NO_MEM_ERR);
587 gbeauche 1.20 QuitEmulator();
588     }
589 gbeauche 1.69 RAMBaseHost = ram_rom_area;
590     ROMBaseHost = RAMBaseHost + RAMSize;
591 gbeauche 1.20 }
592 gbeauche 1.38
593     #if USE_SCRATCHMEM_SUBTERFUGE
594     // Allocate scratch memory
595     ScratchMem = (uint8 *)vm_acquire(SCRATCH_MEM_SIZE);
596     if (ScratchMem == VM_MAP_FAILED) {
597     ErrorAlert(STR_NO_MEM_ERR);
598     QuitEmulator();
599     }
600     ScratchMem += SCRATCH_MEM_SIZE/2; // ScratchMem points to middle of block
601     #endif
602 cebix 1.22
603 gbeauche 1.20 #if DIRECT_ADDRESSING
604 gbeauche 1.33 // RAMBaseMac shall always be zero
605     MEMBaseDiff = (uintptr)RAMBaseHost;
606 gbeauche 1.20 RAMBaseMac = 0;
607 gbeauche 1.33 ROMBaseMac = Host2MacAddr(ROMBaseHost);
608 gbeauche 1.20 #endif
609 gbeauche 1.33 #if REAL_ADDRESSING
610 gbeauche 1.71 RAMBaseMac = Host2MacAddr(RAMBaseHost);
611     ROMBaseMac = Host2MacAddr(ROMBaseHost);
612 cebix 1.12 #endif
613     D(bug("Mac RAM starts at %p (%08x)\n", RAMBaseHost, RAMBaseMac));
614     D(bug("Mac ROM starts at %p (%08x)\n", ROMBaseHost, ROMBaseMac));
615 gbeauche 1.20
616 cebix 1.1 // Get rom file path from preferences
617     const char *rom_path = PrefsFindString("rom");
618    
619     // Load Mac ROM
620     int rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME, O_RDONLY);
621     if (rom_fd < 0) {
622 cebix 1.36 ErrorAlert(STR_NO_ROM_FILE_ERR);
623 cebix 1.1 QuitEmulator();
624     }
625     printf(GetString(STR_READING_ROM_FILE));
626     ROMSize = lseek(rom_fd, 0, SEEK_END);
627     if (ROMSize != 64*1024 && ROMSize != 128*1024 && ROMSize != 256*1024 && ROMSize != 512*1024 && ROMSize != 1024*1024) {
628 cebix 1.36 ErrorAlert(STR_ROM_SIZE_ERR);
629 cebix 1.1 close(rom_fd);
630     QuitEmulator();
631     }
632     lseek(rom_fd, 0, SEEK_SET);
633     if (read(rom_fd, ROMBaseHost, ROMSize) != (ssize_t)ROMSize) {
634 cebix 1.36 ErrorAlert(STR_ROM_FILE_READ_ERR);
635 cebix 1.1 close(rom_fd);
636     QuitEmulator();
637     }
638    
639 cebix 1.12 #if !EMULATED_68K
640     // Get CPU model
641     int mib[2] = {CTL_HW, HW_MODEL};
642     char *model;
643     size_t model_len;
644     sysctl(mib, 2, NULL, &model_len, NULL, 0);
645     model = (char *)malloc(model_len);
646     sysctl(mib, 2, model, &model_len, NULL, 0);
647     D(bug("Model: %s\n", model));
648    
649     // Set CPU and FPU type
650     CPUIs68060 = false;
651     if (strstr(model, "020"))
652     CPUType = 2;
653     else if (strstr(model, "030"))
654     CPUType = 3;
655     else if (strstr(model, "040"))
656     CPUType = 4;
657     else if (strstr(model, "060")) {
658     CPUType = 4;
659     CPUIs68060 = true;
660     } else {
661     printf("WARNING: Cannot detect CPU type, assuming 68020\n");
662     CPUType = 2;
663     }
664 cebix 1.24 FPUType = 1; // NetBSD has an FPU emulation, so the FPU ought to be available at all times
665 cebix 1.12 TwentyFourBitAddressing = false;
666     #endif
667    
668 cebix 1.3 // Initialize everything
669     if (!InitAll())
670 cebix 1.1 QuitEmulator();
671 cebix 1.12 D(bug("Initialization complete\n"));
672    
673 gbeauche 1.51 #if !EMULATED_68K
674     // (Virtual) supervisor mode, disable interrupts
675     EmulatedSR = 0x2700;
676    
677 cebix 1.12 #ifdef HAVE_PTHREADS
678     // Get handle of main thread
679     emul_thread = pthread_self();
680     #endif
681    
682     // Create and install stack for signal handlers
683     sig_stack = malloc(SIG_STACK_SIZE);
684     D(bug("Signal stack at %p\n", sig_stack));
685     if (sig_stack == NULL) {
686 cebix 1.36 ErrorAlert(STR_NOT_ENOUGH_MEMORY_ERR);
687 cebix 1.12 QuitEmulator();
688     }
689     stack_t new_stack;
690     new_stack.ss_sp = sig_stack;
691     new_stack.ss_flags = 0;
692     new_stack.ss_size = SIG_STACK_SIZE;
693     if (sigaltstack(&new_stack, NULL) < 0) {
694     sprintf(str, GetString(STR_SIGALTSTACK_ERR), strerror(errno));
695     ErrorAlert(str);
696     QuitEmulator();
697     }
698    
699     // Install SIGILL handler for emulating privileged instructions and
700     // executing A-Trap and EMUL_OP opcodes
701     sigemptyset(&sigill_sa.sa_mask); // Block virtual 68k interrupts during SIGILL handling
702     sigaddset(&sigill_sa.sa_mask, SIG_IRQ);
703     sigaddset(&sigill_sa.sa_mask, SIGALRM);
704     sigill_sa.sa_handler = (void (*)(int))sigill_handler;
705     sigill_sa.sa_flags = SA_ONSTACK;
706     if (sigaction(SIGILL, &sigill_sa, NULL) < 0) {
707     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGILL", strerror(errno));
708     ErrorAlert(str);
709     QuitEmulator();
710     }
711    
712     // Install virtual 68k interrupt signal handler
713     sigemptyset(&sigirq_sa.sa_mask);
714     sigaddset(&sigirq_sa.sa_mask, SIGALRM);
715     sigirq_sa.sa_handler = (void (*)(int))sigirq_handler;
716     sigirq_sa.sa_flags = SA_ONSTACK | SA_RESTART;
717     if (sigaction(SIG_IRQ, &sigirq_sa, NULL) < 0) {
718     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIG_IRQ", strerror(errno));
719     ErrorAlert(str);
720     QuitEmulator();
721     }
722     #endif
723 cebix 1.1
724 cebix 1.12 #ifdef ENABLE_MON
725     // Setup SIGINT handler to enter mon
726     sigemptyset(&sigint_sa.sa_mask);
727 cebix 1.21 sigint_sa.sa_handler = (void (*)(int))sigint_handler;
728 cebix 1.12 sigint_sa.sa_flags = 0;
729     sigaction(SIGINT, &sigint_sa, NULL);
730     #endif
731 cebix 1.1
732 gbeauche 1.67 #ifndef USE_CPU_EMUL_SERVICES
733 cebix 1.39 #if defined(HAVE_PTHREADS)
734    
735     // POSIX threads available, start 60Hz thread
736 cebix 1.44 Set_pthread_attr(&tick_thread_attr, 0);
737 cebix 1.39 tick_thread_active = (pthread_create(&tick_thread, &tick_thread_attr, tick_func, NULL) == 0);
738     if (!tick_thread_active) {
739     sprintf(str, GetString(STR_TICK_THREAD_ERR), strerror(errno));
740     ErrorAlert(str);
741     QuitEmulator();
742     }
743     D(bug("60Hz thread started\n"));
744    
745     #elif defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
746 cebix 1.12
747     // POSIX.4 timers and real-time signals available, start 60Hz timer
748 cebix 1.1 sigemptyset(&timer_sa.sa_mask);
749 cebix 1.19 timer_sa.sa_sigaction = (void (*)(int, siginfo_t *, void *))one_tick;
750 cebix 1.1 timer_sa.sa_flags = SA_SIGINFO | SA_RESTART;
751     if (sigaction(SIG_TIMER, &timer_sa, NULL) < 0) {
752 cebix 1.12 sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIG_TIMER", strerror(errno));
753     ErrorAlert(str);
754 cebix 1.1 QuitEmulator();
755     }
756     struct sigevent timer_event;
757     timer_event.sigev_notify = SIGEV_SIGNAL;
758     timer_event.sigev_signo = SIG_TIMER;
759     if (timer_create(CLOCK_REALTIME, &timer_event, &timer) < 0) {
760 cebix 1.12 sprintf(str, GetString(STR_TIMER_CREATE_ERR), strerror(errno));
761     ErrorAlert(str);
762 cebix 1.1 QuitEmulator();
763     }
764     struct itimerspec req;
765     req.it_value.tv_sec = 0;
766     req.it_value.tv_nsec = 16625000;
767     req.it_interval.tv_sec = 0;
768     req.it_interval.tv_nsec = 16625000;
769 cebix 1.10 if (timer_settime(timer, 0, &req, NULL) < 0) {
770 cebix 1.12 sprintf(str, GetString(STR_TIMER_SETTIME_ERR), strerror(errno));
771     ErrorAlert(str);
772 cebix 1.1 QuitEmulator();
773     }
774 cebix 1.12 D(bug("60Hz timer started\n"));
775 cebix 1.1
776 cebix 1.12 #else
777    
778     // Start 60Hz timer
779     sigemptyset(&timer_sa.sa_mask); // Block virtual 68k interrupts during SIGARLM handling
780 cebix 1.53 #if !EMULATED_68K
781 cebix 1.12 sigaddset(&timer_sa.sa_mask, SIG_IRQ);
782 cebix 1.53 #endif
783 cebix 1.12 timer_sa.sa_handler = one_tick;
784     timer_sa.sa_flags = SA_ONSTACK | SA_RESTART;
785     if (sigaction(SIGALRM, &timer_sa, NULL) < 0) {
786     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGALRM", strerror(errno));
787     ErrorAlert(str);
788 cebix 1.1 QuitEmulator();
789     }
790 cebix 1.12 struct itimerval req;
791     req.it_interval.tv_sec = req.it_value.tv_sec = 0;
792     req.it_interval.tv_usec = req.it_value.tv_usec = 16625;
793     setitimer(ITIMER_REAL, &req, NULL);
794    
795 cebix 1.1 #endif
796 gbeauche 1.67 #endif
797 cebix 1.1
798 gbeauche 1.67 #ifdef USE_PTHREADS_SERVICES
799 cebix 1.12 // Start XPRAM watchdog thread
800 cebix 1.41 memcpy(last_xpram, XPRAM, XPRAM_SIZE);
801 cebix 1.12 xpram_thread_active = (pthread_create(&xpram_thread, NULL, xpram_func, NULL) == 0);
802     D(bug("XPRAM thread started\n"));
803 cebix 1.4 #endif
804    
805 cebix 1.1 // Start 68k and jump to ROM boot routine
806 cebix 1.12 D(bug("Starting emulation...\n"));
807 cebix 1.1 Start680x0();
808    
809     QuitEmulator();
810     return 0;
811     }
812    
813    
814     /*
815     * Quit emulator
816     */
817    
818     void QuitEmulator(void)
819     {
820 cebix 1.12 D(bug("QuitEmulator\n"));
821    
822     #if EMULATED_68K
823 cebix 1.1 // Exit 680x0 emulation
824     Exit680x0();
825 cebix 1.12 #endif
826 cebix 1.1
827 gbeauche 1.67 #if defined(USE_CPU_EMUL_SERVICES)
828     // Show statistics
829     uint64 emulated_ticks_end = GetTicks_usec();
830     D(bug("%ld ticks in %ld usec = %f ticks/sec [%ld tick checks]\n",
831     (long)emulated_ticks_count, (long)(emulated_ticks_end - emulated_ticks_start),
832     emulated_ticks_count * 1000000.0 / (emulated_ticks_end - emulated_ticks_start), (long)n_check_ticks));
833     #elif defined(USE_PTHREADS_SERVICES)
834 cebix 1.1 // Stop 60Hz thread
835     if (tick_thread_active) {
836     tick_thread_cancel = true;
837     #ifdef HAVE_PTHREAD_CANCEL
838     pthread_cancel(tick_thread);
839     #endif
840     pthread_join(tick_thread, NULL);
841     }
842 cebix 1.39 #elif defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
843     // Stop 60Hz timer
844     timer_delete(timer);
845 cebix 1.12 #else
846     struct itimerval req;
847     req.it_interval.tv_sec = req.it_value.tv_sec = 0;
848     req.it_interval.tv_usec = req.it_value.tv_usec = 0;
849     setitimer(ITIMER_REAL, &req, NULL);
850 cebix 1.1 #endif
851    
852 gbeauche 1.67 #ifdef USE_PTHREADS_SERVICES
853 cebix 1.1 // Stop XPRAM watchdog thread
854     if (xpram_thread_active) {
855     xpram_thread_cancel = true;
856     #ifdef HAVE_PTHREAD_CANCEL
857     pthread_cancel(xpram_thread);
858     #endif
859     pthread_join(xpram_thread, NULL);
860     }
861 cebix 1.12 #endif
862 cebix 1.1
863 cebix 1.3 // Deinitialize everything
864     ExitAll();
865 cebix 1.1
866 cebix 1.22 // Free ROM/RAM areas
867 gbeauche 1.33 if (RAMBaseHost != VM_MAP_FAILED) {
868 gbeauche 1.69 vm_release(RAMBaseHost, RAMSize + 0x100000);
869 cebix 1.22 RAMBaseHost = NULL;
870 cebix 1.17 ROMBaseHost = NULL;
871     }
872 cebix 1.1
873 cebix 1.22 #if USE_SCRATCHMEM_SUBTERFUGE
874 cebix 1.12 // Delete scratch memory area
875 gbeauche 1.33 if (ScratchMem != (uint8 *)VM_MAP_FAILED) {
876     vm_release((void *)(ScratchMem - SCRATCH_MEM_SIZE/2), SCRATCH_MEM_SIZE);
877 cebix 1.17 ScratchMem = NULL;
878     }
879 cebix 1.12 #endif
880    
881     #if REAL_ADDRESSING
882     // Delete Low Memory area
883     if (lm_area_mapped)
884 gbeauche 1.33 vm_release(0, 0x2000);
885 cebix 1.12 #endif
886 gbeauche 1.33
887     // Exit VM wrappers
888     vm_exit();
889 cebix 1.12
890 cebix 1.1 // Exit system routines
891     SysExit();
892    
893     // Exit preferences
894     PrefsExit();
895    
896     // Close X11 server connection
897 gbeauche 1.60 #ifndef USE_SDL_VIDEO
898 cebix 1.1 if (x_display)
899     XCloseDisplay(x_display);
900 gbeauche 1.59 #endif
901 cebix 1.1
902     exit(0);
903     }
904    
905    
906     /*
907     * Code was patched, flush caches if neccessary (i.e. when using a real 680x0
908     * or a dynamically recompiling emulator)
909     */
910    
911     void FlushCodeCache(void *start, uint32 size)
912     {
913 gbeauche 1.50 #if USE_JIT
914     if (UseJIT)
915 gbeauche 1.57 flush_icache_range((uintptr)start, size);
916 gbeauche 1.50 #endif
917 cebix 1.12 #if !EMULATED_68K && defined(__NetBSD__)
918     m68k_sync_icache(start, size);
919     #endif
920 cebix 1.4 }
921    
922    
923     /*
924     * SIGINT handler, enters mon
925     */
926    
927 cebix 1.12 #ifdef ENABLE_MON
928 cebix 1.4 static void sigint_handler(...)
929     {
930 cebix 1.12 #if EMULATED_68K
931 cebix 1.8 uaecptr nextpc;
932 cebix 1.12 extern void m68k_dumpstate(uaecptr *nextpc);
933 cebix 1.8 m68k_dumpstate(&nextpc);
934 cebix 1.34 #endif
935 cebix 1.37 VideoQuitFullScreen();
936 cebix 1.21 char *arg[4] = {"mon", "-m", "-r", NULL};
937     mon(3, arg);
938 cebix 1.4 QuitEmulator();
939 cebix 1.1 }
940     #endif
941    
942    
943 cebix 1.44 #ifdef HAVE_PTHREADS
944     /*
945 cebix 1.45 * Pthread configuration
946 cebix 1.44 */
947 cebix 1.45
948     void Set_pthread_attr(pthread_attr_t *attr, int priority)
949 cebix 1.44 {
950     pthread_attr_init(attr);
951     #if defined(_POSIX_THREAD_PRIORITY_SCHEDULING)
952     // Some of these only work for superuser
953     if (geteuid() == 0) {
954     pthread_attr_setinheritsched(attr, PTHREAD_EXPLICIT_SCHED);
955     pthread_attr_setschedpolicy(attr, SCHED_FIFO);
956     struct sched_param fifo_param;
957     fifo_param.sched_priority = ((sched_get_priority_min(SCHED_FIFO) +
958     sched_get_priority_max(SCHED_FIFO)) / 2 +
959     priority);
960     pthread_attr_setschedparam(attr, &fifo_param);
961     }
962     if (pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM) != 0) {
963     #ifdef PTHREAD_SCOPE_BOUND_NP
964     // If system scope is not available (eg. we're not running
965     // with CAP_SCHED_MGT capability on an SGI box), try bound
966     // scope. It exposes pthread scheduling to the kernel,
967     // without setting realtime priority.
968     pthread_attr_setscope(attr, PTHREAD_SCOPE_BOUND_NP);
969     #endif
970     }
971     #endif
972     }
973     #endif // HAVE_PTHREADS
974    
975    
976 cebix 1.1 /*
977 cebix 1.37 * Mutexes
978     */
979    
980     #ifdef HAVE_PTHREADS
981    
982     struct B2_mutex {
983 cebix 1.44 B2_mutex() {
984     pthread_mutexattr_t attr;
985     pthread_mutexattr_init(&attr);
986     // Initialize the mutex for priority inheritance --
987     // required for accurate timing.
988 gbeauche 1.63 #if defined(HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL) && !defined(__CYGWIN__)
989 cebix 1.44 pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
990     #endif
991     #if defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE) && defined(PTHREAD_MUTEX_NORMAL)
992     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
993     #endif
994 gbeauche 1.49 #ifdef HAVE_PTHREAD_MUTEXATTR_SETPSHARED
995 cebix 1.44 pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);
996 gbeauche 1.49 #endif
997 cebix 1.44 pthread_mutex_init(&m, &attr);
998     pthread_mutexattr_destroy(&attr);
999     }
1000 gbeauche 1.51 ~B2_mutex() {
1001     pthread_mutex_trylock(&m); // Make sure it's locked before
1002     pthread_mutex_unlock(&m); // unlocking it.
1003     pthread_mutex_destroy(&m);
1004     }
1005 cebix 1.37 pthread_mutex_t m;
1006     };
1007    
1008     B2_mutex *B2_create_mutex(void)
1009     {
1010     return new B2_mutex;
1011     }
1012    
1013     void B2_lock_mutex(B2_mutex *mutex)
1014     {
1015     pthread_mutex_lock(&mutex->m);
1016     }
1017    
1018     void B2_unlock_mutex(B2_mutex *mutex)
1019     {
1020     pthread_mutex_unlock(&mutex->m);
1021     }
1022    
1023     void B2_delete_mutex(B2_mutex *mutex)
1024     {
1025     delete mutex;
1026     }
1027    
1028     #else
1029    
1030     struct B2_mutex {
1031     int dummy;
1032     };
1033    
1034     B2_mutex *B2_create_mutex(void)
1035     {
1036     return new B2_mutex;
1037     }
1038    
1039     void B2_lock_mutex(B2_mutex *mutex)
1040     {
1041     }
1042    
1043     void B2_unlock_mutex(B2_mutex *mutex)
1044     {
1045     }
1046    
1047     void B2_delete_mutex(B2_mutex *mutex)
1048     {
1049     delete mutex;
1050     }
1051    
1052     #endif
1053    
1054    
1055     /*
1056 cebix 1.1 * Interrupt flags (must be handled atomically!)
1057     */
1058    
1059     uint32 InterruptFlags = 0;
1060    
1061 cebix 1.12 #if EMULATED_68K
1062 cebix 1.1 void SetInterruptFlag(uint32 flag)
1063     {
1064 cebix 1.37 LOCK_INTFLAGS;
1065 cebix 1.1 InterruptFlags |= flag;
1066 cebix 1.37 UNLOCK_INTFLAGS;
1067 cebix 1.1 }
1068    
1069     void ClearInterruptFlag(uint32 flag)
1070     {
1071 cebix 1.37 LOCK_INTFLAGS;
1072 cebix 1.1 InterruptFlags &= ~flag;
1073 cebix 1.37 UNLOCK_INTFLAGS;
1074 cebix 1.12 }
1075     #endif
1076    
1077     #if !EMULATED_68K
1078     void TriggerInterrupt(void)
1079     {
1080     #if defined(HAVE_PTHREADS)
1081     pthread_kill(emul_thread, SIG_IRQ);
1082     #else
1083     raise(SIG_IRQ);
1084     #endif
1085 cebix 1.22 }
1086    
1087     void TriggerNMI(void)
1088     {
1089     // not yet supported
1090 cebix 1.12 }
1091     #endif
1092    
1093    
1094     /*
1095     * XPRAM watchdog thread (saves XPRAM every minute)
1096     */
1097    
1098     static void xpram_watchdog(void)
1099     {
1100 cebix 1.41 if (memcmp(last_xpram, XPRAM, XPRAM_SIZE)) {
1101     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
1102 cebix 1.12 SaveXPRAM();
1103     }
1104     }
1105    
1106 gbeauche 1.67 #ifdef USE_PTHREADS_SERVICES
1107 cebix 1.12 static void *xpram_func(void *arg)
1108     {
1109     while (!xpram_thread_cancel) {
1110 cebix 1.16 for (int i=0; i<60 && !xpram_thread_cancel; i++)
1111 cebix 1.29 Delay_usec(999999); // Only wait 1 second so we quit promptly when xpram_thread_cancel becomes true
1112 cebix 1.12 xpram_watchdog();
1113     }
1114     return NULL;
1115 cebix 1.1 }
1116 cebix 1.12 #endif
1117 cebix 1.1
1118    
1119     /*
1120     * 60Hz thread (really 60.15Hz)
1121     */
1122    
1123 cebix 1.12 static void one_second(void)
1124     {
1125     // Pseudo Mac 1Hz interrupt, update local time
1126     WriteMacInt32(0x20c, TimerDateTime());
1127    
1128 cebix 1.18 SetInterruptFlag(INTFLAG_1HZ);
1129 cebix 1.14 TriggerInterrupt();
1130    
1131 gbeauche 1.67 #ifndef USE_PTHREADS_SERVICES
1132 cebix 1.12 static int second_counter = 0;
1133     if (++second_counter > 60) {
1134     second_counter = 0;
1135     xpram_watchdog();
1136     }
1137     #endif
1138     }
1139    
1140 cebix 1.1 static void one_tick(...)
1141     {
1142     static int tick_counter = 0;
1143     if (++tick_counter > 60) {
1144     tick_counter = 0;
1145 cebix 1.12 one_second();
1146 cebix 1.1 }
1147    
1148 gbeauche 1.70 #ifndef USE_PTHREADS_SERVICES
1149     // Threads not used to trigger interrupts, perform video refresh from here
1150 cebix 1.12 VideoRefresh();
1151 gbeauche 1.70 #endif
1152    
1153     #ifndef HAVE_PTHREADS
1154     // No threads available, perform networking from here
1155 cebix 1.40 SetInterruptFlag(INTFLAG_ETHER);
1156 cebix 1.12 #endif
1157    
1158 cebix 1.1 // Trigger 60Hz interrupt
1159     if (ROMVersion != ROM_VERSION_CLASSIC || HasMacStarted()) {
1160     SetInterruptFlag(INTFLAG_60HZ);
1161     TriggerInterrupt();
1162     }
1163     }
1164    
1165 gbeauche 1.67 #ifdef USE_PTHREADS_SERVICES
1166 cebix 1.1 static void *tick_func(void *arg)
1167     {
1168 cebix 1.39 uint64 start = GetTicks_usec();
1169     int64 ticks = 0;
1170 cebix 1.16 uint64 next = GetTicks_usec();
1171 cebix 1.1 while (!tick_thread_cancel) {
1172 cebix 1.16 one_tick();
1173     next += 16625;
1174     int64 delay = next - GetTicks_usec();
1175     if (delay > 0)
1176     Delay_usec(delay);
1177     else if (delay < -16625)
1178     next = GetTicks_usec();
1179 cebix 1.39 ticks++;
1180 cebix 1.16 }
1181 cebix 1.39 uint64 end = GetTicks_usec();
1182 gbeauche 1.68 D(bug("%lld ticks in %lld usec = %f ticks/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
1183 cebix 1.16 return NULL;
1184     }
1185     #endif
1186 cebix 1.12
1187    
1188     #if !EMULATED_68K
1189     /*
1190     * Virtual 68k interrupt handler
1191     */
1192    
1193     static void sigirq_handler(int sig, int code, struct sigcontext *scp)
1194     {
1195     // Interrupts disabled? Then do nothing
1196     if (EmulatedSR & 0x0700)
1197     return;
1198    
1199     struct sigstate *state = (struct sigstate *)scp->sc_ap;
1200     M68kRegisters *regs = (M68kRegisters *)&state->ss_frame;
1201    
1202     // Set up interrupt frame on stack
1203     uint32 a7 = regs->a[7];
1204     a7 -= 2;
1205     WriteMacInt16(a7, 0x64);
1206     a7 -= 4;
1207     WriteMacInt32(a7, scp->sc_pc);
1208     a7 -= 2;
1209     WriteMacInt16(a7, scp->sc_ps | EmulatedSR);
1210     scp->sc_sp = regs->a[7] = a7;
1211    
1212     // Set interrupt level
1213     EmulatedSR |= 0x2100;
1214    
1215     // Jump to MacOS interrupt handler on return
1216     scp->sc_pc = ReadMacInt32(0x64);
1217     }
1218 cebix 1.1
1219    
1220     /*
1221 cebix 1.12 * SIGILL handler, for emulation of privileged instructions and executing
1222     * A-Trap and EMUL_OP opcodes
1223 cebix 1.1 */
1224    
1225 cebix 1.12 static void sigill_handler(int sig, int code, struct sigcontext *scp)
1226 cebix 1.1 {
1227 cebix 1.12 struct sigstate *state = (struct sigstate *)scp->sc_ap;
1228     uint16 *pc = (uint16 *)scp->sc_pc;
1229     uint16 opcode = *pc;
1230     M68kRegisters *regs = (M68kRegisters *)&state->ss_frame;
1231    
1232     #define INC_PC(n) scp->sc_pc += (n)
1233    
1234     #define GET_SR (scp->sc_ps | EmulatedSR)
1235    
1236     #define STORE_SR(v) \
1237     scp->sc_ps = (v) & 0xff; \
1238 cebix 1.24 EmulatedSR = (v) & 0xe700; \
1239 cebix 1.12 if (((v) & 0x0700) == 0 && InterruptFlags) \
1240     TriggerInterrupt();
1241    
1242     //printf("opcode %04x at %p, sr %04x, emul_sr %04x\n", opcode, pc, scp->sc_ps, EmulatedSR);
1243    
1244     if ((opcode & 0xf000) == 0xa000) {
1245    
1246     // A-Line instruction, set up A-Line trap frame on stack
1247     uint32 a7 = regs->a[7];
1248     a7 -= 2;
1249     WriteMacInt16(a7, 0x28);
1250     a7 -= 4;
1251     WriteMacInt32(a7, (uint32)pc);
1252     a7 -= 2;
1253     WriteMacInt16(a7, GET_SR);
1254     scp->sc_sp = regs->a[7] = a7;
1255    
1256     // Jump to MacOS A-Line handler on return
1257     scp->sc_pc = ReadMacInt32(0x28);
1258    
1259     } else if ((opcode & 0xff00) == 0x7100) {
1260    
1261     // Extended opcode, push registers on user stack
1262     uint32 a7 = regs->a[7];
1263     a7 -= 4;
1264     WriteMacInt32(a7, (uint32)pc);
1265     a7 -= 2;
1266     WriteMacInt16(a7, scp->sc_ps);
1267     for (int i=7; i>=0; i--) {
1268     a7 -= 4;
1269     WriteMacInt32(a7, regs->a[i]);
1270     }
1271     for (int i=7; i>=0; i--) {
1272     a7 -= 4;
1273     WriteMacInt32(a7, regs->d[i]);
1274     }
1275     scp->sc_sp = regs->a[7] = a7;
1276    
1277     // Jump to EmulOp trampoline code on return
1278     scp->sc_pc = (uint32)EmulOpTrampoline;
1279    
1280     } else switch (opcode) { // Emulate privileged instructions
1281    
1282     case 0x40e7: // move sr,-(sp)
1283     regs->a[7] -= 2;
1284     WriteMacInt16(regs->a[7], GET_SR);
1285     scp->sc_sp = regs->a[7];
1286     INC_PC(2);
1287     break;
1288    
1289     case 0x46df: { // move (sp)+,sr
1290     uint16 sr = ReadMacInt16(regs->a[7]);
1291     STORE_SR(sr);
1292     regs->a[7] += 2;
1293     scp->sc_sp = regs->a[7];
1294     INC_PC(2);
1295     break;
1296     }
1297    
1298     case 0x007c: { // ori #xxxx,sr
1299     uint16 sr = GET_SR | pc[1];
1300     scp->sc_ps = sr & 0xff; // oring bits into the sr can't enable interrupts, so we don't need to call STORE_SR
1301 cebix 1.24 EmulatedSR = sr & 0xe700;
1302 cebix 1.12 INC_PC(4);
1303     break;
1304     }
1305    
1306     case 0x027c: { // andi #xxxx,sr
1307     uint16 sr = GET_SR & pc[1];
1308     STORE_SR(sr);
1309     INC_PC(4);
1310     break;
1311     }
1312    
1313     case 0x46fc: // move #xxxx,sr
1314     STORE_SR(pc[1]);
1315     INC_PC(4);
1316     break;
1317    
1318     case 0x46ef: { // move (xxxx,sp),sr
1319     uint16 sr = ReadMacInt16(regs->a[7] + (int32)(int16)pc[1]);
1320     STORE_SR(sr);
1321     INC_PC(4);
1322     break;
1323     }
1324    
1325     case 0x46d8: // move (a0)+,sr
1326     case 0x46d9: { // move (a1)+,sr
1327     uint16 sr = ReadMacInt16(regs->a[opcode & 7]);
1328     STORE_SR(sr);
1329     regs->a[opcode & 7] += 2;
1330     INC_PC(2);
1331     break;
1332     }
1333 cebix 1.1
1334 cebix 1.12 case 0x40f8: // move sr,xxxx.w
1335     WriteMacInt16(pc[1], GET_SR);
1336     INC_PC(4);
1337     break;
1338    
1339     case 0x40d0: // move sr,(a0)
1340     case 0x40d1: // move sr,(a1)
1341     case 0x40d2: // move sr,(a2)
1342     case 0x40d3: // move sr,(a3)
1343     case 0x40d4: // move sr,(a4)
1344     case 0x40d5: // move sr,(a5)
1345     case 0x40d6: // move sr,(a6)
1346     case 0x40d7: // move sr,(sp)
1347     WriteMacInt16(regs->a[opcode & 7], GET_SR);
1348     INC_PC(2);
1349     break;
1350    
1351     case 0x40c0: // move sr,d0
1352     case 0x40c1: // move sr,d1
1353     case 0x40c2: // move sr,d2
1354     case 0x40c3: // move sr,d3
1355     case 0x40c4: // move sr,d4
1356     case 0x40c5: // move sr,d5
1357     case 0x40c6: // move sr,d6
1358     case 0x40c7: // move sr,d7
1359     regs->d[opcode & 7] = GET_SR;
1360     INC_PC(2);
1361     break;
1362    
1363     case 0x46c0: // move d0,sr
1364     case 0x46c1: // move d1,sr
1365     case 0x46c2: // move d2,sr
1366     case 0x46c3: // move d3,sr
1367     case 0x46c4: // move d4,sr
1368     case 0x46c5: // move d5,sr
1369     case 0x46c6: // move d6,sr
1370     case 0x46c7: { // move d7,sr
1371     uint16 sr = regs->d[opcode & 7];
1372     STORE_SR(sr);
1373     INC_PC(2);
1374     break;
1375 cebix 1.1 }
1376 cebix 1.12
1377     case 0xf327: // fsave -(sp)
1378 cebix 1.35 regs->a[7] -= 4;
1379     WriteMacInt32(regs->a[7], 0x41000000); // Idle frame
1380 cebix 1.24 scp->sc_sp = regs->a[7];
1381     INC_PC(2);
1382     break;
1383 cebix 1.12
1384     case 0xf35f: // frestore (sp)+
1385 cebix 1.35 regs->a[7] += 4;
1386 cebix 1.24 scp->sc_sp = regs->a[7];
1387     INC_PC(2);
1388     break;
1389 cebix 1.12
1390 cebix 1.24 case 0x4e73: { // rte
1391 cebix 1.12 uint32 a7 = regs->a[7];
1392     uint16 sr = ReadMacInt16(a7);
1393     a7 += 2;
1394     scp->sc_ps = sr & 0xff;
1395 cebix 1.24 EmulatedSR = sr & 0xe700;
1396 cebix 1.12 scp->sc_pc = ReadMacInt32(a7);
1397 cebix 1.24 a7 += 4;
1398     uint16 format = ReadMacInt16(a7) >> 12;
1399     a7 += 2;
1400     static const int frame_adj[16] = {
1401     0, 0, 4, 4, 8, 0, 0, 52, 50, 12, 24, 84, 16, 0, 0, 0
1402     };
1403     scp->sc_sp = regs->a[7] = a7 + frame_adj[format];
1404 cebix 1.12 break;
1405 cebix 1.1 }
1406 cebix 1.12
1407     case 0x4e7a: // movec cr,x
1408     switch (pc[1]) {
1409     case 0x0002: // movec cacr,d0
1410     regs->d[0] = 0x3111;
1411     break;
1412     case 0x1002: // movec cacr,d1
1413     regs->d[1] = 0x3111;
1414     break;
1415     case 0x0003: // movec tc,d0
1416 cebix 1.24 case 0x0004: // movec itt0,d0
1417     case 0x0005: // movec itt1,d0
1418     case 0x0006: // movec dtt0,d0
1419     case 0x0007: // movec dtt1,d0
1420     case 0x0806: // movec urp,d0
1421     case 0x0807: // movec srp,d0
1422 cebix 1.12 regs->d[0] = 0;
1423     break;
1424 cebix 1.24 case 0x1000: // movec sfc,d1
1425     case 0x1001: // movec dfc,d1
1426 cebix 1.12 case 0x1003: // movec tc,d1
1427 cebix 1.24 case 0x1801: // movec vbr,d1
1428 cebix 1.12 regs->d[1] = 0;
1429     break;
1430 cebix 1.24 case 0x8801: // movec vbr,a0
1431     regs->a[0] = 0;
1432     break;
1433     case 0x9801: // movec vbr,a1
1434     regs->a[1] = 0;
1435     break;
1436 cebix 1.12 default:
1437     goto ill;
1438     }
1439     INC_PC(4);
1440     break;
1441    
1442     case 0x4e7b: // movec x,cr
1443     switch (pc[1]) {
1444 cebix 1.24 case 0x1000: // movec d1,sfc
1445     case 0x1001: // movec d1,dfc
1446 cebix 1.12 case 0x0801: // movec d0,vbr
1447 cebix 1.24 case 0x1801: // movec d1,vbr
1448 cebix 1.12 break;
1449     case 0x0002: // movec d0,cacr
1450     case 0x1002: // movec d1,cacr
1451     FlushCodeCache(NULL, 0);
1452     break;
1453     default:
1454     goto ill;
1455     }
1456     INC_PC(4);
1457     break;
1458    
1459     case 0xf478: // cpusha dc
1460     case 0xf4f8: // cpusha dc/ic
1461     FlushCodeCache(NULL, 0);
1462     INC_PC(2);
1463     break;
1464    
1465     default:
1466     ill: printf("SIGILL num %d, code %d\n", sig, code);
1467     printf(" context %p:\n", scp);
1468     printf(" onstack %08x\n", scp->sc_onstack);
1469     printf(" sp %08x\n", scp->sc_sp);
1470     printf(" fp %08x\n", scp->sc_fp);
1471     printf(" pc %08x\n", scp->sc_pc);
1472     printf(" opcode %04x\n", opcode);
1473     printf(" sr %08x\n", scp->sc_ps);
1474     printf(" state %p:\n", state);
1475     printf(" flags %d\n", state->ss_flags);
1476     for (int i=0; i<8; i++)
1477     printf(" d%d %08x\n", i, state->ss_frame.f_regs[i]);
1478     for (int i=0; i<8; i++)
1479     printf(" a%d %08x\n", i, state->ss_frame.f_regs[i+8]);
1480    
1481 cebix 1.37 VideoQuitFullScreen();
1482 cebix 1.12 #ifdef ENABLE_MON
1483 cebix 1.21 char *arg[4] = {"mon", "-m", "-r", NULL};
1484     mon(3, arg);
1485 cebix 1.12 #endif
1486     QuitEmulator();
1487     break;
1488 cebix 1.1 }
1489     }
1490 cebix 1.12 #endif
1491 cebix 1.1
1492    
1493     /*
1494     * Display alert
1495     */
1496    
1497 cebix 1.12 #ifdef ENABLE_GTK
1498 cebix 1.1 static void dl_destroyed(void)
1499     {
1500     gtk_main_quit();
1501     }
1502    
1503     static void dl_quit(GtkWidget *dialog)
1504     {
1505     gtk_widget_destroy(dialog);
1506     }
1507    
1508     void display_alert(int title_id, int prefix_id, int button_id, const char *text)
1509     {
1510     char str[256];
1511     sprintf(str, GetString(prefix_id), text);
1512    
1513     GtkWidget *dialog = gtk_dialog_new();
1514     gtk_window_set_title(GTK_WINDOW(dialog), GetString(title_id));
1515     gtk_container_border_width(GTK_CONTAINER(dialog), 5);
1516     gtk_widget_set_uposition(GTK_WIDGET(dialog), 100, 150);
1517     gtk_signal_connect(GTK_OBJECT(dialog), "destroy", GTK_SIGNAL_FUNC(dl_destroyed), NULL);
1518    
1519     GtkWidget *label = gtk_label_new(str);
1520     gtk_widget_show(label);
1521     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), label, TRUE, TRUE, 0);
1522    
1523     GtkWidget *button = gtk_button_new_with_label(GetString(button_id));
1524     gtk_widget_show(button);
1525     gtk_signal_connect_object(GTK_OBJECT(button), "clicked", GTK_SIGNAL_FUNC(dl_quit), GTK_OBJECT(dialog));
1526     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area), button, FALSE, FALSE, 0);
1527     GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1528     gtk_widget_grab_default(button);
1529     gtk_widget_show(dialog);
1530    
1531     gtk_main();
1532     }
1533     #endif
1534    
1535    
1536     /*
1537     * Display error alert
1538     */
1539    
1540     void ErrorAlert(const char *text)
1541     {
1542 gbeauche 1.59 #if defined(ENABLE_GTK) && !defined(USE_SDL_VIDEO)
1543 cebix 1.1 if (PrefsFindBool("nogui") || x_display == NULL) {
1544     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1545     return;
1546     }
1547     VideoQuitFullScreen();
1548     display_alert(STR_ERROR_ALERT_TITLE, STR_GUI_ERROR_PREFIX, STR_QUIT_BUTTON, text);
1549     #else
1550     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1551     #endif
1552     }
1553    
1554    
1555     /*
1556     * Display warning alert
1557     */
1558    
1559     void WarningAlert(const char *text)
1560     {
1561 gbeauche 1.59 #if defined(ENABLE_GTK) && !defined(USE_SDL_VIDEO)
1562 cebix 1.1 if (PrefsFindBool("nogui") || x_display == NULL) {
1563     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1564     return;
1565     }
1566     display_alert(STR_WARNING_ALERT_TITLE, STR_GUI_WARNING_PREFIX, STR_OK_BUTTON, text);
1567     #else
1568     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1569     #endif
1570     }
1571    
1572    
1573     /*
1574     * Display choice alert
1575     */
1576    
1577     bool ChoiceAlert(const char *text, const char *pos, const char *neg)
1578     {
1579     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1580     return false; //!!
1581     }