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