Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / sys / boot / pc32 / libi386 / biosdisk.c
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/boot/i386/libi386/biosdisk.c,v 1.26.2.6 2000/12/28 13:10:47 ps Exp $
27  * $DragonFly: src/sys/boot/pc32/libi386/biosdisk.c,v 1.2 2003/06/17 04:28:18 dillon Exp $
28  */
29
30 /*
31  * BIOS disk device handling.
32  * 
33  * Ideas and algorithms from:
34  *
35  * - NetBSD libi386/biosdisk.c
36  * - FreeBSD biosboot/disk.c
37  *
38  */
39
40 #include <stand.h>
41
42 #include <sys/disklabel.h>
43 #include <sys/diskslice.h>
44 #include <sys/reboot.h>
45
46 #include <stdarg.h>
47
48 #include <bootstrap.h>
49 #include <btxv86.h>
50 #include "libi386.h"
51
52 #define BIOS_NUMDRIVES          0x475
53 #define BIOSDISK_SECSIZE        512
54 #define BUFSIZE                 (1 * BIOSDISK_SECSIZE)
55 #define MAXBDDEV                MAXDEV
56
57 #define DT_ATAPI                0x10            /* disk type for ATAPI floppies */
58 #define WDMAJOR                 0               /* major numbers for devices we frontend for */
59 #define WFDMAJOR                1
60 #define FDMAJOR                 2
61 #define DAMAJOR                 4
62
63 #ifdef DISK_DEBUG
64 # define DEBUG(fmt, args...)    printf("%s: " fmt "\n" , __FUNCTION__ , ## args)
65 #else
66 # define DEBUG(fmt, args...)
67 #endif
68
69 struct open_disk {
70     int                 od_dkunit;              /* disk unit number */
71     int                 od_unit;                /* BIOS unit number */
72     int                 od_cyl;                 /* BIOS geometry */
73     int                 od_hds;
74     int                 od_sec;
75     int                 od_boff;                /* block offset from beginning of BIOS disk */
76     int                 od_flags;
77 #define BD_MODEINT13            0x0000
78 #define BD_MODEEDD1             0x0001
79 #define BD_MODEEDD3             0x0002
80 #define BD_MODEMASK             0x0003
81 #define BD_FLOPPY               0x0004
82 #define BD_LABELOK              0x0008
83 #define BD_PARTTABOK            0x0010
84     struct disklabel            od_disklabel;
85     int                         od_nslices;     /* slice count */
86     struct dos_partition        od_slicetab[MAX_SLICES];
87 };
88
89 /*
90  * List of BIOS devices, translation from disk unit number to
91  * BIOS unit number.
92  */
93 static struct bdinfo
94 {
95     int         bd_unit;                /* BIOS unit number */
96     int         bd_flags;
97     int         bd_type;                /* BIOS 'drive type' (floppy only) */
98 } bdinfo [MAXBDDEV];
99 static int nbdinfo = 0;
100
101 static int      bd_getgeom(struct open_disk *od);
102 static int      bd_read(struct open_disk *od, daddr_t dblk, int blks,
103                     caddr_t dest);
104
105 static int      bd_int13probe(struct bdinfo *bd);
106
107 static void     bd_printslice(struct open_disk *od, struct dos_partition *dp,
108                     char *prefix, int verbose);
109 static void     bd_printbsdslice(struct open_disk *od, daddr_t offset,
110                     char *prefix, int verbose);
111
112 static int      bd_init(void);
113 static int      bd_strategy(void *devdata, int flag, daddr_t dblk,
114                     size_t size, char *buf, size_t *rsize);
115 static int      bd_realstrategy(void *devdata, int flag, daddr_t dblk,
116                     size_t size, char *buf, size_t *rsize);
117 static int      bd_open(struct open_file *f, ...);
118 static int      bd_close(struct open_file *f);
119 static void     bd_print(int verbose);
120
121 struct devsw biosdisk = {
122     "disk", 
123     DEVT_DISK, 
124     bd_init,
125     bd_strategy, 
126     bd_open, 
127     bd_close, 
128     noioctl,
129     bd_print,
130     NULL
131 };
132
133 static int      bd_opendisk(struct open_disk **odp, struct i386_devdesc *dev);
134 static void     bd_closedisk(struct open_disk *od);
135 static int      bd_bestslice(struct open_disk *od);
136 static void     bd_checkextended(struct open_disk *od, int slicenum);
137
138 /*
139  * Translate between BIOS device numbers and our private unit numbers.
140  */
141 int
142 bd_bios2unit(int biosdev)
143 {
144     int         i;
145     
146     DEBUG("looking for bios device 0x%x", biosdev);
147     for (i = 0; i < nbdinfo; i++) {
148         DEBUG("bd unit %d is BIOS device 0x%x", i, bdinfo[i].bd_unit);
149         if (bdinfo[i].bd_unit == biosdev)
150             return(i);
151     }
152     return(-1);
153 }
154
155 int
156 bd_unit2bios(int unit)
157 {
158     if ((unit >= 0) && (unit < nbdinfo))
159         return(bdinfo[unit].bd_unit);
160     return(-1);
161 }
162
163 /*    
164  * Quiz the BIOS for disk devices, save a little info about them.
165  */
166 static int
167 bd_init(void) 
168 {
169     int         base, unit, nfd = 0;
170
171     /* sequence 0, 0x80 */
172     for (base = 0; base <= 0x80; base += 0x80) {
173         for (unit = base; (nbdinfo < MAXBDDEV); unit++) {
174             /* check the BIOS equipment list for number of fixed disks */
175             if((base == 0x80) &&
176                (nfd >= *(unsigned char *)PTOV(BIOS_NUMDRIVES)))
177                 break;
178
179             bdinfo[nbdinfo].bd_unit = unit;
180             bdinfo[nbdinfo].bd_flags = (unit < 0x80) ? BD_FLOPPY : 0;
181
182             if (!bd_int13probe(&bdinfo[nbdinfo]))
183                 break;
184
185             /* XXX we need "disk aliases" to make this simpler */
186             printf("BIOS drive %c: is disk%d\n", 
187                    (unit < 0x80) ? ('A' + unit) : ('C' + unit - 0x80), nbdinfo);
188             nbdinfo++;
189             if (base == 0x80)
190                 nfd++;
191         }
192     }
193     return(0);
194 }
195
196 /*
197  * Try to detect a device supported by the legacy int13 BIOS
198  */
199 static int
200 bd_int13probe(struct bdinfo *bd)
201 {
202     v86.ctl = V86_FLAGS;
203     v86.addr = 0x13;
204     v86.eax = 0x800;
205     v86.edx = bd->bd_unit;
206     v86int();
207     
208     if (!(v86.efl & 0x1) &&                             /* carry clear */
209         ((v86.edx & 0xff) > ((unsigned)bd->bd_unit & 0x7f))) {  /* unit # OK */
210         bd->bd_flags |= BD_MODEINT13;
211         bd->bd_type = v86.ebx & 0xff;
212
213         /* Determine if we can use EDD with this device. */
214         v86.eax = 0x4100;
215         v86.edx = bd->bd_unit;
216         v86.ebx = 0x55aa;
217         v86int();
218         if (!(v86.efl & 0x1) &&                         /* carry clear */
219             ((v86.ebx & 0xffff) == 0xaa55) &&           /* signature */
220             (v86.ecx & 0x1)) {                          /* packets mode ok */
221             bd->bd_flags |= BD_MODEEDD1;
222             if((v86.eax & 0xff00) > 0x300)
223                 bd->bd_flags |= BD_MODEEDD3;
224         }
225         return(1);
226     }
227     return(0);
228 }
229
230 /*
231  * Print information about disks
232  */
233 static void
234 bd_print(int verbose)
235 {
236     int                         i, j;
237     char                        line[80];
238     struct i386_devdesc         dev;
239     struct open_disk            *od;
240     struct dos_partition        *dptr;
241     
242     for (i = 0; i < nbdinfo; i++) {
243         sprintf(line, "    disk%d:   BIOS drive %c:\n", i, 
244                 (bdinfo[i].bd_unit < 0x80) ? ('A' + bdinfo[i].bd_unit) : ('C' + bdinfo[i].bd_unit - 0x80));
245         pager_output(line);
246
247         /* try to open the whole disk */
248         dev.d_kind.biosdisk.unit = i;
249         dev.d_kind.biosdisk.slice = -1;
250         dev.d_kind.biosdisk.partition = -1;
251         
252         if (!bd_opendisk(&od, &dev)) {
253
254             /* Do we have a partition table? */
255             if (od->od_flags & BD_PARTTABOK) {
256                 dptr = &od->od_slicetab[0];
257
258                 /* Check for a "dedicated" disk */
259                 if ((dptr[3].dp_typ == DOSPTYP_386BSD) &&
260                     (dptr[3].dp_start == 0) &&
261                     (dptr[3].dp_size == 50000)) {
262                     sprintf(line, "      disk%d", i);
263                     bd_printbsdslice(od, 0, line, verbose);
264                 } else {
265                     for (j = 0; j < od->od_nslices; j++) {
266                         sprintf(line, "      disk%ds%d", i, j + 1);
267                         bd_printslice(od, &dptr[j], line, verbose);
268                     }
269                 }
270             }
271             bd_closedisk(od);
272         }
273     }
274 }
275
276 /*
277  * Print information about slices on a disk.  For the size calculations we
278  * assume a 512 byte sector.
279  */
280 static void
281 bd_printslice(struct open_disk *od, struct dos_partition *dp, char *prefix,
282         int verbose)
283 {
284         char line[80];
285
286         switch (dp->dp_typ) {
287         case DOSPTYP_386BSD:
288                 bd_printbsdslice(od, (daddr_t)dp->dp_start, prefix, verbose);
289                 return;
290         case DOSPTYP_LINSWP:
291                 if (verbose)
292                         sprintf(line, "%s: Linux swap %.6dMB (%d - %d)\n",
293                             prefix, dp->dp_size / 2048,
294                             dp->dp_start, dp->dp_start + dp->dp_size);
295                 else
296                         sprintf(line, "%s: Linux swap\n", prefix);
297                 break;
298         case DOSPTYP_LINUX:
299                 /*
300                  * XXX
301                  * read the superblock to confirm this is an ext2fs partition?
302                  */
303                 if (verbose)
304                         sprintf(line, "%s: ext2fs  %.6dMB (%d - %d)\n", prefix,
305                             dp->dp_size / 2048, dp->dp_start,
306                             dp->dp_start + dp->dp_size);
307                 else
308                         sprintf(line, "%s: ext2fs\n", prefix);
309                 break;
310         case 0x00:                              /* unused partition */
311         case DOSPTYP_EXT:
312                 return;
313         case 0x01:
314                 if (verbose)
315                         sprintf(line, "%s: FAT-12  %.6dMB (%d - %d)\n", prefix,
316                             dp->dp_size / 2048, dp->dp_start,
317                             dp->dp_start + dp->dp_size);
318                 else
319                         sprintf(line, "%s: FAT-12\n", prefix);
320                 break;
321         case 0x04:
322         case 0x06:
323         case 0x0e:
324                 if (verbose)
325                         sprintf(line, "%s: FAT-16  %.6dMB (%d - %d)\n", prefix,
326                             dp->dp_size / 2048, dp->dp_start,
327                             dp->dp_start + dp->dp_size);
328                 else
329                         sprintf(line, "%s: FAT-16\n", prefix);
330                 break;
331         case 0x0b:
332         case 0x0c:
333                 if (verbose)
334                         sprintf(line, "%s: FAT-32  %.6dMB (%d - %d)\n", prefix,
335                             dp->dp_size / 2048, dp->dp_start,
336                             dp->dp_start + dp->dp_size);
337                 else
338                         sprintf(line, "%s: FAT-32\n", prefix);
339                 break;
340         default:
341                 if (verbose)
342                         sprintf(line, "%s: Unknown fs: 0x%x  %.6dMB (%d - %d)\n",
343                             prefix, dp->dp_typ, dp->dp_size / 2048,
344                             dp->dp_start, dp->dp_start + dp->dp_size);
345                 else
346                         sprintf(line, "%s: Unknown fs: 0x%x\n", prefix,
347                             dp->dp_typ);
348         }
349         pager_output(line);
350 }
351
352 /*
353  * Print out each valid partition in the disklabel of a FreeBSD slice.
354  * For size calculations, we assume a 512 byte sector size.
355  */
356 static void
357 bd_printbsdslice(struct open_disk *od, daddr_t offset, char *prefix,
358     int verbose)
359 {
360     char                line[80];
361     char                buf[BIOSDISK_SECSIZE];
362     struct disklabel    *lp;
363     int                 i;
364
365     /* read disklabel */
366     if (bd_read(od, offset + LABELSECTOR, 1, buf))
367         return;
368     lp =(struct disklabel *)(&buf[0]);
369     if (lp->d_magic != DISKMAGIC) {
370         sprintf(line, "%s: FFS  bad disklabel\n", prefix);
371         pager_output(line);
372         return;
373     }
374     
375     /* Print partitions */
376     for (i = 0; i < lp->d_npartitions; i++) {
377         /*
378          * For each partition, make sure we know what type of fs it is.  If
379          * not, then skip it.  However, since floppies often have bogus
380          * fstypes, print the 'a' partition on a floppy even if it is marked
381          * unused.
382          */
383         if ((lp->d_partitions[i].p_fstype == FS_BSDFFS) ||
384             (lp->d_partitions[i].p_fstype == FS_SWAP) ||
385             (lp->d_partitions[i].p_fstype == FS_VINUM) ||
386             ((lp->d_partitions[i].p_fstype == FS_UNUSED) && 
387              (od->od_flags & BD_FLOPPY) && (i == 0))) {
388
389             /* Only print out statistics in verbose mode */
390             if (verbose)
391                 sprintf(line, "  %s%c: %s  %.6dMB (%d - %d)\n", prefix, 'a' + i,
392                     (lp->d_partitions[i].p_fstype == FS_SWAP) ? "swap" : 
393                     (lp->d_partitions[i].p_fstype == FS_VINUM) ? "vinum" :
394                     "FFS",
395                     lp->d_partitions[i].p_size / 2048,
396                     lp->d_partitions[i].p_offset,
397                     lp->d_partitions[i].p_offset + lp->d_partitions[i].p_size);
398             else
399                 sprintf(line, "  %s%c: %s\n", prefix, 'a' + i,
400                     (lp->d_partitions[i].p_fstype == FS_SWAP) ? "swap" : 
401                     (lp->d_partitions[i].p_fstype == FS_VINUM) ? "vinum" :
402                     "FFS");
403             pager_output(line);
404         }
405     }
406 }
407
408
409 /*
410  * Attempt to open the disk described by (dev) for use by (f).
411  *
412  * Note that the philosophy here is "give them exactly what
413  * they ask for".  This is necessary because being too "smart"
414  * about what the user might want leads to complications.
415  * (eg. given no slice or partition value, with a disk that is
416  *  sliced - are they after the first BSD slice, or the DOS
417  *  slice before it?)
418  */
419 static int 
420 bd_open(struct open_file *f, ...)
421 {
422     va_list                     ap;
423     struct i386_devdesc         *dev;
424     struct open_disk            *od;
425     int                         error;
426
427     va_start(ap, f);
428     dev = va_arg(ap, struct i386_devdesc *);
429     va_end(ap);
430     if ((error = bd_opendisk(&od, dev)))
431         return(error);
432     
433     /*
434      * Save our context
435      */
436     ((struct i386_devdesc *)(f->f_devdata))->d_kind.biosdisk.data = od;
437     DEBUG("open_disk %p, partition at 0x%x", od, od->od_boff);
438     return(0);
439 }
440
441 static int
442 bd_opendisk(struct open_disk **odp, struct i386_devdesc *dev)
443 {
444     struct dos_partition        *dptr;
445     struct disklabel            *lp;
446     struct open_disk            *od;
447     int                         sector, slice, i;
448     int                         error;
449     char                        buf[BUFSIZE];
450
451     if (dev->d_kind.biosdisk.unit >= nbdinfo) {
452         DEBUG("attempt to open nonexistent disk");
453         return(ENXIO);
454     }
455     
456     od = (struct open_disk *)malloc(sizeof(struct open_disk));
457     if (!od) {
458         DEBUG("no memory");
459         return (ENOMEM);
460     }
461
462     /* Look up BIOS unit number, intialise open_disk structure */
463     od->od_dkunit = dev->d_kind.biosdisk.unit;
464     od->od_unit = bdinfo[od->od_dkunit].bd_unit;
465     od->od_flags = bdinfo[od->od_dkunit].bd_flags;
466     od->od_boff = 0;
467     od->od_nslices = 0;
468     error = 0;
469     DEBUG("open '%s', unit 0x%x slice %d partition %c",
470              i386_fmtdev(dev), dev->d_kind.biosdisk.unit, 
471              dev->d_kind.biosdisk.slice, dev->d_kind.biosdisk.partition + 'a');
472
473     /* Get geometry for this open (removable device may have changed) */
474     if (bd_getgeom(od)) {
475         DEBUG("can't get geometry");
476         error = ENXIO;
477         goto out;
478     }
479
480     /*
481      * Following calculations attempt to determine the correct value
482      * for d->od_boff by looking for the slice and partition specified,
483      * or searching for reasonable defaults.
484      */
485
486     /*
487      * Find the slice in the DOS slice table.
488      */
489     if (bd_read(od, 0, 1, buf)) {
490         DEBUG("error reading MBR");
491         error = EIO;
492         goto out;
493     }
494
495     /* 
496      * Check the slice table magic.
497      */
498     if (((u_char)buf[0x1fe] != 0x55) || ((u_char)buf[0x1ff] != 0xaa)) {
499         /* If a slice number was explicitly supplied, this is an error */
500         if (dev->d_kind.biosdisk.slice > 0) {
501             DEBUG("no slice table/MBR (no magic)");
502             error = ENOENT;
503             goto out;
504         }
505         sector = 0;
506         goto unsliced;          /* may be a floppy */
507     }
508
509     /*
510      * copy the partition table, then pick up any extended partitions.
511      */
512     bcopy(buf + DOSPARTOFF, &od->od_slicetab,
513       sizeof(struct dos_partition) * NDOSPART);
514     od->od_nslices = 4;                 /* extended slices start here */
515     for (i = 0; i < NDOSPART; i++)
516         bd_checkextended(od, i);
517     od->od_flags |= BD_PARTTABOK;
518     dptr = &od->od_slicetab[0];
519
520     /* Is this a request for the whole disk? */
521     if (dev->d_kind.biosdisk.slice == -1) {
522         sector = 0;
523         goto unsliced;
524     }
525
526     /*
527      * if a slice number was supplied but not found, this is an error.
528      */
529     if (dev->d_kind.biosdisk.slice > 0) {
530         slice = dev->d_kind.biosdisk.slice - 1;
531         if (slice >= od->od_nslices) {
532             DEBUG("slice %d not found", slice);
533             error = ENOENT;
534             goto out;
535         }
536     }
537
538     /*
539      * Check for the historically bogus MBR found on true dedicated disks
540      */
541     if ((dptr[3].dp_typ == DOSPTYP_386BSD) &&
542       (dptr[3].dp_start == 0) &&
543       (dptr[3].dp_size == 50000)) {
544         sector = 0;
545         goto unsliced;
546     }
547
548     /* Try to auto-detect the best slice; this should always give a slice number */
549     if (dev->d_kind.biosdisk.slice == 0) {
550         slice = bd_bestslice(od);
551         if (slice == -1) {
552             error = ENOENT;
553             goto out;
554         }
555         dev->d_kind.biosdisk.slice = slice;
556     }
557
558     dptr = &od->od_slicetab[0];
559     /*
560      * Accept the supplied slice number unequivocally (we may be looking
561      * at a DOS partition).
562      */
563     dptr += (dev->d_kind.biosdisk.slice - 1);   /* we number 1-4, offsets are 0-3 */
564     sector = dptr->dp_start;
565     DEBUG("slice entry %d at %d, %d sectors", dev->d_kind.biosdisk.slice - 1, sector, dptr->dp_size);
566
567     /*
568      * If we are looking at a BSD slice, and the partition is < 0, assume the 'a' partition
569      */
570     if ((dptr->dp_typ == DOSPTYP_386BSD) && (dev->d_kind.biosdisk.partition < 0))
571         dev->d_kind.biosdisk.partition = 0;
572
573  unsliced:
574     /* 
575      * Now we have the slice offset, look for the partition in the disklabel if we have
576      * a partition to start with.
577      *
578      * XXX we might want to check the label checksum.
579      */
580     if (dev->d_kind.biosdisk.partition < 0) {
581         od->od_boff = sector;           /* no partition, must be after the slice */
582         DEBUG("opening raw slice");
583     } else {
584         
585         if (bd_read(od, sector + LABELSECTOR, 1, buf)) {
586             DEBUG("error reading disklabel");
587             error = EIO;
588             goto out;
589         }
590         DEBUG("copy %d bytes of label from %p to %p", sizeof(struct disklabel), buf + LABELOFFSET, &od->od_disklabel);
591         bcopy(buf + LABELOFFSET, &od->od_disklabel, sizeof(struct disklabel));
592         lp = &od->od_disklabel;
593         od->od_flags |= BD_LABELOK;
594
595         if (lp->d_magic != DISKMAGIC) {
596             DEBUG("no disklabel");
597             error = ENOENT;
598             goto out;
599         }
600         if (dev->d_kind.biosdisk.partition >= lp->d_npartitions) {
601             DEBUG("partition '%c' exceeds partitions in table (a-'%c')",
602                   'a' + dev->d_kind.biosdisk.partition, 'a' + lp->d_npartitions);
603             error = EPART;
604             goto out;
605
606         }
607
608 #ifdef DISK_DEBUG
609         /* Complain if the partition is unused unless this is a floppy. */
610         if ((lp->d_partitions[dev->d_kind.biosdisk.partition].p_fstype == FS_UNUSED) &&
611             !(od->od_flags & BD_FLOPPY))
612             DEBUG("warning, partition marked as unused");
613 #endif
614         
615         od->od_boff = lp->d_partitions[dev->d_kind.biosdisk.partition].p_offset;
616     }
617     
618  out:
619     if (error) {
620         free(od);
621     } else {
622         *odp = od;      /* return the open disk */
623     }
624     return(error);
625 }
626
627 static void
628 bd_checkextended(struct open_disk *od, int slicenum)
629 {
630         char    buf[BIOSDISK_SECSIZE];
631         struct dos_partition *dp;
632         u_int base;
633         int i, start, end;
634
635         dp = &od->od_slicetab[slicenum];
636         start = od->od_nslices;
637
638         if (dp->dp_size == 0)
639                 goto done;
640         if (dp->dp_typ != DOSPTYP_EXT)
641                 goto done;
642         if (bd_read(od, (daddr_t)dp->dp_start, 1, buf))
643                 goto done;
644         if (((u_char)buf[0x1fe] != 0x55) || ((u_char)buf[0x1ff] != 0xaa)) {
645                 DEBUG("no magic in extended table");
646                 goto done;
647         }
648         base = dp->dp_start;
649         dp = (struct dos_partition *)(&buf[DOSPARTOFF]);
650         for (i = 0; i < NDOSPART; i++, dp++) {
651                 if (dp->dp_size == 0)
652                         continue;
653                 if (od->od_nslices == MAX_SLICES)
654                         goto done;
655                 dp->dp_start += base;
656                 bcopy(dp, &od->od_slicetab[od->od_nslices], sizeof(*dp));
657                 od->od_nslices++;
658         }
659         end = od->od_nslices;
660
661         /*
662          * now, recursively check the slices we just added
663          */
664         for (i = start; i < end; i++)
665                 bd_checkextended(od, i);
666 done:
667         return;
668 }
669
670 /*
671  * Search for a slice with the following preferences:
672  *
673  * 1: Active FreeBSD slice
674  * 2: Non-active FreeBSD slice
675  * 3: Active Linux slice
676  * 4: non-active Linux slice
677  * 5: Active FAT/FAT32 slice
678  * 6: non-active FAT/FAT32 slice
679  */
680 #define PREF_RAWDISK    0
681 #define PREF_FBSD_ACT   1
682 #define PREF_FBSD       2
683 #define PREF_LINUX_ACT  3
684 #define PREF_LINUX      4
685 #define PREF_DOS_ACT    5
686 #define PREF_DOS        6
687 #define PREF_NONE       7
688
689 /*
690  * slicelimit is in the range 0 .. NDOSPART
691  */
692 static int
693 bd_bestslice(struct open_disk *od)
694 {
695         struct dos_partition *dp;
696         int pref, preflevel;
697         int i, prefslice;
698         
699         prefslice = 0;
700         preflevel = PREF_NONE;
701
702         dp = &od->od_slicetab[0];
703         for (i = 0; i < od->od_nslices; i++, dp++) {
704
705                 switch (dp->dp_typ) {
706                 case DOSPTYP_386BSD:            /* FreeBSD */
707                         pref = dp->dp_flag & 0x80 ? PREF_FBSD_ACT : PREF_FBSD;
708                         break;
709
710                 case DOSPTYP_LINUX:
711                         pref = dp->dp_flag & 0x80 ? PREF_LINUX_ACT : PREF_LINUX;
712                         break;
713     
714                 case 0x01:              /* DOS/Windows */
715                 case 0x04:
716                 case 0x06:
717                 case 0x0b:
718                 case 0x0c:
719                 case 0x0e:
720                         pref = dp->dp_flag & 0x80 ? PREF_DOS_ACT : PREF_DOS;
721                         break;
722
723                 default:
724                         pref = PREF_NONE;
725                 }
726                 if (pref < preflevel) {
727                         preflevel = pref;
728                         prefslice = i + 1;
729                 }
730         }
731         return (prefslice);
732 }
733  
734 static int 
735 bd_close(struct open_file *f)
736 {
737     struct open_disk    *od = (struct open_disk *)(((struct i386_devdesc *)(f->f_devdata))->d_kind.biosdisk.data);
738
739     bd_closedisk(od);
740     return(0);
741 }
742
743 static void
744 bd_closedisk(struct open_disk *od)
745 {
746     DEBUG("open_disk %p", od);
747 #if 0
748     /* XXX is this required? (especially if disk already open...) */
749     if (od->od_flags & BD_FLOPPY)
750         delay(3000000);
751 #endif
752     free(od);
753 }
754
755 static int 
756 bd_strategy(void *devdata, int rw, daddr_t dblk, size_t size, char *buf, size_t *rsize)
757 {
758     struct bcache_devdata       bcd;
759     struct open_disk    *od = (struct open_disk *)(((struct i386_devdesc *)devdata)->d_kind.biosdisk.data);
760
761     bcd.dv_strategy = bd_realstrategy;
762     bcd.dv_devdata = devdata;
763     return(bcache_strategy(&bcd, od->od_unit, rw, dblk+od->od_boff, size, buf, rsize));
764 }
765
766 static int 
767 bd_realstrategy(void *devdata, int rw, daddr_t dblk, size_t size, char *buf, size_t *rsize)
768 {
769     struct open_disk    *od = (struct open_disk *)(((struct i386_devdesc *)devdata)->d_kind.biosdisk.data);
770     int                 blks;
771 #ifdef BD_SUPPORT_FRAGS
772     char                fragbuf[BIOSDISK_SECSIZE];
773     size_t              fragsize;
774
775     fragsize = size % BIOSDISK_SECSIZE;
776 #else
777     if (size % BIOSDISK_SECSIZE)
778         panic("bd_strategy: %d bytes I/O not multiple of block size", size);
779 #endif
780
781     DEBUG("open_disk %p", od);
782
783     if (rw != F_READ)
784         return(EROFS);
785
786
787     blks = size / BIOSDISK_SECSIZE;
788     DEBUG("read %d from %d to %p", blks, dblk, buf);
789
790     if (rsize)
791         *rsize = 0;
792     if (blks && bd_read(od, dblk, blks, buf)) {
793         DEBUG("read error");
794         return (EIO);
795     }
796 #ifdef BD_SUPPORT_FRAGS
797     DEBUG("bd_strategy: frag read %d from %d+%d to %p", 
798              fragsize, dblk, blks, buf + (blks * BIOSDISK_SECSIZE));
799     if (fragsize && bd_read(od, dblk + blks, 1, fragsize)) {
800         DEBUG("frag read error");
801         return(EIO);
802     }
803     bcopy(fragbuf, buf + (blks * BIOSDISK_SECSIZE), fragsize);
804 #endif
805     if (rsize)
806         *rsize = size;
807     return (0);
808 }
809
810 /* Max number of sectors to bounce-buffer if the request crosses a 64k boundary */
811 #define FLOPPY_BOUNCEBUF        18
812
813 static int
814 bd_read(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest)
815 {
816     u_int       x, bpc, cyl, hd, sec, result, resid, retry, maxfer;
817     caddr_t     p, xp, bbuf, breg;
818     
819     /* Just in case some idiot actually tries to read -1 blocks... */
820     if (blks < 0)
821         return (-1);
822
823     bpc = (od->od_sec * od->od_hds);            /* blocks per cylinder */
824     resid = blks;
825     p = dest;
826
827     /* Decide whether we have to bounce */
828     if ((od->od_unit < 0x80) && 
829         ((VTOP(dest) >> 16) != (VTOP(dest + blks * BIOSDISK_SECSIZE) >> 16))) {
830
831         /* 
832          * There is a 64k physical boundary somewhere in the destination buffer, so we have
833          * to arrange a suitable bounce buffer.  Allocate a buffer twice as large as we
834          * need to.  Use the bottom half unless there is a break there, in which case we
835          * use the top half.
836          */
837         x = min(FLOPPY_BOUNCEBUF, (unsigned)blks);
838         bbuf = malloc(x * 2 * BIOSDISK_SECSIZE);
839         if (((u_int32_t)VTOP(bbuf) & 0xffff0000) == ((u_int32_t)VTOP(dest + x * BIOSDISK_SECSIZE) & 0xffff0000)) {
840             breg = bbuf;
841         } else {
842             breg = bbuf + x * BIOSDISK_SECSIZE;
843         }
844         maxfer = x;                     /* limit transfers to bounce region size */
845     } else {
846         breg = bbuf = NULL;
847         maxfer = 0;
848     }
849     
850     while (resid > 0) {
851         x = dblk;
852         cyl = x / bpc;                  /* block # / blocks per cylinder */
853         x %= bpc;                       /* block offset into cylinder */
854         hd = x / od->od_sec;            /* offset / blocks per track */
855         sec = x % od->od_sec;           /* offset into track */
856
857         /* play it safe and don't cross track boundaries (XXX this is probably unnecessary) */
858         x = min(od->od_sec - sec, resid);
859         if (maxfer > 0)
860             x = min(x, maxfer);         /* fit bounce buffer */
861
862         /* where do we transfer to? */
863         xp = bbuf == NULL ? p : breg;
864
865         /* correct sector number for 1-based BIOS numbering */
866         sec++;
867
868         /* Loop retrying the operation a couple of times.  The BIOS may also retry. */
869         for (retry = 0; retry < 3; retry++) {
870             /* if retrying, reset the drive */
871             if (retry > 0) {
872                 v86.ctl = V86_FLAGS;
873                 v86.addr = 0x13;
874                 v86.eax = 0;
875                 v86.edx = od->od_unit;
876                 v86int();
877             }
878             
879             if(cyl > 1023) {
880                 /* use EDD if the disk supports it, otherwise, return error */
881                 if(od->od_flags & BD_MODEEDD1) {
882                     static unsigned short packet[8];
883
884                     packet[0] = 0x10;
885                     packet[1] = x;
886                     packet[2] = VTOPOFF(xp);
887                     packet[3] = VTOPSEG(xp);
888                     packet[4] = dblk & 0xffff;
889                     packet[5] = dblk >> 16;
890                     packet[6] = 0;
891                     packet[7] = 0;
892                     v86.ctl = V86_FLAGS;
893                     v86.addr = 0x13;
894                     v86.eax = 0x4200;
895                     v86.edx = od->od_unit;
896                     v86.ds = VTOPSEG(packet);
897                     v86.esi = VTOPOFF(packet);
898                     v86int();
899                     result = (v86.efl & 0x1);
900                     if(result == 0)
901                       break;
902                 } else {
903                     result = 1;
904                     break;
905                 }
906             } else {
907                 /* Use normal CHS addressing */
908                 v86.ctl = V86_FLAGS;
909                 v86.addr = 0x13;
910                 v86.eax = 0x200 | x;
911                 v86.ecx = ((cyl & 0xff) << 8) | ((cyl & 0x300) >> 2) | sec;
912                 v86.edx = (hd << 8) | od->od_unit;
913                 v86.es = VTOPSEG(xp);
914                 v86.ebx = VTOPOFF(xp);
915                 v86int();
916                 result = (v86.efl & 0x1);
917                 if (result == 0)
918                   break;
919             }
920         }
921         
922         DEBUG("%d sectors from %d/%d/%d to %p (0x%x) %s", x, cyl, hd, sec - 1, p, VTOP(p), result ? "failed" : "ok");
923         /* BUG here, cannot use v86 in printf because putchar uses it too */
924         DEBUG("ax = 0x%04x cx = 0x%04x dx = 0x%04x status 0x%x", 
925               0x200 | x, ((cyl & 0xff) << 8) | ((cyl & 0x300) >> 2) | sec, (hd << 8) | od->od_unit, (v86.eax >> 8) & 0xff);
926         if (result) {
927             if (bbuf != NULL)
928                 free(bbuf);
929             return(-1);
930         }
931         if (bbuf != NULL)
932             bcopy(breg, p, x * BIOSDISK_SECSIZE);
933         p += (x * BIOSDISK_SECSIZE);
934         dblk += x;
935         resid -= x;
936     }
937         
938 /*    hexdump(dest, (blks * BIOSDISK_SECSIZE)); */
939     if (bbuf != NULL)
940         free(bbuf);
941     return(0);
942 }
943
944 static int
945 bd_getgeom(struct open_disk *od)
946 {
947
948     v86.ctl = V86_FLAGS;
949     v86.addr = 0x13;
950     v86.eax = 0x800;
951     v86.edx = od->od_unit;
952     v86int();
953
954     if ((v86.efl & 0x1) ||                              /* carry set */
955         ((v86.edx & 0xff) <= (unsigned)(od->od_unit & 0x7f)))   /* unit # bad */
956         return(1);
957     
958     /* convert max cyl # -> # of cylinders */
959     od->od_cyl = ((v86.ecx & 0xc0) << 2) + ((v86.ecx & 0xff00) >> 8) + 1;
960     /* convert max head # -> # of heads */
961     od->od_hds = ((v86.edx & 0xff00) >> 8) + 1;
962     od->od_sec = v86.ecx & 0x3f;
963
964     DEBUG("unit 0x%x geometry %d/%d/%d", od->od_unit, od->od_cyl, od->od_hds, od->od_sec);
965     return(0);
966 }
967
968 /*
969  * Return the BIOS geometry of a given "fixed drive" in a format
970  * suitable for the legacy bootinfo structure.  Since the kernel is
971  * expecting raw int 0x13/0x8 values for N_BIOS_GEOM drives, we
972  * prefer to get the information directly, rather than rely on being
973  * able to put it together from information already maintained for
974  * different purposes and for a probably different number of drives.
975  *
976  * For valid drives, the geometry is expected in the format (31..0)
977  * "000000cc cccccccc hhhhhhhh 00ssssss"; and invalid drives are
978  * indicated by returning the geometry of a "1.2M" PC-format floppy
979  * disk.  And, incidentally, what is returned is not the geometry as
980  * such but the highest valid cylinder, head, and sector numbers.
981  */
982 u_int32_t
983 bd_getbigeom(int bunit)
984 {
985
986     v86.ctl = V86_FLAGS;
987     v86.addr = 0x13;
988     v86.eax = 0x800;
989     v86.edx = 0x80 + bunit;
990     v86int();
991     if (v86.efl & 0x1)
992         return 0x4f010f;
993     return ((v86.ecx & 0xc0) << 18) | ((v86.ecx & 0xff00) << 8) |
994            (v86.edx & 0xff00) | (v86.ecx & 0x3f);
995 }
996
997 /*
998  * Return a suitable dev_t value for (dev).
999  *
1000  * In the case where it looks like (dev) is a SCSI disk, we allow the number of
1001  * IDE disks to be specified in $num_ide_disks.  There should be a Better Way.
1002  */
1003 int
1004 bd_getdev(struct i386_devdesc *dev)
1005 {
1006     struct open_disk            *od;
1007     int                         biosdev;
1008     int                         major;
1009     int                         rootdev;
1010     char                        *nip, *cp;
1011     int                         unitofs = 0, i, unit;
1012
1013     biosdev = bd_unit2bios(dev->d_kind.biosdisk.unit);
1014     DEBUG("unit %d BIOS device %d", dev->d_kind.biosdisk.unit, biosdev);
1015     if (biosdev == -1)                          /* not a BIOS device */
1016         return(-1);
1017     if (bd_opendisk(&od, dev) != 0)             /* oops, not a viable device */
1018         return(-1);
1019
1020     if (biosdev < 0x80) {
1021         /* floppy (or emulated floppy) or ATAPI device */
1022         if (bdinfo[dev->d_kind.biosdisk.unit].bd_type == DT_ATAPI) {
1023             /* is an ATAPI disk */
1024             major = WFDMAJOR;
1025         } else {
1026             /* is a floppy disk */
1027             major = FDMAJOR;
1028         }
1029     } else {
1030         /* harddisk */
1031         if ((od->od_flags & BD_LABELOK) && (od->od_disklabel.d_type == DTYPE_SCSI)) {
1032             /* label OK, disk labelled as SCSI */
1033             major = DAMAJOR;
1034             /* check for unit number correction hint, now deprecated */
1035             if ((nip = getenv("num_ide_disks")) != NULL) {
1036                 i = strtol(nip, &cp, 0);
1037                 /* check for parse error */
1038                 if ((cp != nip) && (*cp == 0))
1039                     unitofs = i;
1040             }
1041         } else {
1042             /* assume an IDE disk */
1043             major = WDMAJOR;
1044         }
1045     }
1046     /* default root disk unit number */
1047     unit = (biosdev & 0x7f) - unitofs;
1048
1049     /* XXX a better kludge to set the root disk unit number */
1050     if ((nip = getenv("root_disk_unit")) != NULL) {
1051         i = strtol(nip, &cp, 0);
1052         /* check for parse error */
1053         if ((cp != nip) && (*cp == 0))
1054             unit = i;
1055     }
1056
1057     rootdev = MAKEBOOTDEV(major,
1058                           (dev->d_kind.biosdisk.slice + 1) >> 4,        /* XXX slices may be wrong here */
1059                           (dev->d_kind.biosdisk.slice + 1) & 0xf, 
1060                           unit,
1061                           dev->d_kind.biosdisk.partition);
1062     DEBUG("dev is 0x%x\n", rootdev);
1063     return(rootdev);
1064 }