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