Chameleon

Chameleon Svn Source Tree

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

Source at commit 608 created 13 years 5 months ago.
By meklort, moved setupFakeEFI to earielr, causes pci to be scaned before modules are called.
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
137static int 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
153 // Reserve space for boot args
154 reserveKernBootStruct();
155
156 // Load boot drivers from the specifed root path.
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) {
189printf("Press any key to continue...");
190getc();
191}
192
193if (bootArgs->Video.v_display == VGA_TEXT_MODE)
194{
195setVideoMode( GRAPHICS_MODE, 0 );
196// Draw gray screen. NOTE: no boot image, that's in the gui module
197#ifndef OPTION_ROM
198if(!gVerboseMode) drawColorRectangle(0, 0, DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, 0x01);
199#endif
200}
201
202
203setupBooterLog();
204
205 finalizeBootStruct();
206
207execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgs, NULL, NULL);// Notify modules that the kernel is about to be started
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
327
328#ifndef OPTION_ROM
329 // Loading preboot ramdisk if exists.
330 loadPrebootRAMDisk();
331
332 // Disable rescan option by default
333 gEnableCDROMRescan = false;
334
335 // Enable it with Rescan=y in system config
336 if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan) {
337 gEnableCDROMRescan = true;
338 }
339
340 // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
341 rescanPrompt = false;
342 if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->bootConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) {
343 gEnableCDROMRescan = promptForRescanOption();
344 }
345#endif
346
347
348
349
350#if DEBUG
351 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
352 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
353 getc();
354#endif
355
356
357
358 setBootGlobals(bvChain);
359
360 // Parse args, load and start kernel.
361 while (1) {
362 const char *val;
363 int len;
364 int trycache;
365 long flags, cachetime, kerneltime, exttime, sleeptime, time;
366 int ret = -1;
367 void *binary = (void *)kLoadAddr;
368 bool tryresume;
369 bool tryresumedefault;
370 bool forceresume;
371
372 // additional variable for testing alternate kernel image locations on boot helper partitions.
373 char bootFileSpec[512];
374
375 // Initialize globals.
376
377 sysConfigValid = false;
378 gErrors = false;
379
380 status = getBootOptions(firstRun);
381 firstRun = false;
382 if (status == -1) continue;
383
384 status = processBootOptions();
385 // Status==1 means to chainboot
386 if ( status == 1 ) break;
387 // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL
388 if ( status == -1 )
389 {
390// gBootVolume == NULL usually means the user hit escape.
391if(gBootVolume == NULL)
392{
393freeFilteredBVChain(bvChain);
394#ifndef OPTION_ROM
395if (gEnableCDROMRescan)
396rescanBIOSDevice(gBIOSDev);
397#endif
398
399bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
400setBootGlobals(bvChain);
401}
402continue;
403 }
404
405
406
407 // Other status (e.g. 0) means that we should proceed with boot.
408
409
410// Find out which version mac os we're booting.
411getOSVersion(gMacOSVersion);
412
413if (platformCPUFeature(CPU_FEATURE_EM64T)) {
414archCpuType = CPU_TYPE_X86_64;
415} else {
416archCpuType = CPU_TYPE_I386;
417}
418if (getValueForKey(karch, &val, &len, &bootInfo->bootConfig)) {
419if (strncmp(val, "i386", 4) == 0) {
420archCpuType = CPU_TYPE_I386;
421}
422}
423
424// Notify moduals that we are attempting to boot
425execute_hook("PreBoot", NULL, NULL, NULL, NULL);
426
427if (!getBoolForKey (kWake, &tryresume, &bootInfo->bootConfig)) {
428tryresume = true;
429tryresumedefault = true;
430} else {
431tryresumedefault = false;
432}
433
434if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->bootConfig)) {
435forceresume = false;
436}
437
438if (forceresume) {
439tryresume = true;
440tryresumedefault = false;
441}
442
443while (tryresume) {
444const char *tmp;
445BVRef bvr;
446if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->bootConfig))
447val="/private/var/vm/sleepimage";
448
449// Do this first to be sure that root volume is mounted
450ret = GetFileInfo(0, val, &flags, &sleeptime);
451
452if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
453break;
454
455// Can't check if it was hibernation Wake=y is required
456if (bvr->modTime == 0 && tryresumedefault)
457break;
458
459if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
460break;
461
462if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
463printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",bvr->modTime-sleeptime);
464break;
465}
466
467HibernateBoot((char *)val);
468break;
469}
470
471 // Reset cache name.
472 bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
473
474 sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
475
476 adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
477
478 if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
479 strlcpy(gBootKernelCacheFile, val, len+1);
480 } else {
481 sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePath, adler32);
482 }
483
484 // Check for cache file.
485 trycache = (((gBootMode & kBootModeSafe) == 0) &&
486 !gOverrideKernel &&
487 (gBootFileType == kBlockDeviceType) &&
488 (gMKextName[0] == '\0') &&
489 (gBootKernelCacheFile[0] != '\0'));
490
491verbose("Loading Darwin %s\n", gMacOSVersion);
492
493 if (trycache) do {
494
495 // if we haven't found the kernel yet, don't use the cache
496 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
497 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) {
498 trycache = 0;
499 break;
500 }
501 ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
502 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
503 || (cachetime < kerneltime)) {
504 trycache = 0;
505 break;
506 }
507 ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
508 if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
509 && (cachetime < exttime)) {
510 trycache = 0;
511 break;
512 }
513 if (kerneltime > exttime) {
514 exttime = kerneltime;
515 }
516 if (cachetime != (exttime + 1)) {
517 trycache = 0;
518 break;
519 }
520 } while (0);
521
522 do {
523 if (trycache) {
524 bootFile = gBootKernelCacheFile;
525 verbose("Loading kernel cache %s\n", bootFile);
526 ret = LoadFile(bootFile);
527 binary = (void *)kLoadAddr;
528 if (ret >= 0) {
529 break;
530 }
531 }
532 bootFile = bootInfo->bootFile;
533
534 // Try to load kernel image from alternate locations on boot helper partitions.
535 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
536 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
537 if (ret == -1)
538 {
539sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
540ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
541if (ret == -1)
542{
543sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
544ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
545if (ret == -1)
546{
547// Not found any alternate locations, using the original kernel image path.
548strcpy(bootFileSpec, bootFile);
549}
550}
551 }
552
553 verbose("Loading kernel %s\n", bootFileSpec);
554 ret = LoadThinFatFile(bootFileSpec, &binary);
555 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
556 {
557archCpuType = CPU_TYPE_I386;
558ret = LoadThinFatFile(bootFileSpec, &binary);
559 }
560
561 } while (0);
562
563 clearActivityIndicator();
564#if DEBUG
565 printf("Pausing...");
566 sleep(8);
567#endif
568
569 if (ret <= 0) {
570printf("Can't find %s\n", bootFile);
571
572sleep(1);
573#ifndef OPTION_ROM
574 if (gBootFileType == kNetworkDeviceType) {
575 // Return control back to PXE. Don't unload PXE base code.
576 gUnloadPXEOnExit = false;
577 break;
578 }
579#endif
580 } else {
581 /* Won't return if successful. */
582// Notify modules that ExecKernel is about to be called
583 ret = ExecKernel(binary);
584 }
585 }
586
587 // chainboot
588 if (status==1) {
589if (getVideoMode() == GRAPHICS_MODE) {// if we are already in graphics-mode,
590setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
591}
592 }
593#ifndef OPTION_ROM
594 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
595nbpUnloadBaseCode();
596 }
597#endif
598}
599
600/*!
601 Selects a new BIOS device, taking care to update the global state appropriately.
602 */
603/*
604 static void selectBiosDevice(void)
605 {
606 struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
607 CacheReset();
608 diskFreeMap(oldMap);
609 oldMap = NULL;
610
611 int dev = selectAlternateBootDevice(gBIOSDev);
612
613 BVRef bvchain = scanBootVolumes(dev, 0);
614 BVRef bootVol = selectBootVolume(bvchain);
615 gBootVolume = bootVol;
616 setRootVolume(bootVol);
617 gBIOSDev = dev;
618 }
619 */
620
621static bool getOSVersion(char *str)
622{
623bool valid = false;
624config_file_t systemVersion;
625const char *val;
626int len;
627
628if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion))
629{
630valid = true;
631}
632else if (!loadConfigFile("System/Library/CoreServices/ServerVersion.plist", &systemVersion))
633{
634valid = true;
635}
636
637if (valid)
638{
639if (getValueForKey(kProductVersion, &val, &len, &systemVersion))
640{
641// getValueForKey uses const char for val
642// so copy it and trim
643*str = '\0';
644strncat(str, val, MIN(len, 4));
645}
646else
647valid = false;
648}
649
650return valid;
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: 608