Chameleon

Chameleon Svn Source Tree

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

Source at commit 535 created 13 years 7 months ago.
By meklort, Removed unneeded code when embeded in an option rom
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];
70#ifndef OPTION_ROM
71bool gEnableCDROMRescan;
72bool gScanSingleDrive;
73#endif
74
75int bvCount = 0;
76//intmenucount = 0;
77int gDeviceCount = 0;
78
79boolrecoveryMode = false;
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
89static bool gUnloadPXEOnExit = false;
90
91/*
92 * How long to wait (in seconds) to load the
93 * kernel after displaying the "boot:" prompt.
94 */
95#define kBootErrorTimeout 5
96
97/*
98 * Default path to kernel cache file
99 */
100#define kDefaultCachePath "/System/Library/Caches/com.apple.kernelcaches/kernelcache"
101
102//==========================================================================
103// Zero the BSS.
104
105static void zeroBSS(void)
106{
107extern char _DATA__bss__begin, _DATA__bss__end;
108extern char _DATA__common__begin, _DATA__common__end;
109
110bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
111bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
112}
113
114//==========================================================================
115// Malloc error function
116
117static void malloc_error(char *addr, size_t size, const char *file, int line)
118{
119stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
120}
121
122//==========================================================================
123//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
124//
125void initialize_runtime(void)
126{
127zeroBSS();
128malloc_init(0, 0, 0, malloc_error);
129}
130
131//==========================================================================
132// execKernel - Load the kernel image (mach-o) and jump to its entry point.
133
134static int ExecKernel(void *binary)
135{
136 entry_t kernelEntry;
137 int ret;
138
139 bootArgs->kaddr = bootArgs->ksize = 0;
140
141 ret = DecodeKernel(binary,
142 &kernelEntry,
143 (char **) &bootArgs->kaddr,
144 (int *)&bootArgs->ksize );
145
146 if ( ret != 0 )
147 return ret;
148
149 // Reserve space for boot args
150 reserveKernBootStruct();
151
152 // Load boot drivers from the specifed root path.
153
154 if (!gHaveKernelCache) {
155LoadDrivers("/");
156 }
157
158 clearActivityIndicator();
159
160 if (gErrors) {
161 printf("Errors encountered while starting up the computer.\n");
162 printf("Pausing %d seconds...\n", kBootErrorTimeout);
163 sleep(kBootErrorTimeout);
164 }
165
166md0Ramdisk();
167
168 setupFakeEfi();
169
170 verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
171#ifndef OPTION_ROM
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#endif
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#ifndef OPTION_ROM
251 bool rescanPrompt;
252#endif
253 unsigned int allowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
254 unsigned int denyBVFlags = kBVFlagEFISystem;
255
256#ifndef OPTION_ROM
257 // Set reminder to unload the PXE base code. Neglect to unload
258 // the base code will result in a hang or kernel panic.
259 gUnloadPXEOnExit = true;
260#endif
261
262 // Record the device that the booter was loaded from.
263 gBIOSDev = biosdev & kBIOSDevMask;
264
265 // Initialize boot info structure.
266 initKernBootStruct();
267
268initBooterLog();
269
270 // Setup VGA text mode.
271 // Not sure if it is safe to call setVideoMode() before the
272 // config table has been loaded. Call video_mode() instead.
273#if DEBUG
274 printf("before video_mode\n");
275#endif
276 video_mode( 2 ); // 80x25 mono text mode.
277#if DEBUG
278 printf("after video_mode\n");
279#endif
280
281 // Scan and record the system's hardware information.
282 scan_platform();
283
284 // First get info for boot volume.
285 scanBootVolumes(gBIOSDev, 0);
286 bvChain = getBVChainForBIOSDev(gBIOSDev);
287 setBootGlobals(bvChain);
288
289 // Load boot.plist config file
290 status = loadSystemConfig(&bootInfo->bootConfig);
291
292 if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet) {
293 gBootMode |= kBootModeQuiet;
294 }
295
296 // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
297 if (getBoolForKey(kInsantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu) {
298 firstRun = false;
299 }
300
301#ifndef OPTION_ROM
302// Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
303 if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive) {
304 gScanSingleDrive = true;
305 }
306
307// Create a list of partitions on device(s).
308 if (gScanSingleDrive)
309{
310scanBootVolumes(gBIOSDev, &bvCount);
311 }
312else
313#endif
314{
315scanDisks(gBIOSDev, &bvCount);
316 }
317
318// Create a separated bvr chain using the specified filters.
319 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
320gBootVolume = selectBootVolume(bvChain);
321
322
323// Intialize module system
324if(init_module_system())
325{
326load_all_modules();
327}
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// Notify moduals that we are attempting to boot
412execute_hook("PreBoot", NULL, NULL, NULL, NULL);
413
414// Find out which version mac os we're booting.
415getOSVersion(gMacOSVersion);
416
417if (platformCPUFeature(CPU_FEATURE_EM64T)) {
418archCpuType = CPU_TYPE_X86_64;
419} else {
420archCpuType = CPU_TYPE_I386;
421}
422if (getValueForKey(karch, &val, &len, &bootInfo->bootConfig)) {
423if (strncmp(val, "i386", 4) == 0) {
424archCpuType = CPU_TYPE_I386;
425}
426}
427
428if (!getBoolForKey (kWake, &tryresume, &bootInfo->bootConfig)) {
429tryresume = true;
430tryresumedefault = true;
431} else {
432tryresumedefault = false;
433}
434
435if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->bootConfig)) {
436forceresume = false;
437}
438
439if (forceresume) {
440tryresume = true;
441tryresumedefault = false;
442}
443
444while (tryresume) {
445const char *tmp;
446BVRef bvr;
447if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->bootConfig))
448val="/private/var/vm/sleepimage";
449
450// Do this first to be sure that root volume is mounted
451ret = GetFileInfo(0, val, &flags, &sleeptime);
452
453if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
454break;
455
456// Can't check if it was hibernation Wake=y is required
457if (bvr->modTime == 0 && tryresumedefault)
458break;
459
460if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
461break;
462
463if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
464printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",bvr->modTime-sleeptime);
465break;
466}
467
468HibernateBoot((char *)val);
469break;
470}
471
472 // Reset cache name.
473 bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
474
475 sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
476
477 adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
478
479 if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
480 strlcpy(gBootKernelCacheFile, val, len+1);
481 } else {
482 sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePath, adler32);
483 }
484
485 // Check for cache file.
486 trycache = (((gBootMode & kBootModeSafe) == 0) &&
487 !gOverrideKernel &&
488 (gBootFileType == kBlockDeviceType) &&
489 (gMKextName[0] == '\0') &&
490 (gBootKernelCacheFile[0] != '\0'));
491
492verbose("Loading Darwin %s\n", gMacOSVersion);
493
494 if (trycache) do {
495
496 // if we haven't found the kernel yet, don't use the cache
497 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
498 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) {
499 trycache = 0;
500 break;
501 }
502 ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
503 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
504 || (cachetime < kerneltime)) {
505 trycache = 0;
506 break;
507 }
508 ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
509 if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
510 && (cachetime < exttime)) {
511 trycache = 0;
512 break;
513 }
514 if (kerneltime > exttime) {
515 exttime = kerneltime;
516 }
517 if (cachetime != (exttime + 1)) {
518 trycache = 0;
519 break;
520 }
521 } while (0);
522
523 do {
524 if (trycache) {
525 bootFile = gBootKernelCacheFile;
526 verbose("Loading kernel cache %s\n", bootFile);
527 ret = LoadFile(bootFile);
528 binary = (void *)kLoadAddr;
529 if (ret >= 0) {
530 break;
531 }
532 }
533 bootFile = bootInfo->bootFile;
534
535 // Try to load kernel image from alternate locations on boot helper partitions.
536 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
537 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
538 if (ret == -1)
539 {
540sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
541ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
542if (ret == -1)
543{
544sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
545ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
546if (ret == -1)
547{
548// Not found any alternate locations, using the original kernel image path.
549strcpy(bootFileSpec, bootFile);
550}
551}
552 }
553
554 verbose("Loading kernel %s\n", bootFileSpec);
555 ret = LoadThinFatFile(bootFileSpec, &binary);
556 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
557 {
558archCpuType = CPU_TYPE_I386;
559ret = LoadThinFatFile(bootFileSpec, &binary);
560 }
561
562 } while (0);
563
564 clearActivityIndicator();
565#if DEBUG
566 printf("Pausing...");
567 sleep(8);
568#endif
569
570 if (ret <= 0) {
571printf("Can't find %s\n", bootFile);
572
573sleep(1);
574#ifndef OPTION_ROM
575 if (gBootFileType == kNetworkDeviceType) {
576 // Return control back to PXE. Don't unload PXE base code.
577 gUnloadPXEOnExit = false;
578 break;
579 }
580#endif
581 } else {
582 /* Won't return if successful. */
583// Notify modules that ExecKernel is about to be called
584execute_hook("ExecKernel", binary, NULL, NULL, NULL);
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: 535