Chameleon

Chameleon Svn Source Tree

Root/branches/meklort/i386/boot2/boot.c

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

Archive Download this file

Revision: 145