Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 387