ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Windows/main_windows.cpp
Revision: 1.1
Committed: 2004-12-07T22:40:30Z (19 years, 6 months ago) by gbeauche
Branch: MAIN
Log Message:
native windows version of SheepShaver (does not depend on cygwin.dll)

File Contents

# Content
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 #warning FIXME: support DR emulator
305 #if 0
306 if (vm_mac_acquire(DR_EMULATOR_BASE, DR_EMULATOR_SIZE) < 0) {
307 sprintf(str, GetString(STR_DR_EMULATOR_MMAP_ERR), strerror(errno));
308 ErrorAlert(str);
309 goto quit;
310 }
311 dr_emulator_area_mapped = true;
312 #endif
313 if (vm_mac_acquire(DR_CACHE_BASE, DR_CACHE_SIZE) < 0) {
314 sprintf(str, GetString(STR_DR_CACHE_MMAP_ERR), strerror(errno));
315 ErrorAlert(str);
316 goto quit;
317 }
318 dr_cache_area_mapped = true;
319 DRCacheAddr = (uint32)Mac2HostAddr(DR_CACHE_BASE);
320 D(bug("DR Cache at %p (%08x)\n", DRCacheAddr, DR_CACHE_BASE));
321
322 // Create area for SheepShaver data
323 if (!SheepMem::Init()) {
324 sprintf(str, GetString(STR_SHEEP_MEM_MMAP_ERR), strerror(errno));
325 ErrorAlert(str);
326 goto quit;
327 }
328
329 // Create area for Mac ROM
330 if (vm_mac_acquire(ROM_BASE, ROM_AREA_SIZE) < 0) {
331 sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
332 ErrorAlert(str);
333 goto quit;
334 }
335 ROMBaseHost = Mac2HostAddr(ROM_BASE);
336 rom_area_mapped = true;
337 D(bug("ROM area at %p (%08x)\n", ROMBaseHost, ROM_BASE));
338
339 // Create area for Mac RAM
340 RAMSize = PrefsFindInt32("ramsize");
341 if (RAMSize < 8*1024*1024) {
342 WarningAlert(GetString(STR_SMALL_RAM_WARN));
343 RAMSize = 8*1024*1024;
344 }
345
346 if (vm_mac_acquire(RAM_BASE, RAMSize) < 0) {
347 sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
348 ErrorAlert(str);
349 goto quit;
350 }
351 RAMBaseHost = Mac2HostAddr(RAM_BASE);
352 RAMBase = RAM_BASE;
353 ram_area_mapped = true;
354 D(bug("RAM area at %p (%08x)\n", RAMBaseHost, RAMBase));
355
356 if (RAMBase > ROM_BASE) {
357 ErrorAlert(GetString(STR_RAM_HIGHER_THAN_ROM_ERR));
358 goto quit;
359 }
360
361 // Load Mac ROM
362 rom_path = PrefsFindString("rom");
363 rom_fh = CreateFile(rom_path ? rom_path : ROM_FILE_NAME,
364 GENERIC_READ, 0, NULL, OPEN_EXISTING,
365 FILE_ATTRIBUTE_NORMAL, NULL);
366
367 if (rom_fh == INVALID_HANDLE_VALUE) {
368 rom_fh = CreateFile(rom_path ? rom_path : ROM_FILE_NAME2,
369 GENERIC_READ, 0, NULL, OPEN_EXISTING,
370 FILE_ATTRIBUTE_NORMAL, NULL);
371
372 if (rom_fh == INVALID_HANDLE_VALUE) {
373 ErrorAlert(GetString(STR_NO_ROM_FILE_ERR));
374 goto quit;
375 }
376 }
377 printf(GetString(STR_READING_ROM_FILE));
378 rom_size = GetFileSize(rom_fh, NULL);
379 rom_tmp = new uint8[ROM_SIZE];
380 ReadFile(rom_fh, (void *)rom_tmp, ROM_SIZE, &actual, NULL);
381 CloseHandle(rom_fh);
382
383 // Decode Mac ROM
384 if (!DecodeROM(rom_tmp, actual)) {
385 if (rom_size != 4*1024*1024) {
386 ErrorAlert(GetString(STR_ROM_SIZE_ERR));
387 goto quit;
388 } else {
389 ErrorAlert(GetString(STR_ROM_FILE_READ_ERR));
390 goto quit;
391 }
392 }
393 delete[] rom_tmp;
394
395 // Load NVRAM
396 XPRAMInit();
397
398 // Load XPRAM default values if signature not found
399 if (XPRAM[0x130c] != 0x4e || XPRAM[0x130d] != 0x75
400 || XPRAM[0x130e] != 0x4d || XPRAM[0x130f] != 0x63) {
401 D(bug("Loading XPRAM default values\n"));
402 memset(XPRAM + 0x1300, 0, 0x100);
403 XPRAM[0x130c] = 0x4e; // "NuMc" signature
404 XPRAM[0x130d] = 0x75;
405 XPRAM[0x130e] = 0x4d;
406 XPRAM[0x130f] = 0x63;
407 XPRAM[0x1301] = 0x80; // InternalWaitFlags = DynWait (don't wait for SCSI devices upon bootup)
408 XPRAM[0x1310] = 0xa8; // Standard PRAM values
409 XPRAM[0x1311] = 0x00;
410 XPRAM[0x1312] = 0x00;
411 XPRAM[0x1313] = 0x22;
412 XPRAM[0x1314] = 0xcc;
413 XPRAM[0x1315] = 0x0a;
414 XPRAM[0x1316] = 0xcc;
415 XPRAM[0x1317] = 0x0a;
416 XPRAM[0x131c] = 0x00;
417 XPRAM[0x131d] = 0x02;
418 XPRAM[0x131e] = 0x63;
419 XPRAM[0x131f] = 0x00;
420 XPRAM[0x1308] = 0x13;
421 XPRAM[0x1309] = 0x88;
422 XPRAM[0x130a] = 0x00;
423 XPRAM[0x130b] = 0xcc;
424 XPRAM[0x1376] = 0x00; // OSDefault = MacOS
425 XPRAM[0x1377] = 0x01;
426 }
427
428 // Set boot volume
429 i16 = PrefsFindInt32("bootdrive");
430 XPRAM[0x1378] = i16 >> 8;
431 XPRAM[0x1379] = i16 & 0xff;
432 i16 = PrefsFindInt32("bootdriver");
433 XPRAM[0x137a] = i16 >> 8;
434 XPRAM[0x137b] = i16 & 0xff;
435
436 // Create BootGlobs at top of Mac memory
437 memset(RAMBaseHost + RAMSize - 4096, 0, 4096);
438 BootGlobsAddr = RAMBase + RAMSize - 0x1c;
439 WriteMacInt32(BootGlobsAddr - 5 * 4, RAMBase + RAMSize); // MemTop
440 WriteMacInt32(BootGlobsAddr + 0 * 4, RAMBase); // First RAM bank
441 WriteMacInt32(BootGlobsAddr + 1 * 4, RAMSize);
442 WriteMacInt32(BootGlobsAddr + 2 * 4, (uint32)-1); // End of bank table
443
444 // Init thunks
445 if (!ThunksInit())
446 goto quit;
447
448 // Init drivers
449 SonyInit();
450 DiskInit();
451 CDROMInit();
452 SCSIInit();
453
454 // Init external file system
455 ExtFSInit();
456
457 // Init ADB
458 ADBInit();
459
460 // Init audio
461 AudioInit();
462
463 // Init network
464 EtherInit();
465
466 // Init serial ports
467 SerialInit();
468
469 // Init Time Manager
470 timer_init();
471
472 // Init clipboard
473 ClipInit();
474
475 // Init video
476 if (!VideoInit())
477 goto quit;
478
479 // Install ROM patches
480 if (!PatchROM()) {
481 ErrorAlert(GetString(STR_UNSUPPORTED_ROM_TYPE_ERR));
482 goto quit;
483 }
484
485 // Write protect ROM
486 vm_protect(ROMBaseHost, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_EXECUTE);
487
488 // Initialize Kernel Data
489 memset(kernel_data, 0, sizeof(KernelData));
490 if (ROMType == ROMTYPE_NEWWORLD) {
491 uint32 of_dev_tree = SheepMem::Reserve(4 * sizeof(uint32));
492 Mac_memset(of_dev_tree, 0, 4 * sizeof(uint32));
493 uint32 vector_lookup_tbl = SheepMem::Reserve(128);
494 uint32 vector_mask_tbl = SheepMem::Reserve(64);
495 memset((uint8 *)kernel_data + 0xb80, 0x3d, 0x80);
496 Mac_memset(vector_lookup_tbl, 0, 128);
497 Mac_memset(vector_mask_tbl, 0, 64);
498 kernel_data->v[0xb80 >> 2] = htonl(ROM_BASE);
499 kernel_data->v[0xb84 >> 2] = htonl(of_dev_tree); // OF device tree base
500 kernel_data->v[0xb90 >> 2] = htonl(vector_lookup_tbl);
501 kernel_data->v[0xb94 >> 2] = htonl(vector_mask_tbl);
502 kernel_data->v[0xb98 >> 2] = htonl(ROM_BASE); // OpenPIC base
503 kernel_data->v[0xbb0 >> 2] = htonl(0); // ADB base
504 kernel_data->v[0xc20 >> 2] = htonl(RAMSize);
505 kernel_data->v[0xc24 >> 2] = htonl(RAMSize);
506 kernel_data->v[0xc30 >> 2] = htonl(RAMSize);
507 kernel_data->v[0xc34 >> 2] = htonl(RAMSize);
508 kernel_data->v[0xc38 >> 2] = htonl(0x00010020);
509 kernel_data->v[0xc3c >> 2] = htonl(0x00200001);
510 kernel_data->v[0xc40 >> 2] = htonl(0x00010000);
511 kernel_data->v[0xc50 >> 2] = htonl(RAMBase);
512 kernel_data->v[0xc54 >> 2] = htonl(RAMSize);
513 kernel_data->v[0xf60 >> 2] = htonl(PVR);
514 kernel_data->v[0xf64 >> 2] = htonl(CPUClockSpeed); // clock-frequency
515 kernel_data->v[0xf68 >> 2] = htonl(BusClockSpeed); // bus-frequency
516 kernel_data->v[0xf6c >> 2] = htonl(TimebaseSpeed); // timebase-frequency
517 } else {
518 kernel_data->v[0xc80 >> 2] = htonl(RAMSize);
519 kernel_data->v[0xc84 >> 2] = htonl(RAMSize);
520 kernel_data->v[0xc90 >> 2] = htonl(RAMSize);
521 kernel_data->v[0xc94 >> 2] = htonl(RAMSize);
522 kernel_data->v[0xc98 >> 2] = htonl(0x00010020);
523 kernel_data->v[0xc9c >> 2] = htonl(0x00200001);
524 kernel_data->v[0xca0 >> 2] = htonl(0x00010000);
525 kernel_data->v[0xcb0 >> 2] = htonl(RAMBase);
526 kernel_data->v[0xcb4 >> 2] = htonl(RAMSize);
527 kernel_data->v[0xf80 >> 2] = htonl(PVR);
528 kernel_data->v[0xf84 >> 2] = htonl(CPUClockSpeed); // clock-frequency
529 kernel_data->v[0xf88 >> 2] = htonl(BusClockSpeed); // bus-frequency
530 kernel_data->v[0xf8c >> 2] = htonl(TimebaseSpeed); // timebase-frequency
531 }
532
533 // Initialize extra low memory
534 D(bug("Initializing Low Memory...\n"));
535 Mac_memset(0, 0, 0x3000);
536 WriteMacInt32(XLM_SIGNATURE, FOURCC('B','a','a','h')); // Signature to detect SheepShaver
537 WriteMacInt32(XLM_KERNEL_DATA, KernelDataAddr); // For trap replacement routines
538 WriteMacInt32(XLM_PVR, PVR); // Theoretical PVR
539 WriteMacInt32(XLM_BUS_CLOCK, BusClockSpeed); // For DriverServicesLib patch
540 WriteMacInt16(XLM_EXEC_RETURN_OPCODE, M68K_EXEC_RETURN); // For Execute68k() (RTS from the executed 68k code will jump here and end 68k mode)
541 WriteMacInt32(XLM_ZERO_PAGE, SheepMem::ZeroPage()); // Pointer to read-only page with all bits set to 0
542 WriteMacInt32(XLM_ETHER_INIT, NativeFunction(NATIVE_ETHER_INIT)); // DLPI ethernet driver functions
543 WriteMacInt32(XLM_ETHER_TERM, NativeFunction(NATIVE_ETHER_TERM));
544 WriteMacInt32(XLM_ETHER_OPEN, NativeFunction(NATIVE_ETHER_OPEN));
545 WriteMacInt32(XLM_ETHER_CLOSE, NativeFunction(NATIVE_ETHER_CLOSE));
546 WriteMacInt32(XLM_ETHER_WPUT, NativeFunction(NATIVE_ETHER_WPUT));
547 WriteMacInt32(XLM_ETHER_RSRV, NativeFunction(NATIVE_ETHER_RSRV));
548 WriteMacInt32(XLM_VIDEO_DOIO, NativeFunction(NATIVE_VIDEO_DO_DRIVER_IO));
549 D(bug("Low Memory initialized\n"));
550
551 // Start 60Hz thread
552 tick_thread_cancel = false;
553 tick_thread_active = ((tick_thread = SDL_CreateThread(tick_func, NULL)) != NULL);
554 D(bug("Tick thread installed (%ld)\n", tick_thread));
555
556 // Start NVRAM watchdog thread
557 memcpy(last_xpram, XPRAM, XPRAM_SIZE);
558 nvram_thread_cancel = false;
559 nvram_thread_active = ((nvram_thread = SDL_CreateThread(nvram_func, NULL)) != NULL);
560 D(bug("NVRAM thread installed (%ld)\n", nvram_thread));
561
562 // Jump to ROM boot routine
563 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 SDL_WaitThread(tick_thread, NULL);
586 }
587
588 // Stop NVRAM watchdog thread
589 if (nvram_thread_active) {
590 nvram_thread_cancel = true;
591 SDL_WaitThread(nvram_thread, NULL);
592 }
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 // TODO: implement pause/resume
754 }
755
756 void ResumeEmulator(void)
757 {
758 // TODO: implement pause/resume
759 }
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 static int nvram_func(void *arg)
822 {
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 static int tick_func(void *arg)
837 {
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 }