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