Chameleon

Chameleon Svn Source Tree

Root/branches/azimutz/Chazi/i386/boot2/boot.c

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//#define DEBUG 1
53
54//#include "bootstruct.h"
55//#include "libsa.h"
56#include "boot.h"
57#include "ramdisk.h" // bootstruct.h: memory.h instead of saio_internal.h
58#include "gui.h"
59#include "modules.h"
60#include "fake_efi.h"
61#include "platform.h" // bootstruct.h - device_tree.h
62#include "sl.h" // bootstruct.h: memory.h instead of saio_types.h
63
64long gBootMode; /* defaults to 0 == kBootModeNormal */
65bool gOverrideKernel;
66static char gBootKernelCacheFile[512];
67static char gCacheNameAdler[64 + 256];
68//char *gPlatformName = gCacheNameAdler; disabled
69char gRootDevice[512];
70char gMKextName[512];
71bool gEnableCDROMRescan;
72bool gScanSingleDrive;
73
74int bvCount = 0;
75//intmenucount = 0;
76int gDeviceCount = 0;
77
78BVRef bvr;
79//BVRef menuBVR; - doesn't seem used here
80BVRef bvChain;
81bool useGUI;
82
83//static void selectBiosDevice(void);
84static unsigned long Adler32(unsigned char *buffer, long length);
85
86
87static bool gUnloadPXEOnExit = false;
88
89/*
90 * How long to wait (in seconds) to load the
91 * kernel after displaying the "boot:" prompt.
92 */
93#define kBootErrorTimeout 5
94
95/*
96 * Default path to kernel cache file
97 */
98#define kDefaultCachePath "/System/Library/Caches/com.apple.kernelcaches/kernelcache"
99
100//==========================================================================
101// Zero the BSS.
102
103static void zeroBSS(void)
104{
105extern char _DATA__bss__begin, _DATA__bss__end;
106extern char _DATA__common__begin, _DATA__common__end;
107
108bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
109bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
110}
111
112//==========================================================================
113// Malloc error function
114
115static void malloc_error(char *addr, size_t size, const char *file, int line)
116{
117stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
118}
119
120//==========================================================================
121//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
122//
123void initialize_runtime(void)
124{
125zeroBSS();
126malloc_init(0, 0, 0, malloc_error);
127}
128
129//==========================================================================
130// execKernel - Load the kernel image (mach-o) and jump to its entry point.
131extern void startAutoRes();
132extern void endAutoRes();
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) {
155 LoadDrivers("/");
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
166 setupFakeEfi();
167
168 md0Ramdisk();
169
170 verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
171
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
182 bool dummyVal;
183
184//Azi: Wait=y is breaking other keys when typed "after them" at boot prompt.
185// Works properly if typed in first place or used on Boot.plist.
186if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->bootConfig) && dummyVal) {
187pause();
188}
189
190usb_loop();
191
192// Notify modules that the kernel is about to be started
193execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgs, NULL, NULL);
194
195//AutoResolution - Check if user disabled AutoResolution at the boot prompt.
196getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig);
197// Cancel and/or finalize the patch.
198endAutoRes();
199
200 // If we were in text mode, switch to graphics mode.
201 // This will draw the boot graphics unless we are in
202 // verbose mode.
203
204 if(gVerboseMode)
205 setVideoMode( GRAPHICS_MODE, 0 );
206 else
207 drawBootGraphics();
208
209setupBooterLog();
210
211 finalizeBootStruct();
212
213 // Jump to kernel's entry point. There's no going back now.
214
215 startprog( kernelEntry, bootArgs );
216
217 // Not reached
218
219 return 0;
220}
221
222//==========================================================================
223// This is the entrypoint from real-mode which functions exactly as it did
224// before. Multiboot does its own runtime initialization, does some of its
225// own things, and then calls common_boot.
226void boot(int biosdev)
227{
228initialize_runtime();
229// Enable A20 gate before accessing memory above 1Mb.
230enableA20();
231common_boot(biosdev);
232}
233
234//==========================================================================
235// The 'main' function for the booter. Called by boot0 when booting
236// from a block device, or by the network booter.
237//
238// arguments:
239// biosdev - Value passed from boot1/NBP to specify the device
240// that the booter was loaded from.
241//
242// If biosdev is kBIOSDevNetwork, then this function will return if
243// booting was unsuccessful. This allows the PXE firmware to try the
244// next boot device on its list.
245void common_boot(int biosdev)
246{
247 int status;
248 char *bootFile;
249 unsigned long adler32;
250 bool quiet;
251 bool firstRun = true;
252 bool instantMenu;
253 bool rescanPrompt = false;
254 unsigned int allowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
255 unsigned int denyBVFlags = kBVFlagEFISystem;
256
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
261 // Record the device that the booter was loaded from.
262 gBIOSDev = biosdev & kBIOSDevMask;
263
264 // Initialize boot info structure.
265 initKernBootStruct();
266
267initBooterLog();
268
269 // Setup VGA text mode.
270 // Not sure if it is safe to call setVideoMode() before the
271 // config table has been loaded. Call video_mode() instead.
272#if DEBUG
273 printf("before video_mode\n"); //Azi: this one is not printing... i remember it did
274#endif
275 video_mode( 2 ); // 80x25 mono text mode.
276#if DEBUG
277 printf("after video_mode\n");
278#endif
279
280 // Scan and record the system's hardware information.
281 scan_platform();
282
283 // First get info for boot volume.
284 scanBootVolumes(gBIOSDev, 0);
285 bvChain = getBVChainForBIOSDev(gBIOSDev);
286//Azi: initialising gBIOSBootVolume & gBootVolume for the first time.. i think!?
287// also, kDefaultPartitionKey is checked here, on selectBootVolume.
288 setBootGlobals(bvChain);
289
290// Boot Volume is set as Root at this point so, pointing to Extra, /Extra or bt(0,0)/Extra
291// is exactly the same.Review bt(0,0)/bla bla paths......(Reviewing...)
292
293//Azi: works as expected but... trying this because Kernel=mach_kernel doesn't work on a
294// override Boot.plist; this makes it impossible to override e.g. Kernel=bt(0,0)mach_kernel
295// on the main Boot.plist, when loading kernel from ramdisk btAliased.
296loadPrebootRAMDisk();
297
298 // Load boot.plist config file
299 status = loadSystemConfig(&bootInfo->bootConfig);
300
301 if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet) {
302 gBootMode |= kBootModeQuiet;
303 }
304
305 // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
306 if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu) {
307 firstRun = false;
308 }
309
310// Loading preboot ramdisk if exists.
311//loadPrebootRAMDisk(); //Azi: this needs to be done before load_all_modules()
312// because of btAlias...(Reviewing...)
313
314// Intialize module system
315if (init_module_system())
316{
317load_all_modules();
318}
319
320 // Disable rescan option by default
321 gEnableCDROMRescan = false;
322
323 // If we're loading the booter from cd/dvd media...(Reviewing...)
324if (biosDevIsCDROM(gBIOSDev))
325{
326// ... ask the user for Rescan option by setting "Rescan Prompt"=y in system config...
327if (getBoolForKey(kRescanPromptKey, &rescanPrompt, &bootInfo->bootConfig) && rescanPrompt)
328{
329 gEnableCDROMRescan = promptForRescanOption();
330 }
331else // ... or enable it with Rescan=y in system config.
332 if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan)
333{
334 gEnableCDROMRescan = true;
335 }
336}
337
338//Azi: Is this a cdrom only thing?(Reviewing...)
339 // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
340 if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive)
341{
342scanBootVolumes(gBIOSDev, &bvCount);
343 }
344else
345{
346//Azi: scanDisks uses scanBootVolumes.
347scanDisks(gBIOSDev, &bvCount);
348}
349
350 // Create a separated bvr chain using the specified filters.
351 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
352
353 gBootVolume = selectBootVolume(bvChain);
354
355#if DEBUG
356 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
357 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
358 getc();
359#endif
360
361 useGUI = true;
362 // Override useGUI default
363 getBoolForKey(kGUIKey, &useGUI, &bootInfo->bootConfig);
364
365// AutoResolution - Azi: default to false
366// http://forum.voodooprojects.org/index.php/topic,1227.0.html
367gAutoResolution = false;
368
369// Check if user enabled AutoResolution on Boot.plist...
370getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig);
371
372// Patch the Video Bios with the extracted resolution, before initGui.
373if (gAutoResolution == true)
374{
375startAutoRes();
376}
377
378 if (useGUI && initGUI())
379{
380// initGUI() returned with an error, disabling GUI.
381useGUI = false;
382}
383
384 setBootGlobals(bvChain);
385
386 // Parse args, load and start kernel.
387 while (1) {
388 const char *val;
389 int len;
390 int trycache;
391 long flags, cachetime, kerneltime, exttime, sleeptime, time;
392 int ret = -1;
393 void *binary = (void *)kLoadAddr;
394 bool tryresume;
395 bool tryresumedefault;
396 bool forceresume;
397
398 // additional variable for testing alternate kernel image locations on boot helper partitions.
399 char bootFileSpec[512];
400
401 // Initialize globals.
402
403 sysConfigValid = false;
404 gErrors = false;
405
406 status = getBootOptions(firstRun);
407 firstRun = false;
408 if (status == -1) continue;
409
410//Azi: test (gBootVolume == NULL) - so far Ok!
411// Turn off any GUI elements, draw background and update VRAM.
412if ( bootArgs->Video.v_display == GRAPHICS_MODE )
413{
414gui.devicelist.draw = false;
415gui.bootprompt.draw = false;
416gui.menu.draw = false;
417gui.infobox.draw = false;
418gui.logo.draw = false;
419drawBackground();
420updateVRAM();
421}
422
423status = processBootOptions();
424
425//Azi: AutoResolution - closing Vbios here without restoring, causes an allocation error,
426// if the user tries to boot, after a e.g."Can't find bla_kernel" msg.
427// Doing it on execKernel() instead.
428
429// Status == 1 means to chainboot
430if ( status ==1 ) break;
431
432// Status == -1 means that gBootVolume is NULL. Config file is not mandatory anymore!
433if ( status == -1 )
434{
435// gBootVolume == NULL usually means the user hit escape.(Reviewing...)
436if (gBootVolume == NULL)
437{
438freeFilteredBVChain(bvChain);
439
440if (gEnableCDROMRescan)
441rescanBIOSDevice(gBIOSDev);
442
443bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
444setBootGlobals(bvChain);
445setupDeviceList(&bootInfo->themeConfig);
446}
447continue;
448}
449
450 // Other status (e.g. 0) means that we should proceed with boot.
451
452// If cpu handles 64 bit instructions...
453if (platformCPUFeature(CPU_FEATURE_EM64T))
454{
455// use x86_64 kernel arch,...
456archCpuType = CPU_TYPE_X86_64;
457}
458else
459{
460// else use i386 kernel arch.
461archCpuType = CPU_TYPE_I386;
462}
463// If user override...
464if (getValueForKey(kArchKey, &val, &len, &bootInfo->bootConfig))
465{
466// matches i386...
467if (strncmp(val, "i386", 4) == 0)
468{
469// use i386 kernel arch.
470archCpuType = CPU_TYPE_I386;
471}
472}
473
474if (!getBoolForKey (kWakeKey, &tryresume, &bootInfo->bootConfig)) {
475tryresume = true;
476tryresumedefault = true;
477} else {
478tryresumedefault = false;
479}
480
481if (!getBoolForKey (kForceWakeKey, &forceresume, &bootInfo->bootConfig)) {
482forceresume = false;
483}
484
485if (forceresume) {
486tryresume = true;
487tryresumedefault = false;
488}
489
490while (tryresume) {
491const char *tmp;
492BVRef bvr;
493if (!getValueForKey(kWakeKeyImageKey, &val, &len, &bootInfo->bootConfig))
494val="/private/var/vm/sleepimage";
495
496// Do this first to be sure that root volume is mounted
497ret = GetFileInfo(0, val, &flags, &sleeptime);
498
499if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
500break;
501
502// Can't check if it was hibernation Wake=y is required
503if (bvr->modTime == 0 && tryresumedefault)
504break;
505
506if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
507break;
508
509if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
510printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override.\n",bvr->modTime-sleeptime);
511break;
512}
513
514HibernateBoot((char *)val);
515break;
516}
517
518 // Reset cache name.
519 bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
520
521 sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
522
523 adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
524
525 if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
526 strlcpy(gBootKernelCacheFile, val, len+1);
527 } else {
528 sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePath, adler32);
529 }
530
531 // Check for cache file.
532 trycache = (((gBootMode & kBootModeSafe) == 0) &&
533 !gOverrideKernel &&
534 (gBootFileType == kBlockDeviceType) &&
535 (gMKextName[0] == '\0') &&
536 (gBootKernelCacheFile[0] != '\0'));
537
538verbose("Loading Darwin %s\n", gMacOSVersion);
539
540 if (trycache) do {
541
542 // if we haven't found the kernel yet, don't use the cache
543 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
544 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) {
545 trycache = 0;
546 break;
547 }
548 ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
549 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
550 || (cachetime < kerneltime)) {
551 trycache = 0;
552 break;
553 }
554 ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
555 if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
556 && (cachetime < exttime)) {
557 trycache = 0;
558 break;
559 }
560 if (kerneltime > exttime) {
561 exttime = kerneltime;
562 }
563 if (cachetime != (exttime + 1)) {
564 trycache = 0;
565 break;
566 }
567 } while (0);
568
569 do {
570 if (trycache) {
571 bootFile = gBootKernelCacheFile;
572 verbose("Loading kernel cache %s\n", bootFile);
573 ret = LoadFile(bootFile);
574 binary = (void *)kLoadAddr;
575 if (ret >= 0) {
576 break;
577 }
578 }
579 bootFile = bootInfo->bootFile;
580
581 // Try to load kernel image from alternate locations on boot helper partitions.
582 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
583 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
584 if (ret == -1)
585 {
586sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
587ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
588if (ret == -1)
589{
590sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
591ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
592if (ret == -1)
593{
594// Not found any alternate locations, using the original kernel image path.
595strcpy(bootFileSpec, bootFile);
596}
597}
598 }
599
600 verbose("Loading kernel %s\n", bootFileSpec);
601 ret = LoadThinFatFile(bootFileSpec, &binary);
602 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
603 {
604archCpuType = CPU_TYPE_I386;
605ret = LoadThinFatFile(bootFileSpec, &binary);
606 }
607
608 } while (0);
609
610 clearActivityIndicator();
611/*#if DEBUG
612 printf("Pausing...");
613 sleep(8);
614#endif
615Azi: annoying stuff :P */
616 if (ret <= 0) {
617printf("Can't find %s\n", bootFile);
618
619sleep(1);
620
621 if (gBootFileType == kNetworkDeviceType) {
622 // Return control back to PXE. Don't unload PXE base code.
623 gUnloadPXEOnExit = false;
624 break;
625 }
626 } else {
627 /* Won't return if successful. */
628// Notify modules that ExecKernel is about to be called
629execute_hook("ExecKernel", binary, NULL, NULL, NULL);
630
631 ret = ExecKernel(binary);
632 }
633 }
634
635 // chainboot
636 if (status==1) {
637if (getVideoMode() == GRAPHICS_MODE) {// if we are already in graphics-mode,
638setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
639}
640 }
641
642 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit)
643{
644nbpUnloadBaseCode();
645 }
646}
647
648/*!
649 Selects a new BIOS device, taking care to update the global state appropriately.
650 */
651/*
652static void selectBiosDevice(void)
653{
654 struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
655 CacheReset();
656 diskFreeMap(oldMap);
657 oldMap = NULL;
658
659 int dev = selectAlternateBootDevice(gBIOSDev);
660
661 BVRef bvchain = scanBootVolumes(dev, 0);
662 BVRef bootVol = selectBootVolume(bvchain);
663 gBootVolume = bootVol;
664 setRootVolume(bootVol);
665 gBIOSDev = dev;
666}
667*/
668
669#define BASE 65521L /* largest prime smaller than 65536 */
670#define NMAX 5000
671// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
672
673#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
674#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
675#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
676#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
677#define DO16(buf) DO8(buf,0); DO8(buf,8);
678
679unsigned long Adler32(unsigned char *buf, long len)
680{
681 unsigned long s1 = 1; // adler & 0xffff;
682 unsigned long s2 = 0; // (adler >> 16) & 0xffff;
683 unsigned long result;
684 int k;
685
686 while (len > 0) {
687 k = len < NMAX ? len : NMAX;
688 len -= k;
689 while (k >= 16) {
690 DO16(buf);
691 buf += 16;
692 k -= 16;
693 }
694 if (k != 0) do {
695 s1 += *buf++;
696 s2 += s1;
697 } while (--k);
698 s1 %= BASE;
699 s2 %= BASE;
700 }
701 result = (s2 << 16) | s1;
702 return OSSwapHostToBigInt32(result);
703}
704

Archive Download this file

Revision: 603