Chameleon

Chameleon Svn Source Tree

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

Source at commit 505 created 13 years 7 months ago.
By meklort, Sync with trunk, untested
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 "gui.h"
60#include "platform.h"
61#include "resolution.h"
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];
72bool gEnableCDROMRescan;
73bool gScanSingleDrive;
74
75int bvCount = 0;
76//intmenucount = 0;
77int gDeviceCount = 0;
78
79boolrecoveryMode = false;
80
81BVRef bvr;
82BVRef menuBVR;
83BVRef bvChain;
84bool useGUI;
85
86//static void selectBiosDevice(void);
87static unsigned long Adler32(unsigned char *buffer, long length);
88static bool getOSVersion(char *str);
89
90static bool gUnloadPXEOnExit = false;
91
92/*
93 * How long to wait (in seconds) to load the
94 * kernel after displaying the "boot:" prompt.
95 */
96#define kBootErrorTimeout 5
97
98/*
99 * Default path to kernel cache file
100 */
101#define kDefaultCachePath "/System/Library/Caches/com.apple.kernelcaches/kernelcache"
102
103//==========================================================================
104// Zero the BSS.
105
106static void zeroBSS(void)
107{
108extern char _DATA__bss__begin, _DATA__bss__end;
109extern char _DATA__common__begin, _DATA__common__end;
110
111bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
112bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
113}
114
115//==========================================================================
116// Malloc error function
117
118static void malloc_error(char *addr, size_t size, const char *file, int line)
119{
120stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
121}
122
123//==========================================================================
124//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
125//
126void initialize_runtime(void)
127{
128zeroBSS();
129malloc_init(0, 0, 0, malloc_error);
130}
131
132//==========================================================================
133// execKernel - Load the kernel image (mach-o) and jump to its entry point.
134
135static int ExecKernel(void *binary)
136{
137 entry_t kernelEntry;
138 int ret;
139
140 bootArgs->kaddr = bootArgs->ksize = 0;
141
142 ret = DecodeKernel(binary,
143 &kernelEntry,
144 (char **) &bootArgs->kaddr,
145 (int *)&bootArgs->ksize );
146
147 if ( ret != 0 )
148 return ret;
149
150 // Reserve space for boot args
151 reserveKernBootStruct();
152
153 // Load boot drivers from the specifed root path.
154
155 if (!gHaveKernelCache) {
156 LoadDrivers("/");
157 }
158
159 clearActivityIndicator();
160
161 if (gErrors) {
162 printf("Errors encountered while starting up the computer.\n");
163 printf("Pausing %d seconds...\n", kBootErrorTimeout);
164 sleep(kBootErrorTimeout);
165 }
166
167md0Ramdisk();
168
169 setupFakeEfi();
170
171 md0Ramdisk();
172
173 verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
174
175 // Cleanup the PXE base code.
176
177 if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) {
178if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
179 {
180 printf("nbpUnloadBaseCode error %d\n", (int) ret);
181 sleep(2);
182 }
183 }
184
185 bool dummyVal;
186if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->bootConfig) && dummyVal) {
187printf("Press any key to continue...");
188getc();
189}
190
191usb_loop();
192
193 // If we were in text mode, switch to graphics mode.
194 // This will draw the boot graphics unless we are in
195 // verbose mode.
196
197 if(gVerboseMode)
198 setVideoMode( GRAPHICS_MODE, 0 );
199 else
200 drawBootGraphics();
201
202setupBooterLog();
203
204 finalizeBootStruct();
205
206usb_loop();
207
208execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgs, NULL, NULL);// Notify modules that the kernel is about to be started
209
210// Jump to kernel's entry point. There's no going back now.
211 startprog( kernelEntry, bootArgs );
212
213 // Not reached
214
215 return 0;
216}
217
218//==========================================================================
219// This is the entrypoint from real-mode which functions exactly as it did
220// before. Multiboot does its own runtime initialization, does some of its
221// own things, and then calls common_boot.
222void boot(int biosdev)
223{
224initialize_runtime();
225// Enable A20 gate before accessing memory above 1Mb.
226enableA20();
227common_boot(biosdev);
228}
229
230//==========================================================================
231// The 'main' function for the booter. Called by boot0 when booting
232// from a block device, or by the network booter.
233//
234// arguments:
235// biosdev - Value passed from boot1/NBP to specify the device
236// that the booter was loaded from.
237//
238// If biosdev is kBIOSDevNetwork, then this function will return if
239// booting was unsuccessful. This allows the PXE firmware to try the
240// next boot device on its list.
241void common_boot(int biosdev)
242{
243 int status;
244 char *bootFile;
245 unsigned long adler32;
246 bool quiet;
247 bool firstRun = true;
248 bool instantMenu;
249 bool rescanPrompt;
250 unsigned int allowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
251 unsigned int denyBVFlags = kBVFlagEFISystem;
252
253 // Set reminder to unload the PXE base code. Neglect to unload
254 // the base code will result in a hang or kernel panic.
255 gUnloadPXEOnExit = true;
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// Intialize module system
297if(init_module_system())
298{
299load_all_modules();
300}
301
302
303
304 // Loading preboot ramdisk if exists.
305 loadPrebootRAMDisk();
306
307 // Disable rescan option by default
308 gEnableCDROMRescan = false;
309
310 // Enable it with Rescan=y in system config
311 if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan) {
312 gEnableCDROMRescan = true;
313 }
314
315 // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
316 rescanPrompt = false;
317 if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->bootConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) {
318 gEnableCDROMRescan = promptForRescanOption();
319 }
320
321 // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
322 if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive) {
323 gScanSingleDrive = true;
324 }
325
326 // Create a list of partitions on device(s).
327 if (gScanSingleDrive) {
328 scanBootVolumes(gBIOSDev, &bvCount);
329 } else {
330 scanDisks(gBIOSDev, &bvCount);
331 }
332
333 // Create a separated bvr chain using the specified filters.
334 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
335
336 gBootVolume = selectBootVolume(bvChain);
337
338#if DEBUG
339 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
340 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
341 getc();
342#endif
343
344useGUI = true;
345// Override useGUI default
346getBoolForKey(kGUIKey, &useGUI, &bootInfo->bootConfig);
347if (useGUI && initGUI())
348{
349// initGUI() returned with an error, disabling GUI.
350useGUI = false;
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.
386 if(gBootVolume == NULL)
387 {
388 freeFilteredBVChain(bvChain);
389
390 if (gEnableCDROMRescan)
391 rescanBIOSDevice(gBIOSDev);
392
393 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
394 setBootGlobals(bvChain);
395 setupDeviceList(&bootInfo->themeConfig);
396 }
397 continue;
398 }
399
400 // Other status (e.g. 0) means that we should proceed with boot.
401
402// Turn off any GUI elements
403if( bootArgs->Video.v_display == GRAPHICS_MODE )
404{
405gui.devicelist.draw = false;
406gui.bootprompt.draw = false;
407gui.menu.draw = false;
408gui.infobox.draw = false;
409gui.logo.draw = false;
410drawBackground();
411updateVRAM();
412}
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 {
540 sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
541 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
542 if (ret == -1)
543 {
544 sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
545 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
546 if (ret == -1)
547 {
548 // Not found any alternate locations, using the original kernel image path.
549 strcpy(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 {
558 archCpuType = CPU_TYPE_I386;
559 ret = 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
575 if (gBootFileType == kNetworkDeviceType) {
576 // Return control back to PXE. Don't unload PXE base code.
577 gUnloadPXEOnExit = false;
578 break;
579 }
580 } else {
581 /* Won't return if successful. */
582// Notify modules that ExecKernel is about to be called
583execute_hook("ExecKernel", binary, NULL, NULL, NULL);
584 ret = ExecKernel(binary);
585 }
586 }
587
588 // chainboot
589 if (status==1) {
590if (getVideoMode() == GRAPHICS_MODE) {// if we are already in graphics-mode,
591setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
592}
593 }
594
595 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
596nbpUnloadBaseCode();
597 }
598}
599
600/*!
601 Selects a new BIOS device, taking care to update the global state appropriately.
602 */
603/*
604static 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: 505