Chameleon

Chameleon Svn Source Tree

Root/branches/meklort/i386/boot2/boot.c

Source at commit 150 created 13 years 11 months ago.
By meklort, USBLecayOff patch. Runs immediately before kernel is started / after last file is loaded
1/*
2 * Copyright (c) 1999-2003 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * Portions Copyright (c) 1999-2003 Apple Computer, Inc. All Rights
7 * Reserved. This file contains Original Code and/or Modifications of
8 * Original Code as defined in and that are subject to the Apple Public
9 * Source License Version 2.0 (the "License"). You may not use this file
10 * except in compliance with the License. Please obtain a copy of the
11 * License at http://www.apple.com/publicsource and read it before using
12 * this file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE OR NON- INFRINGEMENT. Please see the
19 * License for the specific language governing rights and limitations
20 * under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24/*
25 * Mach Operating System
26 * Copyright (c) 1990 Carnegie-Mellon University
27 * Copyright (c) 1989 Carnegie-Mellon University
28 * All rights reserved. The CMU software License Agreement specifies
29 * the terms and conditions for use and redistribution.
30 */
31
32/*
33 * INTEL CORPORATION PROPRIETARY INFORMATION
34 *
35 * This software is supplied under the terms of a license agreement or
36 * nondisclosure agreement with Intel Corporation and may not be copied
37 * nor disclosed except in accordance with the terms of that agreement.
38 *
39 * Copyright 1988, 1989 by Intel Corporation
40 */
41
42/*
43 * Copyright 1993 NeXT Computer, Inc.
44 * All rights reserved.
45 */
46
47/*
48 * Completely reworked by Sam Streeper (sam_s@NeXT.com)
49 * Reworked again by Curtis Galloway (galloway@NeXT.com)
50 */
51
52
53#include "boot.h"
54#include "bootstruct.h"
55#include "fake_efi.h"
56#include "sl.h"
57#include "libsa.h"
58#include "ramdisk.h"
59#include "gui.h"
60#include "platform.h"
61#include "resolution.h"
62
63long gBootMode; /* defaults to 0 == kBootModeNormal */
64bool gOverrideKernel;
65static char gBootKernelCacheFile[512];
66static char gCacheNameAdler[64 + 256];
67char *gPlatformName = gCacheNameAdler;
68char gRootDevice[512];
69char gMKextName[512];
70char gMacOSVersion[8];
71bool gEnableCDROMRescan;
72bool gScanSingleDrive;
73
74int bvCount = 0;
75//intmenucount = 0;
76int gDeviceCount = 0;
77
78BVRef bvr;
79BVRef menuBVR;
80BVRef bvChain;
81bool useGUI;
82
83//static void selectBiosDevice(void);
84static unsigned long Adler32(unsigned char *buffer, long length);
85
86
87static bool gUnloadPXEOnExit = false;
88
89extern int usb_loop();
90/*
91 * How long to wait (in seconds) to load the
92 * kernel after displaying the "boot:" prompt.
93 */
94#define kBootErrorTimeout 5
95
96/*
97 * Default path to kernel cache file
98 */
99#define kDefaultCachePath "/System/Library/Caches/com.apple.kernelcaches/kernelcache"
100
101//==========================================================================
102// Zero the BSS.
103
104static void zeroBSS(void)
105{
106extern char _DATA__bss__begin, _DATA__bss__end;
107extern char _DATA__common__begin, _DATA__common__end;
108
109bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
110bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
111}
112
113//==========================================================================
114// Malloc error function
115
116static void malloc_error(char *addr, size_t size, const char *file, int line)
117{
118stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
119}
120
121//==========================================================================
122//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
123//
124void initialize_runtime(void)
125{
126zeroBSS();
127malloc_init(0, 0, 0, malloc_error);
128}
129
130//==========================================================================
131// execKernel - Load the kernel image (mach-o) and jump to its entry point.
132
133static int ExecKernel(void *binary)
134{
135 entry_t kernelEntry;
136 int ret;
137
138 bootArgs->kaddr = bootArgs->ksize = 0;
139
140 ret = DecodeKernel(binary,
141 &kernelEntry,
142 (char **) &bootArgs->kaddr,
143 (int *)&bootArgs->ksize );
144
145 if ( ret != 0 )
146 return ret;
147
148 // Reserve space for boot args
149 reserveKernBootStruct();
150
151 // Load boot drivers from the specifed root path.
152
153 if (!gHaveKernelCache) {
154 LoadDrivers("/");
155 }
156
157 clearActivityIndicator();
158
159 if (gErrors) {
160 printf("Errors encountered while starting up the computer.\n");
161 printf("Pausing %d seconds...\n", kBootErrorTimeout);
162 sleep(kBootErrorTimeout);
163 }
164
165 setupFakeEfi();
166
167 verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
168
169 // Cleanup the PXE base code.
170
171 if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) {
172if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
173 {
174 printf("nbpUnloadBaseCode error %d\n", (int) ret);
175 sleep(2);
176 }
177 }
178
179 bool dummyVal;
180 if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->bootConfig) && dummyVal) {
181printf("Press any key to continue...");
182getc();
183 }
184
185 // If we were in text mode, switch to graphics mode.
186 // This will draw the boot graphics unless we are in
187 // verbose mode.
188
189 if(gVerboseMode)
190 setVideoMode( GRAPHICS_MODE, 0 );
191 else
192 drawBootGraphics();
193
194 finalizeBootStruct();
195
196usb_loop();
197 // Jump to kernel's entry point. There's no going back now.
198 startprog( kernelEntry, bootArgs );
199
200 // Not reached
201
202 return 0;
203}
204
205//==========================================================================
206// This is the entrypoint from real-mode which functions exactly as it did
207// before. Multiboot does its own runtime initialization, does some of its
208// own things, and then calls common_boot.
209void boot(int biosdev)
210{
211initialize_runtime();
212// Enable A20 gate before accessing memory above 1Mb.
213enableA20();
214common_boot(biosdev);
215}
216
217//==========================================================================
218// The 'main' function for the booter. Called by boot0 when booting
219// from a block device, or by the network booter.
220//
221// arguments:
222// biosdev - Value passed from boot1/NBP to specify the device
223// that the booter was loaded from.
224//
225// If biosdev is kBIOSDevNetwork, then this function will return if
226// booting was unsuccessful. This allows the PXE firmware to try the
227// next boot device on its list.
228void common_boot(int biosdev)
229{
230 int status;
231 char *bootFile;
232 unsigned long adler32;
233 bool quiet;
234 bool firstRun = true;
235 bool instantMenu;
236 bool rescanPrompt;
237 unsigned int allowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
238 unsigned int denyBVFlags = kBVFlagEFISystem;
239
240 // Set reminder to unload the PXE base code. Neglect to unload
241 // the base code will result in a hang or kernel panic.
242 gUnloadPXEOnExit = true;
243
244 // Record the device that the booter was loaded from.
245 gBIOSDev = biosdev & kBIOSDevMask;
246
247 // Initialize boot info structure.
248 initKernBootStruct();
249
250 // Setup VGA text mode.
251 // Not sure if it is safe to call setVideoMode() before the
252 // config table has been loaded. Call video_mode() instead.
253#if DEBUG
254 printf("before video_mode\n");
255#endif
256 video_mode( 2 ); // 80x25 mono text mode.
257#if DEBUG
258 printf("after video_mode\n");
259#endif
260
261 // Scan and record the system's hardware information.
262 scan_platform();
263
264 // First get info for boot volume.
265 scanBootVolumes(gBIOSDev, 0);
266 bvChain = getBVChainForBIOSDev(gBIOSDev);
267 setBootGlobals(bvChain);
268
269 // Load boot.plist config file
270 status = loadSystemConfig(&bootInfo->bootConfig);
271
272 if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet) {
273 gBootMode |= kBootModeQuiet;
274 }
275
276 // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
277 if (getBoolForKey(kInsantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu) {
278 firstRun = false;
279 }
280
281 // Loading preboot ramdisk if exists.
282 loadPrebootRAMDisk();
283
284 // Disable rescan option by default
285 gEnableCDROMRescan = false;
286
287 // Enable it with Rescan=y in system config
288 if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan) {
289 gEnableCDROMRescan = true;
290 }
291
292 // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
293 rescanPrompt = false;
294 if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->bootConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) {
295 gEnableCDROMRescan = promptForRescanOption();
296 }
297
298 // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
299 if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive) {
300 gScanSingleDrive = true;
301 }
302
303 // Create a list of partitions on device(s).
304 if (gScanSingleDrive) {
305 scanBootVolumes(gBIOSDev, &bvCount);
306 } else {
307 scanDisks(gBIOSDev, &bvCount);
308 }
309
310 // Create a separated bvr chain using the specified filters.
311 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
312
313 gBootVolume = selectBootVolume(bvChain);
314
315#if DEBUG
316 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
317 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
318 getc();
319#endif
320
321 useGUI = true;
322 // Override useGUI default
323 getBoolForKey(kGUIKey, &useGUI, &bootInfo->bootConfig);
324 if (useGUI) {
325patchVideoBios();
326 /* XXX AsereBLN handle error */
327initGUI();
328 }
329
330 setBootGlobals(bvChain);
331
332 // Parse args, load and start kernel.
333 while (1) {
334 const char *val;
335 int len;
336 int trycache;
337 long flags, cachetime, kerneltime, exttime, sleeptime, time;
338 int ret = -1;
339 void *binary = (void *)kLoadAddr;
340 bool tryresume;
341 bool tryresumedefault;
342 bool forceresume;
343
344 config_file_t systemVersion;// system.plist of booting partition
345
346 // additional variable for testing alternate kernel image locations on boot helper partitions.
347 char bootFileSpec[512];
348
349 // Initialize globals.
350
351 sysConfigValid = false;
352 gErrors = false;
353
354 status = getBootOptions(firstRun);
355 firstRun = false;
356 if (status == -1) continue;
357
358 status = processBootOptions();
359 // Status==1 means to chainboot
360 if ( status == 1 ) break;
361 // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL
362 if ( status == -1 )
363 {
364 // gBootVolume == NULL usually means the user hit escape.
365 if(gBootVolume == NULL)
366 {
367 freeFilteredBVChain(bvChain);
368
369 if (gEnableCDROMRescan)
370 rescanBIOSDevice(gBIOSDev);
371
372 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
373 setBootGlobals(bvChain);
374 }
375 continue;
376 }
377
378 // Other status (e.g. 0) means that we should proceed with boot.
379
380if( bootArgs->Video.v_display == GRAPHICS_MODE )
381drawBackground();
382
383 // Found and loaded a config file. Proceed with boot.
384
385// Turn off any GUI elements
386if( bootArgs->Video.v_display == GRAPHICS_MODE )
387{
388gui.devicelist.draw = false;
389gui.bootprompt.draw = false;
390gui.menu.draw = false;
391gui.infobox.draw = false;
392drawBackground();
393updateVRAM();
394}
395
396// Find out which version mac os we're booting.
397if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion)) {
398if (getValueForKey(kProductVersion, &val, &len, &systemVersion)) {
399// getValueForKey uses const char for val
400// so copy it and trim
401strncpy(gMacOSVersion, val, MIN(len, 4));
402gMacOSVersion[MIN(len, 4)] = '\0';
403}
404}
405
406if (platformCPUFeature(CPU_FEATURE_EM64T)) {
407archCpuType = CPU_TYPE_X86_64;
408} else {
409archCpuType = CPU_TYPE_I386;
410}
411if (getValueForKey(karch, &val, &len, &bootInfo->bootConfig)) {
412if (strncmp(val, "i386", 4) == 0) {
413archCpuType = CPU_TYPE_I386;
414}
415}
416if (getValueForKey(k32BitModeFlag, &val, &len, &bootInfo->bootConfig)) {
417archCpuType = CPU_TYPE_I386;
418}
419
420if (!getBoolForKey (kWake, &tryresume, &bootInfo->bootConfig)) {
421tryresume = true;
422tryresumedefault = true;
423} else {
424tryresumedefault = false;
425}
426
427if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->bootConfig)) {
428forceresume = false;
429}
430
431if (forceresume) {
432tryresume = true;
433tryresumedefault = false;
434}
435
436while (tryresume) {
437const char *tmp;
438BVRef bvr;
439if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->bootConfig))
440val="/private/var/vm/sleepimage";
441
442// Do this first to be sure that root volume is mounted
443ret = GetFileInfo(0, val, &flags, &sleeptime);
444
445if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
446break;
447
448// Can't check if it was hibernation Wake=y is required
449if (bvr->modTime == 0 && tryresumedefault)
450break;
451
452if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
453break;
454
455if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
456printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",bvr->modTime-sleeptime);
457break;
458}
459
460HibernateBoot((char *)val);
461break;
462}
463
464 // Reset cache name.
465 bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
466
467 sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
468
469 adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
470
471 if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
472 strlcpy(gBootKernelCacheFile, val, len+1);
473 } else {
474 sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePath, adler32);
475 }
476
477 // Check for cache file.
478 trycache = (((gBootMode & kBootModeSafe) == 0) &&
479 !gOverrideKernel &&
480 (gBootFileType == kBlockDeviceType) &&
481 (gMKextName[0] == '\0') &&
482 (gBootKernelCacheFile[0] != '\0'));
483
484verbose("Loading Darwin %s\n", gMacOSVersion);
485
486 if (trycache) do {
487
488 // if we haven't found the kernel yet, don't use the cache
489 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
490 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) {
491 trycache = 0;
492 break;
493 }
494 ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
495 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
496 || (cachetime < kerneltime)) {
497 trycache = 0;
498 break;
499 }
500 ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
501 if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
502 && (cachetime < exttime)) {
503 trycache = 0;
504 break;
505 }
506 if (kerneltime > exttime) {
507 exttime = kerneltime;
508 }
509 if (cachetime != (exttime + 1)) {
510 trycache = 0;
511 break;
512 }
513 } while (0);
514
515 do {
516 if (trycache) {
517 bootFile = gBootKernelCacheFile;
518 verbose("Loading kernel cache %s\n", bootFile);
519 ret = LoadFile(bootFile);
520 binary = (void *)kLoadAddr;
521 if (ret >= 0) {
522 break;
523 }
524 }
525 bootFile = bootInfo->bootFile;
526
527 // Try to load kernel image from alternate locations on boot helper partitions.
528 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
529 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
530 if (ret == -1)
531 {
532 sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
533 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
534 if (ret == -1)
535 {
536 sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
537 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
538 if (ret == -1)
539 {
540 // Not found any alternate locations, using the original kernel image path.
541 strcpy(bootFileSpec, bootFile);
542 }
543 }
544 }
545
546 verbose("Loading kernel %s\n", bootFileSpec);
547 ret = LoadThinFatFile(bootFileSpec, &binary);
548 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
549 {
550 archCpuType = CPU_TYPE_I386;
551 ret = LoadThinFatFile(bootFileSpec, &binary);
552 }
553
554 } while (0);
555
556 clearActivityIndicator();
557#if DEBUG
558 printf("Pausing...");
559 sleep(8);
560#endif
561
562 if (ret <= 0) {
563printf("Can't find %s\n", bootFile);
564
565if(gui.initialised) {
566sleep(1);
567drawBackground();
568gui.devicelist.draw = true;
569gui.redraw = true;
570}
571 if (gBootFileType == kNetworkDeviceType) {
572 // Return control back to PXE. Don't unload PXE base code.
573 gUnloadPXEOnExit = false;
574 break;
575 }
576 } else {
577 /* Won't return if successful. */
578 ret = ExecKernel(binary);
579 }
580 }
581
582 // chainboot
583 if (status==1) {
584if (getVideoMode() == GRAPHICS_MODE) {// if we are already in graphics-mode,
585setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
586}
587 }
588
589 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
590nbpUnloadBaseCode();
591 }
592}
593
594/*!
595 Selects a new BIOS device, taking care to update the global state appropriately.
596 */
597/*
598static void selectBiosDevice(void)
599{
600 struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
601 CacheReset();
602 diskFreeMap(oldMap);
603 oldMap = NULL;
604
605 int dev = selectAlternateBootDevice(gBIOSDev);
606
607 BVRef bvchain = scanBootVolumes(dev, 0);
608 BVRef bootVol = selectBootVolume(bvchain);
609 gBootVolume = bootVol;
610 setRootVolume(bootVol);
611 gBIOSDev = dev;
612}
613*/
614
615#define BASE 65521L /* largest prime smaller than 65536 */
616#define NMAX 5000
617// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
618
619#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
620#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
621#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
622#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
623#define DO16(buf) DO8(buf,0); DO8(buf,8);
624
625unsigned long Adler32(unsigned char *buf, long len)
626{
627 unsigned long s1 = 1; // adler & 0xffff;
628 unsigned long s2 = 0; // (adler >> 16) & 0xffff;
629 unsigned long result;
630 int k;
631
632 while (len > 0) {
633 k = len < NMAX ? len : NMAX;
634 len -= k;
635 while (k >= 16) {
636 DO16(buf);
637 buf += 16;
638 k -= 16;
639 }
640 if (k != 0) do {
641 s1 += *buf++;
642 s2 += s1;
643 } while (--k);
644 s1 %= BASE;
645 s2 %= BASE;
646 }
647 result = (s2 << 16) | s1;
648 return OSSwapHostToBigInt32(result);
649}
650

Archive Download this file

Revision: 150