Chameleon

Chameleon Svn Source Tree

Root/trunk/i386/libsaio/disk.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 Intel Corporation
40 */
41
42/*
43 * Copyright 1993 NeXT Computer, Inc.
44 * All rights reserved.
45 */
46
47/*
48 * Copyright 2007 VMware Inc.
49 * "Preboot" ramdisk support added by David Elliott
50 * GPT support added by David Elliott. Based on IOGUIDPartitionScheme.cpp.
51 */
52
53//Azi: style the rest later...
54
55// Allow UFS_SUPPORT to be overridden with preprocessor option.
56#ifndef UFS_SUPPORT
57// zef: Disabled UFS support
58#define UFS_SUPPORT 0
59#endif
60
61#if UFS_SUPPORT
62#include "ufs.h"
63#endif
64#include <limits.h>
65#include <IOKit/storage/IOApplePartitionScheme.h>
66#include <IOKit/storage/IOGUIDPartitionScheme.h>
67#include "libsaio.h"
68#include "boot.h"
69#include "bootstruct.h"
70#include "memory.h"
71#include "fdisk.h"
72#include "hfs.h"
73#include "ntfs.h"
74#include "msdos.h"
75#include "ext2fs.h"
76#include "befs.h"
77#include "freebsd.h"
78#include "openbsd.h"
79#include "xml.h"
80#include "disk.h"
81// For EFI_GUID
82#include "efi.h"
83#include "efi_tables.h"
84
85typedef struct gpt_hdr gpt_hdr;
86typedef struct gpt_ent gpt_ent;
87
88#define PROBEFS_SIZE BPS * 4 /* buffer size for filesystem probe */
89#define CD_BPS 2048 /* CD-ROM block size */
90#define N_CACHE_SECS (BIOS_LEN / BPS) /* Must be a multiple of 4 for CD-ROMs */
91#define UFS_FRONT_PORCH 0
92#define kAPMSector 2 /* Sector number of Apple partition map */
93#define kAPMCDSector 8 /* Translated sector of Apple partition map on a CD */
94
95/*
96 * IORound and IOTrunc convenience functions, in the spirit
97 * of vm's round_page() and trunc_page().
98 */
99#define IORound(value,multiple) \
100 ((((value) + (multiple) - 1) / (multiple)) * (multiple))
101
102#define IOTrunc(value,multiple) \
103 (((value) / (multiple)) * (multiple));
104
105/*
106 * trackbuf points to the start of the track cache. Biosread()
107 * will store the sectors read from disk to this memory area.
108 *
109 * biosbuf points to a sector within the track cache, and is
110 * updated by Biosread().
111 */
112static char * const trackbuf = (char *) ptov(BIOS_ADDR);
113static char * biosbuf;
114
115/*
116 * Map a disk drive to bootable volumes contained within.
117 */
118struct DiskBVMap {
119 int biosdev; // BIOS device number (unique)
120 BVRef bvr; // chain of boot volumes on the disk
121 int bvrcnt; // number of boot volumes
122 struct DiskBVMap * next; // linkage to next mapping
123};
124
125static struct DiskBVMap * gDiskBVMap = NULL;
126static struct disk_blk0 * gBootSector = NULL;
127
128// Function pointers to be filled in if ramdisks are available:
129int (*p_ramdiskReadBytes)( int biosdev, unsigned int blkno,
130 unsigned int byteoff,
131 unsigned int byteCount, void * buffer ) = NULL;
132int (*p_get_ramdisk_info)(int biosdev, struct driveInfo *dip) = NULL;
133
134static bool getOSVersion(BVRef bvr, char *str);
135
136extern void spinActivityIndicator(int sectors);
137
138//==========================================================================
139
140static int getDriveInfo( int biosdev, struct driveInfo *dip )
141{
142static struct driveInfo cached_di;
143int cc;
144
145// Real BIOS devices are 8-bit, so anything above that is for internal use.
146// Don't cache ramdisk drive info since it doesn't require several BIOS
147// calls and is thus not worth it.
148if (biosdev >= 0x100)
149{
150if (p_get_ramdisk_info != NULL)
151{
152cc = (*p_get_ramdisk_info)(biosdev, dip);
153}
154else
155{
156cc = -1;
157}
158if (cc < 0)
159{
160dip->valid = 0;
161return -1;
162}
163else
164{
165return 0;
166}
167}
168
169if (!cached_di.valid || biosdev != cached_di.biosdev)
170{
171cc = get_drive_info(biosdev, &cached_di);
172
173if (cc < 0)
174{
175cached_di.valid = 0;
176DEBUG_DISK(("get_drive_info returned error\n"));
177return (-1); // BIOS call error
178}
179}
180
181bcopy(&cached_di, dip, sizeof(cached_di));
182
183return 0;
184}
185
186//==========================================================================
187// Maps (E)BIOS return codes to message strings.
188
189struct NamedValue {
190unsigned char value;
191const char * name;
192};
193
194//==========================================================================
195
196static const char * getNameForValue( const struct NamedValue * nameTable,
197 unsigned char value )
198{
199const struct NamedValue * np;
200
201for ( np = nameTable; np->value; np++)
202{
203if (np->value == value)
204{
205return np->name;
206}
207}
208
209return NULL;
210}
211
212#define ECC_CORRECTED_ERR 0x11
213
214static const struct NamedValue bios_errors[] =
215{
216{ 0x10, "Media error" },
217{ 0x11, "Corrected ECC error" },
218{ 0x20, "Controller or device error" },
219{ 0x40, "Seek failed" },
220{ 0x80, "Device timeout" },
221{ 0xAA, "Drive not ready" },
222{ 0x00, 0 }
223};
224
225
226//==============================================================================
227
228static const char * bios_error(int errnum)
229{
230static char errorstr[] = "Error 0x00";
231const char * errname;
232
233errname = getNameForValue(bios_errors, errnum);
234
235if (errname)
236{
237return errname;
238}
239
240sprintf(errorstr, "Error 0x%02x", errnum);
241return errorstr; // No string, print error code only
242}
243
244//==========================================================================
245// Use BIOS INT13 calls to read the sector specified. This function will
246// also perform read-ahead to cache a few subsequent sector to the sector
247// cache.
248//
249// Return:
250// 0 on success, or an error code from INT13/F2 or INT13/F42 BIOS call.
251
252static bool cache_valid = false;
253
254static int Biosread( int biosdev, unsigned long long secno )
255{
256static int xbiosdev, xcyl, xhead;
257static unsigned int xsec, xnsecs;
258struct driveInfo di;
259
260int rc = -1;
261int cyl, head, sec;
262int tries = 0;
263int bps, divisor;
264
265if (getDriveInfo(biosdev, &di) < 0)
266{
267return -1;
268}
269
270if (di.no_emulation)
271{
272bps = 2048; /* Always assume 2K block size since the BIOS may lie about the geometry */
273}
274else
275{
276bps = di.di.params.phys_nbps;
277
278if (bps == 0)
279{
280return -1;
281}
282}
283
284divisor = bps / BPS;
285
286DEBUG_DISK(("Biosread dev %x sec %d bps %d\n", biosdev, secno, bps));
287
288// To read the disk sectors, use EBIOS if we can. Otherwise,
289// revert to the standard BIOS calls.
290
291if ((biosdev >= kBIOSDevTypeHardDrive) && (di.uses_ebios & EBIOS_FIXED_DISK_ACCESS))
292{
293if (cache_valid && (biosdev == xbiosdev) && (secno >= xsec) && ((unsigned int)secno < (xsec + xnsecs)))
294{
295biosbuf = trackbuf + (BPS * (secno - xsec));
296return 0;
297}
298
299xnsecs = N_CACHE_SECS;
300xsec = (secno / divisor) * divisor;
301cache_valid = false;
302
303while ((rc = ebiosread(biosdev, secno / divisor, xnsecs / divisor)) && (++tries < 5))
304{
305if (rc == ECC_CORRECTED_ERR)
306{
307rc = 0; /* Ignore corrected ECC errors */
308break;
309}
310
311error(" EBIOS read error: %s\n", bios_error(rc), rc);
312error(" Block 0x%x Sectors %d\n", secno, xnsecs);
313sleep(1);
314}
315}
316
317else
318{
319/* spc = spt * heads */
320int spc = (di.di.params.phys_spt * di.di.params.phys_heads);
321cyl = secno / spc;
322head = (secno % spc) / di.di.params.phys_spt;
323sec = secno % di.di.params.phys_spt;
324
325if (cache_valid && (biosdev == xbiosdev) && (cyl == xcyl) &&
326(head == xhead) && ((unsigned int)sec >= xsec) && ((unsigned int)sec < (xsec + xnsecs)))
327
328{
329// this sector is in trackbuf cache
330biosbuf = trackbuf + (BPS * (sec - xsec));
331return 0;
332}
333
334// Cache up to a track worth of sectors, but do not cross a track boundary.
335
336xcyl = cyl;
337xhead = head;
338xsec = sec;
339xnsecs = ((unsigned int)(sec + N_CACHE_SECS) > di.di.params.phys_spt) ? (di.di.params.phys_spt - sec) : N_CACHE_SECS;
340
341cache_valid = false;
342
343while ((rc = biosread(biosdev, cyl, head, sec, xnsecs)) && (++tries < 5))
344{
345if (rc == ECC_CORRECTED_ERR)
346{
347rc = 0; /* Ignore corrected ECC errors */
348break;
349}
350error(" BIOS read error: %s\n", bios_error(rc), rc);
351error(" Block %d, Cyl %d Head %d Sector %d\n", secno, cyl, head, sec);
352sleep(1);
353}
354}
355
356// If the BIOS reported success, mark the sector cache as valid.
357
358if (rc == 0)
359{
360cache_valid = true;
361}
362
363biosbuf = trackbuf + (secno % divisor) * BPS;
364xbiosdev = biosdev;
365
366spinActivityIndicator(xnsecs);
367
368return rc;
369}
370
371
372//==============================================================================
373
374int testBiosread(int biosdev, unsigned long long secno)
375{
376return Biosread(biosdev, secno);
377}
378
379//==============================================================================
380
381static int readBytes(int biosdev, unsigned long long blkno, unsigned int byteoff, unsigned int byteCount, void * buffer)
382{
383// ramdisks require completely different code for reading.
384if(p_ramdiskReadBytes != NULL && biosdev >= 0x100)
385{
386return (*p_ramdiskReadBytes)(biosdev, blkno, byteoff, byteCount, buffer);
387}
388
389char * cbuf = (char *) buffer;
390int error;
391int copy_len;
392
393DEBUG_DISK(("%s: dev %x block %x [%d] -> 0x%x...", __FUNCTION__, biosdev, blkno, byteCount, (unsigned)cbuf));
394
395for (; byteCount; cbuf += copy_len, blkno++)
396{
397error = Biosread(biosdev, blkno);
398
399if (error)
400{
401DEBUG_DISK(("error\n"));
402
403return (-1);
404}
405
406copy_len = ((byteCount + byteoff) > BPS) ? (BPS - byteoff) : byteCount;
407bcopy( biosbuf + byteoff, cbuf, copy_len );
408byteCount -= copy_len;
409byteoff = 0;
410}
411
412DEBUG_DISK(("done\n"));
413
414return 0;
415}
416
417//==============================================================================
418
419static int isExtendedFDiskPartition( const struct fdisk_part * part )
420{
421static unsigned char extParts[] =
422{
4230x05, /* Extended */
4240x0f, /* Win95 extended */
4250x85, /* Linux extended */
426};
427
428unsigned int i;
429
430for (i = 0; i < sizeof(extParts)/sizeof(extParts[0]); i++)
431{
432if (extParts[i] == part->systid)
433{
434return 1;
435}
436}
437return 0;
438}
439
440//==============================================================================
441
442static int getNextFDiskPartition( int biosdev, int * partno,
443 const struct fdisk_part ** outPart )
444{
445static int sBiosdev = -1;
446static int sNextPartNo;
447static unsigned int sFirstBase;
448static unsigned int sExtBase;
449static unsigned int sExtDepth;
450static struct fdisk_part * sExtPart;
451struct fdisk_part * part;
452
453if ( sBiosdev != biosdev || *partno < 0 )
454{
455// Fetch MBR.
456if ( readBootSector( biosdev, DISK_BLK0, 0 ) )
457{
458return 0;
459}
460
461sBiosdev = biosdev;
462sNextPartNo = 0;
463sFirstBase = 0;
464sExtBase = 0;
465sExtDepth = 0;
466sExtPart = NULL;
467}
468
469while (1)
470{
471part = NULL;
472
473if ( sNextPartNo < FDISK_NPART )
474{
475part = (struct fdisk_part *) gBootSector->parts[sNextPartNo];
476}
477else if ( sExtPart )
478{
479unsigned int blkno = sExtPart->relsect + sFirstBase;
480
481// Save the block offset of the first extended partition.
482
483if (sExtDepth == 0)
484{
485sFirstBase = blkno;
486}
487sExtBase = blkno;
488
489// Load extended partition table.
490
491if ( readBootSector( biosdev, blkno, 0 ) == 0 )
492{
493sNextPartNo = 0;
494sExtDepth++;
495sExtPart = NULL;
496continue;
497}
498// Fall through to part == NULL
499}
500
501if ( part == NULL ) break; // Reached end of partition chain.
502
503// Advance to next partition number.
504
505sNextPartNo++;
506
507if ( isExtendedFDiskPartition(part) )
508{
509sExtPart = part;
510continue;
511}
512
513// Skip empty slots.
514
515if ( part->systid == 0x00 )
516{
517continue;
518}
519
520// Change relative offset to an absolute offset.
521part->relsect += sExtBase;
522
523*outPart = part;
524*partno = sExtDepth ? (int)(sExtDepth + FDISK_NPART) : sNextPartNo;
525
526break;
527}
528
529return (part != NULL);
530}
531
532//==============================================================================
533
534static BVRef newFDiskBVRef( int biosdev, int partno, unsigned int blkoff,
535 const struct fdisk_part * part,
536 FSInit initFunc, FSLoadFile loadFunc,
537 FSReadFile readFunc,
538 FSGetDirEntry getdirFunc,
539 FSGetFileBlock getBlockFunc,
540 FSGetUUID getUUIDFunc,
541 BVGetDescription getDescriptionFunc,
542 BVFree bvFreeFunc,
543 int probe, int type, unsigned int bvrFlags )
544{
545BVRef bvr = (BVRef) malloc( sizeof(*bvr) );
546if ( bvr )
547{
548bzero(bvr, sizeof(*bvr));
549
550bvr->biosdev = biosdev;
551bvr->part_no = partno;
552bvr->part_boff = blkoff;
553bvr->part_type = part->systid;
554bvr->fs_loadfile = loadFunc;
555bvr->fs_readfile = readFunc;
556bvr->fs_getdirentry = getdirFunc;
557bvr->fs_getfileblock= getBlockFunc;
558bvr->fs_getuuid = getUUIDFunc;
559bvr->description = getDescriptionFunc;
560bvr->type = type;
561bvr->bv_free = bvFreeFunc;
562
563if ((part->bootid & FDISK_ACTIVE) && (part->systid == FDISK_HFS))
564{
565bvr->flags |= kBVFlagPrimary;
566}
567
568// Probe the filesystem.
569
570if ( initFunc )
571{
572bvr->flags |= kBVFlagNativeBoot;
573
574if ( probe && initFunc( bvr ) != 0 )
575{
576// filesystem probe failed.
577
578DEBUG_DISK(("%s: failed probe on dev %x part %d\n", __FUNCTION__, biosdev, partno));
579
580(*bvr->bv_free)(bvr);
581bvr = NULL;
582}
583
584if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 )
585{
586bvr->flags |= kBVFlagBootable;
587}
588}
589else if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 )
590{
591bvr->flags |= kBVFlagForeignBoot;
592}
593else
594{
595(*bvr->bv_free)(bvr);
596bvr = NULL;
597}
598}
599
600if (bvr) bvr->flags |= bvrFlags;
601{
602return bvr;
603}
604}
605
606//==============================================================================
607
608BVRef newAPMBVRef( int biosdev, int partno, unsigned int blkoff,
609 const DPME * part,
610 FSInit initFunc, FSLoadFile loadFunc,
611 FSReadFile readFunc,
612 FSGetDirEntry getdirFunc,
613 FSGetFileBlock getBlockFunc,
614 FSGetUUID getUUIDFunc,
615 BVGetDescription getDescriptionFunc,
616 BVFree bvFreeFunc,
617 int probe, int type, unsigned int bvrFlags )
618{
619BVRef bvr = (BVRef) malloc( sizeof(*bvr) );
620if ( bvr )
621{
622bzero(bvr, sizeof(*bvr));
623
624bvr->biosdev = biosdev;
625bvr->part_no = partno;
626bvr->part_boff = blkoff;
627bvr->fs_loadfile = loadFunc;
628bvr->fs_readfile = readFunc;
629bvr->fs_getdirentry = getdirFunc;
630bvr->fs_getfileblock= getBlockFunc;
631bvr->fs_getuuid = getUUIDFunc;
632bvr->description = getDescriptionFunc;
633bvr->type = type;
634bvr->bv_free = bvFreeFunc;
635strlcpy(bvr->name, part->dpme_name, DPISTRLEN);
636strlcpy(bvr->type_name, part->dpme_type, DPISTRLEN);
637
638/*
639if ( part->bootid & FDISK_ACTIVE )
640{
641bvr->flags |= kBVFlagPrimary;
642}
643*/
644
645// Probe the filesystem.
646
647if ( initFunc )
648{
649bvr->flags |= kBVFlagNativeBoot | kBVFlagBootable | kBVFlagSystemVolume;
650
651if ( probe && initFunc( bvr ) != 0 )
652{
653// filesystem probe failed.
654
655DEBUG_DISK(("%s: failed probe on dev %x part %d\n", __FUNCTION__, biosdev, partno));
656
657(*bvr->bv_free)(bvr);
658bvr = NULL;
659}
660}
661/*
662else if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 )
663{
664bvr->flags |= kBVFlagForeignBoot;
665}
666*/
667else
668{
669(*bvr->bv_free)(bvr);
670bvr = NULL;
671}
672}
673if (bvr)
674{
675bvr->flags |= bvrFlags;
676}
677return bvr;
678}
679
680//==============================================================================
681
682// GUID's in LE form:
683// HFS+ partition - 48465300-0000-11AA-AA11-00306543ECAC
684EFI_GUID const GPT_HFS_GUID= { 0x48465300, 0x0000, 0x11AA, { 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }; // 0xAF00 "Apple HFS/HFS+"
685
686// turbo - Apple Boot Partition - 426F6F74-0000-11AA-AA11-00306543ECAC
687EFI_GUID const GPT_BOOT_GUID= { 0x426F6F74, 0x0000, 0x11AA, { 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }; // 0xAB00 "Apple boot"
688
689// turbo - or an EFI System Partition - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
690EFI_GUID const GPT_EFISYS_GUID= { 0xC12A7328, 0xF81F, 0x11D2, { 0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, 0x3B } }; // 0xEF00 "EFI System"
691
692// zef - Basic Data Partition - EBD0A0A2-B9E5-4433-87C0-68B6B72699C7 for foreign OS support
693EFI_GUID const GPT_BASICDATA_GUID= { 0xEBD0A0A2, 0xB9E5, 0x4433, { 0x87, 0xC0, 0x68, 0xB6, 0xB7, 0x26, 0x99, 0xC7 } }; // 0x0100 "Microsoft basic data"
694
695// Microsoft Reserved Partition - E3C9E316-0B5C-4DB8-817DF92DF00215AE
696EFI_GUID const GPT_BASICDATA2_GUID= { 0xE3C9E316, 0x0B5C, 0x4DB8, { 0x81, 0x7D, 0xF9, 0x2D, 0xF0, 0x02, 0x15, 0xAE } }; // 0x0C01 "Microsoft reserved"
697
698// Apple OSX
699//EFI_GUID const GPT_UFS_GUID= { 0x55465300, 0x0000, 0x11AA, { 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }; // 0xA800 "Apple UFS"
700//EFI_GUID const GPT_RAID_GUID= { 0x52414944, 0x0000, 0x11AA, { 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }; // 0xAF01 "Apple RAID"
701//EFI_GUID const GPT_RAID_OFFLINE_GUID= { 0x52414944, 0x5f4f, 0x11AA, { 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }; // 0xAF02 "Apple RAID offline"
702//EFI_GUID const GPT_LABEL_GUID= { 0x4C616265, 0x6C00, 0x11AA, { 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }; // 0xAF03 "Apple label"
703//EFI_GUID const GPT_APPLETV_GUID= { 0x5265636F, 0x7665, 0x11AA, { 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }; // 0xAF04 "Apple TV recovery"
704//EFI_GUID const GPT_CORESTORAGE_GUID= { 0x53746F72, 0x6167, 0x11AA, { 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }; // 0xAF05 "Apple Core storage"
705// same as Apple ZFS
706//EFI_GUID const GPT_ZFS_GUID= { 0x6A898CC3, 0x1DD2, 0x11B2, { 0x99, 0xA6, 0x08, 0x00, 0x20, 0x73, 0x66, 0x31 } }; // 0xBF01 "Solaris /usr & Apple ZFS
707
708BVRef newGPTBVRef( int biosdev, int partno, unsigned int blkoff,
709 const gpt_ent * part,
710 FSInit initFunc, FSLoadFile loadFunc,
711 FSReadFile readFunc,
712 FSGetDirEntry getdirFunc,
713 FSGetFileBlock getBlockFunc,
714 FSGetUUID getUUIDFunc,
715 BVGetDescription getDescriptionFunc,
716 BVFree bvFreeFunc,
717 int probe, int type, unsigned int bvrFlags )
718{
719BVRef bvr = (BVRef) malloc( sizeof(*bvr) );
720if ( bvr ) {
721bzero(bvr, sizeof(*bvr));
722
723bvr->biosdev = biosdev;
724bvr->part_no = partno;
725bvr->part_boff = blkoff;
726bvr->fs_loadfile = loadFunc;
727bvr->fs_readfile = readFunc;
728bvr->fs_getdirentry = getdirFunc;
729bvr->fs_getfileblock= getBlockFunc;
730bvr->fs_getuuid = getUUIDFunc;
731bvr->description = getDescriptionFunc;
732bvr->type = type;
733bvr->bv_free = bvFreeFunc;
734// FIXME: UCS-2 -> UTF-8 the name
735strlcpy(bvr->name, "----", DPISTRLEN);
736if ( (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const*)part->ent_type) == 0) || (efi_guid_compare(&GPT_HFS_GUID, (EFI_GUID const*)part->ent_type) == 0) ) {
737strlcpy(bvr->type_name, "GPT HFS+", DPISTRLEN);
738} else {
739strlcpy(bvr->type_name, "GPT Unknown", DPISTRLEN);
740}
741
742/*
743if ( part->bootid & FDISK_ACTIVE ) {
744bvr->flags |= kBVFlagPrimary;
745}
746*/
747
748// Probe the filesystem.
749
750if ( initFunc ) {
751bvr->flags |= kBVFlagNativeBoot;
752
753if ( probe && initFunc( bvr ) != 0 ) {
754// filesystem probe failed.
755
756DEBUG_DISK(("%s: failed probe on dev %x part %d\n", __FUNCTION__, biosdev, partno));
757
758(*bvr->bv_free)(bvr);
759bvr = NULL;
760}
761if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) {
762bvr->flags |= kBVFlagBootable;
763}
764} else if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) {
765bvr->flags |= kBVFlagForeignBoot;
766} else {
767(*bvr->bv_free)(bvr);
768bvr = NULL;
769}
770}
771if (bvr) {
772bvr->flags |= bvrFlags;
773}
774return bvr;
775}
776
777//==============================================================================
778
779/* A note on partition numbers:
780 * IOKit makes the primary partitions numbers 1-4, and then
781 * extended partitions are numbered consecutively 5 and up.
782 * So, for example, if you have two primary partitions and
783 * one extended partition they will be numbered 1, 2, 5.
784 */
785
786static BVRef diskScanFDiskBootVolumes( int biosdev, int * countPtr )
787{
788 const struct fdisk_part * part;
789 struct DiskBVMap * map;
790 int partno = -1;
791 BVRef bvr;
792#if UFS_SUPPORT
793 BVRef booterUFS = NULL;
794#endif
795 int spc;
796 struct driveInfo di;
797 boot_drive_info_t *dp;
798
799/* Initialize disk info */
800
801if (getDriveInfo(biosdev, &di) != 0)
802{
803return NULL;
804}
805
806dp = &di.di;
807spc = (dp->params.phys_spt * dp->params.phys_heads);
808
809if (spc == 0)
810{
811/* This is probably a CD-ROM; punt on the geometry. */
812spc = 1;
813}
814
815 do {
816 // Create a new mapping.
817
818 map = (struct DiskBVMap *) malloc( sizeof(*map) );
819 if ( map )
820 {
821 map->biosdev = biosdev;
822 map->bvr = NULL;
823 map->bvrcnt = 0;
824 map->next = gDiskBVMap;
825 gDiskBVMap = map;
826
827 // Create a record for each partition found on the disk.
828
829 while ( getNextFDiskPartition( biosdev, &partno, &part ) )
830 {
831 DEBUG_DISK(("%s: part %d [%x]\n", __FUNCTION__,
832 partno, part->systid));
833 bvr = 0;
834
835 switch ( part->systid )
836 {
837#if UFS_SUPPORT
838 case FDISK_UFS:
839 bvr = newFDiskBVRef(
840 biosdev, partno,
841 part->relsect + UFS_FRONT_PORCH/BPS,
842 part,
843 UFSInitPartition,
844 UFSLoadFile,
845 UFSReadFile,
846 UFSGetDirEntry,
847 UFSGetFileBlock,
848 UFSGetUUID,
849 UFSGetDescription,
850 UFSFree,
851 0,
852 kBIOSDevTypeHardDrive, 0);
853 break;
854#endif
855
856 case FDISK_HFS:
857 bvr = newFDiskBVRef(
858 biosdev, partno,
859 part->relsect,
860 part,
861 HFSInitPartition,
862 HFSLoadFile,
863 HFSReadFile,
864 HFSGetDirEntry,
865 HFSGetFileBlock,
866 HFSGetUUID,
867 HFSGetDescription,
868 HFSFree,
869 0,
870 kBIOSDevTypeHardDrive, 0);
871 break;
872
873 // turbo - we want the booter type scanned also
874 case FDISK_BOOTER:
875 if (part->bootid & FDISK_ACTIVE)
876 gBIOSBootVolume = newFDiskBVRef(
877 biosdev, partno,
878 part->relsect,
879 part,
880 HFSInitPartition,
881 HFSLoadFile,
882 HFSReadFile,
883 HFSGetDirEntry,
884 HFSGetFileBlock,
885 HFSGetUUID,
886 HFSGetDescription,
887 HFSFree,
888 0,
889 kBIOSDevTypeHardDrive, 0);
890 break;
891
892#if UFS_SUPPORT
893 case FDISK_BOOTER:
894 booterUFS = newFDiskBVRef(
895 biosdev, partno,
896 ((part->relsect + spc - 1) / spc) * spc,
897 part,
898 UFSInitPartition,
899 UFSLoadFile,
900 UFSReadFile,
901 UFSGetDirEntry,
902 UFSGetFileBlock,
903 UFSGetUUID,
904 UFSGetDescription,
905 UFSFree,
906 0,
907 kBIOSDevTypeHardDrive, 0);
908 break;
909#endif
910
911 case FDISK_FAT32:
912 case FDISK_DOS12:
913 case FDISK_DOS16S:
914 case FDISK_DOS16B:
915 case FDISK_SMALLFAT32:
916 case FDISK_DOS16SLBA:
917 bvr = newFDiskBVRef(
918 biosdev, partno,
919 part->relsect,
920 part,
921 MSDOSInitPartition,
922 MSDOSLoadFile,
923 MSDOSReadFile,
924 MSDOSGetDirEntry,
925 MSDOSGetFileBlock,
926 MSDOSGetUUID,
927 MSDOSGetDescription,
928 MSDOSFree,
929 0,
930 kBIOSDevTypeHardDrive, 0);
931 break;
932
933 case FDISK_NTFS:
934 bvr = newFDiskBVRef(
935 biosdev, partno,
936 part->relsect,
937 part,
938 0, 0, 0, 0, 0,
939 NTFSGetUUID,
940 NTFSGetDescription,
941 (BVFree)free,
942 0, kBIOSDevTypeHardDrive, 0);
943 break;
944
945 case FDISK_LINUX:
946 bvr = newFDiskBVRef(
947 biosdev, partno,
948 part->relsect,
949 part,
950 0, 0, 0, 0, 0,
951 EX2GetUUID,
952 EX2GetDescription,
953 (BVFree)free,
954 0, kBIOSDevTypeHardDrive, 0);
955 break;
956
957 case FDISK_BEFS:
958 bvr = newFDiskBVRef(
959 biosdev, partno,
960 part->relsect,
961 part,
962 0, 0, 0, 0, 0, 0,
963 BeFSGetDescription,
964 (BVFree)free,
965 0, kBIOSDevTypeHardDrive, 0);
966 break;
967
968 case FDISK_FREEBSD:
969 bvr = newFDiskBVRef(
970 biosdev, partno,
971 part->relsect,
972 part,
973 0, 0, 0, 0, 0, 0,
974 FreeBSDGetDescription,
975 (BVFree)free,
976 0, kBIOSDevTypeHardDrive, 0);
977 break;
978
979 case FDISK_OPENBSD:
980 bvr = newFDiskBVRef(
981 biosdev, partno,
982 part->relsect,
983 part,
984 0, 0, 0, 0, 0, 0,
985 OpenBSDGetDescription,
986 (BVFree)free,
987 0, kBIOSDevTypeHardDrive, 0);
988 break;
989
990 default:
991 bvr = newFDiskBVRef(
992 biosdev, partno,
993 part->relsect,
994 part,
995 0, 0, 0, 0, 0, 0, 0,
996 (BVFree)free,
997 0,
998 kBIOSDevTypeHardDrive, 0);
999 break;
1000 }
1001
1002 if ( bvr )
1003 {
1004 bvr->next = map->bvr;
1005 map->bvr = bvr;
1006 map->bvrcnt++;
1007 }
1008 }
1009
1010#if UFS_SUPPORT
1011 // Booting from a CD with an UFS filesystem embedded
1012 // in a booter partition.
1013
1014if ( booterUFS )
1015{
1016if ( map->bvrcnt == 0 )
1017{
1018map->bvr = booterUFS;
1019map->bvrcnt++;
1020}
1021else
1022{
1023free( booterUFS );
1024}
1025}
1026#endif
1027}
1028} while (0);
1029
1030/*
1031 * If no FDisk partition, then we will check for
1032 * an Apple partition map elsewhere.
1033 */
1034#if UNUSED
1035if (map->bvrcnt == 0)
1036{
1037static struct fdisk_part cdpart;
1038cdpart.systid = 0xCD;
1039
1040/* Let's try assuming we are on a hybrid HFS/ISO9660 CD. */
1041bvr = newFDiskBVRef(
1042biosdev, 0,
10430,
1044&cdpart,
1045HFSInitPartition,
1046HFSLoadFile,
1047HFSReadFile,
1048HFSGetDirEntry,
1049HFSGetFileBlock,
1050HFSGetUUID,
1051HFSGetDescription,
1052HFSFree,
10530,
1054kBIOSDevTypeHardDrive, 0);
1055bvr->next = map->bvr;
1056map->bvr = bvr;
1057map->bvrcnt++;
1058}
1059#endif
1060// Actually this should always be true given the above code
1061if(map == gDiskBVMap)
1062{
1063// Don't leave a null map in the chain
1064if(map->bvrcnt == 0 && map->bvr == NULL)
1065{
1066gDiskBVMap = map->next;
1067free(map);
1068map = NULL;
1069}
1070}
1071
1072if (countPtr) *countPtr = map ? map->bvrcnt : 0;
1073
1074return map ? map->bvr : NULL;
1075}
1076
1077//==============================================================================
1078
1079static BVRef diskScanAPMBootVolumes( int biosdev, int * countPtr )
1080{
1081struct DiskBVMap * map;
1082struct Block0 *block0_p;
1083unsigned int blksize;
1084unsigned int factor;
1085void *buffer = malloc(BPS);
1086
1087if (!buffer)
1088{
1089return NULL;
1090}
1091bzero(buffer,BPS);
1092
1093/* Check for alternate block size */
1094if (readBytes( biosdev, 0, 0, BPS, buffer ) != 0)
1095{
1096return NULL;
1097}
1098block0_p = buffer;
1099if (OSSwapBigToHostInt16(block0_p->sbSig) == BLOCK0_SIGNATURE)
1100{
1101blksize = OSSwapBigToHostInt16(block0_p->sbBlkSize);
1102if (blksize != BPS)
1103{
1104free(buffer);
1105buffer = malloc(blksize);
1106if (!buffer)
1107{
1108return NULL;
1109}
1110bzero(buffer,BPS);
1111}
1112factor = blksize / BPS;
1113}
1114else
1115{
1116blksize = BPS;
1117factor = 1;
1118}
1119
1120do
1121{
1122// Create a new mapping.
1123
1124map = (struct DiskBVMap *) malloc( sizeof(*map) );
1125if ( map )
1126{
1127int error;
1128DPME *dpme_p = (DPME *)buffer;
1129UInt32 i, npart = UINT_MAX;
1130BVRef bvr;
1131
1132map->biosdev = biosdev;
1133map->bvr = NULL;
1134map->bvrcnt = 0;
1135map->next = gDiskBVMap;
1136gDiskBVMap = map;
1137
1138for (i=0; i<npart; i++)
1139{
1140error = readBytes( biosdev, (kAPMSector + i) * factor, 0, blksize, buffer );
1141
1142if (error || OSSwapBigToHostInt16(dpme_p->dpme_signature) != DPME_SIGNATURE)
1143{
1144break;
1145}
1146
1147if (i==0)
1148{
1149npart = OSSwapBigToHostInt32(dpme_p->dpme_map_entries);
1150}
1151/*
1152printf("name = %s, %s%s %d -> %d [%d -> %d] {%d}\n",
1153dpme.dpme_name, dpme.dpme_type, (dpme.dpme_flags & DPME_FLAGS_BOOTABLE) ? "(bootable)" : "",
1154dpme.dpme_pblock_start, dpme.dpme_pblocks,
1155dpme.dpme_lblock_start, dpme.dpme_lblocks,
1156dpme.dpme_boot_block);
1157*/
1158
1159if (strcmp(dpme_p->dpme_type, "Apple_HFS") == 0)
1160{
1161bvr = newAPMBVRef(biosdev,
1162i,
1163OSSwapBigToHostInt32(dpme_p->dpme_pblock_start) * factor,
1164dpme_p,
1165HFSInitPartition,
1166HFSLoadFile,
1167HFSReadFile,
1168HFSGetDirEntry,
1169HFSGetFileBlock,
1170HFSGetUUID,
1171HFSGetDescription,
1172HFSFree,
11730,
1174kBIOSDevTypeHardDrive, 0);
1175bvr->next = map->bvr;
1176map->bvr = bvr;
1177map->bvrcnt++;
1178}
1179}
1180}
1181} while (0);
1182
1183free(buffer);
1184
1185if (countPtr) *countPtr = map ? map->bvrcnt : 0;
1186
1187return map ? map->bvr : NULL;
1188}
1189
1190//==============================================================================
1191
1192/*
1193 * Trying to figure out the filsystem type of a given partition.
1194 */
1195static int probeFileSystem(int biosdev, unsigned int blkoff)
1196{
1197// detected filesystem type;
1198int result = -1;
1199int fatbits;
1200
1201// Allocating buffer for 4 sectors.
1202const void * probeBuffer = malloc(PROBEFS_SIZE);
1203if (probeBuffer == NULL)
1204{
1205goto exit;
1206}
1207
1208// Reading first 4 sectors of current partition
1209int error = readBytes(biosdev, blkoff, 0, PROBEFS_SIZE, (void *)probeBuffer);
1210
1211if (error)
1212{
1213goto exit;
1214}
1215
1216if (HFSProbe(probeBuffer))
1217{
1218result = FDISK_HFS;
1219}
1220else if (EX2Probe(probeBuffer))
1221{
1222result = FDISK_LINUX;
1223}
1224else if (FreeBSDProbe(probeBuffer))
1225{
1226result = FDISK_FREEBSD;
1227}
1228
1229else if (OpenBSDProbe(probeBuffer))
1230{
1231result = FDISK_OPENBSD;
1232}
1233
1234else if (BeFSProbe(probeBuffer))
1235{
1236result = FDISK_BEFS;
1237}
1238
1239else if (NTFSProbe(probeBuffer))
1240{
1241result = FDISK_NTFS;
1242}
1243
1244else if ( (fatbits = MSDOSProbe(probeBuffer)) )
1245{
1246switch (fatbits)
1247{
1248case 32:
1249default:
1250result = FDISK_FAT32;
1251break;
1252case 16:
1253result = FDISK_DOS16B;
1254break;
1255case 12:
1256result = FDISK_DOS12;
1257break;
1258}
1259}
1260else
1261{
1262// Couldn't detect filesystem type
1263result = 0;
1264}
1265
1266exit:
1267if (probeBuffer != NULL) free((void *)probeBuffer);
1268{
1269return result;
1270}
1271}
1272
1273//==============================================================================
1274
1275static bool isPartitionUsed(gpt_ent * partition)
1276{
1277
1278// Ask whether the given partition is used.
1279
1280return efi_guid_is_null((EFI_GUID const*)partition->ent_type) ? false : true;
1281}
1282
1283//==============================================================================
1284
1285static BVRef diskScanGPTBootVolumes(int biosdev, int * countPtr)
1286{
1287struct DiskBVMap *map = NULL;
1288
1289void *buffer = malloc(BPS);
1290
1291int error;
1292if ( (error = readBytes( biosdev, /*secno*/0, 0, BPS, buffer )) != 0)
1293{
1294verbose("Failed to read boot sector from BIOS device %02xh. Error=%d\n", biosdev, error);
1295goto scanErr;
1296}
1297struct REAL_disk_blk0 *fdiskMap = buffer;
1298if ( OSSwapLittleToHostInt16(fdiskMap->signature) != DISK_SIGNATURE )
1299{
1300verbose("Failed to find boot signature on BIOS device %02xh\n", biosdev);
1301goto scanErr;
1302}
1303
1304int fdiskID = 0;
1305unsigned index;
1306for ( index = 0; index < FDISK_NPART; index++ )
1307{
1308if ( fdiskMap->parts[index].systid )
1309{
1310if ( fdiskMap->parts[index].systid == 0xEE )
1311{
1312// Fail if two 0xEE partitions are present which
1313// means the FDISK code will wind up parsing it.
1314if ( fdiskID )
1315{
1316goto scanErr;
1317}
1318
1319fdiskID = index + 1;
1320}
1321}
1322}
1323
1324if ( fdiskID == 0 )
1325{
1326goto scanErr;
1327}
1328
1329verbose("Attempting to read GPT\n");
1330
1331if(readBytes(biosdev, 1, 0, BPS, buffer) != 0)
1332{
1333goto scanErr;
1334}
1335
1336gpt_hdr *headerMap = buffer;
1337
1338// Determine whether the partition header signature is present.
1339
1340if ( memcmp(headerMap->hdr_sig, GPT_HDR_SIG, strlen(GPT_HDR_SIG)) )
1341{
1342goto scanErr;
1343}
1344
1345// Determine whether the partition header size is valid.
1346
1347UInt32 headerCheck = OSSwapLittleToHostInt32(headerMap->hdr_crc_self);
1348UInt32 headerSize = OSSwapLittleToHostInt32(headerMap->hdr_size);
1349
1350if ( headerSize < offsetof(gpt_hdr, padding) )
1351{
1352goto scanErr;
1353}
1354
1355if ( headerSize > BPS )
1356{
1357goto scanErr;
1358}
1359
1360// Determine whether the partition header checksum is valid.
1361
1362headerMap->hdr_crc_self = 0;
1363
1364if ( crc32(0, headerMap, headerSize) != headerCheck )
1365{
1366goto scanErr;
1367}
1368
1369// Determine whether the partition entry size is valid.
1370
1371UInt64 gptBlock = 0;
1372UInt32 gptCheck = 0;
1373UInt32 gptCount = 0;
1374UInt32 gptID = 0;
1375gpt_ent * gptMap = 0;
1376UInt32 gptSize = 0;
1377
1378gptBlock = OSSwapLittleToHostInt64(headerMap->hdr_lba_table);
1379gptCheck = OSSwapLittleToHostInt32(headerMap->hdr_crc_table);
1380gptCount = OSSwapLittleToHostInt32(headerMap->hdr_entries);
1381gptSize = OSSwapLittleToHostInt32(headerMap->hdr_entsz);
1382
1383if ( gptSize < sizeof(gpt_ent) )
1384{
1385goto scanErr;
1386}
1387
1388// Allocate a buffer large enough to hold one map, rounded to a media block.
1389free(buffer);
1390buffer = NULL;
1391
1392UInt32 bufferSize = IORound(gptCount * gptSize, BPS);
1393if (bufferSize == 0)
1394{
1395goto scanErr;
1396}
1397buffer = malloc(bufferSize);
1398if (!buffer)
1399{
1400 goto scanErr;
1401}
1402
1403if (readBytes(biosdev, gptBlock, 0, bufferSize, buffer) != 0)
1404{
1405goto scanErr;
1406}
1407verbose("Read GPT\n");
1408
1409// Allocate a new map for this BIOS device and insert it into the chain
1410map = malloc(sizeof(*map));
1411if (!map)
1412{
1413goto scanErr;
1414}
1415map->biosdev = biosdev;
1416map->bvr = NULL;
1417map->bvrcnt = 0;
1418map->next = gDiskBVMap;
1419gDiskBVMap = map;
1420
1421// fdisk like partition type id.
1422int fsType = 0;
1423
1424for(gptID = 1; gptID <= gptCount; ++gptID) {
1425BVRef bvr = NULL;
1426unsigned int bvrFlags = 0;
1427
1428// size on disk can be larger than sizeof(gpt_ent)
1429gptMap = (gpt_ent *) ( buffer + ( (gptID - 1) * gptSize) );
1430
1431// NOTE: EFI_GUID's are in LE and we know we're on an x86.
1432// The IOGUIDPartitionScheme.cpp code uses byte-based UUIDs, we don't.
1433
1434if (isPartitionUsed(gptMap)) {
1435char stringuuid[100];
1436efi_guid_unparse_upper((EFI_GUID*)gptMap->ent_type, stringuuid);
1437verbose("Reading GPT partition %d, type %s\n", gptID, stringuuid);
1438
1439// Getting fdisk like partition type.
1440fsType = probeFileSystem(biosdev, gptMap->ent_lba_start);
1441
1442if ( (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) || (efi_guid_compare(&GPT_HFS_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ) {
1443bvrFlags = (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ? kBVFlagBooter : 0;
1444bvr = newGPTBVRef(biosdev,
1445gptID,
1446gptMap->ent_lba_start,
1447gptMap,
1448HFSInitPartition,
1449HFSLoadFile,
1450HFSReadFile,
1451HFSGetDirEntry,
1452HFSGetFileBlock,
1453HFSGetUUID,
1454HFSGetDescription,
1455HFSFree,
14560,
1457kBIOSDevTypeHardDrive, bvrFlags);
1458}
1459
1460// zef - foreign OS support
1461if ( (efi_guid_compare(&GPT_BASICDATA_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ||
1462(efi_guid_compare(&GPT_BASICDATA2_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ) {
1463switch (fsType)
1464{
1465case FDISK_NTFS:
1466bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap,
14670, 0, 0, 0, 0, 0, NTFSGetDescription,
1468(BVFree)free, 0, kBIOSDevTypeHardDrive, 0);
1469break;
1470
1471case FDISK_LINUX:
1472bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap,
14730, 0, 0, 0, 0, 0, EX2GetDescription,
1474(BVFree)free, 0, kBIOSDevTypeHardDrive, 0);
1475break;
1476
1477default:
1478bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap,
14790, 0, 0, 0, 0, 0, 0,
1480(BVFree)free, 0, kBIOSDevTypeHardDrive, 0);
1481break;
1482}
1483
1484}
1485
1486// turbo - save our booter partition
1487// zef - only on original boot device
1488if ( (efi_guid_compare(&GPT_EFISYS_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ) {
1489switch (fsType) {
1490case FDISK_HFS:
1491if (readBootSector( biosdev, gptMap->ent_lba_start, (void *)0x7e00 ) == 0) {
1492bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap,
1493HFSInitPartition,
1494HFSLoadFile,
1495HFSReadFile,
1496HFSGetDirEntry,
1497HFSGetFileBlock,
1498HFSGetUUID,
1499HFSGetDescription,
1500HFSFree,
15010, kBIOSDevTypeHardDrive, kBVFlagEFISystem);
1502}
1503break;
1504
1505case FDISK_FAT32:
1506if (testFAT32EFIBootSector( biosdev, gptMap->ent_lba_start, (void *)0x7e00 ) == 0) {
1507bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap,
1508MSDOSInitPartition,
1509MSDOSLoadFile,
1510MSDOSReadFile,
1511MSDOSGetDirEntry,
1512MSDOSGetFileBlock,
1513MSDOSGetUUID,
1514MSDOSGetDescription,
1515MSDOSFree,
15160, kBIOSDevTypeHardDrive, kBVFlagEFISystem);
1517}
1518break;
1519
1520default:
1521if (biosdev == gBIOSDev) {
1522gBIOSBootVolume = bvr;
1523}
1524break;
1525}
1526}
1527
1528if (bvr)
1529{
1530// Fixup bvr with the fake fdisk partition type.
1531if (fsType > 0) {
1532bvr->part_type = fsType;
1533}
1534
1535bvr->next = map->bvr;
1536map->bvr = bvr;
1537++map->bvrcnt;
1538}
1539
1540}
1541}
1542
1543scanErr:
1544if (buffer) {
1545free(buffer);
1546}
1547
1548if(map) {
1549if(countPtr) *countPtr = map->bvrcnt;
1550{
1551return map->bvr;
1552}
1553
1554} else {
1555if(countPtr) *countPtr = 0;
1556{
1557return NULL;
1558}
1559}
1560}
1561
1562//==============================================================================
1563
1564static bool getOSVersion(BVRef bvr, char *str)
1565{
1566bool valid = false;
1567config_file_t systemVersion;
1568char dirSpec[512];
1569
1570sprintf(dirSpec, "hd(%d,%d)/System/Library/CoreServices/SystemVersion.plist", BIOS_DEV_UNIT(bvr), bvr->part_no);
1571
1572if (!loadConfigFile(dirSpec, &systemVersion)) {
1573valid = true;
1574} else {
1575sprintf(dirSpec, "hd(%d,%d)/System/Library/CoreServices/ServerVersion.plist", BIOS_DEV_UNIT(bvr), bvr->part_no);
1576
1577if (!loadConfigFile(dirSpec, &systemVersion))
1578{
1579bvr->OSisServer = true;
1580valid = true;
1581}
1582}
1583
1584if (valid) {
1585const char *val;
1586int len;
1587
1588if (getValueForKey(kProductVersion, &val, &len, &systemVersion))
1589{
1590// getValueForKey uses const char for val
1591// so copy it and trim
1592*str = '\0';
1593// crazybirdy
1594if (len > 4 && (val[3] == '1')) {
1595strncat(str, val, MIN(len, 5));
1596} else {
1597strncat(str, val, MIN(len, 4));
1598}
1599} else {
1600valid = false;
1601}
1602}
1603
1604if(!valid)
1605{
1606int fh = -1;
1607sprintf(dirSpec, "hd(%d,%d)/.PhysicalMediaInstall", BIOS_DEV_UNIT(bvr), bvr->part_no);
1608fh = open(dirSpec, 0);
1609
1610if (fh >= 0)
1611{
1612valid = true;
1613bvr->OSisInstaller = true;
1614strcpy(bvr->OSVersion, "10.7"); // 10.7 +
1615close(fh);
1616} else {
1617close(fh);
1618}
1619}
1620return valid;
1621}
1622
1623//==============================================================================
1624
1625static void scanFSLevelBVRSettings(BVRef chain)
1626{
1627BVRef bvr;
1628char dirSpec[512], fileSpec[512];
1629char label[BVSTRLEN];
1630int ret;
1631long flags, time;
1632int fh, fileSize, error;
1633
1634for (bvr = chain; bvr; bvr = bvr->next) {
1635ret = -1;
1636error = 0;
1637
1638//
1639// Check for alternate volume label on boot helper partitions.
1640//
1641if (bvr->flags & kBVFlagBooter) {
1642sprintf(dirSpec, "hd(%d,%d)/System/Library/CoreServices/", BIOS_DEV_UNIT(bvr), bvr->part_no);
1643strcpy(fileSpec, ".disk_label.contentDetails");
1644ret = GetFileInfo(dirSpec, fileSpec, &flags, &time);
1645if (!ret) {
1646fh = open(strcat(dirSpec, fileSpec), 0);
1647fileSize = file_size(fh);
1648if (fileSize > 0 && fileSize < BVSTRLEN) {
1649if (read(fh, label, fileSize) != fileSize) {
1650error = -1;
1651}
1652} else {
1653error = -1;
1654}
1655
1656close(fh);
1657
1658if (!error) {
1659label[fileSize] = '\0';
1660strcpy(bvr->altlabel, label);
1661}
1662}
1663}
1664
1665// Check for SystemVersion.plist or ServerVersion.plist to determine if a volume hosts an installed system.
1666
1667if (bvr->flags & kBVFlagNativeBoot) {
1668if (getOSVersion(bvr,bvr->OSVersion) == true) {
1669bvr->flags |= kBVFlagSystemVolume;
1670}
1671}
1672}
1673}
1674
1675//==============================================================================
1676
1677void rescanBIOSDevice(int biosdev)
1678{
1679struct DiskBVMap *oldMap = diskResetBootVolumes(biosdev);
1680CacheReset();
1681diskFreeMap(oldMap);
1682oldMap = NULL;
1683scanBootVolumes(biosdev, 0);
1684}
1685
1686//==============================================================================
1687
1688struct DiskBVMap* diskResetBootVolumes(int biosdev)
1689{
1690struct DiskBVMap * map;
1691struct DiskBVMap *prevMap = NULL;
1692for ( map = gDiskBVMap; map; prevMap = map, map = map->next ) {
1693if ( biosdev == map->biosdev ) {
1694break;
1695}
1696}
1697
1698if(map != NULL) {
1699verbose("Resetting BIOS device %xh\n", biosdev);
1700// Reset the biosbuf cache
1701cache_valid = false;
1702if(map == gDiskBVMap) {
1703gDiskBVMap = map->next;
1704} else if(prevMap != NULL) {
1705prevMap->next = map->next;
1706} else {
1707stop("");
1708}
1709}
1710// Return the old map, either to be freed, or reinserted later
1711return map;
1712}
1713
1714//==============================================================================
1715
1716// Frees a DiskBVMap and all of its BootVolume's
1717void diskFreeMap(struct DiskBVMap *map)
1718{
1719if(map != NULL)
1720{
1721while(map->bvr != NULL)
1722{
1723BVRef bvr = map->bvr;
1724map->bvr = bvr->next;
1725(*bvr->bv_free)(bvr);
1726}
1727
1728free(map);
1729}
1730}
1731
1732//==============================================================================
1733
1734BVRef diskScanBootVolumes(int biosdev, int * countPtr)
1735{
1736struct DiskBVMap *map;
1737BVRef bvr;
1738int count = 0;
1739
1740// Find an existing mapping for this device.
1741
1742for (map = gDiskBVMap; map; map = map->next)
1743{
1744if (biosdev == map->biosdev)
1745{
1746count = map->bvrcnt;
1747break;
1748}
1749}
1750
1751if (map == NULL)
1752{
1753bvr = diskScanGPTBootVolumes(biosdev, &count);
1754if (bvr == NULL)
1755{
1756bvr = diskScanFDiskBootVolumes(biosdev, &count);
1757}
1758if (bvr == NULL)
1759{
1760bvr = diskScanAPMBootVolumes(biosdev, &count);
1761}
1762if (bvr)
1763{
1764scanFSLevelBVRSettings(bvr);
1765}
1766}
1767else
1768{
1769bvr = map->bvr;
1770}
1771if (countPtr)
1772{
1773*countPtr += count;
1774}
1775return bvr;
1776}
1777
1778//==============================================================================
1779
1780BVRef getBVChainForBIOSDev(int biosdev)
1781{
1782BVRef chain = NULL;
1783struct DiskBVMap * map = NULL;
1784
1785for (map = gDiskBVMap; map; map = map->next)
1786{
1787if (map->biosdev == biosdev)
1788{
1789chain = map->bvr;
1790break;
1791}
1792}
1793
1794return chain;
1795}
1796
1797//==============================================================================
1798
1799BVRef newFilteredBVChain(int minBIOSDev, int maxBIOSDev, unsigned int allowFlags, unsigned int denyFlags, int *count)
1800{
1801BVRef chain = NULL;
1802BVRef bvr = NULL;
1803BVRef newBVR = NULL;
1804BVRef prevBVR = NULL;
1805
1806struct DiskBVMap * map = NULL;
1807int bvCount = 0;
1808
1809const char *raw = 0;
1810char* val = 0;
1811int len;
1812
1813getValueForKey(kHidePartition, &raw, &len, &bootInfo->chameleonConfig);
1814if(raw)
1815{
1816val = XMLDecode(raw);
1817}
1818
1819/*
1820 * Traverse gDISKBVmap to get references for
1821 * individual bvr chains of each drive.
1822 */
1823for (map = gDiskBVMap; map; map = map->next)
1824{
1825for (bvr = map->bvr; bvr; bvr = bvr->next)
1826{
1827/*
1828 * Save the last bvr.
1829 */
1830if (newBVR)
1831{
1832prevBVR = newBVR;
1833}
1834
1835/*
1836 * Allocate and copy the matched bvr entry into a new one.
1837 */
1838newBVR = (BVRef) malloc(sizeof(*newBVR));
1839if (!newBVR)
1840{
1841continue;
1842}
1843bcopy(bvr, newBVR, sizeof(*newBVR));
1844
1845/*
1846 * Adjust the new bvr's fields.
1847 */
1848newBVR->next = NULL;
1849newBVR->filtered = true;
1850
1851if ( (!allowFlags || newBVR->flags & allowFlags)
1852&& (!denyFlags || !(newBVR->flags & denyFlags) )
1853&& (newBVR->biosdev >= minBIOSDev && newBVR->biosdev <= maxBIOSDev)
1854) {
1855newBVR->visible = true;
1856}
1857
1858/*
1859 * Looking for "Hide Partition" entries in 'hd(x,y)|uuid|"label" hd(m,n)|uuid|"label"' format,
1860 * to be able to hide foreign partitions from the boot menu.
1861 *
1862 */
1863if ( (newBVR->flags & kBVFlagForeignBoot) ) {
1864char *start, *next = val;
1865long len = 0;
1866do
1867{
1868start = strbreak(next, &next, &len);
1869if(len && matchVolumeToString(newBVR, start, len) )
1870{
1871newBVR->visible = false;
1872}
1873}
1874while ( next && *next );
1875}
1876
1877/*
1878 * Use the first bvr entry as the starting chain pointer.
1879 */
1880if (!chain) {
1881chain = newBVR;
1882}
1883
1884/*
1885 * Update the previous bvr's link pointer to use the new memory area.
1886 */
1887if (prevBVR) {
1888prevBVR->next = newBVR;
1889}
1890
1891if (newBVR->visible) {
1892bvCount++;
1893}
1894}
1895}
1896
1897#if DEBUG //Azi: warning - too big for boot-log.. far too big.. i mean HUGE!! :P
1898for (bvr = chain; bvr; bvr = bvr->next)
1899{
1900printf(" bvr: %d, dev: %d, part: %d, flags: %d, vis: %d\n", bvr, bvr->biosdev, bvr->part_no, bvr->flags, bvr->visible);
1901}
1902printf("count: %d\n", bvCount);
1903getchar();
1904#endif
1905
1906*count = bvCount;
1907
1908free(val);
1909return chain;
1910}
1911
1912//==============================================================================
1913
1914int freeFilteredBVChain(const BVRef chain)
1915{
1916int ret = 1;
1917BVRef bvr = chain;
1918BVRef nextBVR = NULL;
1919
1920while (bvr)
1921{
1922nextBVR = bvr->next;
1923
1924if (bvr->filtered)
1925{
1926free(bvr);
1927}
1928else
1929{
1930ret = 0;
1931break;
1932}
1933
1934bvr = nextBVR;
1935}
1936
1937return ret;
1938}
1939
1940//==============================================================================
1941
1942static const struct NamedValue fdiskTypes[] =
1943{
1944{ FDISK_NTFS,"Windows NTFS" },
1945{ FDISK_DOS12,"Windows FAT12" },
1946{ FDISK_DOS16B,"Windows FAT16" },
1947{ FDISK_DOS16S,"Windows FAT16" },
1948{ FDISK_DOS16SLBA,"Windows FAT16" },
1949{ FDISK_SMALLFAT32,"Windows FAT32" },
1950{ FDISK_FAT32,"Windows FAT32" },
1951{ FDISK_FREEBSD,"FreeBSD" },
1952{ FDISK_OPENBSD,"OpenBSD" },
1953{ FDISK_LINUX,"Linux" },
1954{ FDISK_UFS,"Apple UFS" },
1955{ FDISK_HFS,"Apple HFS" },
1956{ FDISK_BOOTER,"Apple Boot/UFS" },
1957{ FDISK_BEFS,"Haiku" },
1958{ 0xCD,"CD-ROM" },
1959{ 0x00,0 } /* must be last */
1960};
1961
1962//==============================================================================
1963
1964bool matchVolumeToString( BVRef bvr, const char* match, long matchLen)
1965{
1966char testStr[128];
1967
1968if ( !bvr || !match || !*match)
1969{
1970return 0;
1971}
1972
1973if ( bvr->biosdev < 0x80 || bvr->biosdev >= 0x100 )
1974{
1975 return 0;
1976}
1977
1978// Try to match hd(x,y) first.
1979sprintf(testStr, "hd(%d,%d)", BIOS_DEV_UNIT(bvr), bvr->part_no);
1980if ( matchLen ? !strncmp(match, testStr, matchLen) : !strcmp(match, testStr) )
1981{
1982return true;
1983}
1984
1985// Try to match volume UUID.
1986if ( bvr->fs_getuuid && bvr->fs_getuuid(bvr, testStr) == 0)
1987{
1988if ( matchLen ? !strncmp(match, testStr, matchLen) : !strcmp(match, testStr) )
1989{
1990return true;
1991}
1992}
1993
1994// Try to match volume label (always quoted).
1995if ( bvr->description )
1996{
1997bvr->description(bvr, testStr, sizeof(testStr)-1);
1998if ( matchLen ? !strncmp(match, testStr, matchLen) : !strcmp(match, testStr) )
1999{
2000return true;
2001}
2002}
2003
2004return false;
2005}
2006
2007//==============================================================================
2008
2009/* If Rename Partition has defined an alias, then extract it for description purpose.
2010 * The format for the rename string is the following:
2011 * hd(x,y)|uuid|"label" "alias";hd(m,n)|uuid|"label" "alias"; etc...
2012 */
2013
2014bool getVolumeLabelAlias(BVRef bvr, char* str, long strMaxLen)
2015{
2016char *aliasList, *entryStart, *entryNext;
2017
2018if ( !str || strMaxLen <= 0)
2019{
2020return false;
2021}
2022
2023aliasList = XMLDecode(getStringForKey(kRenamePartition, &bootInfo->chameleonConfig));
2024if ( !aliasList )
2025{
2026return false;
2027}
2028
2029for ( entryStart = entryNext = aliasList; entryNext && *entryNext; entryStart = entryNext )
2030{
2031char *volStart, *volEnd, *aliasStart;
2032long volLen, aliasLen;
2033
2034// Delimit current entry
2035entryNext = strchr(entryStart, ';');
2036if ( entryNext )
2037{
2038*entryNext = '\0';
2039entryNext++;
2040}
2041
2042volStart = strbreak(entryStart, &volEnd, &volLen);
2043if(!volLen)
2044{
2045continue;
2046}
2047
2048aliasStart = strbreak(volEnd, 0, &aliasLen);
2049if(!aliasLen)
2050{
2051continue;
2052}
2053
2054if ( matchVolumeToString(bvr, volStart, volLen) )
2055{
2056strncat(str, aliasStart, MIN(strMaxLen, aliasLen));
2057free(aliasList);
2058
2059return true;
2060}
2061}
2062
2063free(aliasList);
2064return false;
2065}
2066
2067//==============================================================================
2068
2069void getBootVolumeDescription( BVRef bvr, char * str, long strMaxLen, bool useDeviceDescription )
2070{
2071unsigned char type;
2072char *p = str;
2073
2074if(!bvr || !p || strMaxLen <= 0)
2075{
2076return;
2077}
2078
2079type = (unsigned char) bvr->part_type;
2080
2081if (useDeviceDescription)
2082{
2083int len = getDeviceDescription(bvr, str);
2084if(len >= strMaxLen)
2085{
2086return;
2087}
2088
2089strcpy(str + len, bvr->OSisInstaller ? " (Installer) " : " ");
2090len += bvr->OSisInstaller ? 13 : 1;
2091strMaxLen -= len;
2092p += len;
2093}
2094
2095/* See if a partition rename is preferred */
2096if (getVolumeLabelAlias(bvr, p, strMaxLen))
2097{
2098strncpy(bvr->label, p, strMaxLen);
2099return; // we're done here no need to seek for real name
2100}
2101
2102// Get the volume label using filesystem specific functions or use the alternate volume label if available.
2103
2104if (*bvr->altlabel != '\0')
2105{
2106strncpy(p, bvr->altlabel, strMaxLen);
2107}
2108else if (bvr->description)
2109{
2110bvr->description(bvr, p, strMaxLen);
2111}
2112
2113if (*p == '\0')
2114{
2115const char * name = getNameForValue( fdiskTypes, type );
2116
2117if (name == NULL)
2118{
2119name = bvr->type_name;
2120}
2121
2122if (name == NULL)
2123{
2124sprintf(p, "TYPE %02x", type);
2125}
2126else
2127{
2128strncpy(p, name, strMaxLen);
2129}
2130}
2131
2132// Set the devices label
2133sprintf(bvr->label, p);
2134}
2135
2136
2137//==============================================================================
2138
2139int readBootSector(int biosdev, unsigned int secno, void * buffer)
2140{
2141int error;
2142struct disk_blk0 * bootSector = (struct disk_blk0 *) buffer;
2143
2144if (bootSector == NULL)
2145{
2146if (gBootSector == NULL)
2147{
2148gBootSector = (struct disk_blk0 *) malloc(sizeof(*gBootSector));
2149
2150if (gBootSector == NULL)
2151{
2152return -1;
2153}
2154}
2155
2156bootSector = gBootSector;
2157}
2158
2159error = readBytes(biosdev, secno, 0, BPS, bootSector);
2160
2161if (error || bootSector->signature != DISK_SIGNATURE)
2162{
2163return -1;
2164}
2165return 0;
2166}
2167
2168//==============================================================================
2169
2170/*
2171 * Format of boot1f32 block.
2172 */
2173
2174#define BOOT1F32_MAGIC "BOOT "
2175#define BOOT1F32_MAGICLEN 11
2176
2177struct disk_boot1f32_blk
2178{
2179unsigned char init[3];
2180unsigned char fsheader[87];
2181unsigned char magic[BOOT1F32_MAGICLEN];
2182unsigned char bootcode[409];
2183unsigned short signature;
2184};
2185
2186//==============================================================================
2187
2188int testFAT32EFIBootSector( int biosdev, unsigned int secno, void * buffer )
2189{
2190struct disk_boot1f32_blk * bootSector = (struct disk_boot1f32_blk *) buffer;
2191int error;
2192
2193if ( bootSector == NULL )
2194{
2195if ( gBootSector == NULL )
2196{
2197gBootSector = (struct disk_blk0 *) malloc(sizeof(*gBootSector));
2198if ( gBootSector == NULL )
2199{
2200return -1;
2201}
2202}
2203bootSector = (struct disk_boot1f32_blk *) gBootSector;
2204}
2205
2206error = readBytes( biosdev, secno, 0, BPS, bootSector );
2207if ( error || bootSector->signature != DISK_SIGNATURE || strncmp((const char *)bootSector->magic, BOOT1F32_MAGIC, BOOT1F32_MAGICLEN) )
2208{
2209return -1;
2210}
2211return 0;
2212}
2213
2214
2215//==============================================================================
2216// Handle seek request from filesystem modules.
2217
2218void diskSeek(BVRef bvr, long long position)
2219{
2220bvr->fs_boff = position / BPS;
2221bvr->fs_byteoff = position % BPS;
2222}
2223
2224
2225//==============================================================================
2226// Handle read request from filesystem modules.
2227
2228int diskRead(BVRef bvr, long addr, long length)
2229{
2230return readBytes(bvr->biosdev, bvr->fs_boff + bvr->part_boff, bvr->fs_byteoff, length, (void *) addr);
2231}
2232
2233//==============================================================================
2234
2235int rawDiskRead( BVRef bvr, unsigned int secno, void *buffer, unsigned int len )
2236{
2237int secs;
2238unsigned char *cbuf = (unsigned char *)buffer;
2239unsigned int copy_len;
2240int rc;
2241
2242if ((len & (BPS-1)) != 0)
2243{
2244error("raw disk read not sector aligned");
2245return -1;
2246}
2247secno += bvr->part_boff;
2248
2249cache_valid = false;
2250
2251while (len > 0)
2252{
2253secs = len / BPS;
2254if (secs > N_CACHE_SECS)
2255{
2256secs = N_CACHE_SECS;
2257}
2258copy_len = secs * BPS;
2259
2260//printf("rdr: ebiosread(%d, %d, %d)\n", bvr->biosdev, secno, secs);
2261if ((rc = ebiosread(bvr->biosdev, secno, secs)) != 0)
2262{
2263/* Ignore corrected ECC errors */
2264if (rc != ECC_CORRECTED_ERR)
2265{
2266error(" EBIOS read error: %s\n", bios_error(rc), rc);
2267error(" Block %d Sectors %d\n", secno, secs);
2268return rc;
2269}
2270}
2271bcopy( trackbuf, cbuf, copy_len );
2272len -= copy_len;
2273cbuf += copy_len;
2274secno += secs;
2275spinActivityIndicator(secs);
2276}
2277
2278return 0;
2279}
2280
2281//==============================================================================
2282
2283int rawDiskWrite( BVRef bvr, unsigned int secno, void *buffer, unsigned int len )
2284{
2285 int secs;
2286 unsigned char *cbuf = (unsigned char *)buffer;
2287 unsigned int copy_len;
2288 int rc;
2289
2290if ((len & (BPS-1)) != 0)
2291{
2292error("raw disk write not sector aligned");
2293return -1;
2294}
2295secno += bvr->part_boff;
2296
2297cache_valid = false;
2298
2299while (len > 0)
2300{
2301secs = len / BPS;
2302if (secs > N_CACHE_SECS)
2303{
2304secs = N_CACHE_SECS;
2305}
2306copy_len = secs * BPS;
2307
2308bcopy( cbuf, trackbuf, copy_len );
2309//printf("rdr: ebioswrite(%d, %d, %d)\n", bvr->biosdev, secno, secs);
2310if ((rc = ebioswrite(bvr->biosdev, secno, secs)) != 0)
2311{
2312error(" EBIOS write error: %s\n", bios_error(rc), rc);
2313error(" Block %d Sectors %d\n", secno, secs);
2314return rc;
2315}
2316
2317len -= copy_len;
2318cbuf += copy_len;
2319secno += secs;
2320spinActivityIndicator(secs);
2321}
2322
2323return 0;
2324}
2325
2326//==============================================================================
2327
2328int diskIsCDROM(BVRef bvr)
2329{
2330struct driveInfo di;
2331
2332if (getDriveInfo(bvr->biosdev, &di) == 0 && di.no_emulation)
2333{
2334return 1;
2335}
2336return 0;
2337}
2338
2339//==============================================================================
2340
2341int biosDevIsCDROM(int biosdev)
2342{
2343struct driveInfo di;
2344
2345if (getDriveInfo(biosdev, &di) == 0 && di.no_emulation)
2346{
2347return 1;
2348}
2349return 0;
2350}
2351

Archive Download this file

Revision: 2424