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