Chameleon

Chameleon Svn Source Tree

Root/branches/azimutz/Chazileon/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//#define DEBUG 1 //Azi:temp
53
54//Azi:include
55//#include "boot.h" - included on graphics.h, which is included on gui.h
56//#include "bootstruct.h" - same as above
57#include "fake_efi.h"
58#include "gui.h"
59//#include "libsa.h" - included on libsaio.h, which is included on sl.h
60#include "platform.h"
61#include "ramdisk.h"
62#include "sl.h"
63
64#include "edid.h" // Autoresolution
65#include "autoresolution.h" // "was" included on boot.h, which is everywere!! -> gui.h -> graphics.h
66
67long gBootMode; /* defaults to 0 == kBootModeNormal */
68bool gOverrideKernel;
69static char gBootKernelCacheFile[512];
70static char gCacheNameAdler[64 + 256];
71//char *gPlatformName = gCacheNameAdler; Azi: not in use
72char gRootDevice[512];
73char gMKextName[512];
74//char gMacOSVersion[8]; //Azi:sysversion - TODO: check why doesn't work here.
75bool gEnableCDROMRescan;
76bool gScanSingleDrive;
77
78int bvCount = 0;
79//intmenucount = 0;
80int gDeviceCount = 0;
81
82BVRef bvr;
83BVRef menuBVR;
84BVRef bvChain;
85bool useGUI;
86
87//static void selectBiosDevice(void);
88static unsigned long Adler32(unsigned char *buffer, long length);
89
90static bool gUnloadPXEOnExit = false;
91
92/*
93 * How long to wait (in seconds) to load the
94 * kernel after displaying the "boot:" prompt.
95 */
96#define kBootErrorTimeout 5
97
98/*
99 * Default path to kernel cache file
100 */
101#define kDefaultCachePath "/System/Library/Caches/com.apple.kernelcaches/kernelcache"
102
103//==========================================================================
104// Zero the BSS.
105
106static void zeroBSS(void)
107{
108extern char _DATA__bss__begin, _DATA__bss__end;
109extern char _DATA__common__begin, _DATA__common__end;
110
111bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
112bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
113}
114
115//==========================================================================
116// Malloc error function
117
118static void malloc_error(char *addr, size_t size, const char *file, int line)
119{
120stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
121}
122
123//==========================================================================
124//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
125//
126void initialize_runtime(void)
127{
128zeroBSS();
129malloc_init(0, 0, 0, malloc_error);
130}
131
132//==========================================================================
133// execKernel - Load the kernel image (mach-o) and jump to its entry point.
134
135static int ExecKernel(void *binary)
136{
137 entry_t kernelEntry;
138 int ret;
139
140 bootArgs->kaddr = bootArgs->ksize = 0;
141
142 ret = DecodeKernel(binary,
143 &kernelEntry,
144 (char **) &bootArgs->kaddr,
145 (int *)&bootArgs->ksize );
146
147 if ( ret != 0 )
148 return ret;
149
150 // Reserve space for boot args
151 reserveKernBootStruct();
152
153 // Load boot drivers from the specifed root path.
154
155 if (!gHaveKernelCache) {
156 LoadDrivers("/");
157 }
158
159 clearActivityIndicator();
160
161 if (gErrors) {
162 printf("Errors encountered while starting up the computer.\n");
163 printf("Pausing %d seconds...\n", kBootErrorTimeout);
164 sleep(kBootErrorTimeout);
165 }
166
167 setupFakeEfi();
168
169 md0Ramdisk();
170
171 verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
172
173 // Cleanup the PXE base code.
174
175 if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) {
176if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
177 {
178 printf("nbpUnloadBaseCode error %d\n", (int) ret);
179 sleep(2);
180 }
181 }
182
183 bool dummyVal;
184
185//Azi: Wait=y is breaking other keys when typed "after them" at boot prompt.
186// Works properly if typed in first place or used on Boot.plist.
187if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->bootConfig) && dummyVal) {
188pause();
189}
190
191usb_loop();
192
193 // If we were in text mode, switch to graphics mode.
194 // This will draw the boot graphics unless we are in
195 // verbose mode.
196
197 if(gVerboseMode)
198 setVideoMode( GRAPHICS_MODE, 0 );
199 else
200 drawBootGraphics();
201
202 finalizeBootStruct();
203
204 // Jump to kernel's entry point. There's no going back now.
205
206 startprog( kernelEntry, bootArgs );
207
208 // Not reached
209
210 return 0;
211}
212
213//==========================================================================
214// This is the entrypoint from real-mode which functions exactly as it did
215// before. Multiboot does its own runtime initialization, does some of its
216// own things, and then calls common_boot.
217void boot(int biosdev)
218{
219initialize_runtime();
220// Enable A20 gate before accessing memory above 1Mb.
221enableA20();
222common_boot(biosdev);
223}
224
225//==========================================================================
226// The 'main' function for the booter. Called by boot0 when booting
227// from a block device, or by the network booter.
228//
229// arguments:
230// biosdev - Value passed from boot1/NBP to specify the device
231// that the booter was loaded from.
232//
233// If biosdev is kBIOSDevNetwork, then this function will return if
234// booting was unsuccessful. This allows the PXE firmware to try the
235// next boot device on its list.
236void common_boot(int biosdev)
237{
238boolinstantMenu, quiet, rescanPrompt;
239boolfirstRun = true;
240char*bootFile;
241intstatus;
242unsigned intallowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
243unsigned intdenyBVFlags = kBVFlagEFISystem;
244unsigned longadler32;
245
246// Set reminder to unload the PXE base code. Neglect to unload
247// the base code will result in a hang or kernel panic.
248gUnloadPXEOnExit = true;
249
250// Record the device that the booter was loaded from.
251gBIOSDev = biosdev & kBIOSDevMask;
252
253// Initialize boot info structure.
254initKernBootStruct();
255
256// Setup VGA text mode.
257// Not sure if it is safe to call setVideoMode() before the
258// config table has been loaded. Call video_mode() instead.
259#if DEBUG
260printf("before video_mode\n");
261#endif
262video_mode( 2 ); // 80x25 mono text mode.
263#if DEBUG
264printf("after video_mode\n");
265#endif
266
267// Scan and record the system's hardware information.
268scan_platform();
269
270// First get info for boot volume.
271scanBootVolumes(gBIOSDev, 0);
272bvChain = getBVChainForBIOSDev(gBIOSDev);
273setBootGlobals(bvChain);
274
275// Load boot.plist config file
276status = loadSystemConfig(&bootInfo->bootConfig);
277
278if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet)
279{
280gBootMode |= kBootModeQuiet;
281}
282
283// Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
284if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu)
285{
286firstRun = false;
287}
288
289// Loading preboot ramdisk if exists.
290loadPrebootRAMDisk();
291
292// Disable rescan option by default
293gEnableCDROMRescan = false;
294
295// Enable it with Rescan=y in system config
296if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan)
297{
298gEnableCDROMRescan = true;
299}
300
301// Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
302rescanPrompt = false;
303if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->bootConfig)
304&& rescanPrompt && biosDevIsCDROM(gBIOSDev))
305{
306gEnableCDROMRescan = promptForRescanOption();
307}
308
309// Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
310if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive)
311{
312gScanSingleDrive = true;
313}
314
315// Create a list of partitions on device(s).
316if (gScanSingleDrive)
317{
318scanBootVolumes(gBIOSDev, &bvCount);
319}
320else
321{
322scanDisks(gBIOSDev, &bvCount);
323}
324
325// Create a separated bvr chain using the specified filters.
326bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
327
328gBootVolume = selectBootVolume(bvChain);
329
330#if DEBUG
331printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n",
332gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
333printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n",
334gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
335pause(); //getc();
336#endif
337
338useGUI = true;
339
340// Override useGUI default
341getBoolForKey(kGUIKey, &useGUI, &bootInfo->bootConfig);
342
343//Azi:autoresolution begin
344// Before initGui, patch the video bios with the correct resolution
345UInt32 params[4];
346params[3] = 0;
347
348// default to "false" as it doesn't work for everyone atm.
349// http://forum.voodooprojects.org/index.php/topic,1227.0.html
350gAutoResolution = false;
351
352getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig);
353
354//Open the VBios and store VBios or Tables
355map = openVbios(CT_UNKWN);
356
357if (gAutoResolution == true)
358{
359//Get Resolution from Graphics Mode key or EDID
360int count = getNumberArrayFromProperty(kGraphicsModeKey, params, 4);
361if (count < 3)
362getResolution(params);
363else
364{
365if ( params[2] == 256 ) params[2] = 8;
366if ( params[2] == 555 ) params[2] = 16;
367if ( params[2] == 888 ) params[2] = 32;
368}
369
370#ifdef AUTORES_DEBUG
371printf("Resolution: %dx%d\n",params[0], params[1]);
372#endif
373
374//perfom the actual VBIOS patching
375if (params[0] != 0 && params[1] != 0)
376patchVbios(map, params[0], params[1], params[2], 0, 0);
377}
378//Azi:autoresolution end
379
380if (useGUI && initGUI())
381{
382// initGUI() returned with an error, disabling GUI.
383useGUI = false;
384}
385
386setBootGlobals(bvChain);
387
388// Parse args, load and start kernel.
389while (1)
390{
391boolforceresume, tryresume, tryresumedefault;
392const char*val;
393intlen, trycache;
394intret = -1;
395longflags, cachetime, kerneltime, exttime, sleeptime, time;
396void*binary = (void *)kLoadAddr;
397
398config_file_t systemVersion;// system.plist of booting partition - Azi:sysversion
399char osxVersion[8]; // replaces gMacOSVersion here, for now.
400
401// additional variable for testing alternate kernel image locations on boot helper partitions.
402charbootFileSpec[512]; //Azi:HelperConfig - kernel
403
404// Initialize globals.
405
406sysConfigValid = false;
407gErrors = false;
408
409status = getBootOptions(firstRun);
410firstRun = false;
411if ( status == -1 ) continue;
412
413//Azi: doing this earlier to get the verbose from loadOverrideConfig.
414// Draw background, turn off any GUI elements and update VRAM.
415if ( bootArgs->Video.v_display == GRAPHICS_MODE )
416{
417drawBackground(); // order matters!!
418gui.devicelist.draw = false; // Needed when verbose "flips" the screen.
419gui.bootprompt.draw = false; // ?
420gui.menu.draw = false; // ?
421gui.infobox.draw = false; // We can't boot with this drawn; most probably it's not needed!?
422updateVRAM();
423}
424
425//Azi:autoresolution begin
426/*
427 * AutoResolution - Reapply the patch or cancel if Graphics Mode was incorrect
428 *or EDID Info was insane
429 */
430 getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig);
431
432//Restore the vbios for Cancelation
433if ((gAutoResolution == false) && map)
434{
435restoreVbios(map);
436closeVbios(map);
437}
438
439if ((gAutoResolution == true) && map)
440{
441// If mode has been switched during boot menu
442// use the new resolution
443if (map->hasSwitched == true)
444{
445params[0] = map->currentX;
446params[1] = map->currentY;
447params[2] = 32;
448}
449else
450{
451//or get resolution from Graphics Mode or EDID
452int count = getNumberArrayFromProperty(kGraphicsModeKey, params, 4);
453if (count < 3)
454getResolution(params);
455else
456{
457if ( params[2] == 256 ) params[2] = 8;
458if ( params[2] == 555 ) params[2] = 16;
459if ( params[2] == 888 ) params[2] = 32;
460}
461}
462
463//Resolution has changed, reapply the patch
464if ((params[0] != 0) && (params[1] != 0) && (params[0] != map->currentX) &&
465(params[1] != map->currentY))
466{
467patchVbios(map, params[0], params[1], params[2], 0, 0);
468}
469closeVbios(map); // doesn't print to screen from here
470}
471//Azi:autoresolution end
472
473status = processBootOptions();
474
475// Status == 1 means to chainboot
476if ( status ==1 ) break;
477
478// Status == -1 means that gBootVolume is NULL - Azi: little edit to reflect current status.
479if ( status == -1 )
480{
481// gBootVolume == NULL usually means the user hit escape.
482if (gBootVolume == NULL) //Azi: hitting escape makes me boot when "at" boot prompt.
483{
484freeFilteredBVChain(bvChain);
485
486if (gEnableCDROMRescan)
487rescanBIOSDevice(gBIOSDev);
488
489bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
490setBootGlobals(bvChain);
491}
492continue;
493}
494
495// Other status (e.g. 0) means that we should proceed with boot.
496
497//Azi:autoresolution old - testing
498
499//Azi: still calling this here. The call on processBootOptions() gets hidden from verbose and
500// for some reason gMacOSVersion doesn't get initialized on boot.c like on the others. Later...
501// Find out which version mac os we're booting.
502if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion)) {
503if (getValueForKey(kProductVersion, &val, &len, &systemVersion)) {
504// getValueForKey uses const char for val
505// so copy it and trim
506strncpy(osxVersion, val, MIN(len, 4));
507osxVersion[MIN(len, 4)] = '\0';
508}
509}
510
511// If cpu doesn't handle 64 bit instructions,...
512if (!platformCPUFeature(CPU_FEATURE_EM64T) ||
513// ... user forced i386 kernel architecture on cpu with "em64t"...
514getValueForKey(kArchI386Flag, &val, &len, &bootInfo->bootConfig) ||
515// ... or forced Legacy Mode...
516getValueForKey(kLegacyModeFlag, &val, &len, &bootInfo->bootConfig))
517{
518// ... use i386 kernel arch.
519archCpuType = CPU_TYPE_I386;
520}
521else
522{
523// Else use x86_64 kernel arch.
524archCpuType = CPU_TYPE_X86_64;
525}
526// Override i386/-legacy, if flagged on Boot.plist.
527if (getValueForKey(kArchX86_64Flag, &val, &len, &bootInfo->bootConfig))
528{
529archCpuType = CPU_TYPE_X86_64;
530}
531
532if (!getBoolForKey (kWakeKey, &tryresume, &bootInfo->bootConfig))
533{
534tryresume = true;
535tryresumedefault = true;
536}
537else
538{
539tryresumedefault = false;
540}
541
542if (!getBoolForKey (kForceWakeKey, &forceresume, &bootInfo->bootConfig))
543{
544forceresume = false;
545}
546
547if (forceresume)
548{
549tryresume = true;
550tryresumedefault = false;
551}
552
553while (tryresume)
554{
555const char *tmp;
556BVRef bvr;
557if (!getValueForKey(kWakeImageKey, &val, &len, &bootInfo->bootConfig))
558val="/private/var/vm/sleepimage";
559
560// Do this first to be sure that root volume is mounted
561ret = GetFileInfo(0, val, &flags, &sleeptime);
562
563if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
564break;
565
566// Can't check if it was hibernation Wake=y is required
567if (bvr->modTime == 0 && tryresumedefault)
568break;
569
570if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
571break;
572
573if (!forceresume && ((sleeptime+3)<bvr->modTime))
574{
575printf("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",
576bvr->modTime-sleeptime);
577break;
578}
579HibernateBoot((char *)val);
580break;
581}
582
583// Reset cache name.
584bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
585
586sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
587
588adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
589
590if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig))
591{
592strlcpy(gBootKernelCacheFile, val, len+1);
593}
594else
595{
596sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePath, adler32);
597}
598
599// Check for cache file.
600trycache = (((gBootMode & kBootModeSafe) == 0) &&
601!gOverrideKernel &&
602(gBootFileType == kBlockDeviceType) &&
603(gMKextName[0] == '\0') &&
604(gBootKernelCacheFile[0] != '\0'));
605
606verbose("Loading Darwin %s\n", osxVersion); //Azi:sysversion
607
608if (trycache) do
609{
610// if we haven't found the kernel yet, don't use the cache
611ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
612if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
613{
614trycache = 0;
615break;
616}
617
618ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
619if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
620|| (cachetime < kerneltime))
621{
622trycache = 0;
623break;
624}
625
626ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
627if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
628&& (cachetime < exttime))
629{
630trycache = 0;
631break;
632}
633
634if (kerneltime > exttime)
635{
636exttime = kerneltime;
637}
638
639if (cachetime != (exttime + 1))
640{
641trycache = 0;
642break;
643}
644} while (0);
645
646do
647{
648if (trycache)
649{
650bootFile = gBootKernelCacheFile;
651verbose("Loading kernel cache %s\n", bootFile); //Azi: i never saw this!! check!!!
652ret = LoadFile(bootFile);
653binary = (void *)kLoadAddr;
654if (ret >= 0)
655{
656break;
657}
658}
659
660bootFile = bootInfo->bootFile;
661
662// Try to load kernel image from alternate locations on boot helper partitions.
663sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile); //Azi:HelperConfig - kernel
664
665ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
666if (ret == -1)
667{
668sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
669
670ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
671if (ret == -1)
672{
673sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
674
675ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
676if (ret == -1)
677{
678// Not found any alternate locations, using the original kernel image path.
679strcpy(bootFileSpec, bootFile);
680}
681}
682}
683
684verbose("Loading kernel %s\n", bootFileSpec);
685
686ret = LoadThinFatFile(bootFileSpec, &binary);
687if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
688{
689archCpuType = CPU_TYPE_I386;
690ret = LoadThinFatFile(bootFileSpec, &binary);
691}
692
693} while (0);
694
695clearActivityIndicator();
696/*#if DEBUG
697printf("Pausing...");
698sleep(8);
699#endif Azi: annoying! Can't see the point atm... */
700
701if (ret <= 0)
702{
703printf("Can't find %s\n", bootFile);
704
705if(gui.initialised)
706{
707sleep(1);
708drawBackground();
709gui.devicelist.draw = true;
710gui.redraw = true;
711}
712
713if (gBootFileType == kNetworkDeviceType) {
714// Return control back to PXE. Don't unload PXE base code.
715gUnloadPXEOnExit = false;
716break;
717}
718}
719else
720{
721/* Won't return if successful. */
722ret = ExecKernel(binary);
723}
724}
725
726// chainboot
727if (status==1)
728{
729if (getVideoMode() == GRAPHICS_MODE)
730{// if we are already in graphics-mode,
731setVideoMode(VGA_TEXT_MODE, 0); // switch back to text mode
732}
733}
734
735if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit)
736{
737nbpUnloadBaseCode();
738}
739}
740
741/*!
742 Selects a new BIOS device, taking care to update the global state appropriately.
743 */
744/*
745static void selectBiosDevice(void)
746{
747 struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
748 CacheReset();
749 diskFreeMap(oldMap);
750 oldMap = NULL;
751
752 int dev = selectAlternateBootDevice(gBIOSDev);
753
754 BVRef bvchain = scanBootVolumes(dev, 0);
755 BVRef bootVol = selectBootVolume(bvchain);
756 gBootVolume = bootVol;
757 setRootVolume(bootVol);
758 gBIOSDev = dev;
759}
760*/
761
762#define BASE 65521L /* largest prime smaller than 65536 */
763#define NMAX 5000
764// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
765
766#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
767#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
768#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
769#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
770#define DO16(buf) DO8(buf,0); DO8(buf,8);
771
772unsigned long Adler32(unsigned char *buf, long len)
773{
774 unsigned long s1 = 1; // adler & 0xffff;
775 unsigned long s2 = 0; // (adler >> 16) & 0xffff;
776 unsigned long result;
777 int k;
778
779 while (len > 0) {
780 k = len < NMAX ? len : NMAX;
781 len -= k;
782 while (k >= 16) {
783 DO16(buf);
784 buf += 16;
785 k -= 16;
786 }
787 if (k != 0) do {
788 s1 += *buf++;
789 s2 += s1;
790 } while (--k);
791 s1 %= BASE;
792 s2 %= BASE;
793 }
794 result = (s2 << 16) | s1;
795 return OSSwapHostToBigInt32(result);
796}
797

Archive Download this file

Revision: 380