Chameleon

Chameleon Svn Source Tree

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

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

Archive Download this file

Revision: 550