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