Chameleon

Chameleon Svn Source Tree

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

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

Archive Download this file

Revision: 712