Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 164