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; disabled
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
202setupBooterLog();
203
204 finalizeBootStruct();
205
206 // Jump to kernel's entry point. There's no going back now.
207
208 startprog( kernelEntry, bootArgs );
209
210 // Not reached
211
212 return 0;
213}
214
215//==========================================================================
216// This is the entrypoint from real-mode which functions exactly as it did
217// before. Multiboot does its own runtime initialization, does some of its
218// own things, and then calls common_boot.
219void boot(int biosdev)
220{
221initialize_runtime();
222// Enable A20 gate before accessing memory above 1Mb.
223enableA20();
224common_boot(biosdev);
225}
226
227//==========================================================================
228// The 'main' function for the booter. Called by boot0 when booting
229// from a block device, or by the network booter.
230//
231// arguments:
232// biosdev - Value passed from boot1/NBP to specify the device
233// that the booter was loaded from.
234//
235// If biosdev is kBIOSDevNetwork, then this function will return if
236// booting was unsuccessful. This allows the PXE firmware to try the
237// next boot device on its list.
238void common_boot(int biosdev)
239{
240boolinstantMenu, quiet, rescanPrompt;
241boolfirstRun = true;
242char*bootFile;
243intstatus;
244unsigned intallowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
245unsigned intdenyBVFlags = kBVFlagEFISystem;
246unsigned longadler32;
247
248// Set reminder to unload the PXE base code. Neglect to unload
249// the base code will result in a hang or kernel panic.
250gUnloadPXEOnExit = true;
251
252// Record the device that the booter was loaded from.
253gBIOSDev = biosdev & kBIOSDevMask;
254
255// Initialize boot info structure.
256initKernBootStruct();
257
258initBooterLog();
259
260// Setup VGA text mode.
261// Not sure if it is safe to call setVideoMode() before the
262// config table has been loaded. Call video_mode() instead.
263#if DEBUG
264printf("before video_mode\n");
265#endif
266video_mode( 2 ); // 80x25 mono text mode.
267#if DEBUG
268printf("after video_mode\n");
269#endif
270
271// Scan and record the system's hardware information.
272scan_platform();
273
274// First get info for boot volume.
275scanBootVolumes(gBIOSDev, 0);
276bvChain = getBVChainForBIOSDev(gBIOSDev);
277setBootGlobals(bvChain);
278
279// Load boot.plist config file
280status = loadSystemConfig(&bootInfo->bootConfig);
281
282if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet)
283{
284gBootMode |= kBootModeQuiet;
285}
286
287// Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
288if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu)
289{
290firstRun = false;
291}
292
293// Loading preboot ramdisk if exists.
294loadPrebootRAMDisk();
295
296// Disable rescan option by default
297gEnableCDROMRescan = false;
298
299// Enable it with Rescan=y in system config
300if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan)
301{
302gEnableCDROMRescan = true;
303}
304
305// Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
306rescanPrompt = false;
307if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->bootConfig)
308&& rescanPrompt && biosDevIsCDROM(gBIOSDev))
309{
310gEnableCDROMRescan = promptForRescanOption();
311}
312
313// Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
314if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive)
315{
316gScanSingleDrive = true;
317}
318
319// Create a list of partitions on device(s).
320if (gScanSingleDrive)
321{
322scanBootVolumes(gBIOSDev, &bvCount);
323}
324else
325{
326scanDisks(gBIOSDev, &bvCount);
327}
328
329// Create a separated bvr chain using the specified filters.
330bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
331
332gBootVolume = selectBootVolume(bvChain);
333
334#if DEBUG
335printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n",
336gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
337printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n",
338gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
339pause(); //getc();
340#endif
341
342useGUI = true;
343
344// Override useGUI default
345getBoolForKey(kGUIKey, &useGUI, &bootInfo->bootConfig);
346
347//Azi:autoresolution begin
348// Before initGui, patch the video bios with the correct resolution
349UInt32 params[4];
350params[3] = 0;
351
352// default to "false" as it doesn't work for everyone atm.
353// http://forum.voodooprojects.org/index.php/topic,1227.0.html
354gAutoResolution = false;
355
356getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig);
357
358//Open the VBios and store VBios or Tables
359map = openVbios(CT_UNKWN);
360
361if (gAutoResolution == true)
362{
363//Get Resolution from Graphics Mode key or EDID
364int count = getNumberArrayFromProperty(kGraphicsModeKey, params, 4);
365if (count < 3)
366getResolution(params);
367else
368{
369if ( params[2] == 256 ) params[2] = 8;
370if ( params[2] == 555 ) params[2] = 16;
371if ( params[2] == 888 ) params[2] = 32;
372}
373
374#ifdef AUTORES_DEBUG
375printf("Resolution: %dx%d\n",params[0], params[1]);
376#endif
377
378//perfom the actual VBIOS patching
379if (params[0] != 0 && params[1] != 0)
380patchVbios(map, params[0], params[1], params[2], 0, 0);
381}
382//Azi:autoresolution end
383
384if (useGUI && initGUI())
385{
386// initGUI() returned with an error, disabling GUI.
387useGUI = false;
388}
389
390setBootGlobals(bvChain);
391
392// Parse args, load and start kernel.
393while (1)
394{
395boolforceresume, tryresume, tryresumedefault;
396const char*val;
397intlen, trycache;
398intret = -1;
399longflags, cachetime, kerneltime, exttime, sleeptime, time;
400void*binary = (void *)kLoadAddr;
401
402config_file_t systemVersion;// system.plist of booting partition - Azi:sysversion
403char osxVersion[8]; // replaces gMacOSVersion here, for now.
404
405// additional variable for testing alternate kernel image locations on boot helper partitions.
406charbootFileSpec[512]; //Azi:HelperConfig - kernel
407
408// Initialize globals.
409
410sysConfigValid = false;
411gErrors = false;
412
413status = getBootOptions(firstRun);
414firstRun = false;
415if ( status == -1 ) continue;
416
417//Azi: doing this earlier to get the verbose from loadOverrideConfig.
418// Turn off any GUI elements, draw background and update VRAM.
419if ( bootArgs->Video.v_display == GRAPHICS_MODE )
420{
421gui.devicelist.draw = false;
422gui.bootprompt.draw = false;
423gui.menu.draw = false;
424gui.infobox.draw = false;
425gui.logo.draw = false;
426drawBackground();
427updateVRAM();
428}
429
430//Azi:autoresolution begin
431/*
432 * AutoResolution - Reapply the patch or cancel if Graphics Mode was incorrect
433 *or EDID Info was insane
434 */
435 getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig);
436
437//Restore the vbios for Cancelation
438if ((gAutoResolution == false) && map)
439{
440restoreVbios(map);
441closeVbios(map);
442}
443
444if ((gAutoResolution == true) && map)
445{
446// If mode has been switched during boot menu
447// use the new resolution
448if (map->hasSwitched == true)
449{
450params[0] = map->currentX;
451params[1] = map->currentY;
452params[2] = 32;
453}
454else
455{
456//or get resolution from Graphics Mode or EDID
457int count = getNumberArrayFromProperty(kGraphicsModeKey, params, 4);
458if (count < 3)
459getResolution(params);
460else
461{
462if ( params[2] == 256 ) params[2] = 8;
463if ( params[2] == 555 ) params[2] = 16;
464if ( params[2] == 888 ) params[2] = 32;
465}
466}
467
468//Resolution has changed, reapply the patch
469if ((params[0] != 0) && (params[1] != 0) && (params[0] != map->currentX) &&
470(params[1] != map->currentY))
471{
472patchVbios(map, params[0], params[1], params[2], 0, 0);
473}
474closeVbios(map); // doesn't print to screen from here
475}
476//Azi:autoresolution end
477
478status = processBootOptions();
479
480// Status == 1 means to chainboot
481if ( status ==1 ) break;
482
483// Status == -1 means that gBootVolume is NULL - Azi: little edit to reflect current status.
484if ( status == -1 )
485{
486// gBootVolume == NULL usually means the user hit escape.
487if (gBootVolume == NULL) //Azi: hitting escape makes me boot when "at" boot prompt.
488{
489freeFilteredBVChain(bvChain);
490
491if (gEnableCDROMRescan)
492rescanBIOSDevice(gBIOSDev);
493
494bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
495setBootGlobals(bvChain);
496setupDeviceList(&bootInfo->themeConfig); //Azi: check this - position test!!!
497}
498continue;
499}
500
501// Other status (e.g. 0) means that we should proceed with boot.
502
503//Azi:autoresolution old - testing
504
505//Azi: still calling this here. The call on processBootOptions() gets hidden from verbose and
506// for some reason gMacOSVersion doesn't get initialized on boot.c like on the others. Later...
507// Find out which version mac os we're booting.
508if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion)) {
509if (getValueForKey(kProductVersion, &val, &len, &systemVersion)) {
510// getValueForKey uses const char for val
511// so copy it and trim
512strncpy(osxVersion, val, MIN(len, 4));
513osxVersion[MIN(len, 4)] = '\0';
514}
515}
516
517// If cpu doesn't handle 64 bit instructions,...
518if (!platformCPUFeature(CPU_FEATURE_EM64T) ||
519// ... user forced i386 kernel architecture on cpu with "em64t"...
520getValueForKey(kArchI386Flag, &val, &len, &bootInfo->bootConfig) ||
521// ... or forced Legacy Mode...
522getValueForKey(kLegacyModeFlag, &val, &len, &bootInfo->bootConfig))
523{
524// ... use i386 kernel arch.
525archCpuType = CPU_TYPE_I386;
526}
527else
528{
529// Else use x86_64 kernel arch.
530archCpuType = CPU_TYPE_X86_64;
531}
532// Override i386/-legacy, if flagged on Boot.plist.
533if (getValueForKey(kArchX86_64Flag, &val, &len, &bootInfo->bootConfig))
534{
535archCpuType = CPU_TYPE_X86_64;
536}
537
538if (!getBoolForKey (kWakeKey, &tryresume, &bootInfo->bootConfig))
539{
540tryresume = true;
541tryresumedefault = true;
542}
543else
544{
545tryresumedefault = false;
546}
547
548if (!getBoolForKey (kForceWakeKey, &forceresume, &bootInfo->bootConfig))
549{
550forceresume = false;
551}
552
553if (forceresume)
554{
555tryresume = true;
556tryresumedefault = false;
557}
558
559while (tryresume)
560{
561const char *tmp;
562BVRef bvr;
563if (!getValueForKey(kWakeImageKey, &val, &len, &bootInfo->bootConfig))
564val="/private/var/vm/sleepimage";
565
566// Do this first to be sure that root volume is mounted
567ret = GetFileInfo(0, val, &flags, &sleeptime);
568
569if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
570break;
571
572// Can't check if it was hibernation Wake=y is required
573if (bvr->modTime == 0 && tryresumedefault)
574break;
575
576if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
577break;
578
579if (!forceresume && ((sleeptime+3)<bvr->modTime))
580{
581printf("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",
582bvr->modTime-sleeptime);
583break;
584}
585HibernateBoot((char *)val);
586break;
587}
588
589// Reset cache name.
590bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
591
592sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
593
594adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
595
596if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig))
597{
598strlcpy(gBootKernelCacheFile, val, len+1);
599}
600else
601{
602sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePath, adler32);
603}
604
605// Check for cache file.
606trycache = (((gBootMode & kBootModeSafe) == 0) &&
607!gOverrideKernel &&
608(gBootFileType == kBlockDeviceType) &&
609(gMKextName[0] == '\0') &&
610(gBootKernelCacheFile[0] != '\0'));
611
612verbose("Loading Darwin %s\n", osxVersion); //Azi:sysversion
613
614if (trycache) do
615{
616// if we haven't found the kernel yet, don't use the cache
617ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
618if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
619{
620trycache = 0;
621break;
622}
623
624ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
625if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
626|| (cachetime < kerneltime))
627{
628trycache = 0;
629break;
630}
631
632ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
633if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
634&& (cachetime < exttime))
635{
636trycache = 0;
637break;
638}
639
640if (kerneltime > exttime)
641{
642exttime = kerneltime;
643}
644
645if (cachetime != (exttime + 1))
646{
647trycache = 0;
648break;
649}
650} while (0);
651
652do
653{
654if (trycache)
655{
656bootFile = gBootKernelCacheFile;
657verbose("Loading kernel cache %s\n", bootFile); //Azi: i never saw this!! check!!!
658ret = LoadFile(bootFile);
659binary = (void *)kLoadAddr;
660if (ret >= 0)
661{
662break;
663}
664}
665
666bootFile = bootInfo->bootFile;
667
668// Try to load kernel image from alternate locations on boot helper partitions.
669sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile); //Azi:HelperConfig - kernel
670
671ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
672if (ret == -1)
673{
674sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
675
676ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
677if (ret == -1)
678{
679sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
680
681ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
682if (ret == -1)
683{
684// Not found any alternate locations, using the original kernel image path.
685strcpy(bootFileSpec, bootFile);
686}
687}
688}
689
690verbose("Loading kernel %s\n", bootFileSpec);
691
692ret = LoadThinFatFile(bootFileSpec, &binary);
693if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
694{
695archCpuType = CPU_TYPE_I386;
696ret = LoadThinFatFile(bootFileSpec, &binary);
697}
698
699} while (0);
700
701clearActivityIndicator();
702/*#if DEBUG
703printf("Pausing...");
704sleep(8);
705#endif Azi: annoying! Can't see the point atm... */
706
707if (ret <= 0)
708{
709printf("Can't find %s\n", bootFile);
710
711sleep(1);
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: 386