Home | History | Annotate | Line # | Download | only in ata
wd.c revision 1.96
      1 /*
      2  * Copyright (c) 1994 Charles Hannum.
      3  * Copyright (c) 1990 The Regents of the University of California.
      4  * All rights reserved.
      5  *
      6  * This code is derived from software contributed to Berkeley by
      7  * William Jolitz.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. All advertising materials mentioning features or use of this software
     18  *    must display the following acknowledgement:
     19  *	This product includes software developed by the University of
     20  *	California, Berkeley and its contributors.
     21  * 4. Neither the name of the University nor the names of its contributors
     22  *    may be used to endorse or promote products derived from this software
     23  *    without specific prior written permission.
     24  *
     25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     35  * SUCH DAMAGE.
     36  *
     37  *	from: @(#)wd.c	7.2 (Berkeley) 5/9/91
     38  *	$Id: wd.c,v 1.96 1994/10/20 16:36:21 mycroft Exp $
     39  */
     40 
     41 #define	INSTRUMENT	/* instrumentation stuff by Brad Parker */
     42 
     43 #include <sys/param.h>
     44 #include <sys/dkbad.h>
     45 #include <sys/systm.h>
     46 #include <sys/kernel.h>
     47 #include <sys/conf.h>
     48 #include <sys/file.h>
     49 #include <sys/stat.h>
     50 #include <sys/ioctl.h>
     51 #include <sys/buf.h>
     52 #include <sys/uio.h>
     53 #include <sys/malloc.h>
     54 #include <sys/device.h>
     55 #include <sys/disklabel.h>
     56 #include <sys/disk.h>
     57 #include <sys/syslog.h>
     58 #ifdef INSTRUMENT
     59 #include <sys/dkstat.h>
     60 #endif
     61 
     62 #include <vm/vm.h>
     63 
     64 #include <machine/cpu.h>
     65 #include <machine/pio.h>
     66 
     67 #ifndef NEWCONFIG
     68 #include <i386/isa/isa_device.h>
     69 #endif
     70 #include <i386/isa/isavar.h>
     71 #include <i386/isa/icu.h>
     72 #include <i386/isa/wdreg.h>
     73 
     74 #define WDCNDELAY	100000	/* delay = 100us; so 10s for a controller state change */
     75 #define WDCDELAY	100
     76 #define	RECOVERYTIME	hz/2	/* time to recover from an error */
     77 
     78 #if 0
     79 /* If you enable this, it will report any delays more than 100us * N long. */
     80 #define WDCNDELAY_DEBUG	10
     81 #endif
     82 
     83 #define	WDIORETRIES	5	/* number of retries before giving up */
     84 
     85 #define	WDUNIT(dev)			DISKUNIT(dev)
     86 #define	WDPART(dev)			DISKPART(dev)
     87 #define	MAKEWDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
     88 
     89 #define	WDLABELDEV(dev)	(MAKEWDDEV(major(dev), WDUNIT(dev), RAW_PART))
     90 
     91 #define b_cylin	b_resid		/* cylinder number for doing IO to */
     92 				/* shares an entry in the buf struct */
     93 
     94 /*
     95  * Drive states.  Used to initialize drive.
     96  */
     97 #define	CLOSED		0		/* disk is closed */
     98 #define	RECAL		1		/* recalibrate */
     99 #define	RECAL_WAIT	2		/* done recalibrating */
    100 #define	GEOMETRY	3		/* upload geometry */
    101 #define	GEOMETRY_WAIT	4		/* done uploading geometry */
    102 #define	OPEN		5		/* done with open */
    103 
    104 /*
    105  * Drive status.
    106  */
    107 struct wd_softc {
    108 	struct device sc_dev;
    109 	struct dkdevice sc_dk;
    110 
    111 	long	sc_bcount;	/* byte count left */
    112 	long	sc_mbcount;	/* total byte count left */
    113 	short	sc_skip;	/* blocks already transferred */
    114 	short	sc_mskip;	/* blocks already transferred for multi */
    115 	char	sc_drive;	/* physical unit number */
    116 	char	sc_state;	/* control state */
    117 
    118 	u_char	sc_flags;	/* drive characteistics found */
    119 #define	WDF_BSDLABEL	0x01	/* has a BSD disk label */
    120 #define	WDF_BADSECT	0x02	/* has a bad144 badsector table */
    121 #define	WDF_WRITEPROT	0x04	/* manual unit write protect */
    122 #define	WDF_WLABEL	0x08	/* label is writable */
    123 	TAILQ_ENTRY(wd_softc) sc_drivechain;
    124 	struct buf sc_q;
    125 	struct wdparams sc_params; /* ESDI/IDE drive/controller parameters */
    126 	long	sc_badsect[127];	/* 126 plus trailing -1 marker */
    127 };
    128 
    129 struct wdc_softc {
    130 	struct device sc_dev;
    131 	struct intrhand sc_ih;
    132 
    133 	u_char	sc_flags;
    134 #define	WDCF_ACTIVE	0x00001	/* controller is active */
    135 #define	WDCF_SINGLE	0x00004	/* sector at a time mode */
    136 #define	WDCF_ERROR	0x00008	/* processing a disk error */
    137 	u_char	sc_status;	/* copy of status register */
    138 	u_char	sc_error;	/* copy of error register */
    139 	u_short	sc_iobase;	/* i/o port base */
    140 	int	sc_timeout;	/* timeout counter */
    141 	int	sc_errors;	/* count of errors during current transfer */
    142 	TAILQ_HEAD(drivehead, wd_softc) sc_drives;
    143 };
    144 
    145 int wdcprobe(), wdprobe(), wdcintr();
    146 void wdcattach(), wdattach();
    147 
    148 struct cfdriver wdccd = {
    149 	NULL, "wdc", wdcprobe, wdcattach, DV_DULL, sizeof(struct wd_softc)
    150 };
    151 
    152 struct cfdriver wdcd = {
    153 	NULL, "wd", wdprobe, wdattach, DV_DISK, sizeof(struct wd_softc)
    154 };
    155 
    156 void wdfinish __P((struct wd_softc *, struct buf *));
    157 static void wdstart __P((struct wd_softc *));
    158 static void wdcstart __P((struct wdc_softc *));
    159 static int wdcommand __P((struct wd_softc *, int, int, int, int, int));
    160 static int wdcontrol __P((struct wd_softc *));
    161 static int wdsetctlr __P((struct wd_softc *));
    162 static int wdgetctlr __P((struct wd_softc *));
    163 static void bad144intern __P((struct wd_softc *));
    164 static int wdcreset __P((struct wdc_softc *));
    165 static void wdcrestart __P((void *arg));
    166 static void wdcunwedge __P((struct wdc_softc *));
    167 static void wdctimeout __P((void *arg));
    168 void wddisksort __P((struct buf *, struct buf *));
    169 static void wderror __P((void *, struct buf *, char *));
    170 int wdcwait __P((struct wdc_softc *, int));
    171 /* ST506 spec says that if READY or SEEKCMPLT go off, then the read or write
    172    command is aborted. */
    173 #define	wait_for_drq(d)		wdcwait(d, WDCS_READY | WDCS_SEEKCMPLT | WDCS_DRQ)
    174 #define	wait_for_ready(d)	wdcwait(d, WDCS_READY | WDCS_SEEKCMPLT)
    175 #define	wait_for_unbusy(d)	wdcwait(d, 0)
    176 
    177 /*
    178  * Probe for controller.
    179  */
    180 int
    181 wdcprobe(parent, self, aux)
    182 	struct device *parent, *self;
    183 	void *aux;
    184 {
    185 	struct wdc_softc *wdc = (void *)self;
    186 	struct isa_attach_args *ia = aux;
    187 	struct wd_softc *wd;
    188 	u_short iobase;
    189 
    190 	wdc->sc_iobase = iobase = ia->ia_iobase;
    191 
    192 	/* Check if we have registers that work. */
    193 	outb(iobase+wd_error, 0x5a);	/* Error register not writable. */
    194 	outb(iobase+wd_cyl_lo, 0xa5);	/* But all of cyllo are implemented. */
    195 	if (inb(iobase+wd_error) == 0x5a || inb(iobase+wd_cyl_lo) != 0xa5)
    196 		return 0;
    197 
    198 	if (wdcreset(wdc) != 0) {
    199 		delay(500000);
    200 		if (wdcreset(wdc) != 0)
    201 			return 0;
    202 	}
    203 
    204 	/*
    205 	 * XXX wdcommand() accepts a wd_softc, so we have to make it one.
    206 	 */
    207 	wd = (void *)malloc(sizeof(struct wd_softc), M_TEMP, M_NOWAIT);
    208 	bzero(wd, sizeof(struct wd_softc));
    209 	wd->sc_drive = 0;
    210 	wd->sc_dev.dv_unit = 0;
    211 	wd->sc_dev.dv_parent = (void *)wdc;
    212 
    213 	/* Execute a controller only command. */
    214 	if (wdcommand(wd, 0, 0, 0, 0, WDCC_DIAGNOSE) != 0 ||
    215 	    wait_for_unbusy(wdc) != 0)
    216 		goto lose;
    217 
    218 	free(wd, M_TEMP);
    219 	ia->ia_iosize = 8;
    220 	ia->ia_msize = 0;
    221 	return 1;
    222 
    223 lose:
    224 	free(wd, M_TEMP);
    225 	return 0;
    226 }
    227 
    228 struct wdc_attach_args {
    229 	int wa_drive;
    230 };
    231 
    232 int
    233 wdprint(aux, wdc)
    234 	void *aux;
    235 	char *wdc;
    236 {
    237 	struct wdc_attach_args *wa = aux;
    238 
    239 	if (!wdc)
    240 		printf(" drive %d", wa->wa_drive);
    241 	return QUIET;
    242 }
    243 
    244 void
    245 wdcattach(parent, self, aux)
    246 	struct device *parent, *self;
    247 	void *aux;
    248 {
    249 	struct wdc_softc *wdc = (void *)self;
    250 	struct isa_attach_args *ia = aux;
    251 	struct wdc_attach_args wa;
    252 
    253 	printf("\n");
    254 
    255 	for (wa.wa_drive = 0; wa.wa_drive < 2; wa.wa_drive++)
    256 		(void)config_found(self, &wa, wdprint);
    257 
    258 	TAILQ_INIT(&wdc->sc_drives);
    259 	wdctimeout(wdc);
    260 	wdc->sc_ih.ih_fun = wdcintr;
    261 	wdc->sc_ih.ih_arg = wdc;
    262 	wdc->sc_ih.ih_level = IPL_BIO;
    263 	intr_establish(ia->ia_irq, &wdc->sc_ih);
    264 }
    265 
    266 int
    267 wdprobe(parent, self, aux)
    268 	struct device *parent, *self;
    269 	void *aux;
    270 {
    271 	struct wd_softc *wd = (void *)self;
    272 	struct cfdata *cf = wd->sc_dev.dv_cfdata;
    273 	struct wdc_attach_args *wa = aux;
    274 	int drive = wa->wa_drive;
    275 #ifdef NEWCONFIG
    276 
    277 #define cf_drive cf_loc[0]
    278 	if (cf->cf_drive != -1 && cf->cf_drive != drive)
    279 		return 0;
    280 #undef cf_drive
    281 #else
    282 	struct isa_device *id = (void *)cf->cf_loc;
    283 
    284 	if (id->id_physid != -1 && id->id_physid != drive)
    285 		return 0;
    286 #endif
    287 
    288 	wd->sc_drive = drive;
    289 
    290 	if (wdgetctlr(wd) != 0)
    291 		return 0;
    292 
    293 	return 1;
    294 }
    295 
    296 void
    297 wdattach(parent, self, aux)
    298 	struct device *parent, *self;
    299 	void *aux;
    300 {
    301 	struct wd_softc *wd = (void *)self;
    302 	int i, blank;
    303 
    304 	if (wd->sc_params.wdp_heads == 0)
    305 		printf(": (unknown size) <");
    306 	else
    307 		printf(": %dMB %d cyl, %d head, %d sec, %d bytes/sec <",
    308 		    wd->sc_dk.dk_label.d_ncylinders *
    309 		    wd->sc_dk.dk_label.d_secpercyl /
    310 		    (1048576 / wd->sc_dk.dk_label.d_secsize),
    311 		    wd->sc_dk.dk_label.d_ncylinders,
    312 		    wd->sc_dk.dk_label.d_ntracks,
    313 		    wd->sc_dk.dk_label.d_nsectors,
    314 		    wd->sc_dk.dk_label.d_secsize);
    315 	for (i = blank = 0; i < sizeof(wd->sc_params.wdp_model); i++) {
    316 		char c = wd->sc_params.wdp_model[i];
    317 		if (c == '\0')
    318 			break;
    319 		if (c != ' ') {
    320 			if (blank)
    321 				printf(" %c", c);
    322 			else
    323 				printf("%c", c);
    324 			blank = 0;
    325 		} else
    326 			blank = 1;
    327 	}
    328 	printf(">\n");
    329 }
    330 
    331 /*
    332  * Read/write routine for a buffer.  Finds the proper unit, range checks
    333  * arguments, and schedules the transfer.  Does not wait for the transfer to
    334  * complete.  Multi-page transfers are supported.  All I/O requests must be a
    335  * multiple of a sector in length.
    336  */
    337 void
    338 wdstrategy(bp)
    339 	struct buf *bp;
    340 {
    341 	struct wd_softc *wd;	/* disk unit to do the IO */
    342 	int lunit = WDUNIT(bp->b_dev);
    343 	int s;
    344 
    345 	/* Valid unit, controller, and request?  */
    346 	if (lunit >= wdcd.cd_ndevs ||
    347 	    (wd = wdcd.cd_devs[lunit]) == 0 ||
    348 	    bp->b_blkno < 0 ||
    349 	    (bp->b_bcount % DEV_BSIZE) != 0 ||
    350 	    (bp->b_bcount / DEV_BSIZE) >= (1 << NBBY)) {
    351 		bp->b_error = EINVAL;
    352 		goto bad;
    353 	}
    354 
    355 	/* "Soft" write protect check. */
    356 	if ((wd->sc_flags & WDF_WRITEPROT) && (bp->b_flags & B_READ) == 0) {
    357 		bp->b_error = EROFS;
    358 		goto bad;
    359 	}
    360 
    361 	/* If it's a null transfer, return immediately. */
    362 	if (bp->b_bcount == 0)
    363 		goto done;
    364 
    365 	/* Have partitions and want to use them? */
    366 	if (WDPART(bp->b_dev) != RAW_PART) {
    367 		if ((wd->sc_flags & WDF_BSDLABEL) == 0) {
    368 			bp->b_error = EIO;
    369 			goto bad;
    370 		}
    371 		/*
    372 		 * Do bounds checking, adjust transfer. if error, process.
    373 		 * If end of partition, just return.
    374 		 */
    375 		if (bounds_check_with_label(bp, &wd->sc_dk.dk_label,
    376 		    (wd->sc_flags & WDF_WLABEL) != 0) <= 0)
    377 			goto done;
    378 		/* Otherwise, process transfer request. */
    379 	}
    380 
    381 	/* Don't bother doing rotational optimization. */
    382 	bp->b_cylin = 0;
    383 
    384 	/* Queue transfer on drive, activate drive and controller if idle. */
    385 	s = splbio();
    386 	wddisksort(&wd->sc_q, bp);
    387 	if (!wd->sc_q.b_active)
    388 		wdstart(wd);		/* Start drive. */
    389 #ifdef DIAGNOSTIC
    390 	else {
    391 		struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
    392 		if ((wdc->sc_flags & WDCF_ACTIVE) == 0) {
    393 			printf("wdstrategy: controller inactive\n");
    394 			wdcstart(wdc);
    395 		}
    396 	}
    397 #endif
    398 	splx(s);
    399 	return;
    400 
    401 bad:
    402 	bp->b_flags |= B_ERROR;
    403 done:
    404 	/* Toss transfer; we're done early. */
    405 	biodone(bp);
    406 }
    407 
    408 /*
    409  * Need to skip over multitransfer bufs.
    410  */
    411 void
    412 wddisksort(dp, bp)
    413 	struct buf *dp, *bp;
    414 {
    415 	struct buf *ap;
    416 
    417 	while ((ap = dp->b_actf) && ap->b_flags & B_XXX)
    418 		dp = ap;
    419 	disksort(dp, bp);
    420 }
    421 
    422 /*
    423  * Routine to queue a command to the controller.  The unit's request is linked
    424  * into the active list for the controller.  If the controller is idle, the
    425  * transfer is started.
    426  */
    427 static void
    428 wdstart(wd)
    429 	struct wd_softc *wd;
    430 {
    431 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
    432 	int active = wdc->sc_drives.tqh_first != 0;
    433 
    434 	/* Link onto controller queue. */
    435 	wd->sc_q.b_active = 1;
    436 	TAILQ_INSERT_TAIL(&wdc->sc_drives, wd, sc_drivechain);
    437 
    438 	/* If controller not already active, start it. */
    439 	if (!active)
    440 		wdcstart(wdc);
    441 }
    442 
    443 void
    444 wdfinish(wd, bp)
    445 	struct wd_softc *wd;
    446 	struct buf *bp;
    447 {
    448 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
    449 
    450 #ifdef INSTRUMENT
    451 	dk_busy &= ~(1 << wd->sc_dev.dv_unit);
    452 #endif
    453 	wdc->sc_flags &= ~(WDCF_SINGLE | WDCF_ERROR);
    454 	wdc->sc_errors = 0;
    455 	/*
    456 	 * If this is the only buf or the last buf in the transfer (taking into
    457 	 * account any residual, in case we erred)...
    458 	 */
    459 	wd->sc_mbcount -= wd->sc_bcount;
    460 	if (wd->sc_mbcount == 0) {
    461 		wd->sc_mskip = 0;
    462 		/*
    463 		 * ...then move this drive to the end of the queue to give
    464 		 * others a `fair' chance.
    465 		 */
    466 		if (wd->sc_drivechain.tqe_next) {
    467 			TAILQ_REMOVE(&wdc->sc_drives, wd, sc_drivechain);
    468 			if (bp->b_actf) {
    469 				TAILQ_INSERT_TAIL(&wdc->sc_drives, wd,
    470 				    sc_drivechain);
    471 			} else
    472 				wd->sc_q.b_active = 0;
    473 		}
    474 	}
    475 	bp->b_resid = wd->sc_bcount;
    476 	bp->b_flags &= ~B_XXX;
    477 	wd->sc_skip = 0;
    478 	wd->sc_q.b_actf = bp->b_actf;
    479 	biodone(bp);
    480 }
    481 
    482 /*
    483  * Controller startup routine.  This does the calculation, and starts a
    484  * single-sector read or write operation.  Called to start a transfer, or from
    485  * the interrupt routine to continue a multi-sector transfer.
    486  * RESTRICTIONS:
    487  * 1.	The transfer length must be an exact multiple of the sector size.
    488  */
    489 static void
    490 wdcstart(wdc)
    491 	struct wdc_softc *wdc;
    492 {
    493 	struct wd_softc *wd;	/* disk unit for IO */
    494 	struct buf *bp;
    495 
    496 loop:
    497 	/* Is there a drive for the controller to do a transfer with? */
    498 	wd = wdc->sc_drives.tqh_first;
    499 	if (wd == NULL)
    500 		return;
    501 
    502 	/* Is there a transfer to this drive?  If not, deactivate drive. */
    503 	bp = wd->sc_q.b_actf;
    504 	if (bp == NULL) {
    505 		TAILQ_REMOVE(&wdc->sc_drives, wd, sc_drivechain);
    506 		wd->sc_q.b_active = 0;
    507 		goto loop;
    508 	}
    509 
    510 	if (wdc->sc_errors >= WDIORETRIES) {
    511 		wderror(wd, bp, "hard error");
    512 		bp->b_error = EIO;
    513 		bp->b_flags |= B_ERROR;
    514 		wdfinish(wd, bp);
    515 		goto loop;
    516 	}
    517 
    518 	/* Mark the controller active and set a timeout. */
    519 	wdc->sc_flags |= WDCF_ACTIVE;
    520 	wdc->sc_timeout = 4;
    521 
    522 	/* Do control operations specially. */
    523 	if (wd->sc_state < OPEN) {
    524 		/*
    525 		 * Actually, we want to be careful not to mess with the control
    526 		 * state if the device is currently busy, but we can assume
    527 		 * that we never get to this point if that's the case.
    528 		 */
    529 		(void) wdcontrol(wd);
    530 		return;
    531 	}
    532 
    533 	/*
    534 	 * WDCF_ERROR is set by wdcunwedge() and wdcintr() when an error is
    535 	 * encountered.  If we are in multi-sector mode, then we switch to
    536 	 * single-sector mode and retry the operation from the start.
    537 	 */
    538 	if (wdc->sc_flags & WDCF_ERROR) {
    539 		wdc->sc_flags &= ~WDCF_ERROR;
    540 		if ((wdc->sc_flags & WDCF_SINGLE) == 0) {
    541 			wdc->sc_flags |= WDCF_SINGLE;
    542 			wd->sc_skip = wd->sc_mskip = 0;
    543 		}
    544 	}
    545 
    546 	if (wd->sc_skip == 0) {
    547 #ifdef WDDEBUG
    548 		printf("\n%s: wdcstart %s %d@%d; map ", wd->sc_dev.dv_xname,
    549 		    (bp->b_flags & B_READ) ? "read" : "write", bp->b_bcount,
    550 		    bp->b_blkno);
    551 #endif
    552 		wd->sc_bcount = bp->b_bcount;
    553 #ifdef INSTRUMENT
    554 		dk_busy |= (1 << wd->sc_dev.dv_unit);
    555 		dk_wds[wd->sc_dev.dv_unit] += bp->b_bcount >> 6;
    556 #endif
    557 	} else {
    558 #ifdef WDDEBUG
    559 		printf(" %d)%x", wd->sc_skip, inb(wd->sc_iobase+wd_altsts));
    560 #endif
    561 	}
    562 
    563 	if (wd->sc_mskip == 0) {
    564 		wd->sc_mbcount = wd->sc_bcount;
    565 		/* If multi-sector, try to cluster. */
    566 		if ((wdc->sc_flags & WDCF_SINGLE) == 0) {
    567 			struct buf *oldbp, *nextbp;
    568 			oldbp = bp;
    569 			nextbp = bp->b_actf;
    570 			oldbp->b_flags |= B_XXX;
    571 			while (nextbp && oldbp->b_dev == nextbp->b_dev &&
    572 			    nextbp->b_blkno ==
    573 			    (oldbp->b_blkno + (oldbp->b_bcount / wd->sc_dk.dk_label.d_secsize)) &&
    574 			    (oldbp->b_flags & B_READ) == (nextbp->b_flags & B_READ)) {
    575 				if ((wd->sc_mbcount + nextbp->b_bcount) / wd->sc_dk.dk_label.d_secsize >= 240)
    576 					break;
    577 				wd->sc_mbcount += nextbp->b_bcount;
    578 				nextbp->b_flags |= B_XXX;
    579 				oldbp = nextbp;
    580 				nextbp = nextbp->b_actf;
    581 			}
    582 		}
    583 	}
    584 
    585 	/* If starting a multisector transfer, or doing single transfers. */
    586 	if (wd->sc_mskip == 0 || (wdc->sc_flags & WDCF_SINGLE)) {
    587 		struct disklabel *lp;
    588 		long blkno, nblks;
    589 		long cylin, head, sector;
    590 		int command;
    591 
    592 		lp = &wd->sc_dk.dk_label;
    593 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE) + wd->sc_skip;
    594 		if (WDPART(bp->b_dev) != RAW_PART)
    595 			blkno += lp->d_partitions[WDPART(bp->b_dev)].p_offset;
    596 		if (wdc->sc_flags & WDCF_SINGLE)
    597 			nblks = 1;
    598 		else
    599 			nblks = howmany(wd->sc_mbcount, lp->d_secsize);
    600 
    601 		/*
    602 		 * Check for bad sectors if we have them, and not formatting.  Only do
    603 		 * this in single-sector mode, or when starting a multiple-sector
    604 		 * transfer.
    605 		 */
    606 		if ((wd->sc_flags & WDF_BADSECT)
    607 #ifdef B_FORMAT
    608 		    && (bp->b_flags & B_FORMAT) == 0
    609 #endif
    610 		    ) {
    611 			long blkdiff;
    612 			int i;
    613 
    614 			for (i = 0; (blkdiff = wd->sc_badsect[i]) != -1; i++) {
    615 				blkdiff -= blkno;
    616 				if (blkdiff < 0)
    617 					continue;
    618 				if (blkdiff >= nblks)
    619 					break;
    620 				if (blkdiff == 0) {
    621 					/* Replace current block of transfer. */
    622 					blkno =
    623 					    lp->d_secperunit - lp->d_nsectors - i - 1;
    624 					if (wdc->sc_flags & WDCF_SINGLE)
    625 						break;
    626 				} else {
    627 					/* If clustered, try unclustering. */
    628 					if (wd->sc_mbcount > wd->sc_bcount) {
    629 						nblks = howmany(wd->sc_bcount, lp->d_secsize);
    630 						if (blkdiff >= nblks) {
    631 							/* Unclustering was enough. */
    632 							wd->sc_mbcount = wd->sc_bcount;
    633 							break;
    634 						}
    635 					}
    636 					/* Bad block inside transfer. */
    637 				}
    638 				/* Force single-sector mode. */
    639 				wd->sc_mbcount = wd->sc_bcount;
    640 				wdc->sc_flags |= WDCF_SINGLE;
    641 				nblks = 1;
    642 			}
    643 			/* Tranfer is okay now. */
    644 		}
    645 
    646 		cylin = blkno / lp->d_secpercyl;
    647 		head = (blkno % lp->d_secpercyl) / lp->d_nsectors;
    648 		sector = blkno % lp->d_nsectors;
    649 		sector++;	/* Sectors begin with 1, not 0. */
    650 
    651 #ifdef INSTRUMENT
    652 		++dk_seek[wd->sc_dev.dv_unit];
    653 		++dk_xfer[wd->sc_dev.dv_unit];
    654 #endif
    655 
    656 #ifdef B_FORMAT
    657 		if (bp->b_flags & B_FORMAT) {
    658 			sector = lp->d_gap3;
    659 			nblks = lp->d_nsectors;
    660 			command = WDCC_FORMAT;
    661 		} else
    662 #endif
    663 			command =
    664 			    (bp->b_flags & B_READ) ? WDCC_READ : WDCC_WRITE;
    665 
    666 		/* Initiate command! */
    667 		if (wdcommand(wd, cylin, head, sector, nblks, command) != 0) {
    668 			wderror(wd, NULL,
    669 			    "wdcstart: timeout waiting for unbusy");
    670 			wdcunwedge(wdc);
    671 			return;
    672 		}
    673 #ifdef WDDEBUG
    674 		printf("sector %d cylin %d head %d addr %x sts %x\n", sector,
    675 		    cylin, head, bp->b_data, inb(wd->sc_iobase+wd_altsts));
    676 #endif
    677 	}
    678 
    679 	/* If this is a read operation, just go away until it's done. */
    680 	if (bp->b_flags & B_READ)
    681 		return;
    682 
    683 	if (wait_for_drq(wdc) < 0) {
    684 		wderror(wd, NULL, "wdcstart: timeout waiting for drq");
    685 		wdcunwedge(wdc);
    686 		return;
    687 	}
    688 
    689 	/* Then send it! */
    690 	outsw(wdc->sc_iobase+wd_data, bp->b_data + wd->sc_skip * DEV_BSIZE,
    691 	    DEV_BSIZE / sizeof(short));
    692 }
    693 
    694 /*
    695  * Interrupt routine for the controller.  Acknowledge the interrupt, check for
    696  * errors on the current operation, mark it done if necessary, and start the
    697  * next request.  Also check for a partially done transfer, and continue with
    698  * the next chunk if so.
    699  */
    700 int
    701 wdcintr(wdc)
    702 	struct wdc_softc *wdc;
    703 {
    704 	struct wd_softc *wd;
    705 	struct buf *bp;
    706 
    707 	if ((wdc->sc_flags & WDCF_ACTIVE) == 0) {
    708 		/* Clear the pending interrupt. */
    709 		(void) inb(wdc->sc_iobase+wd_status);
    710 		return 0;
    711 	}
    712 
    713 	wd = wdc->sc_drives.tqh_first;
    714 	bp = wd->sc_q.b_actf;
    715 
    716 #ifdef WDDEBUG
    717 	printf("I%d ", ctrlr);
    718 #endif
    719 
    720 	if (wait_for_unbusy(wdc) < 0) {
    721 		wderror(wd, NULL, "wdcintr: timeout waiting for unbusy");
    722 		wdc->sc_status |= WDCS_ERR;	/* XXX */
    723 	}
    724 
    725 	/* Is it not a transfer, but a control operation? */
    726 	if (wd->sc_state < OPEN) {
    727 		if (wdcontrol(wd))
    728 			wdcstart(wdc);
    729 		return 1;
    730 	}
    731 
    732 	wdc->sc_flags &= ~WDCF_ACTIVE;
    733 	wdc->sc_timeout = 0;
    734 
    735 	/* Have we an error? */
    736 	if (wdc->sc_status & WDCS_ERR) {
    737 	lose:
    738 #ifdef WDDEBUG
    739 		wderror(wd, NULL, "wdcintr");
    740 #endif
    741 		if ((wdc->sc_flags & WDCF_SINGLE) == 0) {
    742 			wdc->sc_flags |= WDCF_ERROR;
    743 			goto restart;
    744 		}
    745 
    746 #ifdef B_FORMAT
    747 		if (bp->b_flags & B_FORMAT)
    748 			goto bad;
    749 #endif
    750 
    751 		if (++wdc->sc_errors < WDIORETRIES)
    752 			goto restart;
    753 		wderror(wd, bp, "hard error");
    754 
    755 	bad:
    756 		bp->b_error = EIO;
    757 		bp->b_flags |= B_ERROR;
    758 		goto done;
    759 	}
    760 
    761 	if (wdc->sc_status & WDCS_ECCCOR)
    762 		wderror(wd, bp, "soft ecc");
    763 
    764 	/* If this was a read, fetch the data. */
    765 	if (bp->b_flags & B_READ) {
    766 		/* Ready to receive data? */
    767 		if ((wdc->sc_status & (WDCS_READY | WDCS_SEEKCMPLT | WDCS_DRQ))
    768 		    != (WDCS_READY | WDCS_SEEKCMPLT | WDCS_DRQ)) {
    769 			wderror(wd, NULL, "wdcintr: read intr before drq");
    770 			wdcunwedge(wdc);
    771 			return 1;
    772 		}
    773 
    774 		/* Suck in data. */
    775 		insw(wdc->sc_iobase+wd_data,
    776 		    bp->b_data + wd->sc_skip * DEV_BSIZE,
    777 		    DEV_BSIZE / sizeof(short));
    778 	}
    779 
    780 	/* If we encountered any abnormalities, flag it as a soft error. */
    781 	if (wdc->sc_errors) {
    782 		wderror(wd, bp, "soft error");
    783 		wdc->sc_errors = 0;
    784 	}
    785 
    786 	/* Ready for the next block, if any. */
    787 	wd->sc_skip++;
    788 	wd->sc_mskip++;
    789 	wd->sc_bcount -= DEV_BSIZE;
    790 	wd->sc_mbcount -= DEV_BSIZE;
    791 
    792 	/* See if more to transfer. */
    793 	if (wd->sc_bcount > 0)
    794 		goto restart;
    795 
    796 done:
    797 	/* Done with this transfer, with or without error. */
    798 	wdfinish(wd, bp);
    799 
    800 restart:
    801 	/* Start the next transfer, if any. */
    802 	wdcstart(wdc);
    803 
    804 	return 1;
    805 }
    806 
    807 /*
    808  * Initialize a drive.
    809  */
    810 int
    811 wdopen(dev, flag, fmt, p)
    812 	dev_t dev;
    813 	int flag, fmt;
    814 	struct proc *p;
    815 {
    816 	int lunit;
    817 	struct wd_softc *wd;
    818 	int part = WDPART(dev);
    819 	struct partition *pp;
    820 	char *msg;
    821 	int error;
    822 
    823 	lunit = WDUNIT(dev);
    824 	if (lunit >= wdcd.cd_ndevs)
    825 		return ENXIO;
    826 	wd = wdcd.cd_devs[lunit];
    827 	if (wd == 0)
    828 		return ENXIO;
    829 
    830 	if ((wd->sc_flags & WDF_BSDLABEL) == 0) {
    831 		wd->sc_flags |= WDF_WRITEPROT;
    832 		wd->sc_q.b_actf = NULL;
    833 
    834 		/*
    835 		 * Use the default sizes until we've read the label, or longer
    836 		 * if there isn't one there.
    837 		 */
    838 		bzero(&wd->sc_dk.dk_label, sizeof(wd->sc_dk.dk_label));
    839 		wd->sc_dk.dk_label.d_type = DTYPE_ST506;
    840 		wd->sc_dk.dk_label.d_ncylinders = 1024;
    841 		wd->sc_dk.dk_label.d_secsize = DEV_BSIZE;
    842 		wd->sc_dk.dk_label.d_ntracks = 8;
    843 		wd->sc_dk.dk_label.d_nsectors = 17;
    844 		wd->sc_dk.dk_label.d_secpercyl = 17*8;
    845 		wd->sc_dk.dk_label.d_secperunit = 17*8*1024;
    846 		wd->sc_state = RECAL;
    847 
    848 		/* Read label using "raw" partition. */
    849 		msg = readdisklabel(WDLABELDEV(dev), wdstrategy,
    850 		    &wd->sc_dk.dk_label, &wd->sc_dk.dk_cpulabel);
    851 		if (msg) {
    852 			/*
    853 			 * This probably happened because the drive's default
    854 			 * geometry doesn't match the DOS geometry.  We
    855 			 * assume the DOS geometry is now in the label and try
    856 			 * again.  XXX This is a kluge.
    857 			 */
    858 			if (wd->sc_state > GEOMETRY)
    859 				wd->sc_state = GEOMETRY;
    860 			msg = readdisklabel(WDLABELDEV(dev), wdstrategy,
    861 			    &wd->sc_dk.dk_label, &wd->sc_dk.dk_cpulabel);
    862 		}
    863 		if (msg) {
    864 			log(LOG_WARNING, "%s: cannot find label (%s)\n",
    865 			    wd->sc_dev.dv_xname, msg);
    866 			if (part != RAW_PART)
    867 				return EINVAL;	/* XXX needs translation */
    868 		} else {
    869 			if (wd->sc_state > GEOMETRY)
    870 				wd->sc_state = GEOMETRY;
    871 			wd->sc_flags |= WDF_BSDLABEL;
    872 			wd->sc_flags &= ~WDF_WRITEPROT;
    873 			if (wd->sc_dk.dk_label.d_flags & D_BADSECT)
    874 				wd->sc_flags |= WDF_BADSECT;
    875 		}
    876 	}
    877 
    878 	if (wd->sc_flags & WDF_BADSECT)
    879 		bad144intern(wd);
    880 
    881 	/*
    882 	 * Warn if a partition is opened that overlaps another partition which
    883 	 * is open unless one is the "raw" partition (whole disk).
    884 	 */
    885 	if ((wd->sc_dk.dk_openmask & (1 << part)) == 0 && part != RAW_PART) {
    886 		int start, end;
    887 
    888 		pp = &wd->sc_dk.dk_label.d_partitions[part];
    889 		start = pp->p_offset;
    890 		end = pp->p_offset + pp->p_size;
    891 		for (pp = wd->sc_dk.dk_label.d_partitions;
    892 		    pp < &wd->sc_dk.dk_label.d_partitions[wd->sc_dk.dk_label.d_npartitions];
    893 		    pp++) {
    894 			if (pp->p_offset + pp->p_size <= start ||
    895 			    pp->p_offset >= end)
    896 				continue;
    897 			if (pp - wd->sc_dk.dk_label.d_partitions == RAW_PART)
    898 				continue;
    899 			if (wd->sc_dk.dk_openmask & (1 << (pp - wd->sc_dk.dk_label.d_partitions)))
    900 				log(LOG_WARNING,
    901 				    "%s%c: overlaps open partition (%c)\n",
    902 				    wd->sc_dev.dv_xname, part + 'a',
    903 				    pp - wd->sc_dk.dk_label.d_partitions + 'a');
    904 		}
    905 	}
    906 	if (part != RAW_PART &&
    907 	    (part >= wd->sc_dk.dk_label.d_npartitions ||
    908 	     wd->sc_dk.dk_label.d_partitions[part].p_fstype == FS_UNUSED)) {
    909 		error = ENXIO;
    910 		goto bad;
    911 	}
    912 
    913 	/* Insure only one open at a time. */
    914 	switch (fmt) {
    915 	case S_IFCHR:
    916 		wd->sc_dk.dk_copenmask |= (1 << part);
    917 		break;
    918 	case S_IFBLK:
    919 		wd->sc_dk.dk_bopenmask |= (1 << part);
    920 		break;
    921 	}
    922 	wd->sc_dk.dk_openmask = wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
    923 
    924 	return 0;
    925 
    926 bad:
    927 	return error;
    928 }
    929 
    930 /*
    931  * Implement operations other than read/write.
    932  * Called from wdcstart or wdcintr during opens and formats.
    933  * Uses finite-state-machine to track progress of operation in progress.
    934  * Returns 0 if operation still in progress, 1 if completed.
    935  */
    936 static int
    937 wdcontrol(wd)
    938 	struct wd_softc *wd;
    939 {
    940 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
    941 
    942 	switch (wd->sc_state) {
    943 	case RECAL:			/* Set SDH, step rate, do restore. */
    944 		if (wdcommand(wd, 0, 0, 0, 0, WDCC_RESTORE | WD_STEP) != 0) {
    945 			wderror(wd, NULL, "wdcontrol: wdcommand failed");
    946 			wdcunwedge(wdc);
    947 			return 0;
    948 		}
    949 		wd->sc_state = RECAL_WAIT;
    950 		return 0;
    951 
    952 	case RECAL_WAIT:
    953 		if (wdc->sc_status & WDCS_ERR) {
    954 			wderror(wd, NULL, "wdcontrol: recal failed");
    955 			wdcunwedge(wdc);
    956 			return 0;
    957 		}
    958 		/* fall through */
    959 	case GEOMETRY:
    960 		if (wdsetctlr(wd) != 0) {
    961 			/* Already printed a message. */
    962 			wdcunwedge(wdc);
    963 			return 0;
    964 		}
    965 		wd->sc_state = GEOMETRY_WAIT;
    966 		return 0;
    967 
    968 	case GEOMETRY_WAIT:
    969 		if (wdc->sc_status & WDCS_ERR) {
    970 			wderror(wd, NULL, "wdcontrol: geometry failed");
    971 			wdcunwedge(wdc);
    972 			return 0;
    973 		}
    974 
    975 		wdc->sc_errors = 0;
    976 		wd->sc_state = OPEN;
    977 		/*
    978 		 * The rest of the initialization can be done by normal means.
    979 		 */
    980 		return 1;
    981 	}
    982 
    983 #ifdef DIAGNOSTIC
    984 	panic("wdcontrol: impossible");
    985 #endif
    986 }
    987 
    988 /*
    989  * Send a command and wait uninterruptibly until controller is finished.
    990  * Return -1 if controller busy for too long, otherwise return non-zero if
    991  * error.  Intended for brief controller commands at critical points.
    992  * Assumes interrupts are blocked.
    993  */
    994 static int
    995 wdcommand(wd, cylin, head, sector, count, cmd)
    996 	struct wd_softc *wd;
    997 	int cylin, head, sector, count;
    998 	int cmd;
    999 {
   1000 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
   1001 	int stat;
   1002 	u_short iobase;
   1003 
   1004 	/* Select drive. */
   1005 	iobase = wdc->sc_iobase;
   1006 	outb(iobase+wd_sdh, WDSD_IBM | (wd->sc_drive << 4) | head);
   1007 
   1008 	/* Wait for it to become ready to accept a command. */
   1009 	if (cmd == WDCC_DIAGNOSE || cmd == WDCC_IDC)
   1010 		stat = wait_for_unbusy(wdc);
   1011 	else
   1012 		stat = wdcwait(wdc, WDCS_READY);
   1013 	if (stat < 0)
   1014 		return -1;
   1015 
   1016 	/* Load parameters. */
   1017 	outb(iobase+wd_precomp, wd->sc_dk.dk_label.d_precompcyl / 4);
   1018 	outb(iobase+wd_cyl_lo, cylin);
   1019 	outb(iobase+wd_cyl_hi, cylin >> 8);
   1020 	outb(iobase+wd_sector, sector);
   1021 	outb(iobase+wd_seccnt, count);
   1022 
   1023 	/* Send command, await results. */
   1024 	outb(iobase+wd_command, cmd);
   1025 
   1026 	return 0;
   1027 }
   1028 
   1029 /*
   1030  * Issue IDC to drive to tell it just what geometry it is to be.
   1031  */
   1032 static int
   1033 wdsetctlr(wd)
   1034 	struct wd_softc *wd;
   1035 {
   1036 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
   1037 
   1038 #ifdef WDDEBUG
   1039 	printf("wd(%d,%d) C%dH%dS%d\n", wd->sc_ctrlr, wd->sc_drive,
   1040 	    wd->sc_dk.dk_label.d_ncylinders, wd->sc_dk.dk_label.d_ntracks,
   1041 	    wd->sc_dk.dk_label.d_nsectors);
   1042 #endif
   1043 
   1044 	if (wdcommand(wd, wd->sc_dk.dk_label.d_ncylinders,
   1045 	    wd->sc_dk.dk_label.d_ntracks - 1, 0, wd->sc_dk.dk_label.d_nsectors,
   1046 	    WDCC_IDC) != 0) {
   1047 		wderror(wd, NULL, "wdsetctlr: wdcommand failed");
   1048 		return -1;
   1049 	}
   1050 
   1051 	return 0;
   1052 }
   1053 
   1054 /*
   1055  * Issue READP to drive to ask it what it is.
   1056  */
   1057 static int
   1058 wdgetctlr(wd)
   1059 	struct wd_softc *wd;
   1060 {
   1061 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
   1062 	int i;
   1063 	char tb[DEV_BSIZE];
   1064 	struct wdparams *wp;
   1065 
   1066 	if (wdcommand(wd, 0, 0, 0, 0, WDCC_READP) != 0 ||
   1067 	    wait_for_drq(wdc) != 0) {
   1068 		/*
   1069 		 * If WDCC_READP fails then we might have an old drive so we
   1070 		 * try a seek to 0; if that passes then the drive is there but
   1071 		 * it's OLD AND KRUSTY.
   1072 		 */
   1073 		if (wdcommand(wd, 0, 0, 0, 0, WDCC_RESTORE | WD_STEP) != 0 ||
   1074 		    wait_for_ready(wdc) != 0)
   1075 			return -1;
   1076 
   1077 		strncpy(wd->sc_dk.dk_label.d_typename, "ST506",
   1078 		    sizeof wd->sc_dk.dk_label.d_typename);
   1079 		strncpy(wd->sc_params.wdp_model, "Unknown Type",
   1080 		    sizeof wd->sc_params.wdp_model);
   1081 		wd->sc_dk.dk_label.d_type = DTYPE_ST506;
   1082 	} else {
   1083 		/* Obtain parameters. */
   1084 		wp = &wd->sc_params;
   1085 		insw(wdc->sc_iobase+wd_data, tb, sizeof(tb) / sizeof(short));
   1086 		bcopy(tb, wp, sizeof(struct wdparams));
   1087 
   1088 		/* Shuffle string byte order. */
   1089 		for (i = 0; i < sizeof(wp->wdp_model); i += 2) {
   1090 			u_short *p;
   1091 			p = (u_short *)(wp->wdp_model + i);
   1092 			*p = ntohs(*p);
   1093 		}
   1094 
   1095 		strncpy(wd->sc_dk.dk_label.d_typename, "ESDI/IDE",
   1096 		    sizeof wd->sc_dk.dk_label.d_typename);
   1097 		wd->sc_dk.dk_label.d_type = DTYPE_ESDI;
   1098 		bcopy(wp->wdp_model+20, wd->sc_dk.dk_label.d_packname, 14-1);
   1099 
   1100 		/* Update disklabel given drive information. */
   1101 		wd->sc_dk.dk_label.d_ncylinders =
   1102 		    wp->wdp_fixedcyl + wp->wdp_removcyl /*+- 1*/;
   1103 		wd->sc_dk.dk_label.d_ntracks = wp->wdp_heads;
   1104 		wd->sc_dk.dk_label.d_nsectors = wp->wdp_sectors;
   1105 		wd->sc_dk.dk_label.d_secpercyl =
   1106 		    wd->sc_dk.dk_label.d_ntracks * wd->sc_dk.dk_label.d_nsectors;
   1107 		wd->sc_dk.dk_label.d_partitions[1].p_size =
   1108 		    wd->sc_dk.dk_label.d_secpercyl * wp->wdp_sectors;
   1109 		wd->sc_dk.dk_label.d_partitions[1].p_offset = 0;
   1110 	}
   1111 
   1112 #if 0
   1113 	printf("gc %x cyl %d trk %d sec %d type %d sz %d model %s\n",
   1114 	    wp->wdp_config, wp->wdp_fixedcyl + wp->wdp_removcyl, wp->wdp_heads,
   1115 	    wp->wdp_sectors, wp->wdp_cntype, wp->wdp_cnsbsz, wp->wdp_model);
   1116 #endif
   1117 
   1118 	wd->sc_dk.dk_label.d_subtype |= DSTYPE_GEOMETRY;
   1119 
   1120 	/* XXX sometimes possibly needed */
   1121 	(void) inb(wdc->sc_iobase+wd_status);
   1122 
   1123 	return 0;
   1124 }
   1125 
   1126 int
   1127 wdclose(dev, flag, fmt)
   1128 	dev_t dev;
   1129 	int flag, fmt;
   1130 {
   1131 	struct wd_softc *wd = wdcd.cd_devs[WDUNIT(dev)];
   1132 	int part = WDPART(dev);
   1133 
   1134 	switch (fmt) {
   1135 	case S_IFCHR:
   1136 		wd->sc_dk.dk_copenmask &= ~(1 << part);
   1137 		break;
   1138 	case S_IFBLK:
   1139 		wd->sc_dk.dk_bopenmask &= ~(1 << part);
   1140 		break;
   1141 	}
   1142 	wd->sc_dk.dk_openmask = wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1143 
   1144 	return 0;
   1145 }
   1146 
   1147 int
   1148 wdioctl(dev, cmd, addr, flag, p)
   1149 	dev_t dev;
   1150 	int cmd;
   1151 	caddr_t addr;
   1152 	int flag;
   1153 	struct proc *p;
   1154 {
   1155 	int lunit = WDUNIT(dev);
   1156 	struct wd_softc *wd = wdcd.cd_devs[lunit];
   1157 	int error;
   1158 
   1159 	switch (cmd) {
   1160 	case DIOCSBAD:
   1161 		if ((flag & FWRITE) == 0)
   1162 			return EBADF;
   1163 		wd->sc_dk.dk_cpulabel.bad = *(struct dkbad *)addr;
   1164 		wd->sc_flags |= WDF_BADSECT;
   1165 		bad144intern(wd);
   1166 		return 0;
   1167 
   1168 	case DIOCGDINFO:
   1169 		*(struct disklabel *)addr = wd->sc_dk.dk_label;
   1170 		return 0;
   1171 
   1172 	case DIOCGPART:
   1173 		((struct partinfo *)addr)->disklab = &wd->sc_dk.dk_label;
   1174 		((struct partinfo *)addr)->part =
   1175 		    &wd->sc_dk.dk_label.d_partitions[WDPART(dev)];
   1176 		return 0;
   1177 
   1178 	case DIOCSDINFO:
   1179 		if ((flag & FWRITE) == 0)
   1180 			return EBADF;
   1181 		error = setdisklabel(&wd->sc_dk.dk_label,
   1182 		    (struct disklabel *)addr,
   1183 		    /*(wd->sc_flags & WDF_BSDLABEL) ? wd->sc_dk.dk_openmask : */0,
   1184 		    &wd->sc_dk.dk_cpulabel);
   1185 		if (error == 0) {
   1186 			wd->sc_flags |= WDF_BSDLABEL;
   1187 			if (wd->sc_state > GEOMETRY)
   1188 				wd->sc_state = GEOMETRY;
   1189 		}
   1190 		return error;
   1191 
   1192 	case DIOCWLABEL:
   1193 		wd->sc_flags &= ~WDF_WRITEPROT;
   1194 		if ((flag & FWRITE) == 0)
   1195 			return EBADF;
   1196 		if (*(int *)addr)
   1197 			wd->sc_flags |= WDF_WLABEL;
   1198 		else
   1199 			wd->sc_flags &= ~WDF_WLABEL;
   1200 		return 0;
   1201 
   1202 	case DIOCWDINFO:
   1203 		wd->sc_flags &= ~WDF_WRITEPROT;
   1204 		if ((flag & FWRITE) == 0)
   1205 			return EBADF;
   1206 		error = setdisklabel(&wd->sc_dk.dk_label,
   1207 		    (struct disklabel *)addr,
   1208 		    /*(wd->sc_flags & WDF_BSDLABEL) ? wd->sc_dk.dk_openmask : */0,
   1209 		    &wd->sc_dk.dk_cpulabel);
   1210 		if (error == 0) {
   1211 			wd->sc_flags |= WDF_BSDLABEL;
   1212 			if (wd->sc_state > GEOMETRY)
   1213 				wd->sc_state = GEOMETRY;
   1214 
   1215 			/* Simulate opening partition 0 so write succeeds. */
   1216 			wd->sc_dk.dk_openmask |= (1 << 0);	/* XXX */
   1217 			error = writedisklabel(WDLABELDEV(dev), wdstrategy,
   1218 			    &wd->sc_dk.dk_label, &wd->sc_dk.dk_cpulabel);
   1219 			wd->sc_dk.dk_openmask =
   1220 			    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1221 		}
   1222 		return error;
   1223 
   1224 #ifdef notyet
   1225 	case DIOCGDINFOP:
   1226 		*(struct disklabel **)addr = &wd->sc_dk.dk_label;
   1227 		return 0;
   1228 
   1229 	case DIOCWFORMAT:
   1230 		if ((flag & FWRITE) == 0)
   1231 			return EBADF;
   1232 	{
   1233 		register struct format_op *fop;
   1234 		struct iovec aiov;
   1235 		struct uio auio;
   1236 
   1237 		fop = (struct format_op *)addr;
   1238 		aiov.iov_base = fop->df_buf;
   1239 		aiov.iov_len = fop->df_count;
   1240 		auio.uio_iov = &aiov;
   1241 		auio.uio_iovcnt = 1;
   1242 		auio.uio_resid = fop->df_count;
   1243 		auio.uio_segflg = 0;
   1244 		auio.uio_offset =
   1245 		    fop->df_startblk * wd->sc_dk.dk_label.d_secsize;
   1246 		auio.uio_procp = p;
   1247 		error = physio(wdformat, NULL, dev, B_WRITE, minphys,
   1248 		    &auio);
   1249 		fop->df_count -= auio.uio_resid;
   1250 		fop->df_reg[0] = wdc->sc_status;
   1251 		fop->df_reg[1] = wdc->sc_error;
   1252 		return error;
   1253 	}
   1254 #endif
   1255 
   1256 	default:
   1257 		return ENOTTY;
   1258 	}
   1259 
   1260 #ifdef DIAGNOSTIC
   1261 	panic("wdioctl: impossible");
   1262 #endif
   1263 }
   1264 
   1265 #ifdef B_FORMAT
   1266 int
   1267 wdformat(struct buf *bp)
   1268 {
   1269 
   1270 	bp->b_flags |= B_FORMAT;
   1271 	return wdstrategy(bp);
   1272 }
   1273 #endif
   1274 
   1275 int
   1276 wdsize(dev)
   1277 	dev_t dev;
   1278 {
   1279 	int lunit = WDUNIT(dev), part = WDPART(dev);
   1280 	struct wd_softc *wd;
   1281 
   1282 	if (lunit >= wdcd.cd_ndevs)
   1283 		return -1;
   1284 	wd = wdcd.cd_devs[lunit];
   1285 	if (wd == 0)
   1286 		return -1;
   1287 
   1288 	if (wd->sc_state < OPEN || (wd->sc_flags & WDF_BSDLABEL) == 0) {
   1289 		int val;
   1290 		val = wdopen(MAKEWDDEV(major(dev), lunit, RAW_PART), FREAD,
   1291 		    S_IFBLK, 0);
   1292 		/* XXX Clear the open flag? */
   1293 		if (val != 0)
   1294 			return -1;
   1295 	}
   1296 
   1297 	if ((wd->sc_flags & (WDF_WRITEPROT | WDF_BSDLABEL)) != WDF_BSDLABEL)
   1298 		return -1;
   1299 
   1300 	return (int)wd->sc_dk.dk_label.d_partitions[part].p_size;
   1301 }
   1302 
   1303 /*
   1304  * Dump core after a system crash.
   1305  */
   1306 int
   1307 wddump(dev)
   1308 	dev_t dev;
   1309 {
   1310 	struct wd_softc *wd;	/* disk unit to do the IO */
   1311 	struct wdc_softc *wdc;
   1312 	long num;		/* number of sectors to write */
   1313 	int lunit, part;
   1314 	long blkoff, blkno;
   1315 	long cylin, head, sector;
   1316 	long secpertrk, secpercyl, nblocks;
   1317 	char *addr;
   1318 	static wddoingadump = 0;
   1319 	extern caddr_t CADDR1;
   1320 	extern pt_entry_t *CMAP1;
   1321 
   1322 	addr = (char *)0;	/* starting address */
   1323 
   1324 #if DO_NOT_KNOW_HOW
   1325 	/* Toss any characters present prior to dump, ie. non-blocking getc. */
   1326 	while (cngetc())
   1327 		;
   1328 #endif
   1329 
   1330 	lunit = WDUNIT(dev);
   1331 	/* Check for acceptable drive number. */
   1332 	if (lunit >= wdcd.cd_ndevs)
   1333 		return ENXIO;
   1334 	wd = wdcd.cd_devs[lunit];
   1335 	/* Was it ever initialized? */
   1336 	if (wd == 0 || wd->sc_state < OPEN || wd->sc_flags & WDF_WRITEPROT)
   1337 		return ENXIO;
   1338 
   1339 	wdc = (void *)wd->sc_dev.dv_parent;
   1340 
   1341 	/* Convert to disk sectors. */
   1342 	num = ctob(physmem) / wd->sc_dk.dk_label.d_secsize;
   1343 
   1344 	secpertrk = wd->sc_dk.dk_label.d_nsectors;
   1345 	secpercyl = wd->sc_dk.dk_label.d_secpercyl;
   1346 	part = WDPART(dev);
   1347 	nblocks = wd->sc_dk.dk_label.d_partitions[part].p_size;
   1348 	blkoff = wd->sc_dk.dk_label.d_partitions[part].p_offset;
   1349 
   1350 	/*printf("part %x, nblocks %d, dumplo %d, num %d\n", part, nblocks,
   1351 	    dumplo, num);*/
   1352 
   1353 	/* Check transfer bounds against partition size. */
   1354 	if (dumplo < 0 || dumplo + num > nblocks)
   1355 		return EINVAL;
   1356 
   1357 	if (wddoingadump)
   1358 		return EFAULT;
   1359 	wddoingadump = 1;
   1360 
   1361 	/* Recalibrate. */
   1362 	if (wdcommand(wd, 0, 0, 0, 0, WDCC_RESTORE | WD_STEP) != 0 ||
   1363 	    wait_for_ready(wdc) != 0 || wdsetctlr(wd) != 0 ||
   1364 	    wait_for_ready(wdc) != 0) {
   1365 		wderror(wd, NULL, "wddump: recal failed");
   1366 		return EIO;
   1367 	}
   1368 
   1369 	blkno = dumplo + blkoff;
   1370 	while (num > 0) {
   1371 		/* Compute disk address. */
   1372 		cylin = blkno / secpercyl;
   1373 		head = (blkno % secpercyl) / secpertrk;
   1374 		sector = blkno % secpertrk;
   1375 
   1376 		if (wd->sc_flags & WDF_BADSECT) {
   1377 			long newblk;
   1378 			int i;
   1379 
   1380 			for (i = 0; wd->sc_badsect[i] != -1; i++) {
   1381 				if (blkno < wd->sc_badsect[i]) {
   1382 					/* Sorted list, passed our block by. */
   1383 					break;
   1384 				} else if (blkno == wd->sc_badsect[i]) {
   1385 					newblk =
   1386 					    wd->sc_dk.dk_label.d_secperunit -
   1387 					    wd->sc_dk.dk_label.d_nsectors -
   1388 					    i - 1;
   1389 					cylin = newblk / secpercyl;
   1390 					head = (newblk % secpercyl) / secpertrk;
   1391 					sector = newblk % secpertrk;
   1392 					/* Found and replaced; done. */
   1393 					break;
   1394 				}
   1395 			}
   1396 		}
   1397 		sector++;		/* origin 1 */
   1398 
   1399 #ifdef notdef
   1400 		/* Let's just talk about this first. */
   1401 		printf("cylin %d, head %d, sector %d, addr 0x%x", cylin, head,
   1402 		    sector, addr);
   1403 #endif
   1404 		if (wdcommand(wd, cylin, head, sector, 1, WDCC_WRITE) != 0) {
   1405 			wderror(wd, NULL, "wddump: wdcommand failed");
   1406 			return EIO;
   1407 		}
   1408 		if (wait_for_drq(wdc) != 0) {
   1409 			wderror(wd, NULL, "wddump: timeout waiting for drq");
   1410 			return EIO;
   1411 		}
   1412 
   1413 #ifdef notdef	/* Cannot use this since this address was mapped differently. */
   1414 		pmap_enter(kernel_pmap, CADDR1, trunc_page(addr), VM_PROT_READ, TRUE);
   1415 #else
   1416 		*CMAP1 = PG_V | PG_KW | ctob((long)addr);
   1417 		tlbflush();
   1418 #endif
   1419 
   1420 		outsw(wdc->sc_iobase+wd_data, CADDR1 + ((int)addr & PGOFSET),
   1421 		    DEV_BSIZE / sizeof(short));
   1422 
   1423 		/* Check data request (should be done). */
   1424 		if (wait_for_ready(wdc) != 0) {
   1425 			wderror(wd, NULL, "wddump: timeout waiting for ready");
   1426 			return EIO;
   1427 		}
   1428 		if (wdc->sc_status & WDCS_DRQ) {
   1429 			wderror(wd, NULL, "wddump: extra drq");
   1430 			return EIO;
   1431 		}
   1432 
   1433 		if ((unsigned)addr % 1048576 == 0)
   1434 			printf("%d ", num / (1048576 / DEV_BSIZE));
   1435 
   1436 		/* Update block count. */
   1437 		num--;
   1438 		blkno++;
   1439 		(int)addr += DEV_BSIZE;
   1440 
   1441 #if DO_NOT_KNOW_HOW
   1442 		/* Operator aborting dump? non-blocking getc() */
   1443 		if (cngetc())
   1444 			return EINTR;
   1445 #endif
   1446 	}
   1447 	return 0;
   1448 }
   1449 
   1450 /*
   1451  * Internalize the bad sector table.
   1452  */
   1453 void
   1454 bad144intern(wd)
   1455 	struct wd_softc *wd;
   1456 {
   1457 	int i;
   1458 
   1459 	for (i = 0; i < 127; i++)
   1460 		wd->sc_badsect[i] = -1;
   1461 	for (i = 0; i < 126; i++) {
   1462 		if (wd->sc_dk.dk_cpulabel.bad.bt_bad[i].bt_cyl == 0xffff)
   1463 			break;
   1464 		wd->sc_badsect[i] =
   1465 		    wd->sc_dk.dk_cpulabel.bad.bt_bad[i].bt_cyl *
   1466 		    wd->sc_dk.dk_label.d_secpercyl +
   1467 		    (wd->sc_dk.dk_cpulabel.bad.bt_bad[i].bt_trksec >> 8) *
   1468 			wd->sc_dk.dk_label.d_nsectors +
   1469 		    (wd->sc_dk.dk_cpulabel.bad.bt_bad[i].bt_trksec & 0x00ff);
   1470 	}
   1471 }
   1472 
   1473 static int
   1474 wdcreset(wdc)
   1475 	struct wdc_softc *wdc;
   1476 {
   1477 	u_short iobase = wdc->sc_iobase;
   1478 
   1479 	/* Reset the device. */
   1480 	outb(iobase+wd_ctlr, WDCTL_RST | WDCTL_IDS);
   1481 	delay(1000);
   1482 	outb(iobase+wd_ctlr, WDCTL_IDS);
   1483 	delay(1000);
   1484 	(void) inb(iobase+wd_error);
   1485 	outb(iobase+wd_ctlr, WDCTL_4BIT);
   1486 
   1487 	if (wait_for_unbusy(wdc) < 0) {
   1488 		printf("%s: reset failed\n", wdc->sc_dev.dv_xname);
   1489 		return 1;
   1490 	}
   1491 
   1492 	return 0;
   1493 }
   1494 
   1495 static void
   1496 wdcrestart(arg)
   1497 	void *arg;
   1498 {
   1499 	struct wdc_softc *wdc = (struct wdc_softc *)arg;
   1500 	int s = splbio();
   1501 
   1502 	wdcstart(wdc);
   1503 	splx(s);
   1504 }
   1505 
   1506 /*
   1507  * Unwedge the controller after an unexpected error.  We do this by resetting
   1508  * it, marking all drives for recalibration, and stalling the queue for a short
   1509  * period to give the reset time to finish.
   1510  * NOTE: We use a timeout here, so this routine must not be called during
   1511  * autoconfig or dump.
   1512  */
   1513 static void
   1514 wdcunwedge(wdc)
   1515 	struct wdc_softc *wdc;
   1516 {
   1517 	int lunit;
   1518 
   1519 	wdc->sc_timeout = 0;
   1520 	(void) wdcreset(wdc);
   1521 
   1522 	/* Schedule recalibrate for all drives on this controller. */
   1523 	for (lunit = 0; lunit < wdcd.cd_ndevs; lunit++) {
   1524 		struct wd_softc *wd = wdcd.cd_devs[lunit];
   1525 		if (!wd || (void *)wd->sc_dev.dv_parent != wdc)
   1526 			continue;
   1527 		if (wd->sc_state > RECAL)
   1528 			wd->sc_state = RECAL;
   1529 	}
   1530 
   1531 	wdc->sc_flags |= WDCF_ERROR;
   1532 	++wdc->sc_errors;
   1533 
   1534 	/* Wake up in a little bit and restart the operation. */
   1535 	timeout(wdcrestart, wdc, RECOVERYTIME);
   1536 }
   1537 
   1538 int
   1539 wdcwait(wdc, mask)
   1540 	struct wdc_softc *wdc;
   1541 	int mask;
   1542 {
   1543 	u_short iobase = wdc->sc_iobase;
   1544 	int timeout = 0;
   1545 	u_char status;
   1546 	extern int cold;
   1547 
   1548 	for (;;) {
   1549 		wdc->sc_status = status = inb(iobase+wd_status);
   1550 		if ((status & WDCS_BUSY) == 0 && (status & mask) == mask)
   1551 			break;
   1552 		if (++timeout > WDCNDELAY)
   1553 			return -1;
   1554 		delay(WDCDELAY);
   1555 	}
   1556 	if (status & WDCS_ERR) {
   1557 		wdc->sc_error = inb(iobase+wd_error);
   1558 		return WDCS_ERR;
   1559 	}
   1560 #ifdef WDCNDELAY_DEBUG
   1561 	/* After autoconfig, there should be no long delays. */
   1562 	if (!cold && timeout > WDCNDELAY_DEBUG)
   1563 		printf("%s: warning: busy-wait took %dus\n",
   1564 		    wdc->sc_dev.dv_xname, WDCDELAY * timeout);
   1565 #endif
   1566 	return 0;
   1567 }
   1568 
   1569 static void
   1570 wdctimeout(arg)
   1571 	void *arg;
   1572 {
   1573 	struct wdc_softc *wdc = (struct wdc_softc *)arg;
   1574 	int s = splbio();
   1575 
   1576 	if (wdc->sc_timeout && --wdc->sc_timeout == 0) {
   1577 		wderror(wdc, NULL, "lost interrupt");
   1578 		wdcunwedge(wdc);
   1579 	}
   1580 	timeout(wdctimeout, wdc, hz);
   1581 	splx(s);
   1582 }
   1583 
   1584 static void
   1585 wderror(dev, bp, msg)
   1586 	void *dev;
   1587 	struct buf *bp;
   1588 	char *msg;
   1589 {
   1590 	struct wd_softc *wd = dev;
   1591 	struct wdc_softc *wdc = dev;
   1592 
   1593 	if (bp)
   1594 		diskerr(bp, "wd", msg, LOG_PRINTF, wd->sc_skip,
   1595 		    &wd->sc_dk.dk_label);
   1596 	else
   1597 		printf("%s: %s: status %b error %b\n", wdc->sc_dev.dv_xname,
   1598 		    msg, wdc->sc_status, WDCS_BITS, wdc->sc_error, WDERR_BITS);
   1599 }
   1600