Chameleon

Chameleon Svn Source Tree

Root/trunk/i386/boot2/boot.c

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

Archive Download this file

Revision: 1