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