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