Chameleon

Chameleon Svn Source Tree

Root/branches/azimutz/trunkAutoResolution/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/*
26 * Mach Operating System
27 * Copyright (c) 1990 Carnegie-Mellon University
28 * Copyright (c) 1989 Carnegie-Mellon University
29 * All rights reserved. The CMU software License Agreement specifies
30 * the terms and conditions for use and redistribution.
31 */
32
33/*
34 *INTEL CORPORATION PROPRIETARY INFORMATION
35 *
36 *This software is supplied under the terms of a licenseagreement or
37 *nondisclosure agreement with Intel Corporation and may not be copied
38 *nor disclosed except in accordance with the terms of that agreement.
39 *
40 *Copyright 1988, 1989 by Intel Corporation
41 */
42
43/*
44 * Copyright 1993 NeXT Computer, Inc.
45 * All rights reserved.
46 */
47
48/*
49 * Completely reworked by Sam Streeper (sam_s@NeXT.com)
50 * Reworked again by Curtis Galloway (galloway@NeXT.com)
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 "autoresolution.h" //autoresolution
62#include "edid.h"//||
63#include "modules.h"
64
65/*
66 * How long to wait (in seconds) to load the
67 * kernel after displaying the "boot:" prompt.
68 */
69#define kBootErrorTimeout 5
70
71boolgOverrideKernel, gEnableCDROMRescan, gScanSingleDrive, useGUI;
72static boolgUnloadPXEOnExit = false;
73
74static chargCacheNameAdler[64 + 256];
75char*gPlatformName = gCacheNameAdler;
76
77chargRootDevice[512];
78chargMKextName[512];
79chargMacOSVersion[8];
80intbvCount = 0, gDeviceCount = 0;
81//intmenucount = 0;
82longgBootMode; /* defaults to 0 == kBootModeNormal */
83BVRefbvr, menuBVR, bvChain;
84
85static boolcheckOSVersion(const char * version);
86static boolgetOSVersion();
87static unsigned longAdler32(unsigned char *buffer, long length);
88//static voidselectBiosDevice(void);
89
90/** options.c **/
91extern char* msgbuf;
92void showTextBuffer(char *buf, int size);
93
94
95//==========================================================================
96// Zero the BSS.
97
98static void zeroBSS(void)
99{
100extern char _DATA__bss__begin, _DATA__bss__end;
101extern char _DATA__common__begin, _DATA__common__end;
102
103bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
104bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
105}
106
107//==========================================================================
108// Malloc error function
109
110static void malloc_error(char *addr, size_t size, const char *file, int line)
111{
112stop("\nMemory allocation error! Addr: 0x%x, Size: 0x%x, File: %s, Line: %d\n",
113 (unsigned)addr, (unsigned)size, file, line);
114}
115
116//==========================================================================
117//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
118//
119void initialize_runtime(void)
120{
121zeroBSS();
122malloc_init(0, 0, 0, malloc_error);
123}
124
125//==========================================================================
126// execKernel - Load the kernel image (mach-o) and jump to its entry point.
127
128static int ExecKernel(void *binary)
129{
130intret;
131entry_tkernelEntry;
132
133bootArgs->kaddr = bootArgs->ksize = 0;
134execute_hook("ExecKernel", (void*)binary, NULL, NULL, NULL);
135
136ret = DecodeKernel(binary,
137 &kernelEntry,
138 (char **) &bootArgs->kaddr,
139 (int *)&bootArgs->ksize );
140
141if ( ret != 0 )
142return ret;
143
144// Reserve space for boot args
145reserveKernBootStruct();
146
147// Notify modules that the kernel has been decoded
148execute_hook("DecodedKernel", (void*)binary, NULL, NULL, NULL);
149
150setupFakeEfi();
151
152// Load boot drivers from the specifed root path.
153//if (!gHaveKernelCache)
154LoadDrivers("/");
155
156execute_hook("DriversLoaded", (void*)binary, NULL, NULL, NULL);
157
158clearActivityIndicator();
159
160if (gErrors) {
161printf("Errors encountered while starting up the computer.\n");
162printf("Pausing %d seconds...\n", kBootErrorTimeout);
163sleep(kBootErrorTimeout);
164}
165
166md0Ramdisk();
167
168verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
169
170// Cleanup the PXE base code.
171
172if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) {
173if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
174{
175printf("nbpUnloadBaseCode error %d\n", (int) ret);
176sleep(2);
177}
178}
179
180bool dummyVal;
181if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->chameleonConfig) && dummyVal) {
182showTextBuffer(msgbuf, strlen(msgbuf));
183}
184
185usb_loop();
186
187//autoresolution - Check if user disabled AutoResolution at the boot prompt.
188getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig); //Azi: bootConfig ??
189
190// User disabled AutoResolution at boot prompt...
191if ((gAutoResolution == false) && map)
192{
193// restore and close Vbios for patch cancelation.
194restoreVbios(map);
195closeVbios(map);
196}
197
198//Azi: while testing, i didn't got any problems when booting without
199// closing Vbios... closing it just in case. (check again later!)
200if ((gAutoResolution == true) && map)
201{
202closeVbios(map);
203
204// gAutoResolution was just set to false on closeVbios();
205// we need it to be "true" for drawBootGraphics().
206gAutoResolution = true;
207}
208
209//Azi: closing Vbios after "if (gVerboseMode)" stuff eliminates the need for setting
210// AutoResolution = true above; but creates another bug when booting in TextMode with -v arg.
211// Simptoms include: staring some seconds at a nicely drawn white screen, after boot prompt.
212// Think i'm just going to end up removing setting gAutoResolution = false
213// on closeVbios().. the more i think, the less sense it makes doing it there!!
214//autoresolution - end
215
216// Notify modules that the kernel is about to be started
217if (checkOSVersion("10.7"))
218{
219execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgs, NULL, NULL);
220}
221else
222{
223execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgsPreLion, NULL, NULL);
224}
225
226// If we were in text mode, switch to graphics mode.
227// This will draw the boot graphics unless we are in
228// verbose mode.
229if (gVerboseMode)
230setVideoMode( GRAPHICS_MODE, 0 );
231else
232drawBootGraphics();
233
234setupBooterLog();
235
236finalizeBootStruct();
237
238// Jump to kernel's entry point. There's no going back now.
239if (checkOSVersion("10.7")) {
240
241// Masking out so that Lion doesn't doublefault
242outb(0x21, 0xff);/* Maskout all interrupts Pic1 */
243outb(0xa1, 0xff);/* Maskout all interrupts Pic2 */
244
245startprog( kernelEntry, bootArgs );
246}
247else {
248startprog( kernelEntry, bootArgsPreLion );
249}
250
251// Not reached
252return 0;
253}
254
255
256//==========================================================================
257// LoadKernelCache - Try to load Kernel Cache.
258// return the length of the loaded cache file or -1 on error
259long LoadKernelCache(const char* cacheFile, void **binary) {
260charkernelCacheFile[512];
261charkernelCachePath[512];
262longflags, time, cachetime, kerneltime, exttime, ret=-1;
263 unsigned long adler32;
264
265// Use specify kernel cache file if not empty
266if (cacheFile[0] != 0)
267strlcpy(kernelCacheFile, cacheFile, sizeof(kernelCacheFile));
268else {
269// Lion prelink kernel cache file
270if (checkOSVersion("10.7")) {
271sprintf(kernelCacheFile, "%skernelcache", kDefaultCachePathSnow);
272}
273// Snow Leopard prelink kernel cache file
274else if (checkOSVersion("10.6")) {
275sprintf(kernelCacheFile, "kernelcache_%s", (archCpuType == CPU_TYPE_I386)
276? "i386" : "x86_64");
277int lnam = strlen(kernelCacheFile) + 9; //with adler32
278
279char* name;
280long prev_time = 0;
281
282struct dirstuff* cacheDir = opendir(kDefaultCachePathSnow);
283
284while(readdir(cacheDir, (const char**)&name, &flags, &time) >= 0)
285{
286if (((flags & kFileTypeMask) != kFileTypeDirectory) && time > prev_time
287&& strstr(name, kernelCacheFile) && (name[lnam] != '.'))
288{
289sprintf(kernelCacheFile, "%s%s", kDefaultCachePathSnow, name);
290prev_time = time;
291}
292}
293}
294else {
295// Reset cache name.
296bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
297sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
298adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
299sprintf(kernelCacheFile, "%s.%08lX", kDefaultCachePathLeo, adler32);
300}
301}
302
303// kernelCacheFile must start with a /
304if (kernelCacheFile[0] != '/') {
305char *str = strdup(kernelCacheFile);
306if (str == NULL)
307return -1;
308sprintf(kernelCacheFile, "/%s", str);
309free(str);
310}
311
312// Check if the kernel cache file exists
313ret = -1;
314
315// If boot from a boot helper partition check the kernel cache file on it
316if (gBootVolume->flags & kBVFlagBooter) {
317sprintf(kernelCachePath, "com.apple.boot.P%s", kernelCacheFile);
318ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime);
319if ((ret == -1) || ((flags & kFileTypeMask) != kFileTypeFlat))
320{
321sprintf(kernelCachePath, "com.apple.boot.R%s", kernelCacheFile);
322ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime);
323if ((ret == -1) || ((flags & kFileTypeMask) != kFileTypeFlat))
324{
325sprintf(kernelCachePath, "com.apple.boot.S%s", kernelCacheFile);
326ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime);
327if ((flags & kFileTypeMask) != kFileTypeFlat)
328ret = -1;
329}
330}
331}
332// If not found, use the original kernel cache path.
333if (ret == -1) {
334strcpy(kernelCachePath, kernelCacheFile);
335ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime);
336if ((flags & kFileTypeMask) != kFileTypeFlat)
337ret = -1;
338}
339
340// Exit if kernel cache file wasn't found
341if (ret == -1) {
342verbose("No Kernel Cache File '%s' found\n", kernelCacheFile);
343return -1;
344}
345
346// Check if the kernel cache file is more recent (mtime)
347// than the kernel file or the S/L/E directory
348ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
349// Check if the kernel file is more recent than the cache file
350if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeFlat)
351&& (kerneltime > cachetime)) {
352verbose("Kernel file (%s) is more recent than KernelCache (%s), ignoring KernelCache\n",
353bootInfo->bootFile, kernelCacheFile);
354return -1;
355}
356
357ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
358// Check if the S/L/E directory time is more recent than the cache file
359if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
360&& (exttime > cachetime)) {
361verbose("/System/Library/Extensions is more recent than KernelCache (%s), ignoring KernelCache\n",
362kernelCacheFile);
363return -1;
364}
365
366// Since the kernel cache file exists and is the most recent try to load it
367verbose("Loading kernel cache %s\n", kernelCachePath);
368
369if (checkOSVersion("10.7")) {
370ret = LoadThinFatFile(kernelCachePath, binary);
371} else {
372ret = LoadFile(kernelCachePath);
373*binary = (void *)kLoadAddr;
374}
375return ret; // ret contain the length of the binary
376}
377
378//==========================================================================
379// This is the entrypoint from real-mode which functions exactly as it did
380// before. Multiboot does its own runtime initialization, does some of its
381// own things, and then calls common_boot.
382void boot(int biosdev)
383{
384initialize_runtime();
385// Enable A20 gate before accessing memory above 1Mb.
386enableA20();
387common_boot(biosdev);
388}
389
390//==========================================================================
391// The 'main' function for the booter. Called by boot0 when booting
392// from a block device, or by the network booter.
393//
394// arguments:
395// biosdev - Value passed from boot1/NBP to specify the device
396// that the booter was loaded from.
397//
398// If biosdev is kBIOSDevNetwork, then this function will return if
399// booting was unsuccessful. This allows the PXE firmware to try the
400// next boot device on its list.
401void common_boot(int biosdev)
402{
403bool quiet;
404bool firstRun = true;
405bool instantMenu;
406bool rescanPrompt;
407intstatus;
408unsigned intallowBVFlags = kBVFlagSystemVolume | kBVFlagForeignBoot;
409unsigned intdenyBVFlags = kBVFlagEFISystem;
410
411// Set reminder to unload the PXE base code. Neglect to unload
412// the base code will result in a hang or kernel panic.
413gUnloadPXEOnExit = true;
414
415// Record the device that the booter was loaded from.
416gBIOSDev = biosdev & kBIOSDevMask;
417
418// Initialize boot info structure.
419initKernBootStruct();
420
421initBooterLog();
422
423// Setup VGA text mode.
424// Not sure if it is safe to call setVideoMode() before the
425// config table has been loaded. Call video_mode() instead.
426#if DEBUG
427printf("before video_mode\n");
428#endif
429video_mode( 2 ); // 80x25 mono text mode.
430#if DEBUG
431printf("after video_mode\n");
432#endif
433
434// Scan and record the system's hardware information.
435scan_platform();
436
437// First get info for boot volume.
438scanBootVolumes(gBIOSDev, 0);
439bvChain = getBVChainForBIOSDev(gBIOSDev);
440setBootGlobals(bvChain);
441
442// Load boot.plist config file
443status = loadChameleonConfig(&bootInfo->chameleonConfig);
444
445if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->chameleonConfig) && quiet) {
446gBootMode |= kBootModeQuiet;
447}
448
449// Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
450if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->chameleonConfig) && instantMenu) {
451firstRun = false;
452}
453
454// Loading preboot ramdisk if exists.
455loadPrebootRAMDisk();
456
457// Disable rescan option by default
458gEnableCDROMRescan = false;
459
460// Enable it with Rescan=y in system config
461if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->chameleonConfig)
462&& gEnableCDROMRescan) {
463gEnableCDROMRescan = true;
464}
465
466// Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
467rescanPrompt = false;
468if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->chameleonConfig)
469&& rescanPrompt && biosDevIsCDROM(gBIOSDev))
470{
471gEnableCDROMRescan = promptForRescanOption();
472}
473
474// Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
475if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->chameleonConfig)
476&& gScanSingleDrive) {
477gScanSingleDrive = true;
478}
479
480// Create a list of partitions on device(s).
481if (gScanSingleDrive) {
482scanBootVolumes(gBIOSDev, &bvCount);
483} else {
484scanDisks(gBIOSDev, &bvCount);
485}
486
487// Create a separated bvr chain using the specified filters.
488bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
489
490gBootVolume = selectBootVolume(bvChain);
491
492// Intialize module system
493init_module_system();
494
495#if DEBUG
496printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n",
497 gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
498printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n",
499 gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
500getchar();
501#endif
502
503useGUI = true;
504// Override useGUI default
505getBoolForKey(kGUIKey, &useGUI, &bootInfo->chameleonConfig);
506
507//autoresolution - default to false
508// http://forum.voodooprojects.org/index.php/topic,1227.0.html
509gAutoResolution = false;
510
511// Check if user enabled AutoResolution on Boot.plist...
512getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig);
513
514// Patch the Video Bios with the extracted resolution, before initGui.
515if (gAutoResolution == true)
516{
517paramsAR[3] = 0;
518
519// Open the Vbios and store Vbios or Tables
520//Azi: doing this only if gAutoResolution = true
521map = openVbios(CT_UNKWN);
522
523//Get resolution from Graphics Mode key...
524int count = getNumberArrayFromProperty(kGraphicsModeKey, paramsAR, 4);
525// ... or EDID.
526if (count < 3)
527{
528getResolution(paramsAR); //Azi: hum...
529// check the DEBUG/PRINT stuff... also on TEXT MODE (this is not printing to screen). ???
530// don't forget we now have boot-log and it prints fine there.
531//Azi:autoresolution - these PRINT replace a previous existing #ifdef AUTORES_DEBUG
532// and were moved from gui.c, initGUI().
533PRINT("Resolution: %dx%d (EDID)\n",paramsAR[0], paramsAR[1]);
534}
535else //Azi: check theme.plist ??
536{
537PRINT("Resolution: %dx%d (Graphics Mode key)\n",paramsAR[0], paramsAR[1]);
538
539//Azi: hum...
540if ( paramsAR[2] == 256 ) paramsAR[2] = 8;
541if ( paramsAR[2] == 555 ) paramsAR[2] = 16;
542if ( paramsAR[2] == 888 ) paramsAR[2] = 32;
543}
544
545// perfom the actual Vbios patching
546if (paramsAR[0] != 0 && paramsAR[1] != 0)
547{
548patchVbios(map, paramsAR[0], paramsAR[1], paramsAR[2], 0, 0);
549}
550
551//Azi: passing resolution for TEXT MODE "verbose" boot. (check again later!)***
552if (bootArgs->Video.v_display == VGA_TEXT_MODE)
553{
554gui.screen.width = paramsAR[0];
555gui.screen.height = paramsAR[1];
556}
557
558// If the patch is working properly, we're almost done (we need? to close Vbios).
559// If not and it's just a matter of wrong resolution, we can try re-apply the patch;
560// see "case kF2Key:", options.c.
561}
562//autoresolution - end
563
564if (useGUI && initGUI())
565{
566// initGUI() returned with an error, disabling GUI.
567useGUI = false;
568}
569
570setBootGlobals(bvChain);
571
572// Parse args, load and start kernel.
573while (1)
574{
575booltryresume, tryresumedefault, forceresume;
576booluseKernelCache = false; // by default don't use prelink kernel cache
577const char*val;
578intlen, ret = -1;
579longflags, sleeptime, time;
580void*binary = (void *)kLoadAddr;
581
582char bootFile[sizeof(bootInfo->bootFile)];
583charbootFilePath[512];
584charkernelCacheFile[512];
585
586// Initialize globals.
587sysConfigValid = false;
588gErrors = false;
589
590status = getBootOptions(firstRun);
591firstRun = false;
592if (status == -1) continue;
593
594status = processBootOptions();
595// Status == 1 means to chainboot
596if ( status ==1 ) break;
597// Status == -1 means that the config file couldn't be loaded or that gBootVolume is NULL
598if ( status == -1 )
599{
600// gBootVolume == NULL usually means the user hit escape.
601if (gBootVolume == NULL)
602{
603freeFilteredBVChain(bvChain);
604
605if (gEnableCDROMRescan)
606rescanBIOSDevice(gBIOSDev);
607
608bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
609setBootGlobals(bvChain);
610setupDeviceList(&bootInfo->themeConfig);
611}
612continue;
613}
614
615// Other status (e.g. 0) means that we should proceed with boot.
616
617// Turn off any GUI elements
618if ( bootArgs->Video.v_display == GRAPHICS_MODE )
619{
620gui.devicelist.draw = false;
621gui.bootprompt.draw = false;
622gui.menu.draw = false;
623gui.infobox.draw = false;
624gui.logo.draw = false;
625drawBackground();
626updateVRAM();
627}
628
629//Azi: autoresolution stuff moved to ExecKernel();
630// Closing Vbios here without restoring it, causes an allocation error.
631
632// Find out which version mac os we're booting.
633getOSVersion();
634
635if (platformCPUFeature(CPU_FEATURE_EM64T)) {
636archCpuType = CPU_TYPE_X86_64;
637} else {
638archCpuType = CPU_TYPE_I386;
639}
640
641if (getValueForKey(karch, &val, &len, &bootInfo->chameleonConfig)) {
642if (strncmp(val, "i386", 4) == 0) {
643archCpuType = CPU_TYPE_I386;
644}
645}
646
647if (getValueForKey(kKernelArchKey, &val, &len, &bootInfo->chameleonConfig)) {
648if (strncmp(val, "i386", 4) == 0) {
649archCpuType = CPU_TYPE_I386;
650}
651}
652
653// Notify modules that we are attempting to boot
654execute_hook("PreBoot", NULL, NULL, NULL, NULL);
655
656if (!getBoolForKey (kWake, &tryresume, &bootInfo->chameleonConfig)) {
657tryresume = true;
658tryresumedefault = true;
659} else {
660tryresumedefault = false;
661}
662
663if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->chameleonConfig)) {
664forceresume = false;
665}
666
667if (forceresume) {
668tryresume = true;
669tryresumedefault = false;
670}
671
672while (tryresume) {
673const char *tmp;
674BVRef bvr;
675if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->chameleonConfig))
676val = "/private/var/vm/sleepimage";
677
678// Do this first to be sure that root volume is mounted
679ret = GetFileInfo(0, val, &flags, &sleeptime);
680
681if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
682break;
683
684// Can't check if it was hibernation Wake=y is required
685if (bvr->modTime == 0 && tryresumedefault)
686break;
687
688if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
689break;
690
691if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
692#if DEBUG
693printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",
694bvr->modTime-sleeptime);
695#endif
696break;
697}
698
699HibernateBoot((char *)val);
700break;
701}
702
703verbose("Loading Darwin %s\n", gMacOSVersion);
704
705// If boot from boot helper partitions and OS is Lion use prelink kernel.
706// We need to find a solution to load extra mkext with a prelink kernel.
707if (gBootVolume->flags & kBVFlagBooter && checkOSVersion("10.7"))
708useKernelCache = true;
709else
710useKernelCache = false; // by default don't use prelink kernel cache
711
712getBoolForKey(kUseKernelCache, &useKernelCache, &bootInfo->chameleonConfig);
713
714if (useKernelCache) do {
715
716// Determine the name of the Kernel Cache
717if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
718if (val[0] == '\\')
719{
720len--;
721val++;
722}
723strlcpy(kernelCacheFile, val, len + 1);
724} else {
725kernelCacheFile[0] = 0; // Use default kernel cache file
726}
727
728if (gOverrideKernel && kernelCacheFile[0] == 0) {
729verbose("Using a non default kernel (%s) without specifying 'Kernel Cache' path, KernelCache will not be used\n",
730bootInfo->bootFile);
731useKernelCache = false;
732break;
733}
734if (gMKextName[0] != 0) {
735verbose("Using a specific MKext Cache (%s), KernelCache will not be used\n",
736gMKextName);
737useKernelCache = false;
738break;
739}
740if (gBootFileType != kBlockDeviceType)
741useKernelCache = false;
742
743} while(0);
744
745do {
746if (useKernelCache) {
747ret = LoadKernelCache(kernelCacheFile, &binary);
748if (ret >= 0)
749break;
750}
751
752bool bootFileWithDevice = false;
753// Check if bootFile start with a device ex: bt(0,0)/Extra/mach_kernel
754if (strncmp(bootInfo->bootFile,"bt(",3) == 0 ||
755strncmp(bootInfo->bootFile,"hd(",3) == 0 ||
756strncmp(bootInfo->bootFile,"rd(",3) == 0)
757bootFileWithDevice = true;
758
759// bootFile must start with a / if it not start with a device name
760if (!bootFileWithDevice && (bootInfo->bootFile)[0] != '/')
761sprintf(bootFile, "/%s", bootInfo->bootFile); // append a leading /
762else
763strlcpy(bootFile, bootInfo->bootFile, sizeof(bootFile));
764
765// Try to load kernel image from alternate locations on boot helper partitions.
766ret = -1;
767if ((gBootVolume->flags & kBVFlagBooter) && !bootFileWithDevice) {
768sprintf(bootFilePath, "com.apple.boot.P%s", bootFile);
769ret = GetFileInfo(NULL, bootFilePath, &flags, &time);
770if (ret == -1)
771{
772sprintf(bootFilePath, "com.apple.boot.R%s", bootFile);
773ret = GetFileInfo(NULL, bootFilePath, &flags, &time);
774if (ret == -1)
775{
776sprintf(bootFilePath, "com.apple.boot.S%s", bootFile);
777ret = GetFileInfo(NULL, bootFilePath, &flags, &time);
778}
779}
780}
781if (ret == -1) {
782// No alternate location found, using the original kernel image path.
783strlcpy(bootFilePath, bootFile,sizeof(bootFilePath));
784}
785
786verbose("Loading kernel %s\n", bootFilePath);
787ret = LoadThinFatFile(bootFilePath, &binary);
788if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
789{
790archCpuType = CPU_TYPE_I386;
791ret = LoadThinFatFile(bootFilePath, &binary);
792}
793} while (0);
794
795clearActivityIndicator();
796
797#if DEBUG
798printf("Pausing...");
799sleep(8);
800#endif
801
802if (ret <= 0) {
803printf("Can't find %s\n", bootFile);
804sleep(1);
805
806if (gBootFileType == kNetworkDeviceType) {
807// Return control back to PXE. Don't unload PXE base code.
808gUnloadPXEOnExit = false;
809break;
810}
811pause();
812
813} else {
814/* Won't return if successful. */
815ret = ExecKernel(binary);
816}
817}
818
819// chainboot
820if (status == 1) {
821// if we are already in graphics-mode,
822if (getVideoMode() == GRAPHICS_MODE) {
823setVideoMode(VGA_TEXT_MODE, 0); // switch back to text mode.
824}
825}
826
827if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
828nbpUnloadBaseCode();
829}
830}
831
832/*!
833Selects a new BIOS device, taking care to update the global state appropriately.
834 */
835/*
836static void selectBiosDevice(void)
837{
838struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
839CacheReset();
840diskFreeMap(oldMap);
841oldMap = NULL;
842
843int dev = selectAlternateBootDevice(gBIOSDev);
844
845BVRef bvchain = scanBootVolumes(dev, 0);
846BVRef bootVol = selectBootVolume(bvchain);
847gBootVolume = bootVol;
848setRootVolume(bootVol);
849gBIOSDev = dev;
850}
851*/
852
853bool checkOSVersion(const char * version)
854{
855return ((gMacOSVersion[0] == version[0]) && (gMacOSVersion[1] == version[1])
856&& (gMacOSVersion[2] == version[2]) && (gMacOSVersion[3] == version[3]));
857}
858
859bool getOSVersion()
860{
861boolvalid = false;
862const char*val;
863intlen;
864config_file_tsystemVersion;
865
866if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion))
867{
868valid = true;
869}
870else if (!loadConfigFile("System/Library/CoreServices/ServerVersion.plist", &systemVersion))
871{
872valid = true;
873}
874
875if (valid)
876{
877if(getValueForKey(kProductVersion, &val, &len, &systemVersion))
878{
879// getValueForKey uses const char for val
880// so copy it and trim
881*gMacOSVersion = '\0';
882strncat(gMacOSVersion, val, MIN(len, 4));
883}
884else
885valid = false;
886}
887
888return valid;
889}
890
891#define BASE 65521L /* largest prime smaller than 65536 */
892#define NMAX 5000
893// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
894
895#define DO1(buf, i){s1 += buf[i]; s2 += s1;}
896#define DO2(buf, i)DO1(buf, i); DO1(buf, i + 1);
897#define DO4(buf, i)DO2(buf, i); DO2(buf, i + 2);
898#define DO8(buf, i)DO4(buf, i); DO4(buf, i + 4);
899#define DO16(buf)DO8(buf, 0); DO8(buf, 8);
900
901unsigned long Adler32(unsigned char *buf, long len)
902{
903unsigned long s1 = 1; // adler & 0xffff;
904unsigned long s2 = 0; // (adler >> 16) & 0xffff;
905unsigned long result;
906int k;
907
908while (len > 0) {
909k = len < NMAX ? len : NMAX;
910len -= k;
911while (k >= 16) {
912DO16(buf);
913buf += 16;
914k -= 16;
915}
916if (k != 0) do {
917s1 += *buf++;
918s2 += s1;
919} while (--k);
920s1 %= BASE;
921s2 %= BASE;
922}
923result = (s2 << 16) | s1;
924return OSSwapHostToBigInt32(result);
925}
926

Archive Download this file

Revision: 1467