Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 4