Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 711