Chameleon

Chameleon Svn Source Tree

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

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

Archive Download this file

Revision: 554