ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Windows/main_windows.cpp
Revision: 1.3
Committed: 2004-12-11T09:42:34Z (19 years, 11 months ago) by gbeauche
Branch: MAIN
Changes since 1.2: +18 -15 lines
Log Message:
native windows threads, set a higher thread priority to the tick thread,
implement Pause/ResumeEmulator()

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    
29     #include "sysdeps.h"
30     #include "main.h"
31     #include "version.h"
32     #include "prefs.h"
33     #include "prefs_editor.h"
34     #include "cpu_emulation.h"
35     #include "emul_op.h"
36     #include "xlowmem.h"
37     #include "xpram.h"
38     #include "timer.h"
39     #include "adb.h"
40     #include "sony.h"
41     #include "disk.h"
42     #include "cdrom.h"
43     #include "scsi.h"
44     #include "video.h"
45     #include "audio.h"
46     #include "ether.h"
47     #include "serial.h"
48     #include "clip.h"
49     #include "extfs.h"
50     #include "sys.h"
51     #include "macos_util.h"
52     #include "rom_patches.h"
53     #include "user_strings.h"
54     #include "vm_alloc.h"
55     #include "sigsegv.h"
56     #include "thunks.h"
57 gbeauche 1.3 #include "util_windows.h"
58 gbeauche 1.1
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 gbeauche 1.3 static HANDLE nvram_thread = NULL; // NVRAM watchdog
103 gbeauche 1.1 static bool tick_thread_active = false; // Flag: MacOS thread installed
104     static volatile bool tick_thread_cancel; // Flag: Cancel 60Hz thread
105 gbeauche 1.3 static HANDLE tick_thread = NULL; // 60Hz thread
106     static HANDLE emul_thread = NULL; // MacOS thread
107 gbeauche 1.1 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 gbeauche 1.3 static DWORD WINAPI nvram_func(void *arg);
121     static DWORD WINAPI tick_func(void *arg);
122 gbeauche 1.1
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 gbeauche 1.3 tick_thread_active = ((tick_thread = create_thread(tick_func)) != NULL);
551     SetThreadPriority(tick_thread, THREAD_PRIORITY_ABOVE_NORMAL);
552 gbeauche 1.1 D(bug("Tick thread installed (%ld)\n", tick_thread));
553    
554     // Start NVRAM watchdog thread
555     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
556     nvram_thread_cancel = false;
557 gbeauche 1.3 nvram_thread_active = ((nvram_thread = create_thread(nvram_func, NULL)) != NULL);
558     SetThreadPriority(nvram_thread, THREAD_PRIORITY_BELOW_NORMAL);
559 gbeauche 1.1 D(bug("NVRAM thread installed (%ld)\n", nvram_thread));
560    
561 gbeauche 1.3 // Get my thread ID and jump to ROM boot routine
562     emul_thread = GetCurrentThread();
563 gbeauche 1.1 D(bug("Jumping to ROM\n"));
564     jump_to_rom(ROM_BASE + 0x310000);
565     D(bug("Returned from ROM\n"));
566    
567     quit:
568     Quit();
569     return 0;
570     }
571    
572    
573     /*
574     * Cleanup and quit
575     */
576    
577     static void Quit(void)
578     {
579     // Exit PowerPC emulation
580     exit_emul_ppc();
581    
582     // Stop 60Hz thread
583     if (tick_thread_active) {
584     tick_thread_cancel = true;
585 gbeauche 1.3 wait_thread(tick_thread);
586 gbeauche 1.1 }
587    
588     // Stop NVRAM watchdog thread
589     if (nvram_thread_active) {
590     nvram_thread_cancel = true;
591 gbeauche 1.3 wait_thread(nvram_thread);
592 gbeauche 1.1 }
593    
594     // Save NVRAM
595     XPRAMExit();
596    
597     // Exit clipboard
598     ClipExit();
599    
600     // Exit Time Manager
601     TimerExit();
602    
603     // Exit serial
604     SerialExit();
605    
606     // Exit network
607     EtherExit();
608    
609     // Exit audio
610     AudioExit();
611    
612     // Exit ADB
613     ADBExit();
614    
615     // Exit video
616     VideoExit();
617    
618     // Exit external file system
619     ExtFSExit();
620    
621     // Exit drivers
622     SCSIExit();
623     CDROMExit();
624     DiskExit();
625     SonyExit();
626    
627     // Delete thunks
628     ThunksExit();
629    
630     // Delete SheepShaver globals
631     SheepMem::Exit();
632    
633     // Delete RAM area
634     if (ram_area_mapped)
635     vm_mac_release(RAM_BASE, RAMSize);
636    
637     // Delete ROM area
638     if (rom_area_mapped)
639     vm_mac_release(ROM_BASE, ROM_AREA_SIZE);
640    
641     // Delete DR cache areas
642     if (dr_emulator_area_mapped)
643     vm_mac_release(DR_EMULATOR_BASE, DR_EMULATOR_SIZE);
644     if (dr_cache_area_mapped)
645     vm_mac_release(DR_CACHE_BASE, DR_CACHE_SIZE);
646    
647     // Delete Kernel Data area
648     kernel_data_exit();
649    
650     // Delete Low Memory area
651     if (lm_area_mapped)
652     vm_mac_release(0, 0x3000);
653    
654     // Exit system routines
655     SysExit();
656    
657     // Exit preferences
658     PrefsExit();
659    
660     #ifdef ENABLE_MON
661     // Exit mon
662     mon_exit();
663     #endif
664    
665     exit(0);
666     }
667    
668    
669     /*
670     * Initialize Kernel Data segments
671     */
672    
673     static HANDLE kernel_handle; // Shared memory handle for Kernel Data
674     static DWORD allocation_granule; // Minimum size of allocateable are (64K)
675     static DWORD kernel_area_size; // Size of Kernel Data area
676    
677     static bool kernel_data_init(void)
678     {
679     char str[256];
680     SYSTEM_INFO si;
681     GetSystemInfo(&si);
682     allocation_granule = si.dwAllocationGranularity;
683     kernel_area_size = (KERNEL_AREA_SIZE + allocation_granule - 1) & -allocation_granule;
684    
685     char rcs[10];
686     LPVOID kernel_addr;
687     kernel_handle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, kernel_area_size, NULL);
688     if (kernel_handle == NULL) {
689     sprintf(rcs, "%d", GetLastError());
690     sprintf(str, GetString(STR_KD_SHMGET_ERR), rcs);
691     ErrorAlert(str);
692     return false;
693     }
694     kernel_addr = (LPVOID)Mac2HostAddr(KERNEL_DATA_BASE & -allocation_granule);
695     if (MapViewOfFileEx(kernel_handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, kernel_area_size, kernel_addr) != kernel_addr) {
696     sprintf(rcs, "%d", GetLastError());
697     sprintf(str, GetString(STR_KD_SHMAT_ERR), rcs);
698     ErrorAlert(str);
699     return false;
700     }
701     kernel_addr = (LPVOID)Mac2HostAddr(KERNEL_DATA2_BASE & -allocation_granule);
702     if (MapViewOfFileEx(kernel_handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, kernel_area_size, kernel_addr) != kernel_addr) {
703     sprintf(rcs, "%d", GetLastError());
704     sprintf(str, GetString(STR_KD2_SHMAT_ERR), rcs);
705     ErrorAlert(str);
706     return false;
707     }
708     return true;
709     }
710    
711    
712     /*
713     * Deallocate Kernel Data segments
714     */
715    
716     static void kernel_data_exit(void)
717     {
718     if (kernel_handle) {
719     UnmapViewOfFile(Mac2HostAddr(KERNEL_DATA_BASE & -allocation_granule));
720     UnmapViewOfFile(Mac2HostAddr(KERNEL_DATA2_BASE & -allocation_granule));
721     CloseHandle(kernel_handle);
722     }
723     }
724    
725    
726     /*
727     * Jump into Mac ROM, start 680x0 emulator
728     */
729    
730     void jump_to_rom(uint32 entry)
731     {
732     init_emul_ppc();
733     emul_ppc(entry);
734     }
735    
736    
737     /*
738     * Quit emulator (cause return from jump_to_rom)
739     */
740    
741     void QuitEmulator(void)
742     {
743     Quit();
744     }
745    
746    
747     /*
748     * Pause/resume emulator
749     */
750    
751     void PauseEmulator(void)
752     {
753 gbeauche 1.3 SuspendThread(emul_thread);
754 gbeauche 1.1 }
755    
756     void ResumeEmulator(void)
757     {
758 gbeauche 1.3 ResumeThread(emul_thread);
759 gbeauche 1.1 }
760    
761    
762     /*
763     * Dump 68k registers
764     */
765    
766     void Dump68kRegs(M68kRegisters *r)
767     {
768     // Display 68k registers
769     for (int i=0; i<8; i++) {
770     printf("d%d: %08x", i, r->d[i]);
771     if (i == 3 || i == 7)
772     printf("\n");
773     else
774     printf(", ");
775     }
776     for (int i=0; i<8; i++) {
777     printf("a%d: %08x", i, r->a[i]);
778     if (i == 3 || i == 7)
779     printf("\n");
780     else
781     printf(", ");
782     }
783     }
784    
785    
786     /*
787     * Make code executable
788     */
789    
790     void MakeExecutable(int dummy, uint32 start, uint32 length)
791     {
792     if ((start >= ROM_BASE) && (start < (ROM_BASE + ROM_SIZE)))
793     return;
794     FlushCodeCache(start, start + length);
795     }
796    
797    
798     /*
799     * Patch things after system startup (gets called by disk driver accRun routine)
800     */
801    
802     void PatchAfterStartup(void)
803     {
804     ExecuteNative(NATIVE_VIDEO_INSTALL_ACCEL);
805     InstallExtFS();
806     }
807    
808    
809     /*
810     * NVRAM watchdog thread (saves NVRAM every minute)
811     */
812    
813     static void nvram_watchdog(void)
814     {
815     if (memcmp(last_xpram, XPRAM, XPRAM_SIZE)) {
816     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
817     SaveXPRAM();
818     }
819     }
820    
821 gbeauche 1.3 static DWORD nvram_func(void *arg)
822 gbeauche 1.1 {
823     while (!nvram_thread_cancel) {
824     for (int i=0; i<60 && !nvram_thread_cancel; i++)
825     Delay_usec(999999); // Only wait 1 second so we quit promptly when nvram_thread_cancel becomes true
826     nvram_watchdog();
827     }
828     return 0;
829     }
830    
831    
832     /*
833     * 60Hz thread (really 60.15Hz)
834     */
835    
836 gbeauche 1.3 static DWORD tick_func(void *arg)
837 gbeauche 1.1 {
838     int tick_counter = 0;
839     uint64 start = GetTicks_usec();
840     int64 ticks = 0;
841     uint64 next = GetTicks_usec();
842    
843     while (!tick_thread_cancel) {
844    
845     // Wait
846     next += 16625;
847     int64 delay = next - GetTicks_usec();
848     if (delay > 0)
849     Delay_usec(delay);
850     else if (delay < -16625)
851     next = GetTicks_usec();
852     ticks++;
853    
854     // Pseudo Mac 1Hz interrupt, update local time
855     if (++tick_counter > 60) {
856     tick_counter = 0;
857     WriteMacInt32(0x20c, TimerDateTime());
858     }
859    
860     // Trigger 60Hz interrupt
861     if (ReadMacInt32(XLM_IRQ_NEST) == 0) {
862     SetInterruptFlag(INTFLAG_VIA);
863     TriggerInterrupt();
864     }
865     }
866    
867     uint64 end = GetTicks_usec();
868     D(bug("%Ld ticks in %Ld usec = %f ticks/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
869     return 0;
870     }
871    
872    
873     /*
874     * Mutexes
875     */
876    
877     struct B2_mutex {
878     B2_mutex() { m = SDL_CreateMutex(); }
879     ~B2_mutex() { if (m) SDL_DestroyMutex(m); }
880     SDL_mutex *m;
881     };
882    
883     B2_mutex *B2_create_mutex(void)
884     {
885     return new B2_mutex;
886     }
887    
888     void B2_lock_mutex(B2_mutex *mutex)
889     {
890     if (mutex)
891     SDL_LockMutex(mutex->m);
892     }
893    
894     void B2_unlock_mutex(B2_mutex *mutex)
895     {
896     if (mutex)
897     SDL_UnlockMutex(mutex->m);
898     }
899    
900     void B2_delete_mutex(B2_mutex *mutex)
901     {
902     delete mutex;
903     }
904    
905    
906     /*
907     * Interrupt flags (must be handled atomically!)
908     */
909    
910     volatile uint32 InterruptFlags = 0;
911    
912     void SetInterruptFlag(uint32 flag)
913     {
914     atomic_or((int *)&InterruptFlags, flag);
915     }
916    
917     void ClearInterruptFlag(uint32 flag)
918     {
919     atomic_and((int *)&InterruptFlags, ~flag);
920     }
921    
922    
923     /*
924     * Disable interrupts
925     */
926    
927     void DisableInterrupt(void)
928     {
929     WriteMacInt32(XLM_IRQ_NEST, int32(ReadMacInt32(XLM_IRQ_NEST)) + 1);
930     }
931    
932    
933     /*
934     * Enable interrupts
935     */
936    
937     void EnableInterrupt(void)
938     {
939     WriteMacInt32(XLM_IRQ_NEST, int32(ReadMacInt32(XLM_IRQ_NEST)) - 1);
940     }
941    
942    
943     /*
944     * Helpers to share 32-bit addressable data with MacOS
945     */
946    
947     bool SheepMem::Init(void)
948     {
949     // Size of a native page
950     page_size = vm_page_size();
951    
952     // Allocate SheepShaver globals
953     proc = base;
954     if (vm_mac_acquire(base, size) < 0)
955     return false;
956    
957     // Allocate page with all bits set to 0, right in the middle
958     // This is also used to catch undesired overlaps between proc and data areas
959     zero_page = proc + (size / 2);
960     Mac_memset(zero_page, 0, page_size);
961     if (vm_protect(Mac2HostAddr(zero_page), page_size, VM_PAGE_READ) < 0)
962     return false;
963    
964     // Allocate alternate stack for PowerPC interrupt routine
965     sig_stack = base + size;
966     if (vm_mac_acquire(sig_stack, SIG_STACK_SIZE) < 0)
967     return false;
968    
969     data = base + size;
970     return true;
971     }
972    
973     void SheepMem::Exit(void)
974     {
975     if (data) {
976     // Delete SheepShaver globals
977     vm_mac_release(base, size);
978    
979     // Delete alternate stack for PowerPC interrupt routine
980     vm_mac_release(sig_stack, SIG_STACK_SIZE);
981     }
982     }
983    
984    
985     /*
986     * Get the main window handle
987     */
988    
989     #ifdef USE_SDL_VIDEO
990     #include <SDL_syswm.h>
991     static HWND GetMainWindowHandle(void)
992     {
993     SDL_SysWMinfo wmInfo;
994     wmInfo.version.major = SDL_MAJOR_VERSION;
995     wmInfo.version.minor = SDL_MINOR_VERSION;
996     wmInfo.version.patch = SDL_PATCHLEVEL;
997     return SDL_GetWMInfo(&wmInfo) ? wmInfo.window : NULL;
998     }
999     #endif
1000    
1001    
1002     /*
1003     * Display alert
1004     */
1005    
1006     static void display_alert(int title_id, const char *text, int flags)
1007     {
1008     HWND hMainWnd = GetMainWindowHandle();
1009     MessageBox(hMainWnd, text, GetString(title_id), MB_OK | flags);
1010     }
1011    
1012    
1013     /*
1014     * Display error alert
1015     */
1016    
1017     void ErrorAlert(const char *text)
1018     {
1019     if (PrefsFindBool("nogui"))
1020     return;
1021    
1022     VideoQuitFullScreen();
1023     display_alert(STR_ERROR_ALERT_TITLE, text, MB_ICONSTOP);
1024     }
1025    
1026    
1027     /*
1028     * Display warning alert
1029     */
1030    
1031     void WarningAlert(const char *text)
1032     {
1033     if (PrefsFindBool("nogui"))
1034     return;
1035    
1036     display_alert(STR_WARNING_ALERT_TITLE, text, MB_ICONINFORMATION);
1037     }
1038    
1039    
1040     /*
1041     * Display choice alert
1042     */
1043    
1044     bool ChoiceAlert(const char *text, const char *pos, const char *neg)
1045     {
1046     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1047     return false; //!!
1048     }