ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Windows/main_windows.cpp
Revision: 1.5
Committed: 2004-12-18T22:21:04Z (19 years, 11 months ago) by gbeauche
Branch: MAIN
Changes since 1.4: +1 -1 lines
Log Message:
s/vm_page_size/vm_get_page_size/

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