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