Chameleon

Chameleon Svn Source Tree

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

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

Archive Download this file

Revision: 521