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