]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/boot/i386/libi386/biosdisk.c
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / sys / boot / i386 / libi386 / biosdisk.c
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 /*
31  * BIOS disk device handling.
32  * 
33  * Ideas and algorithms from:
34  *
35  * - NetBSD libi386/biosdisk.c
36  * - FreeBSD biosboot/disk.c
37  *
38  */
39
40 #include <stand.h>
41
42 #include <sys/disklabel.h>
43 #include <sys/diskmbr.h>
44 #include <sys/gpt.h>
45 #include <machine/bootinfo.h>
46
47 #include <stdarg.h>
48 #include <uuid.h>
49
50 #include <bootstrap.h>
51 #include <btxv86.h>
52 #include "libi386.h"
53
54 #define BIOS_NUMDRIVES          0x475
55 #define BIOSDISK_SECSIZE        512
56 #define BUFSIZE                 (1 * BIOSDISK_SECSIZE)
57 #define MAXBDDEV                MAXDEV
58
59 #define DT_ATAPI                0x10            /* disk type for ATAPI floppies */
60 #define WDMAJOR                 0               /* major numbers for devices we frontend for */
61 #define WFDMAJOR                1
62 #define FDMAJOR                 2
63 #define DAMAJOR                 4
64
65 #ifdef DISK_DEBUG
66 # define DEBUG(fmt, args...)    printf("%s: " fmt "\n" , __func__ , ## args)
67 #else
68 # define DEBUG(fmt, args...)
69 #endif
70
71 #ifdef LOADER_GPT_SUPPORT
72 struct gpt_part {
73     int         gp_index;
74     uuid_t      gp_type;
75     uint64_t    gp_start;
76     uint64_t    gp_end;
77 };
78 #endif
79
80 struct open_disk {
81     int                 od_dkunit;              /* disk unit number */
82     int                 od_unit;                /* BIOS unit number */
83     int                 od_cyl;                 /* BIOS geometry */
84     int                 od_hds;
85     int                 od_sec;
86     daddr_t                     od_boff;                /* block offset from beginning of BIOS disk */
87     int                 od_flags;
88 #define BD_MODEINT13            0x0000
89 #define BD_MODEEDD1             0x0001
90 #define BD_MODEEDD3             0x0002
91 #define BD_MODEMASK             0x0003
92 #define BD_FLOPPY               0x0004
93 #define BD_LABELOK              0x0008
94 #define BD_PARTTABOK            0x0010
95 #ifdef LOADER_GPT_SUPPORT
96 #define BD_GPTOK                0x0020
97 #endif
98     union {
99         struct {
100             struct disklabel            mbr_disklabel;
101             int                         mbr_nslices;    /* slice count */
102             struct dos_partition        mbr_slicetab[NEXTDOSPART];
103         } _mbr;
104 #ifdef LOADER_GPT_SUPPORT
105         struct {
106             int                         gpt_nparts;             
107             struct gpt_part             *gpt_partitions;
108         } _gpt;
109 #endif
110     } _data;
111 };
112
113 #define od_disklabel            _data._mbr.mbr_disklabel
114 #define od_nslices              _data._mbr.mbr_nslices
115 #define od_slicetab             _data._mbr.mbr_slicetab
116 #ifdef LOADER_GPT_SUPPORT
117 #define od_nparts               _data._gpt.gpt_nparts
118 #define od_partitions           _data._gpt.gpt_partitions
119 #endif
120
121 /*
122  * List of BIOS devices, translation from disk unit number to
123  * BIOS unit number.
124  */
125 static struct bdinfo
126 {
127     int         bd_unit;                /* BIOS unit number */
128     int         bd_flags;
129     int         bd_type;                /* BIOS 'drive type' (floppy only) */
130 } bdinfo [MAXBDDEV];
131 static int nbdinfo = 0;
132
133 static int      bd_getgeom(struct open_disk *od);
134 static int      bd_read(struct open_disk *od, daddr_t dblk, int blks,
135                     caddr_t dest);
136 static int      bd_write(struct open_disk *od, daddr_t dblk, int blks,
137                     caddr_t dest);
138
139 static int      bd_int13probe(struct bdinfo *bd);
140
141 #ifdef LOADER_GPT_SUPPORT
142 static void     bd_printgptpart(struct open_disk *od, struct gpt_part *gp,
143                     char *prefix, int verbose);
144 #endif
145 static void     bd_printslice(struct open_disk *od, struct dos_partition *dp,
146                     char *prefix, int verbose);
147 static void     bd_printbsdslice(struct open_disk *od, daddr_t offset,
148                     char *prefix, int verbose);
149
150 static int      bd_init(void);
151 static int      bd_strategy(void *devdata, int flag, daddr_t dblk,
152                     size_t size, char *buf, size_t *rsize);
153 static int      bd_realstrategy(void *devdata, int flag, daddr_t dblk,
154                     size_t size, char *buf, size_t *rsize);
155 static int      bd_open(struct open_file *f, ...);
156 static int      bd_close(struct open_file *f);
157 static void     bd_print(int verbose);
158
159 struct devsw biosdisk = {
160     "disk", 
161     DEVT_DISK, 
162     bd_init,
163     bd_strategy, 
164     bd_open, 
165     bd_close, 
166     noioctl,
167     bd_print,
168     NULL
169 };
170
171 static int      bd_opendisk(struct open_disk **odp, struct i386_devdesc *dev);
172 static void     bd_closedisk(struct open_disk *od);
173 static int      bd_open_mbr(struct open_disk *od, struct i386_devdesc *dev);
174 static int      bd_bestslice(struct open_disk *od);
175 static void     bd_checkextended(struct open_disk *od, int slicenum);
176 #ifdef LOADER_GPT_SUPPORT
177 static int      bd_open_gpt(struct open_disk *od, struct i386_devdesc *dev);
178 static struct gpt_part *bd_best_gptpart(struct open_disk *od);
179 #endif
180
181 /*
182  * Translate between BIOS device numbers and our private unit numbers.
183  */
184 int
185 bd_bios2unit(int biosdev)
186 {
187     int         i;
188     
189     DEBUG("looking for bios device 0x%x", biosdev);
190     for (i = 0; i < nbdinfo; i++) {
191         DEBUG("bd unit %d is BIOS device 0x%x", i, bdinfo[i].bd_unit);
192         if (bdinfo[i].bd_unit == biosdev)
193             return(i);
194     }
195     return(-1);
196 }
197
198 int
199 bd_unit2bios(int unit)
200 {
201     if ((unit >= 0) && (unit < nbdinfo))
202         return(bdinfo[unit].bd_unit);
203     return(-1);
204 }
205
206 /*    
207  * Quiz the BIOS for disk devices, save a little info about them.
208  */
209 static int
210 bd_init(void) 
211 {
212     int         base, unit, nfd = 0;
213
214     /* sequence 0, 0x80 */
215     for (base = 0; base <= 0x80; base += 0x80) {
216         for (unit = base; (nbdinfo < MAXBDDEV); unit++) {
217 #ifndef VIRTUALBOX
218             /* check the BIOS equipment list for number of fixed disks */
219             if((base == 0x80) &&
220                (nfd >= *(unsigned char *)PTOV(BIOS_NUMDRIVES)))
221                 break;
222 #endif
223
224             bdinfo[nbdinfo].bd_unit = unit;
225             bdinfo[nbdinfo].bd_flags = (unit < 0x80) ? BD_FLOPPY : 0;
226
227             if (!bd_int13probe(&bdinfo[nbdinfo]))
228                 break;
229
230             /* XXX we need "disk aliases" to make this simpler */
231             printf("BIOS drive %c: is disk%d\n", 
232                    (unit < 0x80) ? ('A' + unit) : ('C' + unit - 0x80), nbdinfo);
233             nbdinfo++;
234             if (base == 0x80)
235                 nfd++;
236         }
237     }
238     return(0);
239 }
240
241 /*
242  * Try to detect a device supported by the legacy int13 BIOS
243  */
244 static int
245 bd_int13probe(struct bdinfo *bd)
246 {
247     v86.ctl = V86_FLAGS;
248     v86.addr = 0x13;
249     v86.eax = 0x800;
250     v86.edx = bd->bd_unit;
251     v86int();
252     
253     if (!(v86.efl & 0x1) &&                             /* carry clear */
254         ((v86.edx & 0xff) > ((unsigned)bd->bd_unit & 0x7f))) {  /* unit # OK */
255         if ((v86.ecx & 0x3f) == 0) {                    /* absurd sector size */
256                 DEBUG("Invalid geometry for unit %d", bd->bd_unit);
257                 return(0);                              /* skip device */
258         }
259         bd->bd_flags |= BD_MODEINT13;
260         bd->bd_type = v86.ebx & 0xff;
261
262         /* Determine if we can use EDD with this device. */
263         v86.eax = 0x4100;
264         v86.edx = bd->bd_unit;
265         v86.ebx = 0x55aa;
266         v86int();
267         if (!(v86.efl & 0x1) &&                         /* carry clear */
268             ((v86.ebx & 0xffff) == 0xaa55) &&           /* signature */
269             (v86.ecx & 0x1)) {                          /* packets mode ok */
270             bd->bd_flags |= BD_MODEEDD1;
271             if((v86.eax & 0xff00) >= 0x3000)
272                 bd->bd_flags |= BD_MODEEDD3;
273         }
274         return(1);
275     }
276     return(0);
277 }
278
279 /*
280  * Print information about disks
281  */
282 static void
283 bd_print(int verbose)
284 {
285     int                         i, j;
286     char                        line[80];
287     struct i386_devdesc         dev;
288     struct open_disk            *od;
289     struct dos_partition        *dptr;
290     
291     for (i = 0; i < nbdinfo; i++) {
292         sprintf(line, "    disk%d:   BIOS drive %c:\n", i, 
293                 (bdinfo[i].bd_unit < 0x80) ? ('A' + bdinfo[i].bd_unit) : ('C' + bdinfo[i].bd_unit - 0x80));
294         pager_output(line);
295
296         /* try to open the whole disk */
297         dev.d_unit = i;
298         dev.d_kind.biosdisk.slice = -1;
299         dev.d_kind.biosdisk.partition = -1;
300         
301         if (!bd_opendisk(&od, &dev)) {
302
303 #ifdef LOADER_GPT_SUPPORT
304             /* Do we have a GPT table? */
305             if (od->od_flags & BD_GPTOK) {
306                 for (j = 0; j < od->od_nparts; j++) {
307                     sprintf(line, "      disk%dp%d", i,
308                         od->od_partitions[j].gp_index);
309                     bd_printgptpart(od, &od->od_partitions[j], line, verbose);
310                 }
311             } else
312 #endif
313             /* Do we have a partition table? */
314             if (od->od_flags & BD_PARTTABOK) {
315                 dptr = &od->od_slicetab[0];
316
317                 /* Check for a "dedicated" disk */
318                 if ((dptr[3].dp_typ == DOSPTYP_386BSD) &&
319                     (dptr[3].dp_start == 0) &&
320                     (dptr[3].dp_size == 50000)) {
321                     sprintf(line, "      disk%d", i);
322                     bd_printbsdslice(od, 0, line, verbose);
323                 } else {
324                     for (j = 0; j < od->od_nslices; j++) {
325                         sprintf(line, "      disk%ds%d", i, j + 1);
326                         bd_printslice(od, &dptr[j], line, verbose);
327                     }
328                 }
329             }
330             bd_closedisk(od);
331         }
332     }
333 }
334
335 /* Given a size in 512 byte sectors, convert it to a human-readable number. */
336 static char *
337 display_size(uint64_t size)
338 {
339     static char buf[80];
340     char unit;
341
342     size /= 2;
343     unit = 'K';
344     if (size >= 10485760000LL) {
345         size /= 1073741824;
346         unit = 'T';
347     } else if (size >= 10240000) {
348         size /= 1048576;
349         unit = 'G';
350     } else if (size >= 10000) {
351         size /= 1024;
352         unit = 'M';
353     }
354     sprintf(buf, "%.6ld%cB", (long)size, unit);
355     return (buf);
356 }
357
358 #ifdef LOADER_GPT_SUPPORT
359 static uuid_t efi = GPT_ENT_TYPE_EFI;
360 static uuid_t freebsd_boot = GPT_ENT_TYPE_FREEBSD_BOOT;
361 static uuid_t freebsd_ufs = GPT_ENT_TYPE_FREEBSD_UFS;
362 static uuid_t freebsd_swap = GPT_ENT_TYPE_FREEBSD_SWAP;
363 static uuid_t freebsd_zfs = GPT_ENT_TYPE_FREEBSD_ZFS;
364 static uuid_t ms_basic_data = GPT_ENT_TYPE_MS_BASIC_DATA;
365
366 static void
367 bd_printgptpart(struct open_disk *od, struct gpt_part *gp, char *prefix,
368     int verbose)
369 {
370     char stats[80];
371     char line[96];
372
373     if (verbose)
374         sprintf(stats, " %s", display_size(gp->gp_end + 1 - gp->gp_start));
375     else
376         stats[0] = '\0';
377
378     if (uuid_equal(&gp->gp_type, &efi, NULL))
379         sprintf(line, "%s: EFI         %s\n", prefix, stats);
380     else if (uuid_equal(&gp->gp_type, &ms_basic_data, NULL))
381         sprintf(line, "%s: FAT/NTFS    %s\n", prefix, stats);
382     else if (uuid_equal(&gp->gp_type, &freebsd_boot, NULL))
383         sprintf(line, "%s: FreeBSD boot%s\n", prefix, stats);
384     else if (uuid_equal(&gp->gp_type, &freebsd_ufs, NULL))
385         sprintf(line, "%s: FreeBSD UFS %s\n", prefix, stats);
386     else if (uuid_equal(&gp->gp_type, &freebsd_zfs, NULL))
387         sprintf(line, "%s: FreeBSD ZFS %s\n", prefix, stats);
388     else if (uuid_equal(&gp->gp_type, &freebsd_swap, NULL))
389         sprintf(line, "%s: FreeBSD swap%s\n", prefix, stats);
390     else
391         sprintf(line, "%s: %08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x%s\n",
392             prefix,
393             gp->gp_type.time_low, gp->gp_type.time_mid,
394             gp->gp_type.time_hi_and_version,
395             gp->gp_type.clock_seq_hi_and_reserved, gp->gp_type.clock_seq_low,
396             gp->gp_type.node[0], gp->gp_type.node[1], gp->gp_type.node[2],
397             gp->gp_type.node[3], gp->gp_type.node[4], gp->gp_type.node[5],
398             stats);
399     pager_output(line);
400 }
401 #endif
402
403 /*
404  * Print information about slices on a disk.  For the size calculations we
405  * assume a 512 byte sector.
406  */
407 static void
408 bd_printslice(struct open_disk *od, struct dos_partition *dp, char *prefix,
409         int verbose)
410 {
411         char stats[80];
412         char line[80];
413
414         if (verbose)
415                 sprintf(stats, " %s (%d - %d)", display_size(dp->dp_size),
416                     dp->dp_start, dp->dp_start + dp->dp_size);
417         else
418                 stats[0] = '\0';
419
420         switch (dp->dp_typ) {
421         case DOSPTYP_386BSD:
422                 bd_printbsdslice(od, (daddr_t)dp->dp_start, prefix, verbose);
423                 return;
424         case DOSPTYP_LINSWP:
425                 sprintf(line, "%s: Linux swap%s\n", prefix, stats);
426                 break;
427         case DOSPTYP_LINUX:
428                 /*
429                  * XXX
430                  * read the superblock to confirm this is an ext2fs partition?
431                  */
432                 sprintf(line, "%s: ext2fs%s\n", prefix, stats);
433                 break;
434         case 0x00:                              /* unused partition */
435         case DOSPTYP_EXT:
436                 return;
437         case 0x01:
438                 sprintf(line, "%s: FAT-12%s\n", prefix, stats);
439                 break;
440         case 0x04:
441         case 0x06:
442         case 0x0e:
443                 sprintf(line, "%s: FAT-16%s\n", prefix, stats);
444                 break;
445         case 0x07:
446                 sprintf(line, "%s: NTFS/HPFS%s\n", prefix, stats);
447                 break;
448         case 0x0b:
449         case 0x0c:
450                 sprintf(line, "%s: FAT-32%s\n", prefix, stats);
451                 break;
452         default:
453                 sprintf(line, "%s: Unknown fs: 0x%x %s\n", prefix, dp->dp_typ,
454                     stats);
455         }
456         pager_output(line);
457 }
458
459 /*
460  * Print out each valid partition in the disklabel of a FreeBSD slice.
461  * For size calculations, we assume a 512 byte sector size.
462  */
463 static void
464 bd_printbsdslice(struct open_disk *od, daddr_t offset, char *prefix,
465     int verbose)
466 {
467     char                line[80];
468     char                buf[BIOSDISK_SECSIZE];
469     struct disklabel    *lp;
470     int                 i;
471
472     /* read disklabel */
473     if (bd_read(od, offset + LABELSECTOR, 1, buf))
474         return;
475     lp =(struct disklabel *)(&buf[0]);
476     if (lp->d_magic != DISKMAGIC) {
477         sprintf(line, "%s: FFS  bad disklabel\n", prefix);
478         pager_output(line);
479         return;
480     }
481     
482     /* Print partitions */
483     for (i = 0; i < lp->d_npartitions; i++) {
484         /*
485          * For each partition, make sure we know what type of fs it is.  If
486          * not, then skip it.  However, since floppies often have bogus
487          * fstypes, print the 'a' partition on a floppy even if it is marked
488          * unused.
489          */
490         if ((lp->d_partitions[i].p_fstype == FS_BSDFFS) ||
491             (lp->d_partitions[i].p_fstype == FS_SWAP) ||
492             (lp->d_partitions[i].p_fstype == FS_VINUM) ||
493             ((lp->d_partitions[i].p_fstype == FS_UNUSED) && 
494              (od->od_flags & BD_FLOPPY) && (i == 0))) {
495
496             /* Only print out statistics in verbose mode */
497             if (verbose)
498                 sprintf(line, "  %s%c: %s %s (%d - %d)\n", prefix, 'a' + i,
499                     (lp->d_partitions[i].p_fstype == FS_SWAP) ? "swap " : 
500                     (lp->d_partitions[i].p_fstype == FS_VINUM) ? "vinum" :
501                     "FFS  ",
502                     display_size(lp->d_partitions[i].p_size),
503                     lp->d_partitions[i].p_offset,
504                     lp->d_partitions[i].p_offset + lp->d_partitions[i].p_size);
505             else
506                 sprintf(line, "  %s%c: %s\n", prefix, 'a' + i,
507                     (lp->d_partitions[i].p_fstype == FS_SWAP) ? "swap" : 
508                     (lp->d_partitions[i].p_fstype == FS_VINUM) ? "vinum" :
509                     "FFS");
510             pager_output(line);
511         }
512     }
513 }
514
515
516 /*
517  * Attempt to open the disk described by (dev) for use by (f).
518  *
519  * Note that the philosophy here is "give them exactly what
520  * they ask for".  This is necessary because being too "smart"
521  * about what the user might want leads to complications.
522  * (eg. given no slice or partition value, with a disk that is
523  *  sliced - are they after the first BSD slice, or the DOS
524  *  slice before it?)
525  */
526 static int 
527 bd_open(struct open_file *f, ...)
528 {
529     va_list                     ap;
530     struct i386_devdesc         *dev;
531     struct open_disk            *od;
532     int                         error;
533
534     va_start(ap, f);
535     dev = va_arg(ap, struct i386_devdesc *);
536     va_end(ap);
537     if ((error = bd_opendisk(&od, dev)))
538         return(error);
539     
540     /*
541      * Save our context
542      */
543     ((struct i386_devdesc *)(f->f_devdata))->d_kind.biosdisk.data = od;
544     DEBUG("open_disk %p, partition at 0x%x", od, od->od_boff);
545     return(0);
546 }
547
548 static int
549 bd_opendisk(struct open_disk **odp, struct i386_devdesc *dev)
550 {
551     struct open_disk            *od;
552     int                         error;
553
554     if (dev->d_unit >= nbdinfo) {
555         DEBUG("attempt to open nonexistent disk");
556         return(ENXIO);
557     }
558     
559     od = (struct open_disk *)malloc(sizeof(struct open_disk));
560     if (!od) {
561         DEBUG("no memory");
562         return (ENOMEM);
563     }
564
565     /* Look up BIOS unit number, intialise open_disk structure */
566     od->od_dkunit = dev->d_unit;
567     od->od_unit = bdinfo[od->od_dkunit].bd_unit;
568     od->od_flags = bdinfo[od->od_dkunit].bd_flags;
569     od->od_boff = 0;
570     error = 0;
571     DEBUG("open '%s', unit 0x%x slice %d partition %d",
572              i386_fmtdev(dev), dev->d_unit, 
573              dev->d_kind.biosdisk.slice, dev->d_kind.biosdisk.partition);
574
575     /* Get geometry for this open (removable device may have changed) */
576     if (bd_getgeom(od)) {
577         DEBUG("can't get geometry");
578         error = ENXIO;
579         goto out;
580     }
581
582     /* Determine disk layout. */
583 #ifdef LOADER_GPT_SUPPORT
584     error = bd_open_gpt(od, dev);
585     if (error)
586 #endif
587         error = bd_open_mbr(od, dev);
588     
589  out:
590     if (error) {
591         free(od);
592     } else {
593         *odp = od;      /* return the open disk */
594     }
595     return(error);
596 }
597
598 static int
599 bd_open_mbr(struct open_disk *od, struct i386_devdesc *dev)
600 {
601     struct dos_partition        *dptr;
602     struct disklabel            *lp;
603     int                         sector, slice, i;
604     int                         error;
605     char                        buf[BUFSIZE];
606
607     /*
608      * Following calculations attempt to determine the correct value
609      * for d->od_boff by looking for the slice and partition specified,
610      * or searching for reasonable defaults.
611      */
612
613     /*
614      * Find the slice in the DOS slice table.
615      */
616     od->od_nslices = 0;
617     if (bd_read(od, 0, 1, buf)) {
618         DEBUG("error reading MBR");
619         return (EIO);
620     }
621
622     /* 
623      * Check the slice table magic.
624      */
625     if (((u_char)buf[0x1fe] != 0x55) || ((u_char)buf[0x1ff] != 0xaa)) {
626         /* If a slice number was explicitly supplied, this is an error */
627         if (dev->d_kind.biosdisk.slice > 0) {
628             DEBUG("no slice table/MBR (no magic)");
629             return (ENOENT);
630         }
631         sector = 0;
632         goto unsliced;          /* may be a floppy */
633     }
634
635     /*
636      * copy the partition table, then pick up any extended partitions.
637      */
638     bcopy(buf + DOSPARTOFF, &od->od_slicetab,
639       sizeof(struct dos_partition) * NDOSPART);
640     od->od_nslices = 4;                 /* extended slices start here */
641     for (i = 0; i < NDOSPART; i++)
642         bd_checkextended(od, i);
643     od->od_flags |= BD_PARTTABOK;
644     dptr = &od->od_slicetab[0];
645
646     /* Is this a request for the whole disk? */
647     if (dev->d_kind.biosdisk.slice == -1) {
648         sector = 0;
649         goto unsliced;
650     }
651
652     /*
653      * if a slice number was supplied but not found, this is an error.
654      */
655     if (dev->d_kind.biosdisk.slice > 0) {
656         slice = dev->d_kind.biosdisk.slice - 1;
657         if (slice >= od->od_nslices) {
658             DEBUG("slice %d not found", slice);
659             return (ENOENT);
660         }
661     }
662
663     /*
664      * Check for the historically bogus MBR found on true dedicated disks
665      */
666     if ((dptr[3].dp_typ == DOSPTYP_386BSD) &&
667       (dptr[3].dp_start == 0) &&
668       (dptr[3].dp_size == 50000)) {
669         sector = 0;
670         goto unsliced;
671     }
672
673     /* Try to auto-detect the best slice; this should always give a slice number */
674     if (dev->d_kind.biosdisk.slice == 0) {
675         slice = bd_bestslice(od);
676         if (slice == -1) {
677             return (ENOENT);
678         }
679         dev->d_kind.biosdisk.slice = slice;
680     }
681
682     dptr = &od->od_slicetab[0];
683     /*
684      * Accept the supplied slice number unequivocally (we may be looking
685      * at a DOS partition).
686      */
687     dptr += (dev->d_kind.biosdisk.slice - 1);   /* we number 1-4, offsets are 0-3 */
688     sector = dptr->dp_start;
689     DEBUG("slice entry %d at %d, %d sectors", dev->d_kind.biosdisk.slice - 1, sector, dptr->dp_size);
690
691     /*
692      * If we are looking at a BSD slice, and the partition is < 0, assume the 'a' partition
693      */
694     if ((dptr->dp_typ == DOSPTYP_386BSD) && (dev->d_kind.biosdisk.partition < 0))
695         dev->d_kind.biosdisk.partition = 0;
696
697  unsliced:
698     /* 
699      * Now we have the slice offset, look for the partition in the disklabel if we have
700      * a partition to start with.
701      *
702      * XXX we might want to check the label checksum.
703      */
704     if (dev->d_kind.biosdisk.partition < 0) {
705         od->od_boff = sector;           /* no partition, must be after the slice */
706         DEBUG("opening raw slice");
707     } else {
708         
709         if (bd_read(od, sector + LABELSECTOR, 1, buf)) {
710             DEBUG("error reading disklabel");
711             return (EIO);
712         }
713         DEBUG("copy %d bytes of label from %p to %p", sizeof(struct disklabel), buf + LABELOFFSET, &od->od_disklabel);
714         bcopy(buf + LABELOFFSET, &od->od_disklabel, sizeof(struct disklabel));
715         lp = &od->od_disklabel;
716         od->od_flags |= BD_LABELOK;
717
718         if (lp->d_magic != DISKMAGIC) {
719             DEBUG("no disklabel");
720             return (ENOENT);
721         }
722         if (dev->d_kind.biosdisk.partition >= lp->d_npartitions) {
723             DEBUG("partition '%c' exceeds partitions in table (a-'%c')",
724                   'a' + dev->d_kind.biosdisk.partition, 'a' + lp->d_npartitions);
725             return (EPART);
726         }
727
728 #ifdef DISK_DEBUG
729         /* Complain if the partition is unused unless this is a floppy. */
730         if ((lp->d_partitions[dev->d_kind.biosdisk.partition].p_fstype == FS_UNUSED) &&
731             !(od->od_flags & BD_FLOPPY))
732             DEBUG("warning, partition marked as unused");
733 #endif
734         
735         od->od_boff = 
736                 lp->d_partitions[dev->d_kind.biosdisk.partition].p_offset -
737                 lp->d_partitions[RAW_PART].p_offset +
738                 sector;
739     }
740     return (0);
741 }
742
743 static void
744 bd_checkextended(struct open_disk *od, int slicenum)
745 {
746         char    buf[BIOSDISK_SECSIZE];
747         struct dos_partition *dp;
748         u_int base;
749         int i, start, end;
750
751         dp = &od->od_slicetab[slicenum];
752         start = od->od_nslices;
753
754         if (dp->dp_size == 0)
755                 goto done;
756         if (dp->dp_typ != DOSPTYP_EXT)
757                 goto done;
758         if (bd_read(od, (daddr_t)dp->dp_start, 1, buf))
759                 goto done;
760         if (((u_char)buf[0x1fe] != 0x55) || ((u_char)buf[0x1ff] != 0xaa)) {
761                 DEBUG("no magic in extended table");
762                 goto done;
763         }
764         base = dp->dp_start;
765         dp = (struct dos_partition *)(&buf[DOSPARTOFF]);
766         for (i = 0; i < NDOSPART; i++, dp++) {
767                 if (dp->dp_size == 0)
768                         continue;
769                 if (od->od_nslices == NEXTDOSPART)
770                         goto done;
771                 dp->dp_start += base;
772                 bcopy(dp, &od->od_slicetab[od->od_nslices], sizeof(*dp));
773                 od->od_nslices++;
774         }
775         end = od->od_nslices;
776
777         /*
778          * now, recursively check the slices we just added
779          */
780         for (i = start; i < end; i++)
781                 bd_checkextended(od, i);
782 done:
783         return;
784 }
785
786 /*
787  * Search for a slice with the following preferences:
788  *
789  * 1: Active FreeBSD slice
790  * 2: Non-active FreeBSD slice
791  * 3: Active Linux slice
792  * 4: non-active Linux slice
793  * 5: Active FAT/FAT32 slice
794  * 6: non-active FAT/FAT32 slice
795  */
796 #define PREF_RAWDISK    0
797 #define PREF_FBSD_ACT   1
798 #define PREF_FBSD       2
799 #define PREF_LINUX_ACT  3
800 #define PREF_LINUX      4
801 #define PREF_DOS_ACT    5
802 #define PREF_DOS        6
803 #define PREF_NONE       7
804
805 /*
806  * slicelimit is in the range 0 .. NDOSPART
807  */
808 static int
809 bd_bestslice(struct open_disk *od)
810 {
811         struct dos_partition *dp;
812         int pref, preflevel;
813         int i, prefslice;
814         
815         prefslice = 0;
816         preflevel = PREF_NONE;
817
818         dp = &od->od_slicetab[0];
819         for (i = 0; i < od->od_nslices; i++, dp++) {
820
821                 switch (dp->dp_typ) {
822                 case DOSPTYP_386BSD:            /* FreeBSD */
823                         pref = dp->dp_flag & 0x80 ? PREF_FBSD_ACT : PREF_FBSD;
824                         break;
825
826                 case DOSPTYP_LINUX:
827                         pref = dp->dp_flag & 0x80 ? PREF_LINUX_ACT : PREF_LINUX;
828                         break;
829     
830                 case 0x01:              /* DOS/Windows */
831                 case 0x04:
832                 case 0x06:
833                 case 0x0b:
834                 case 0x0c:
835                 case 0x0e:
836                         pref = dp->dp_flag & 0x80 ? PREF_DOS_ACT : PREF_DOS;
837                         break;
838
839                 default:
840                         pref = PREF_NONE;
841                 }
842                 if (pref < preflevel) {
843                         preflevel = pref;
844                         prefslice = i + 1;
845                 }
846         }
847         return (prefslice);
848 }
849
850 #ifdef LOADER_GPT_SUPPORT
851 static int
852 bd_open_gpt(struct open_disk *od, struct i386_devdesc *dev)
853 {
854     struct dos_partition *dp;
855     struct gpt_hdr *hdr;
856     struct gpt_ent *ent;
857     struct gpt_part *gp;
858     int entries_per_sec, error, i, part;
859     daddr_t lba, elba;
860     char gpt[BIOSDISK_SECSIZE], tbl[BIOSDISK_SECSIZE];
861
862     /*
863      * Following calculations attempt to determine the correct value
864      * for d->od_boff by looking for the slice and partition specified,
865      * or searching for reasonable defaults.
866      */
867     error = 0;
868
869     /* First, read the MBR and see if we have a PMBR. */
870     if (bd_read(od, 0, 1, tbl)) {
871         DEBUG("error reading MBR");
872         return (EIO);
873     }
874
875     /* Check the slice table magic. */
876     if (((u_char)tbl[0x1fe] != 0x55) || ((u_char)tbl[0x1ff] != 0xaa))
877         return (ENXIO);
878
879     /* Check for GPT slice. */
880     part = 0;
881     dp = (struct dos_partition *)(tbl + DOSPARTOFF);
882     for (i = 0; i < NDOSPART; i++) {
883         if (dp[i].dp_typ == 0xee)
884             part++;
885         else if ((part != 1) && (dp[i].dp_typ != 0x00))
886             return (EINVAL);
887     }
888     if (part != 1)
889         return (EINVAL);
890
891     /* Read primary GPT table header. */
892     if (bd_read(od, 1, 1, gpt)) {
893         DEBUG("error reading GPT header");
894         return (EIO);
895     }
896     hdr = (struct gpt_hdr *)gpt;
897     if (bcmp(hdr->hdr_sig, GPT_HDR_SIG, sizeof(hdr->hdr_sig)) != 0 ||
898         hdr->hdr_lba_self != 1 || hdr->hdr_revision < 0x00010000 ||
899         hdr->hdr_entsz < sizeof(*ent) ||
900         BIOSDISK_SECSIZE % hdr->hdr_entsz != 0) {
901         DEBUG("Invalid GPT header\n");
902         return (EINVAL);
903     }
904
905     /* Now walk the partition table to count the number of valid partitions. */
906     part = 0;
907     entries_per_sec = BIOSDISK_SECSIZE / hdr->hdr_entsz;
908     elba = hdr->hdr_lba_table + hdr->hdr_entries / entries_per_sec;
909     for (lba = hdr->hdr_lba_table; lba < elba; lba++) {
910         if (bd_read(od, lba, 1, tbl)) {
911             DEBUG("error reading GPT table");
912             return (EIO);
913         }
914         for (i = 0; i < entries_per_sec; i++) {
915             ent = (struct gpt_ent *)(tbl + i * hdr->hdr_entsz);
916             if (uuid_is_nil(&ent->ent_type, NULL) || ent->ent_lba_start == 0 ||
917                 ent->ent_lba_end < ent->ent_lba_start)
918                 continue;
919             part++;
920         }
921     }
922
923     /* Save the important information about all the valid partitions. */
924     od->od_nparts = part;
925     if (part != 0) {
926         od->od_partitions = malloc(part * sizeof(struct gpt_part));
927         part = 0;       
928         for (lba = hdr->hdr_lba_table; lba < elba; lba++) {
929             if (bd_read(od, lba, 1, tbl)) {
930                 DEBUG("error reading GPT table");
931                 error = EIO;
932                 goto out;
933             }
934             for (i = 0; i < entries_per_sec; i++) {
935                 ent = (struct gpt_ent *)(tbl + i * hdr->hdr_entsz);
936                 if (uuid_is_nil(&ent->ent_type, NULL) ||
937                     ent->ent_lba_start == 0 ||
938                     ent->ent_lba_end < ent->ent_lba_start)
939                     continue;
940                 od->od_partitions[part].gp_index = (lba - hdr->hdr_lba_table) *
941                     entries_per_sec + i + 1;
942                 od->od_partitions[part].gp_type = ent->ent_type;
943                 od->od_partitions[part].gp_start = ent->ent_lba_start;
944                 od->od_partitions[part].gp_end = ent->ent_lba_end;
945                 part++;
946             }
947         }
948     }
949     od->od_flags |= BD_GPTOK;
950
951     /* Is this a request for the whole disk? */
952     if (dev->d_kind.biosdisk.slice < 0) {
953         od->od_boff = 0;
954         return (0);
955     }
956
957     /*
958      * If a partition number was supplied, then the user is trying to use
959      * an MBR address rather than a GPT address, so fail.
960      */
961     if (dev->d_kind.biosdisk.partition != 0xff) {
962         error = ENOENT;
963         goto out;
964     }
965
966     /* If a slice number was supplied but not found, this is an error. */
967     gp = NULL;
968     if (dev->d_kind.biosdisk.slice > 0) {
969         for (i = 0; i < od->od_nparts; i++) {
970             if (od->od_partitions[i].gp_index == dev->d_kind.biosdisk.slice) {
971                 gp = &od->od_partitions[i];
972                 break;
973             }
974         }
975         if (gp == NULL) {
976             DEBUG("partition %d not found", dev->d_kind.biosdisk.slice);
977             error = ENOENT;
978             goto out;
979         }
980     }
981
982     /* Try to auto-detect the best partition. */
983     if (dev->d_kind.biosdisk.slice == 0) {
984         gp = bd_best_gptpart(od);
985         if (gp == NULL) {
986             error = ENOENT;
987             goto out;
988         }
989         dev->d_kind.biosdisk.slice = gp->gp_index;
990     }
991     od->od_boff = gp->gp_start;
992
993 out:
994     if (error) {
995         if (od->od_nparts > 0)
996             free(od->od_partitions);
997         od->od_flags &= ~BD_GPTOK;
998     }
999     return (error);
1000 }
1001
1002 static struct gpt_part *
1003 bd_best_gptpart(struct open_disk *od)
1004 {
1005     struct gpt_part *gp, *prefpart;
1006     int i, pref, preflevel;
1007         
1008     prefpart = NULL;
1009     preflevel = PREF_NONE;
1010
1011     gp = od->od_partitions;
1012     for (i = 0; i < od->od_nparts; i++, gp++) {
1013         /* Windows. XXX: Also Linux. */
1014         if (uuid_equal(&gp->gp_type, &ms_basic_data, NULL))
1015             pref = PREF_DOS;
1016         /* FreeBSD */
1017         else if (uuid_equal(&gp->gp_type, &freebsd_ufs, NULL) ||
1018             uuid_equal(&gp->gp_type, &freebsd_zfs, NULL))
1019             pref = PREF_FBSD;
1020         else
1021             pref = PREF_NONE;
1022         if (pref < preflevel) {
1023             preflevel = pref;
1024             prefpart = gp;
1025         }
1026     }
1027     return (prefpart);
1028 }
1029 #endif
1030
1031 static int 
1032 bd_close(struct open_file *f)
1033 {
1034     struct open_disk    *od = (struct open_disk *)(((struct i386_devdesc *)(f->f_devdata))->d_kind.biosdisk.data);
1035
1036     bd_closedisk(od);
1037     return(0);
1038 }
1039
1040 static void
1041 bd_closedisk(struct open_disk *od)
1042 {
1043     DEBUG("open_disk %p", od);
1044 #if 0
1045     /* XXX is this required? (especially if disk already open...) */
1046     if (od->od_flags & BD_FLOPPY)
1047         delay(3000000);
1048 #endif
1049 #ifdef LOADER_GPT_SUPPORT
1050     if (od->od_flags & BD_GPTOK && od->od_nparts > 0)
1051         free(od->od_partitions);
1052 #endif
1053     free(od);
1054 }
1055
1056 static int 
1057 bd_strategy(void *devdata, int rw, daddr_t dblk, size_t size, char *buf, size_t *rsize)
1058 {
1059     struct bcache_devdata       bcd;
1060     struct open_disk    *od = (struct open_disk *)(((struct i386_devdesc *)devdata)->d_kind.biosdisk.data);
1061
1062     bcd.dv_strategy = bd_realstrategy;
1063     bcd.dv_devdata = devdata;
1064     return(bcache_strategy(&bcd, od->od_unit, rw, dblk+od->od_boff, size, buf, rsize));
1065 }
1066
1067 static int 
1068 bd_realstrategy(void *devdata, int rw, daddr_t dblk, size_t size, char *buf, size_t *rsize)
1069 {
1070     struct open_disk    *od = (struct open_disk *)(((struct i386_devdesc *)devdata)->d_kind.biosdisk.data);
1071     int                 blks;
1072 #ifdef BD_SUPPORT_FRAGS
1073     char                fragbuf[BIOSDISK_SECSIZE];
1074     size_t              fragsize;
1075
1076     fragsize = size % BIOSDISK_SECSIZE;
1077 #else
1078     if (size % BIOSDISK_SECSIZE)
1079         panic("bd_strategy: %d bytes I/O not multiple of block size", size);
1080 #endif
1081
1082     DEBUG("open_disk %p", od);
1083     blks = size / BIOSDISK_SECSIZE;
1084     if (rsize)
1085         *rsize = 0;
1086
1087     switch(rw){
1088     case F_READ:
1089         DEBUG("read %d from %lld to %p", blks, dblk, buf);
1090
1091         if (blks && bd_read(od, dblk, blks, buf)) {
1092             DEBUG("read error");
1093             return (EIO);
1094         }
1095 #ifdef BD_SUPPORT_FRAGS
1096         DEBUG("bd_strategy: frag read %d from %d+%d to %p",
1097             fragsize, dblk, blks, buf + (blks * BIOSDISK_SECSIZE));
1098         if (fragsize && bd_read(od, dblk + blks, 1, fragsize)) {
1099             DEBUG("frag read error");
1100             return(EIO);
1101         }
1102         bcopy(fragbuf, buf + (blks * BIOSDISK_SECSIZE), fragsize);
1103 #endif
1104         break;
1105     case F_WRITE :
1106         DEBUG("write %d from %d to %p", blks, dblk, buf);
1107
1108         if (blks && bd_write(od, dblk, blks, buf)) {
1109             DEBUG("write error");
1110             return (EIO);
1111         }
1112 #ifdef BD_SUPPORT_FRAGS
1113         if(fragsize) {
1114             DEBUG("Attempted to write a frag");
1115             return (EIO);
1116         }
1117 #endif
1118         break;
1119     default:
1120         /* DO NOTHING */
1121         return (EROFS);
1122     }
1123
1124     if (rsize)
1125         *rsize = size;
1126     return (0);
1127 }
1128
1129 /* Max number of sectors to bounce-buffer if the request crosses a 64k boundary */
1130 #define FLOPPY_BOUNCEBUF        18
1131
1132 static int
1133 bd_edd_io(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest, int write)
1134 {
1135     static struct edd_packet packet;
1136
1137     packet.len = 0x10;
1138     packet.count = blks;
1139     packet.offset = VTOPOFF(dest);
1140     packet.seg = VTOPSEG(dest);
1141     packet.lba = dblk;
1142     v86.ctl = V86_FLAGS;
1143     v86.addr = 0x13;
1144     if (write)
1145         /* Should we Write with verify ?? 0x4302 ? */
1146         v86.eax = 0x4300;
1147     else
1148         v86.eax = 0x4200;
1149     v86.edx = od->od_unit;
1150     v86.ds = VTOPSEG(&packet);
1151     v86.esi = VTOPOFF(&packet);
1152     v86int();
1153     return (v86.efl & 0x1);
1154 }
1155
1156 static int
1157 bd_chs_io(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest, int write)
1158 {
1159     u_int       x, bpc, cyl, hd, sec;
1160
1161     bpc = (od->od_sec * od->od_hds);    /* blocks per cylinder */
1162     x = dblk;
1163     cyl = x / bpc;                      /* block # / blocks per cylinder */
1164     x %= bpc;                           /* block offset into cylinder */
1165     hd = x / od->od_sec;                /* offset / blocks per track */
1166     sec = x % od->od_sec;               /* offset into track */
1167
1168     /* correct sector number for 1-based BIOS numbering */
1169     sec++;
1170
1171     if (cyl > 1023)
1172         /* CHS doesn't support cylinders > 1023. */
1173         return (1);
1174
1175     v86.ctl = V86_FLAGS;
1176     v86.addr = 0x13;
1177     if (write)
1178         v86.eax = 0x300 | blks;
1179     else
1180         v86.eax = 0x200 | blks;
1181     v86.ecx = ((cyl & 0xff) << 8) | ((cyl & 0x300) >> 2) | sec;
1182     v86.edx = (hd << 8) | od->od_unit;
1183     v86.es = VTOPSEG(dest);
1184     v86.ebx = VTOPOFF(dest);
1185     v86int();
1186     return (v86.efl & 0x1);
1187 }
1188
1189 static int
1190 bd_io(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest, int write)
1191 {
1192     u_int       x, sec, result, resid, retry, maxfer;
1193     caddr_t     p, xp, bbuf, breg;
1194     
1195     /* Just in case some idiot actually tries to read/write -1 blocks... */
1196     if (blks < 0)
1197         return (-1);
1198
1199     resid = blks;
1200     p = dest;
1201
1202     /* Decide whether we have to bounce */
1203     if (VTOP(dest) >> 20 != 0 || ((od->od_unit < 0x80) && 
1204         ((VTOP(dest) >> 16) != (VTOP(dest + blks * BIOSDISK_SECSIZE) >> 16)))) {
1205
1206         /* 
1207          * There is a 64k physical boundary somewhere in the
1208          * destination buffer, or the destination buffer is above
1209          * first 1MB of physical memory so we have to arrange a
1210          * suitable bounce buffer.  Allocate a buffer twice as large
1211          * as we need to.  Use the bottom half unless there is a break
1212          * there, in which case we use the top half.
1213          */
1214         x = min(FLOPPY_BOUNCEBUF, (unsigned)blks);
1215         bbuf = alloca(x * 2 * BIOSDISK_SECSIZE);
1216         if (((u_int32_t)VTOP(bbuf) & 0xffff0000) ==
1217             ((u_int32_t)VTOP(bbuf + x * BIOSDISK_SECSIZE) & 0xffff0000)) {
1218             breg = bbuf;
1219         } else {
1220             breg = bbuf + x * BIOSDISK_SECSIZE;
1221         }
1222         maxfer = x;             /* limit transfers to bounce region size */
1223     } else {
1224         breg = bbuf = NULL;
1225         maxfer = 0;
1226     }
1227     
1228     while (resid > 0) {
1229         /*
1230          * Play it safe and don't cross track boundaries.
1231          * (XXX this is probably unnecessary)
1232          */
1233         sec = dblk % od->od_sec;        /* offset into track */
1234         x = min(od->od_sec - sec, resid);
1235         if (maxfer > 0)
1236             x = min(x, maxfer);         /* fit bounce buffer */
1237
1238         /* where do we transfer to? */
1239         xp = bbuf == NULL ? p : breg;
1240
1241         /*
1242          * Put your Data In, Put your Data out,
1243          * Put your Data In, and shake it all about 
1244          */
1245         if (write && bbuf != NULL)
1246             bcopy(p, breg, x * BIOSDISK_SECSIZE);
1247
1248         /*
1249          * Loop retrying the operation a couple of times.  The BIOS
1250          * may also retry.
1251          */
1252         for (retry = 0; retry < 3; retry++) {
1253             /* if retrying, reset the drive */
1254             if (retry > 0) {
1255                 v86.ctl = V86_FLAGS;
1256                 v86.addr = 0x13;
1257                 v86.eax = 0;
1258                 v86.edx = od->od_unit;
1259                 v86int();
1260             }
1261
1262             if (od->od_flags & BD_MODEEDD1)
1263                 result = bd_edd_io(od, dblk, x, xp, write);
1264             else
1265                 result = bd_chs_io(od, dblk, x, xp, write);
1266             if (result == 0)
1267                 break;
1268         }
1269
1270         if (write)
1271             DEBUG("Write %d sector(s) from %p (0x%x) to %lld %s", x,
1272                 p, VTOP(p), dblk, result ? "failed" : "ok");
1273         else
1274             DEBUG("Read %d sector(s) from %lld to %p (0x%x) %s", x,
1275                 dblk, p, VTOP(p), result ? "failed" : "ok");
1276         if (result) {
1277             return(-1);
1278         }
1279         if (!write && bbuf != NULL)
1280             bcopy(breg, p, x * BIOSDISK_SECSIZE);
1281         p += (x * BIOSDISK_SECSIZE);
1282         dblk += x;
1283         resid -= x;
1284     }
1285
1286 /*    hexdump(dest, (blks * BIOSDISK_SECSIZE)); */
1287     return(0);
1288 }
1289
1290 static int
1291 bd_read(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest)
1292 {
1293
1294     return (bd_io(od, dblk, blks, dest, 0));
1295 }
1296
1297 static int
1298 bd_write(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest)
1299 {
1300
1301     return (bd_io(od, dblk, blks, dest, 1));
1302 }
1303
1304 static int
1305 bd_getgeom(struct open_disk *od)
1306 {
1307
1308     v86.ctl = V86_FLAGS;
1309     v86.addr = 0x13;
1310     v86.eax = 0x800;
1311     v86.edx = od->od_unit;
1312     v86int();
1313
1314     if ((v86.efl & 0x1) ||                              /* carry set */
1315         ((v86.edx & 0xff) <= (unsigned)(od->od_unit & 0x7f)))   /* unit # bad */
1316         return(1);
1317     
1318     /* convert max cyl # -> # of cylinders */
1319     od->od_cyl = ((v86.ecx & 0xc0) << 2) + ((v86.ecx & 0xff00) >> 8) + 1;
1320     /* convert max head # -> # of heads */
1321     od->od_hds = ((v86.edx & 0xff00) >> 8) + 1;
1322     od->od_sec = v86.ecx & 0x3f;
1323
1324     DEBUG("unit 0x%x geometry %d/%d/%d", od->od_unit, od->od_cyl, od->od_hds, od->od_sec);
1325     return(0);
1326 }
1327
1328 /*
1329  * Return the BIOS geometry of a given "fixed drive" in a format
1330  * suitable for the legacy bootinfo structure.  Since the kernel is
1331  * expecting raw int 0x13/0x8 values for N_BIOS_GEOM drives, we
1332  * prefer to get the information directly, rather than rely on being
1333  * able to put it together from information already maintained for
1334  * different purposes and for a probably different number of drives.
1335  *
1336  * For valid drives, the geometry is expected in the format (31..0)
1337  * "000000cc cccccccc hhhhhhhh 00ssssss"; and invalid drives are
1338  * indicated by returning the geometry of a "1.2M" PC-format floppy
1339  * disk.  And, incidentally, what is returned is not the geometry as
1340  * such but the highest valid cylinder, head, and sector numbers.
1341  */
1342 u_int32_t
1343 bd_getbigeom(int bunit)
1344 {
1345
1346     v86.ctl = V86_FLAGS;
1347     v86.addr = 0x13;
1348     v86.eax = 0x800;
1349     v86.edx = 0x80 + bunit;
1350     v86int();
1351     if (v86.efl & 0x1)
1352         return 0x4f010f;
1353     return ((v86.ecx & 0xc0) << 18) | ((v86.ecx & 0xff00) << 8) |
1354            (v86.edx & 0xff00) | (v86.ecx & 0x3f);
1355 }
1356
1357 /*
1358  * Return a suitable dev_t value for (dev).
1359  *
1360  * In the case where it looks like (dev) is a SCSI disk, we allow the number of
1361  * IDE disks to be specified in $num_ide_disks.  There should be a Better Way.
1362  */
1363 int
1364 bd_getdev(struct i386_devdesc *dev)
1365 {
1366     struct open_disk            *od;
1367     int                         biosdev;
1368     int                         major;
1369     int                         rootdev;
1370     char                        *nip, *cp;
1371     int                         unitofs = 0, i, unit;
1372
1373     biosdev = bd_unit2bios(dev->d_unit);
1374     DEBUG("unit %d BIOS device %d", dev->d_unit, biosdev);
1375     if (biosdev == -1)                          /* not a BIOS device */
1376         return(-1);
1377     if (bd_opendisk(&od, dev) != 0)             /* oops, not a viable device */
1378         return(-1);
1379
1380     if (biosdev < 0x80) {
1381         /* floppy (or emulated floppy) or ATAPI device */
1382         if (bdinfo[dev->d_unit].bd_type == DT_ATAPI) {
1383             /* is an ATAPI disk */
1384             major = WFDMAJOR;
1385         } else {
1386             /* is a floppy disk */
1387             major = FDMAJOR;
1388         }
1389     } else {
1390         /* harddisk */
1391         if ((od->od_flags & BD_LABELOK) && (od->od_disklabel.d_type == DTYPE_SCSI)) {
1392             /* label OK, disk labelled as SCSI */
1393             major = DAMAJOR;
1394             /* check for unit number correction hint, now deprecated */
1395             if ((nip = getenv("num_ide_disks")) != NULL) {
1396                 i = strtol(nip, &cp, 0);
1397                 /* check for parse error */
1398                 if ((cp != nip) && (*cp == 0))
1399                     unitofs = i;
1400             }
1401         } else {
1402             /* assume an IDE disk */
1403             major = WDMAJOR;
1404         }
1405     }
1406     /* default root disk unit number */
1407     unit = (biosdev & 0x7f) - unitofs;
1408
1409     /* XXX a better kludge to set the root disk unit number */
1410     if ((nip = getenv("root_disk_unit")) != NULL) {
1411         i = strtol(nip, &cp, 0);
1412         /* check for parse error */
1413         if ((cp != nip) && (*cp == 0))
1414             unit = i;
1415     }
1416
1417     rootdev = MAKEBOOTDEV(major, dev->d_kind.biosdisk.slice + 1, unit,
1418         dev->d_kind.biosdisk.partition);
1419     DEBUG("dev is 0x%x\n", rootdev);
1420     return(rootdev);
1421 }