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