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