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#include "platform.h"
61
62long gBootMode; /* defaults to 0 == kBootModeNormal */
63bool gOverrideKernel;
64static char gBootKernelCacheFile[512];
65static char gCacheNameAdler[64 + 256];
66char *gPlatformName = gCacheNameAdler;
67char gRootDevice[512];
68char gMKextName[512];
69char gMacOSVersion[8];
70bool gEnableCDROMRescan;
71bool gScanSingleDrive;
72
73int bvCount = 0;
74//intmenucount = 0;
75int gDeviceCount = 0;
76
77BVRef bvr;
78BVRef menuBVR;
79BVRef bvChain;
80bool useGUI;
81
82//static void selectBiosDevice(void);
83static unsigned long Adler32(unsigned char *buffer, long length);
84
85
86static bool gUnloadPXEOnExit = false;
87
88/*
89 * How long to wait (in seconds) to load the
90 * kernel after displaying the "boot:" prompt.
91 */
92#define kBootErrorTimeout 5
93
94/*
95 * Default path to kernel cache file
96 */
97#define kDefaultCachePath "/System/Library/Caches/com.apple.kernelcaches/kernelcache"
98
99//==========================================================================
100// Zero the BSS.
101
102static void zeroBSS(void)
103{
104extern char _DATA__bss__begin, _DATA__bss__end;
105extern char _DATA__common__begin, _DATA__common__end;
106
107bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
108bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
109}
110
111//==========================================================================
112// Malloc error function
113
114static void malloc_error(char *addr, size_t size, const char *file, int line)
115{
116stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
117}
118
119//==========================================================================
120//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
121//
122void initialize_runtime(void)
123{
124zeroBSS();
125malloc_init(0, 0, 0, malloc_error);
126}
127
128//==========================================================================
129// execKernel - Load the kernel image (mach-o) and jump to its entry point.
130
131static int ExecKernel(void *binary)
132{
133 entry_t kernelEntry;
134 int ret;
135
136 bootArgs->kaddr = bootArgs->ksize = 0;
137
138 ret = DecodeKernel(binary,
139 &kernelEntry,
140 (char **) &bootArgs->kaddr,
141 (int *)&bootArgs->ksize );
142
143 if ( ret != 0 )
144 return ret;
145
146 // Reserve space for boot args
147 reserveKernBootStruct();
148
149 // Load boot drivers from the specifed root path.
150
151 if (!gHaveKernelCache) {
152 LoadDrivers("/");
153 }
154
155 clearActivityIndicator();
156
157 if (gErrors) {
158 printf("Errors encountered while starting up the computer.\n");
159 printf("Pausing %d seconds...\n", kBootErrorTimeout);
160 sleep(kBootErrorTimeout);
161 }
162
163 setupFakeEfi();
164
165 verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
166
167 // Cleanup the PXE base code.
168
169 if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) {
170if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
171 {
172 printf("nbpUnloadBaseCode error %d\n", (int) ret);
173 sleep(2);
174 }
175 }
176
177 bool dummyVal;
178if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->bootConfig) && dummyVal) {
179printf("Press any key to continue...");
180getc();
181}
182
183usb_loop();
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
196 // Jump to kernel's entry point. There's no going back now.
197
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) {
325 /* XXX AsereBLN handle error */
326initGUI();
327 }
328
329 setBootGlobals(bvChain);
330
331 // Parse args, load and start kernel.
332 while (1) {
333 const char *val;
334 int len;
335 int trycache;
336 long flags, cachetime, kerneltime, exttime, sleeptime, time;
337 int ret = -1;
338 void *binary = (void *)kLoadAddr;
339 bool tryresume;
340 bool tryresumedefault;
341 bool forceresume;
342
343 config_file_t systemVersion;// system.plist of booting partition
344
345 // additional variable for testing alternate kernel image locations on boot helper partitions.
346 char bootFileSpec[512];
347
348 // Initialize globals.
349
350 sysConfigValid = false;
351 gErrors = false;
352
353 status = getBootOptions(firstRun);
354 firstRun = false;
355 if (status == -1) continue;
356
357 status = processBootOptions();
358 // Status==1 means to chainboot
359 if ( status == 1 ) break;
360 // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL
361 if ( status == -1 )
362 {
363 // gBootVolume == NULL usually means the user hit escape.
364 if(gBootVolume == NULL)
365 {
366 freeFilteredBVChain(bvChain);
367
368 if (gEnableCDROMRescan)
369 rescanBIOSDevice(gBIOSDev);
370
371 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
372 setBootGlobals(bvChain);
373 }
374 continue;
375 }
376
377 // Other status (e.g. 0) means that we should proceed with boot.
378
379if( bootArgs->Video.v_display == GRAPHICS_MODE )
380drawBackground();
381
382 // Found and loaded a config file. Proceed with boot.
383
384// Turn off any GUI elements
385if( bootArgs->Video.v_display == GRAPHICS_MODE )
386{
387gui.devicelist.draw = false;
388gui.bootprompt.draw = false;
389gui.menu.draw = false;
390gui.infobox.draw = false;
391drawBackground();
392updateVRAM();
393}
394
395// Find out which version mac os we're booting.
396if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion)) {
397if (getValueForKey(kProductVersion, &val, &len, &systemVersion)) {
398// getValueForKey uses const char for val
399// so copy it and trim
400strncpy(gMacOSVersion, val, MIN(len, 4));
401gMacOSVersion[MIN(len, 4)] = '\0';
402}
403}
404
405if (platformCPUFeature(CPU_FEATURE_EM64T)) {
406archCpuType = CPU_TYPE_X86_64;
407} else {
408archCpuType = CPU_TYPE_I386;
409}
410if (getValueForKey(karch, &val, &len, &bootInfo->bootConfig)) {
411if (strncmp(val, "i386", 4) == 0) {
412archCpuType = CPU_TYPE_I386;
413}
414}
415if (getValueForKey(k32BitModeFlag, &val, &len, &bootInfo->bootConfig)) {
416archCpuType = CPU_TYPE_I386;
417}
418
419if (!getBoolForKey (kWake, &tryresume, &bootInfo->bootConfig)) {
420tryresume = true;
421tryresumedefault = true;
422} else {
423tryresumedefault = false;
424}
425
426if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->bootConfig)) {
427forceresume = false;
428}
429
430if (forceresume) {
431tryresume = true;
432tryresumedefault = false;
433}
434
435while (tryresume) {
436const char *tmp;
437BVRef bvr;
438if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->bootConfig))
439val="/private/var/vm/sleepimage";
440
441// Do this first to be sure that root volume is mounted
442ret = GetFileInfo(0, val, &flags, &sleeptime);
443
444if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
445break;
446
447// Can't check if it was hibernation Wake=y is required
448if (bvr->modTime == 0 && tryresumedefault)
449break;
450
451if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
452break;
453
454if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
455printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",bvr->modTime-sleeptime);
456break;
457}
458
459HibernateBoot((char *)val);
460break;
461}
462
463 // Reset cache name.
464 bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
465
466 sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
467
468 adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
469
470 if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
471 strlcpy(gBootKernelCacheFile, val, len+1);
472 } else {
473 sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePath, adler32);
474 }
475
476 // Check for cache file.
477 trycache = (((gBootMode & kBootModeSafe) == 0) &&
478 !gOverrideKernel &&
479 (gBootFileType == kBlockDeviceType) &&
480 (gMKextName[0] == '\0') &&
481 (gBootKernelCacheFile[0] != '\0'));
482
483verbose("Loading Darwin %s\n", gMacOSVersion);
484
485 if (trycache) do {
486
487 // if we haven't found the kernel yet, don't use the cache
488 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
489 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) {
490 trycache = 0;
491 break;
492 }
493 ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
494 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
495 || (cachetime < kerneltime)) {
496 trycache = 0;
497 break;
498 }
499 ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
500 if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
501 && (cachetime < exttime)) {
502 trycache = 0;
503 break;
504 }
505 if (kerneltime > exttime) {
506 exttime = kerneltime;
507 }
508 if (cachetime != (exttime + 1)) {
509 trycache = 0;
510 break;
511 }
512 } while (0);
513
514 do {
515 if (trycache) {
516 bootFile = gBootKernelCacheFile;
517 verbose("Loading kernel cache %s\n", bootFile);
518 ret = LoadFile(bootFile);
519 binary = (void *)kLoadAddr;
520 if (ret >= 0) {
521 break;
522 }
523 }
524 bootFile = bootInfo->bootFile;
525
526 // Try to load kernel image from alternate locations on boot helper partitions.
527 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
528 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
529 if (ret == -1)
530 {
531 sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
532 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
533 if (ret == -1)
534 {
535 sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
536 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
537 if (ret == -1)
538 {
539 // Not found any alternate locations, using the original kernel image path.
540 strcpy(bootFileSpec, bootFile);
541 }
542 }
543 }
544
545 verbose("Loading kernel %s\n", bootFileSpec);
546 ret = LoadThinFatFile(bootFileSpec, &binary);
547 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
548 {
549 archCpuType = CPU_TYPE_I386;
550 ret = LoadThinFatFile(bootFileSpec, &binary);
551 }
552
553 } while (0);
554
555 clearActivityIndicator();
556#if DEBUG
557 printf("Pausing...");
558 sleep(8);
559#endif
560
561 if (ret <= 0) {
562printf("Can't find %s\n", bootFile);
563
564if(gui.initialised) {
565sleep(1);
566drawBackground();
567gui.devicelist.draw = true;
568gui.redraw = true;
569}
570 if (gBootFileType == kNetworkDeviceType) {
571 // Return control back to PXE. Don't unload PXE base code.
572 gUnloadPXEOnExit = false;
573 break;
574 }
575 } else {
576 /* Won't return if successful. */
577 ret = ExecKernel(binary);
578 }
579 }
580
581 // chainboot
582 if (status==1) {
583if (getVideoMode() == GRAPHICS_MODE) {// if we are already in graphics-mode,
584setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
585}
586 }
587
588 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
589nbpUnloadBaseCode();
590 }
591}
592
593/*!
594 Selects a new BIOS device, taking care to update the global state appropriately.
595 */
596/*
597static void selectBiosDevice(void)
598{
599 struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
600 CacheReset();
601 diskFreeMap(oldMap);
602 oldMap = NULL;
603
604 int dev = selectAlternateBootDevice(gBIOSDev);
605
606 BVRef bvchain = scanBootVolumes(dev, 0);
607 BVRef bootVol = selectBootVolume(bvchain);
608 gBootVolume = bootVol;
609 setRootVolume(bootVol);
610 gBIOSDev = dev;
611}
612*/
613
614#define BASE 65521L /* largest prime smaller than 65536 */
615#define NMAX 5000
616// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
617
618#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
619#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
620#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
621#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
622#define DO16(buf) DO8(buf,0); DO8(buf,8);
623
624unsigned long Adler32(unsigned char *buf, long len)
625{
626 unsigned long s1 = 1; // adler & 0xffff;
627 unsigned long s2 = 0; // (adler >> 16) & 0xffff;
628 unsigned long result;
629 int k;
630
631 while (len > 0) {
632 k = len < NMAX ? len : NMAX;
633 len -= k;
634 while (k >= 16) {
635 DO16(buf);
636 buf += 16;
637 k -= 16;
638 }
639 if (k != 0) do {
640 s1 += *buf++;
641 s2 += s1;
642 } while (--k);
643 s1 %= BASE;
644 s2 %= BASE;
645 }
646 result = (s2 << 16) | s1;
647 return OSSwapHostToBigInt32(result);
648}
649

Archive Download this file

Revision: 203