ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Windows/main_windows.cpp
Revision: 1.2
Committed: 2004-12-11T08:59:57Z (19 years, 11 months ago) by gbeauche
Branch: MAIN
Changes since 1.1: +0 -3 lines
Log Message:
new NATMEM_OFFSET (0x02000000) makes it possible to allocate space for
the MacOS DR emulator code, though the usual limitations exist there

File Contents

# User Rev Content
1 gbeauche 1.1 /*
2     * main_windows.cpp - Emulation core, Windows implementation
3     *
4     * SheepShaver (C) 1997-2004 Christian Bauer and Marc Hellwig
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 <errno.h>
22     #include <stdio.h>
23     #include <stdlib.h>
24     #include <string.h>
25    
26     #include <SDL.h>
27     #include <SDL_mutex.h>
28     #include <SDL_thread.h>
29    
30     #include "sysdeps.h"
31     #include "main.h"
32     #include "version.h"
33     #include "prefs.h"
34     #include "prefs_editor.h"
35     #include "cpu_emulation.h"
36     #include "emul_op.h"
37     #include "xlowmem.h"
38     #include "xpram.h"
39     #include "timer.h"
40     #include "adb.h"
41     #include "sony.h"
42     #include "disk.h"
43     #include "cdrom.h"
44     #include "scsi.h"
45     #include "video.h"
46     #include "audio.h"
47     #include "ether.h"
48     #include "serial.h"
49     #include "clip.h"
50     #include "extfs.h"
51     #include "sys.h"
52     #include "macos_util.h"
53     #include "rom_patches.h"
54     #include "user_strings.h"
55     #include "vm_alloc.h"
56     #include "sigsegv.h"
57     #include "thunks.h"
58    
59     #define DEBUG 0
60     #include "debug.h"
61    
62     #ifdef ENABLE_MON
63     #include "mon.h"
64     #endif
65    
66    
67     // Constants
68     const char ROM_FILE_NAME[] = "ROM";
69     const char ROM_FILE_NAME2[] = "Mac OS ROM";
70    
71     const uintptr RAM_BASE = 0x10000000; // Base address of RAM
72     const uint32 SIG_STACK_SIZE = 0x10000; // Size of signal stack
73    
74    
75     // Global variables (exported)
76     uint32 RAMBase; // Base address of Mac RAM
77     uint32 RAMSize; // Size of Mac RAM
78     uint32 KernelDataAddr; // Address of Kernel Data
79     uint32 BootGlobsAddr; // Address of BootGlobs structure at top of Mac RAM
80     uint32 DRCacheAddr; // Address of DR Cache
81     uint32 PVR; // Theoretical PVR
82     int64 CPUClockSpeed; // Processor clock speed (Hz)
83     int64 BusClockSpeed; // Bus clock speed (Hz)
84     int64 TimebaseSpeed; // Timebase clock speed (Hz)
85     uint8 *RAMBaseHost; // Base address of Mac RAM (host address space)
86     uint8 *ROMBaseHost; // Base address of Mac ROM (host address space)
87    
88    
89     // Global variables
90     static bool lm_area_mapped = false; // Flag: Low Memory area mmap()ped
91     static int kernel_area = -1; // SHM ID of Kernel Data area
92     static bool rom_area_mapped = false; // Flag: Mac ROM mmap()ped
93     static bool ram_area_mapped = false; // Flag: Mac RAM mmap()ped
94     static bool dr_cache_area_mapped = false; // Flag: Mac DR Cache mmap()ped
95     static bool dr_emulator_area_mapped = false;// Flag: Mac DR Emulator mmap()ped
96     static KernelData *kernel_data; // Pointer to Kernel Data
97     static EmulatorData *emulator_data;
98    
99     static uint8 last_xpram[XPRAM_SIZE]; // Buffer for monitoring XPRAM changes
100     static bool nvram_thread_active = false; // Flag: NVRAM watchdog installed
101     static volatile bool nvram_thread_cancel; // Flag: Cancel NVRAM thread
102     static SDL_Thread *nvram_thread = NULL; // NVRAM watchdog
103     static bool tick_thread_active = false; // Flag: MacOS thread installed
104     static volatile bool tick_thread_cancel; // Flag: Cancel 60Hz thread
105     static SDL_Thread *tick_thread = NULL; // 60Hz thread
106     static SDL_Thread *emul_thread = NULL; // MacOS thread
107     static uintptr sig_stack = 0; // Stack for PowerPC interrupt routine
108    
109     uint32 SheepMem::page_size; // Size of a native page
110     uintptr SheepMem::zero_page = 0; // Address of ro page filled in with zeros
111     uintptr SheepMem::base = 0x60000000; // Address of SheepShaver data
112     uintptr SheepMem::proc; // Bottom address of SheepShave procedures
113     uintptr SheepMem::data; // Top of SheepShaver data (stack like storage)
114    
115    
116     // Prototypes
117     static bool kernel_data_init(void);
118     static void kernel_data_exit(void);
119     static void Quit(void);
120     static int nvram_func(void *arg);
121     static int tick_func(void *arg);
122    
123     static void jump_to_rom(uint32 entry);
124     extern void emul_ppc(uint32 start);
125     extern void init_emul_ppc(void);
126     extern void exit_emul_ppc(void);
127     sigsegv_return_t sigsegv_handler(sigsegv_address_t, sigsegv_address_t);
128    
129    
130     /*
131     * Return signal stack base
132     */
133    
134     uintptr SignalStackBase(void)
135     {
136     return sig_stack + SIG_STACK_SIZE;
137     }
138    
139    
140     /*
141     * Atomic operations
142     */
143    
144     #if HAVE_SPINLOCKS
145     static spinlock_t atomic_ops_lock = SPIN_LOCK_UNLOCKED;
146     #else
147     #define spin_lock(LOCK)
148     #define spin_unlock(LOCK)
149     #endif
150    
151     int atomic_add(int *var, int v)
152     {
153     spin_lock(&atomic_ops_lock);
154     int ret = *var;
155     *var += v;
156     spin_unlock(&atomic_ops_lock);
157     return ret;
158     }
159    
160     int atomic_and(int *var, int v)
161     {
162     spin_lock(&atomic_ops_lock);
163     int ret = *var;
164     *var &= v;
165     spin_unlock(&atomic_ops_lock);
166     return ret;
167     }
168    
169     int atomic_or(int *var, int v)
170     {
171     spin_lock(&atomic_ops_lock);
172     int ret = *var;
173     *var |= v;
174     spin_unlock(&atomic_ops_lock);
175     return ret;
176     }
177    
178    
179     /*
180     * Memory management helpers
181     */
182    
183     static inline int vm_mac_acquire(uint32 addr, uint32 size)
184     {
185     return vm_acquire_fixed(Mac2HostAddr(addr), size);
186     }
187    
188     static inline int vm_mac_release(uint32 addr, uint32 size)
189     {
190     return vm_release(Mac2HostAddr(addr), size);
191     }
192    
193    
194     /*
195     * Main program
196     */
197    
198     static void usage(const char *prg_name)
199     {
200     printf("Usage: %s [OPTION...]\n", prg_name);
201     printf("\nUnix options:\n");
202     printf(" --display STRING\n X display to use\n");
203     PrefsPrintUsage();
204     exit(0);
205     }
206    
207     int main(int argc, char **argv)
208     {
209     char str[256];
210     int16 i16;
211     HANDLE rom_fh;
212     const char *rom_path;
213     uint32 rom_size;
214     DWORD actual;
215     uint8 *rom_tmp;
216    
217     // Initialize variables
218     RAMBase = 0;
219     tzset();
220    
221     // Print some info
222     printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
223     printf(" %s\n", GetString(STR_ABOUT_TEXT2));
224    
225     // Read preferences
226     PrefsInit(argc, argv);
227    
228     // Parse command line arguments
229     for (int i=1; i<argc; i++) {
230     if (strcmp(argv[i], "--help") == 0) {
231     usage(argv[0]);
232     } else if (argv[i][0] == '-') {
233     fprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
234     usage(argv[0]);
235     }
236     }
237    
238     // Initialize SDL system
239     int sdl_flags = 0;
240     #ifdef USE_SDL_VIDEO
241     sdl_flags |= SDL_INIT_VIDEO;
242     #endif
243     #ifdef USE_SDL_AUDIO
244     sdl_flags |= SDL_INIT_AUDIO;
245     #endif
246     assert(sdl_flags != 0);
247     if (SDL_Init(sdl_flags) == -1) {
248     char str[256];
249     sprintf(str, "Could not initialize SDL: %s.\n", SDL_GetError());
250     ErrorAlert(str);
251     goto quit;
252     }
253     atexit(SDL_Quit);
254    
255     #ifdef ENABLE_MON
256     // Initialize mon
257     mon_init();
258     #endif
259    
260     // Install SIGSEGV handler for CPU emulator
261     if (!sigsegv_install_handler(sigsegv_handler)) {
262     sprintf(str, GetString(STR_SIGSEGV_INSTALL_ERR), strerror(errno));
263     ErrorAlert(str);
264     goto quit;
265     }
266    
267     // Initialize VM system
268     vm_init();
269    
270     // Get system info
271     PVR = 0x00040000; // Default: 604
272     CPUClockSpeed = 100000000; // Default: 100MHz
273     BusClockSpeed = 100000000; // Default: 100MHz
274     TimebaseSpeed = 25000000; // Default: 25MHz
275     PVR = 0x000c0000; // Default: 7400 (with AltiVec)
276     D(bug("PVR: %08x (assumed)\n", PVR));
277    
278     // Init system routines
279     SysInit();
280    
281     // Show preferences editor
282     if (!PrefsFindBool("nogui"))
283     if (!PrefsEditor())
284     goto quit;
285    
286     // Create Low Memory area (0x0000..0x3000)
287     if (vm_mac_acquire(0, 0x3000) < 0) {
288     sprintf(str, GetString(STR_LOW_MEM_MMAP_ERR), strerror(errno));
289     ErrorAlert(str);
290     goto quit;
291     }
292     lm_area_mapped = true;
293    
294     // Create areas for Kernel Data
295     if (!kernel_data_init())
296     goto quit;
297     kernel_data = (KernelData *)Mac2HostAddr(KERNEL_DATA_BASE);
298     emulator_data = &kernel_data->ed;
299     KernelDataAddr = KERNEL_DATA_BASE;
300     D(bug("Kernel Data at %p (%08x)\n", kernel_data, KERNEL_DATA_BASE));
301     D(bug("Emulator Data at %p (%08x)\n", emulator_data, KERNEL_DATA_BASE + offsetof(KernelData, ed)));
302    
303     // Create area for DR Cache
304     if (vm_mac_acquire(DR_EMULATOR_BASE, DR_EMULATOR_SIZE) < 0) {
305     sprintf(str, GetString(STR_DR_EMULATOR_MMAP_ERR), strerror(errno));
306     ErrorAlert(str);
307     goto quit;
308     }
309     dr_emulator_area_mapped = true;
310     if (vm_mac_acquire(DR_CACHE_BASE, DR_CACHE_SIZE) < 0) {
311     sprintf(str, GetString(STR_DR_CACHE_MMAP_ERR), strerror(errno));
312     ErrorAlert(str);
313     goto quit;
314     }
315     dr_cache_area_mapped = true;
316     DRCacheAddr = (uint32)Mac2HostAddr(DR_CACHE_BASE);
317     D(bug("DR Cache at %p (%08x)\n", DRCacheAddr, DR_CACHE_BASE));
318    
319     // Create area for SheepShaver data
320     if (!SheepMem::Init()) {
321     sprintf(str, GetString(STR_SHEEP_MEM_MMAP_ERR), strerror(errno));
322     ErrorAlert(str);
323     goto quit;
324     }
325    
326     // Create area for Mac ROM
327     if (vm_mac_acquire(ROM_BASE, ROM_AREA_SIZE) < 0) {
328     sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
329     ErrorAlert(str);
330     goto quit;
331     }
332     ROMBaseHost = Mac2HostAddr(ROM_BASE);
333     rom_area_mapped = true;
334     D(bug("ROM area at %p (%08x)\n", ROMBaseHost, ROM_BASE));
335    
336     // Create area for Mac RAM
337     RAMSize = PrefsFindInt32("ramsize");
338     if (RAMSize < 8*1024*1024) {
339     WarningAlert(GetString(STR_SMALL_RAM_WARN));
340     RAMSize = 8*1024*1024;
341     }
342    
343     if (vm_mac_acquire(RAM_BASE, RAMSize) < 0) {
344     sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
345     ErrorAlert(str);
346     goto quit;
347     }
348     RAMBaseHost = Mac2HostAddr(RAM_BASE);
349     RAMBase = RAM_BASE;
350     ram_area_mapped = true;
351     D(bug("RAM area at %p (%08x)\n", RAMBaseHost, RAMBase));
352    
353     if (RAMBase > ROM_BASE) {
354     ErrorAlert(GetString(STR_RAM_HIGHER_THAN_ROM_ERR));
355     goto quit;
356     }
357    
358     // Load Mac ROM
359     rom_path = PrefsFindString("rom");
360     rom_fh = CreateFile(rom_path ? rom_path : ROM_FILE_NAME,
361     GENERIC_READ, 0, NULL, OPEN_EXISTING,
362     FILE_ATTRIBUTE_NORMAL, NULL);
363    
364     if (rom_fh == INVALID_HANDLE_VALUE) {
365     rom_fh = CreateFile(rom_path ? rom_path : ROM_FILE_NAME2,
366     GENERIC_READ, 0, NULL, OPEN_EXISTING,
367     FILE_ATTRIBUTE_NORMAL, NULL);
368    
369     if (rom_fh == INVALID_HANDLE_VALUE) {
370     ErrorAlert(GetString(STR_NO_ROM_FILE_ERR));
371     goto quit;
372     }
373     }
374     printf(GetString(STR_READING_ROM_FILE));
375     rom_size = GetFileSize(rom_fh, NULL);
376     rom_tmp = new uint8[ROM_SIZE];
377     ReadFile(rom_fh, (void *)rom_tmp, ROM_SIZE, &actual, NULL);
378     CloseHandle(rom_fh);
379    
380     // Decode Mac ROM
381     if (!DecodeROM(rom_tmp, actual)) {
382     if (rom_size != 4*1024*1024) {
383     ErrorAlert(GetString(STR_ROM_SIZE_ERR));
384     goto quit;
385     } else {
386     ErrorAlert(GetString(STR_ROM_FILE_READ_ERR));
387     goto quit;
388     }
389     }
390     delete[] rom_tmp;
391    
392     // Load NVRAM
393     XPRAMInit();
394    
395     // Load XPRAM default values if signature not found
396     if (XPRAM[0x130c] != 0x4e || XPRAM[0x130d] != 0x75
397     || XPRAM[0x130e] != 0x4d || XPRAM[0x130f] != 0x63) {
398     D(bug("Loading XPRAM default values\n"));
399     memset(XPRAM + 0x1300, 0, 0x100);
400     XPRAM[0x130c] = 0x4e; // "NuMc" signature
401     XPRAM[0x130d] = 0x75;
402     XPRAM[0x130e] = 0x4d;
403     XPRAM[0x130f] = 0x63;
404     XPRAM[0x1301] = 0x80; // InternalWaitFlags = DynWait (don't wait for SCSI devices upon bootup)
405     XPRAM[0x1310] = 0xa8; // Standard PRAM values
406     XPRAM[0x1311] = 0x00;
407     XPRAM[0x1312] = 0x00;
408     XPRAM[0x1313] = 0x22;
409     XPRAM[0x1314] = 0xcc;
410     XPRAM[0x1315] = 0x0a;
411     XPRAM[0x1316] = 0xcc;
412     XPRAM[0x1317] = 0x0a;
413     XPRAM[0x131c] = 0x00;
414     XPRAM[0x131d] = 0x02;
415     XPRAM[0x131e] = 0x63;
416     XPRAM[0x131f] = 0x00;
417     XPRAM[0x1308] = 0x13;
418     XPRAM[0x1309] = 0x88;
419     XPRAM[0x130a] = 0x00;
420     XPRAM[0x130b] = 0xcc;
421     XPRAM[0x1376] = 0x00; // OSDefault = MacOS
422     XPRAM[0x1377] = 0x01;
423     }
424    
425     // Set boot volume
426     i16 = PrefsFindInt32("bootdrive");
427     XPRAM[0x1378] = i16 >> 8;
428     XPRAM[0x1379] = i16 & 0xff;
429     i16 = PrefsFindInt32("bootdriver");
430     XPRAM[0x137a] = i16 >> 8;
431     XPRAM[0x137b] = i16 & 0xff;
432    
433     // Create BootGlobs at top of Mac memory
434     memset(RAMBaseHost + RAMSize - 4096, 0, 4096);
435     BootGlobsAddr = RAMBase + RAMSize - 0x1c;
436     WriteMacInt32(BootGlobsAddr - 5 * 4, RAMBase + RAMSize); // MemTop
437     WriteMacInt32(BootGlobsAddr + 0 * 4, RAMBase); // First RAM bank
438     WriteMacInt32(BootGlobsAddr + 1 * 4, RAMSize);
439     WriteMacInt32(BootGlobsAddr + 2 * 4, (uint32)-1); // End of bank table
440    
441     // Init thunks
442     if (!ThunksInit())
443     goto quit;
444    
445     // Init drivers
446     SonyInit();
447     DiskInit();
448     CDROMInit();
449     SCSIInit();
450    
451     // Init external file system
452     ExtFSInit();
453    
454     // Init ADB
455     ADBInit();
456    
457     // Init audio
458     AudioInit();
459    
460     // Init network
461     EtherInit();
462    
463     // Init serial ports
464     SerialInit();
465    
466     // Init Time Manager
467     timer_init();
468    
469     // Init clipboard
470     ClipInit();
471    
472     // Init video
473     if (!VideoInit())
474     goto quit;
475    
476     // Install ROM patches
477     if (!PatchROM()) {
478     ErrorAlert(GetString(STR_UNSUPPORTED_ROM_TYPE_ERR));
479     goto quit;
480     }
481    
482     // Write protect ROM
483     vm_protect(ROMBaseHost, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_EXECUTE);
484    
485     // Initialize Kernel Data
486     memset(kernel_data, 0, sizeof(KernelData));
487     if (ROMType == ROMTYPE_NEWWORLD) {
488     uint32 of_dev_tree = SheepMem::Reserve(4 * sizeof(uint32));
489     Mac_memset(of_dev_tree, 0, 4 * sizeof(uint32));
490     uint32 vector_lookup_tbl = SheepMem::Reserve(128);
491     uint32 vector_mask_tbl = SheepMem::Reserve(64);
492     memset((uint8 *)kernel_data + 0xb80, 0x3d, 0x80);
493     Mac_memset(vector_lookup_tbl, 0, 128);
494     Mac_memset(vector_mask_tbl, 0, 64);
495     kernel_data->v[0xb80 >> 2] = htonl(ROM_BASE);
496     kernel_data->v[0xb84 >> 2] = htonl(of_dev_tree); // OF device tree base
497     kernel_data->v[0xb90 >> 2] = htonl(vector_lookup_tbl);
498     kernel_data->v[0xb94 >> 2] = htonl(vector_mask_tbl);
499     kernel_data->v[0xb98 >> 2] = htonl(ROM_BASE); // OpenPIC base
500     kernel_data->v[0xbb0 >> 2] = htonl(0); // ADB base
501     kernel_data->v[0xc20 >> 2] = htonl(RAMSize);
502     kernel_data->v[0xc24 >> 2] = htonl(RAMSize);
503     kernel_data->v[0xc30 >> 2] = htonl(RAMSize);
504     kernel_data->v[0xc34 >> 2] = htonl(RAMSize);
505     kernel_data->v[0xc38 >> 2] = htonl(0x00010020);
506     kernel_data->v[0xc3c >> 2] = htonl(0x00200001);
507     kernel_data->v[0xc40 >> 2] = htonl(0x00010000);
508     kernel_data->v[0xc50 >> 2] = htonl(RAMBase);
509     kernel_data->v[0xc54 >> 2] = htonl(RAMSize);
510     kernel_data->v[0xf60 >> 2] = htonl(PVR);
511     kernel_data->v[0xf64 >> 2] = htonl(CPUClockSpeed); // clock-frequency
512     kernel_data->v[0xf68 >> 2] = htonl(BusClockSpeed); // bus-frequency
513     kernel_data->v[0xf6c >> 2] = htonl(TimebaseSpeed); // timebase-frequency
514     } else {
515     kernel_data->v[0xc80 >> 2] = htonl(RAMSize);
516     kernel_data->v[0xc84 >> 2] = htonl(RAMSize);
517     kernel_data->v[0xc90 >> 2] = htonl(RAMSize);
518     kernel_data->v[0xc94 >> 2] = htonl(RAMSize);
519     kernel_data->v[0xc98 >> 2] = htonl(0x00010020);
520     kernel_data->v[0xc9c >> 2] = htonl(0x00200001);
521     kernel_data->v[0xca0 >> 2] = htonl(0x00010000);
522     kernel_data->v[0xcb0 >> 2] = htonl(RAMBase);
523     kernel_data->v[0xcb4 >> 2] = htonl(RAMSize);
524     kernel_data->v[0xf80 >> 2] = htonl(PVR);
525     kernel_data->v[0xf84 >> 2] = htonl(CPUClockSpeed); // clock-frequency
526     kernel_data->v[0xf88 >> 2] = htonl(BusClockSpeed); // bus-frequency
527     kernel_data->v[0xf8c >> 2] = htonl(TimebaseSpeed); // timebase-frequency
528     }
529    
530     // Initialize extra low memory
531     D(bug("Initializing Low Memory...\n"));
532     Mac_memset(0, 0, 0x3000);
533     WriteMacInt32(XLM_SIGNATURE, FOURCC('B','a','a','h')); // Signature to detect SheepShaver
534     WriteMacInt32(XLM_KERNEL_DATA, KernelDataAddr); // For trap replacement routines
535     WriteMacInt32(XLM_PVR, PVR); // Theoretical PVR
536     WriteMacInt32(XLM_BUS_CLOCK, BusClockSpeed); // For DriverServicesLib patch
537     WriteMacInt16(XLM_EXEC_RETURN_OPCODE, M68K_EXEC_RETURN); // For Execute68k() (RTS from the executed 68k code will jump here and end 68k mode)
538     WriteMacInt32(XLM_ZERO_PAGE, SheepMem::ZeroPage()); // Pointer to read-only page with all bits set to 0
539     WriteMacInt32(XLM_ETHER_INIT, NativeFunction(NATIVE_ETHER_INIT)); // DLPI ethernet driver functions
540     WriteMacInt32(XLM_ETHER_TERM, NativeFunction(NATIVE_ETHER_TERM));
541     WriteMacInt32(XLM_ETHER_OPEN, NativeFunction(NATIVE_ETHER_OPEN));
542     WriteMacInt32(XLM_ETHER_CLOSE, NativeFunction(NATIVE_ETHER_CLOSE));
543     WriteMacInt32(XLM_ETHER_WPUT, NativeFunction(NATIVE_ETHER_WPUT));
544     WriteMacInt32(XLM_ETHER_RSRV, NativeFunction(NATIVE_ETHER_RSRV));
545     WriteMacInt32(XLM_VIDEO_DOIO, NativeFunction(NATIVE_VIDEO_DO_DRIVER_IO));
546     D(bug("Low Memory initialized\n"));
547    
548     // Start 60Hz thread
549     tick_thread_cancel = false;
550     tick_thread_active = ((tick_thread = SDL_CreateThread(tick_func, NULL)) != NULL);
551     D(bug("Tick thread installed (%ld)\n", tick_thread));
552    
553     // Start NVRAM watchdog thread
554     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
555     nvram_thread_cancel = false;
556     nvram_thread_active = ((nvram_thread = SDL_CreateThread(nvram_func, NULL)) != NULL);
557     D(bug("NVRAM thread installed (%ld)\n", nvram_thread));
558    
559     // Jump to ROM boot routine
560     D(bug("Jumping to ROM\n"));
561     jump_to_rom(ROM_BASE + 0x310000);
562     D(bug("Returned from ROM\n"));
563    
564     quit:
565     Quit();
566     return 0;
567     }
568    
569    
570     /*
571     * Cleanup and quit
572     */
573    
574     static void Quit(void)
575     {
576     // Exit PowerPC emulation
577     exit_emul_ppc();
578    
579     // Stop 60Hz thread
580     if (tick_thread_active) {
581     tick_thread_cancel = true;
582     SDL_WaitThread(tick_thread, NULL);
583     }
584    
585     // Stop NVRAM watchdog thread
586     if (nvram_thread_active) {
587     nvram_thread_cancel = true;
588     SDL_WaitThread(nvram_thread, NULL);
589     }
590    
591     // Save NVRAM
592     XPRAMExit();
593    
594     // Exit clipboard
595     ClipExit();
596    
597     // Exit Time Manager
598     TimerExit();
599    
600     // Exit serial
601     SerialExit();
602    
603     // Exit network
604     EtherExit();
605    
606     // Exit audio
607     AudioExit();
608    
609     // Exit ADB
610     ADBExit();
611    
612     // Exit video
613     VideoExit();
614    
615     // Exit external file system
616     ExtFSExit();
617    
618     // Exit drivers
619     SCSIExit();
620     CDROMExit();
621     DiskExit();
622     SonyExit();
623    
624     // Delete thunks
625     ThunksExit();
626    
627     // Delete SheepShaver globals
628     SheepMem::Exit();
629    
630     // Delete RAM area
631     if (ram_area_mapped)
632     vm_mac_release(RAM_BASE, RAMSize);
633    
634     // Delete ROM area
635     if (rom_area_mapped)
636     vm_mac_release(ROM_BASE, ROM_AREA_SIZE);
637    
638     // Delete DR cache areas
639     if (dr_emulator_area_mapped)
640     vm_mac_release(DR_EMULATOR_BASE, DR_EMULATOR_SIZE);
641     if (dr_cache_area_mapped)
642     vm_mac_release(DR_CACHE_BASE, DR_CACHE_SIZE);
643    
644     // Delete Kernel Data area
645     kernel_data_exit();
646    
647     // Delete Low Memory area
648     if (lm_area_mapped)
649     vm_mac_release(0, 0x3000);
650    
651     // Exit system routines
652     SysExit();
653    
654     // Exit preferences
655     PrefsExit();
656    
657     #ifdef ENABLE_MON
658     // Exit mon
659     mon_exit();
660     #endif
661    
662     exit(0);
663     }
664    
665    
666     /*
667     * Initialize Kernel Data segments
668     */
669    
670     static HANDLE kernel_handle; // Shared memory handle for Kernel Data
671     static DWORD allocation_granule; // Minimum size of allocateable are (64K)
672     static DWORD kernel_area_size; // Size of Kernel Data area
673    
674     static bool kernel_data_init(void)
675     {
676     char str[256];
677     SYSTEM_INFO si;
678     GetSystemInfo(&si);
679     allocation_granule = si.dwAllocationGranularity;
680     kernel_area_size = (KERNEL_AREA_SIZE + allocation_granule - 1) & -allocation_granule;
681    
682     char rcs[10];
683     LPVOID kernel_addr;
684     kernel_handle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, kernel_area_size, NULL);
685     if (kernel_handle == NULL) {
686     sprintf(rcs, "%d", GetLastError());
687     sprintf(str, GetString(STR_KD_SHMGET_ERR), rcs);
688     ErrorAlert(str);
689     return false;
690     }
691     kernel_addr = (LPVOID)Mac2HostAddr(KERNEL_DATA_BASE & -allocation_granule);
692     if (MapViewOfFileEx(kernel_handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, kernel_area_size, kernel_addr) != kernel_addr) {
693     sprintf(rcs, "%d", GetLastError());
694     sprintf(str, GetString(STR_KD_SHMAT_ERR), rcs);
695     ErrorAlert(str);
696     return false;
697     }
698     kernel_addr = (LPVOID)Mac2HostAddr(KERNEL_DATA2_BASE & -allocation_granule);
699     if (MapViewOfFileEx(kernel_handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, kernel_area_size, kernel_addr) != kernel_addr) {
700     sprintf(rcs, "%d", GetLastError());
701     sprintf(str, GetString(STR_KD2_SHMAT_ERR), rcs);
702     ErrorAlert(str);
703     return false;
704     }
705     return true;
706     }
707    
708    
709     /*
710     * Deallocate Kernel Data segments
711     */
712    
713     static void kernel_data_exit(void)
714     {
715     if (kernel_handle) {
716     UnmapViewOfFile(Mac2HostAddr(KERNEL_DATA_BASE & -allocation_granule));
717     UnmapViewOfFile(Mac2HostAddr(KERNEL_DATA2_BASE & -allocation_granule));
718     CloseHandle(kernel_handle);
719     }
720     }
721    
722    
723     /*
724     * Jump into Mac ROM, start 680x0 emulator
725     */
726    
727     void jump_to_rom(uint32 entry)
728     {
729     init_emul_ppc();
730     emul_ppc(entry);
731     }
732    
733    
734     /*
735     * Quit emulator (cause return from jump_to_rom)
736     */
737    
738     void QuitEmulator(void)
739     {
740     Quit();
741     }
742    
743    
744     /*
745     * Pause/resume emulator
746     */
747    
748     void PauseEmulator(void)
749     {
750     // TODO: implement pause/resume
751     }
752    
753     void ResumeEmulator(void)
754     {
755     // TODO: implement pause/resume
756     }
757    
758    
759     /*
760     * Dump 68k registers
761     */
762    
763     void Dump68kRegs(M68kRegisters *r)
764     {
765     // Display 68k registers
766     for (int i=0; i<8; i++) {
767     printf("d%d: %08x", i, r->d[i]);
768     if (i == 3 || i == 7)
769     printf("\n");
770     else
771     printf(", ");
772     }
773     for (int i=0; i<8; i++) {
774     printf("a%d: %08x", i, r->a[i]);
775     if (i == 3 || i == 7)
776     printf("\n");
777     else
778     printf(", ");
779     }
780     }
781    
782    
783     /*
784     * Make code executable
785     */
786    
787     void MakeExecutable(int dummy, uint32 start, uint32 length)
788     {
789     if ((start >= ROM_BASE) && (start < (ROM_BASE + ROM_SIZE)))
790     return;
791     FlushCodeCache(start, start + length);
792     }
793    
794    
795     /*
796     * Patch things after system startup (gets called by disk driver accRun routine)
797     */
798    
799     void PatchAfterStartup(void)
800     {
801     ExecuteNative(NATIVE_VIDEO_INSTALL_ACCEL);
802     InstallExtFS();
803     }
804    
805    
806     /*
807     * NVRAM watchdog thread (saves NVRAM every minute)
808     */
809    
810     static void nvram_watchdog(void)
811     {
812     if (memcmp(last_xpram, XPRAM, XPRAM_SIZE)) {
813     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
814     SaveXPRAM();
815     }
816     }
817    
818     static int nvram_func(void *arg)
819     {
820     while (!nvram_thread_cancel) {
821     for (int i=0; i<60 && !nvram_thread_cancel; i++)
822     Delay_usec(999999); // Only wait 1 second so we quit promptly when nvram_thread_cancel becomes true
823     nvram_watchdog();
824     }
825     return 0;
826     }
827    
828    
829     /*
830     * 60Hz thread (really 60.15Hz)
831     */
832    
833     static int tick_func(void *arg)
834     {
835     int tick_counter = 0;
836     uint64 start = GetTicks_usec();
837     int64 ticks = 0;
838     uint64 next = GetTicks_usec();
839    
840     while (!tick_thread_cancel) {
841    
842     // Wait
843     next += 16625;
844     int64 delay = next - GetTicks_usec();
845     if (delay > 0)
846     Delay_usec(delay);
847     else if (delay < -16625)
848     next = GetTicks_usec();
849     ticks++;
850    
851     // Pseudo Mac 1Hz interrupt, update local time
852     if (++tick_counter > 60) {
853     tick_counter = 0;
854     WriteMacInt32(0x20c, TimerDateTime());
855     }
856    
857     // Trigger 60Hz interrupt
858     if (ReadMacInt32(XLM_IRQ_NEST) == 0) {
859     SetInterruptFlag(INTFLAG_VIA);
860     TriggerInterrupt();
861     }
862     }
863    
864     uint64 end = GetTicks_usec();
865     D(bug("%Ld ticks in %Ld usec = %f ticks/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
866     return 0;
867     }
868    
869    
870     /*
871     * Mutexes
872     */
873    
874     struct B2_mutex {
875     B2_mutex() { m = SDL_CreateMutex(); }
876     ~B2_mutex() { if (m) SDL_DestroyMutex(m); }
877     SDL_mutex *m;
878     };
879    
880     B2_mutex *B2_create_mutex(void)
881     {
882     return new B2_mutex;
883     }
884    
885     void B2_lock_mutex(B2_mutex *mutex)
886     {
887     if (mutex)
888     SDL_LockMutex(mutex->m);
889     }
890    
891     void B2_unlock_mutex(B2_mutex *mutex)
892     {
893     if (mutex)
894     SDL_UnlockMutex(mutex->m);
895     }
896    
897     void B2_delete_mutex(B2_mutex *mutex)
898     {
899     delete mutex;
900     }
901    
902    
903     /*
904     * Interrupt flags (must be handled atomically!)
905     */
906    
907     volatile uint32 InterruptFlags = 0;
908    
909     void SetInterruptFlag(uint32 flag)
910     {
911     atomic_or((int *)&InterruptFlags, flag);
912     }
913    
914     void ClearInterruptFlag(uint32 flag)
915     {
916     atomic_and((int *)&InterruptFlags, ~flag);
917     }
918    
919    
920     /*
921     * Disable interrupts
922     */
923    
924     void DisableInterrupt(void)
925     {
926     WriteMacInt32(XLM_IRQ_NEST, int32(ReadMacInt32(XLM_IRQ_NEST)) + 1);
927     }
928    
929    
930     /*
931     * Enable interrupts
932     */
933    
934     void EnableInterrupt(void)
935     {
936     WriteMacInt32(XLM_IRQ_NEST, int32(ReadMacInt32(XLM_IRQ_NEST)) - 1);
937     }
938    
939    
940     /*
941     * Helpers to share 32-bit addressable data with MacOS
942     */
943    
944     bool SheepMem::Init(void)
945     {
946     // Size of a native page
947     page_size = vm_page_size();
948    
949     // Allocate SheepShaver globals
950     proc = base;
951     if (vm_mac_acquire(base, size) < 0)
952     return false;
953    
954     // Allocate page with all bits set to 0, right in the middle
955     // This is also used to catch undesired overlaps between proc and data areas
956     zero_page = proc + (size / 2);
957     Mac_memset(zero_page, 0, page_size);
958     if (vm_protect(Mac2HostAddr(zero_page), page_size, VM_PAGE_READ) < 0)
959     return false;
960    
961     // Allocate alternate stack for PowerPC interrupt routine
962     sig_stack = base + size;
963     if (vm_mac_acquire(sig_stack, SIG_STACK_SIZE) < 0)
964     return false;
965    
966     data = base + size;
967     return true;
968     }
969    
970     void SheepMem::Exit(void)
971     {
972     if (data) {
973     // Delete SheepShaver globals
974     vm_mac_release(base, size);
975    
976     // Delete alternate stack for PowerPC interrupt routine
977     vm_mac_release(sig_stack, SIG_STACK_SIZE);
978     }
979     }
980    
981    
982     /*
983     * Get the main window handle
984     */
985    
986     #ifdef USE_SDL_VIDEO
987     #include <SDL_syswm.h>
988     static HWND GetMainWindowHandle(void)
989     {
990     SDL_SysWMinfo wmInfo;
991     wmInfo.version.major = SDL_MAJOR_VERSION;
992     wmInfo.version.minor = SDL_MINOR_VERSION;
993     wmInfo.version.patch = SDL_PATCHLEVEL;
994     return SDL_GetWMInfo(&wmInfo) ? wmInfo.window : NULL;
995     }
996     #endif
997    
998    
999     /*
1000     * Display alert
1001     */
1002    
1003     static void display_alert(int title_id, const char *text, int flags)
1004     {
1005     HWND hMainWnd = GetMainWindowHandle();
1006     MessageBox(hMainWnd, text, GetString(title_id), MB_OK | flags);
1007     }
1008    
1009    
1010     /*
1011     * Display error alert
1012     */
1013    
1014     void ErrorAlert(const char *text)
1015     {
1016     if (PrefsFindBool("nogui"))
1017     return;
1018    
1019     VideoQuitFullScreen();
1020     display_alert(STR_ERROR_ALERT_TITLE, text, MB_ICONSTOP);
1021     }
1022    
1023    
1024     /*
1025     * Display warning alert
1026     */
1027    
1028     void WarningAlert(const char *text)
1029     {
1030     if (PrefsFindBool("nogui"))
1031     return;
1032    
1033     display_alert(STR_WARNING_ALERT_TITLE, text, MB_ICONINFORMATION);
1034     }
1035    
1036    
1037     /*
1038     * Display choice alert
1039     */
1040    
1041     bool ChoiceAlert(const char *text, const char *pos, const char *neg)
1042     {
1043     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1044     return false; //!!
1045     }