Home | History | Annotate | Line # | Download | only in ata
wd.c revision 1.99
      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.99 1994/10/20 19:22:01 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 
     77 #define	WAITTIME	(4 * hz)	/* time to wait for a completion */
     78 #define	RECOVERYTIME	(hz / 2)	/* time to recover from an error */
     79 
     80 #if 0
     81 /* If you enable this, it will report any delays more than 100us * N long. */
     82 #define WDCNDELAY_DEBUG	10
     83 #endif
     84 
     85 #define	WDIORETRIES	5	/* number of retries before giving up */
     86 
     87 #define	WDUNIT(dev)			DISKUNIT(dev)
     88 #define	WDPART(dev)			DISKPART(dev)
     89 #define	MAKEWDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
     90 
     91 #define	WDLABELDEV(dev)	(MAKEWDDEV(major(dev), WDUNIT(dev), RAW_PART))
     92 
     93 #define b_cylin	b_resid		/* cylinder number for doing IO to */
     94 				/* shares an entry in the buf struct */
     95 
     96 /*
     97  * Drive states.  Used to initialize drive.
     98  */
     99 #define	CLOSED		0		/* disk is closed */
    100 #define	RECAL		1		/* recalibrate */
    101 #define	RECAL_WAIT	2		/* done recalibrating */
    102 #define	GEOMETRY	3		/* upload geometry */
    103 #define	GEOMETRY_WAIT	4		/* done uploading geometry */
    104 #define	OPEN		5		/* done with open */
    105 
    106 /*
    107  * Drive status.
    108  */
    109 struct wd_softc {
    110 	struct device sc_dev;
    111 	struct dkdevice sc_dk;
    112 
    113 	long	sc_bcount;	/* byte count left */
    114 	long	sc_mbcount;	/* total byte count left */
    115 	short	sc_skip;	/* blocks already transferred */
    116 	short	sc_mskip;	/* blocks already transferred for multi */
    117 	char	sc_drive;	/* physical unit number */
    118 	char	sc_state;	/* control state */
    119 
    120 	u_char	sc_flags;	/* drive characteistics found */
    121 #define	WDF_BSDLABEL	0x01	/* has a BSD disk label */
    122 #define	WDF_BADSECT	0x02	/* has a bad144 badsector table */
    123 #define	WDF_WRITEPROT	0x04	/* manual unit write protect */
    124 #define	WDF_WLABEL	0x08	/* label is writable */
    125 	TAILQ_ENTRY(wd_softc) sc_drivechain;
    126 	struct buf sc_q;
    127 	struct wdparams sc_params; /* ESDI/IDE drive/controller parameters */
    128 	long	sc_badsect[127];	/* 126 plus trailing -1 marker */
    129 };
    130 
    131 struct wdc_softc {
    132 	struct device sc_dev;
    133 	struct intrhand sc_ih;
    134 
    135 	u_char	sc_flags;
    136 #define	WDCF_ACTIVE	0x00001	/* controller is active */
    137 #define	WDCF_SINGLE	0x00004	/* sector at a time mode */
    138 #define	WDCF_ERROR	0x00008	/* processing a disk error */
    139 	u_char	sc_status;	/* copy of status register */
    140 	u_char	sc_error;	/* copy of error register */
    141 	u_short	sc_iobase;	/* i/o port base */
    142 	int	sc_errors;	/* count of errors during current transfer */
    143 	TAILQ_HEAD(drivehead, wd_softc) sc_drives;
    144 };
    145 
    146 int wdcprobe(), wdprobe(), wdcintr();
    147 void wdcattach(), wdattach();
    148 
    149 struct cfdriver wdccd = {
    150 	NULL, "wdc", wdcprobe, wdcattach, DV_DULL, sizeof(struct wd_softc)
    151 };
    152 
    153 struct cfdriver wdcd = {
    154 	NULL, "wd", wdprobe, wdattach, DV_DISK, sizeof(struct wd_softc)
    155 };
    156 
    157 void wdfinish __P((struct wd_softc *, struct buf *));
    158 static void wdstart __P((struct wd_softc *));
    159 static void wdcstart __P((struct wdc_softc *));
    160 static int wdcommand __P((struct wd_softc *, int, int, int, int, int));
    161 static int wdcontrol __P((struct wd_softc *));
    162 static int wdsetctlr __P((struct wd_softc *));
    163 static int wdgetctlr __P((struct wd_softc *));
    164 static void bad144intern __P((struct wd_softc *));
    165 static int wdcreset __P((struct wdc_softc *));
    166 static void wdcrestart __P((void *arg));
    167 static void wdcunwedge __P((struct wdc_softc *));
    168 static void wdctimeout __P((void *arg));
    169 void wddisksort __P((struct buf *, struct buf *));
    170 static void wderror __P((void *, struct buf *, char *));
    171 int wdcwait __P((struct wdc_softc *, int));
    172 /* ST506 spec says that if READY or SEEKCMPLT go off, then the read or write
    173    command is aborted. */
    174 #define	wait_for_drq(d)		wdcwait(d, WDCS_READY | WDCS_SEEKCMPLT | WDCS_DRQ)
    175 #define	wait_for_ready(d)	wdcwait(d, WDCS_READY | WDCS_SEEKCMPLT)
    176 #define	wait_for_unbusy(d)	wdcwait(d, 0)
    177 
    178 /*
    179  * Probe for controller.
    180  */
    181 int
    182 wdcprobe(parent, self, aux)
    183 	struct device *parent, *self;
    184 	void *aux;
    185 {
    186 	struct wdc_softc *wdc = (void *)self;
    187 	struct isa_attach_args *ia = aux;
    188 	struct wd_softc *wd;
    189 	u_short iobase;
    190 
    191 	wdc->sc_iobase = iobase = ia->ia_iobase;
    192 
    193 	/* Check if we have registers that work. */
    194 	outb(iobase+wd_error, 0x5a);	/* Error register not writable. */
    195 	outb(iobase+wd_cyl_lo, 0xa5);	/* But all of cyllo are implemented. */
    196 	if (inb(iobase+wd_error) == 0x5a || inb(iobase+wd_cyl_lo) != 0xa5)
    197 		return 0;
    198 
    199 	if (wdcreset(wdc) != 0) {
    200 		delay(500000);
    201 		if (wdcreset(wdc) != 0)
    202 			return 0;
    203 	}
    204 
    205 	/*
    206 	 * XXX wdcommand() accepts a wd_softc, so we have to make it one.
    207 	 */
    208 	wd = (void *)malloc(sizeof(struct wd_softc), M_TEMP, M_NOWAIT);
    209 	bzero(wd, sizeof(struct wd_softc));
    210 	wd->sc_drive = 0;
    211 	wd->sc_dev.dv_unit = 0;
    212 	wd->sc_dev.dv_parent = (void *)wdc;
    213 
    214 	/* Execute a controller only command. */
    215 	if (wdcommand(wd, 0, 0, 0, 0, WDCC_DIAGNOSE) != 0 ||
    216 	    wait_for_unbusy(wdc) != 0)
    217 		goto lose;
    218 
    219 	free(wd, M_TEMP);
    220 	ia->ia_iosize = 8;
    221 	ia->ia_msize = 0;
    222 	return 1;
    223 
    224 lose:
    225 	free(wd, M_TEMP);
    226 	return 0;
    227 }
    228 
    229 struct wdc_attach_args {
    230 	int wa_drive;
    231 };
    232 
    233 int
    234 wdprint(aux, wdc)
    235 	void *aux;
    236 	char *wdc;
    237 {
    238 	struct wdc_attach_args *wa = aux;
    239 
    240 	if (!wdc)
    241 		printf(" drive %d", wa->wa_drive);
    242 	return QUIET;
    243 }
    244 
    245 void
    246 wdcattach(parent, self, aux)
    247 	struct device *parent, *self;
    248 	void *aux;
    249 {
    250 	struct wdc_softc *wdc = (void *)self;
    251 	struct isa_attach_args *ia = aux;
    252 	struct wdc_attach_args wa;
    253 
    254 	printf("\n");
    255 
    256 	for (wa.wa_drive = 0; wa.wa_drive < 2; wa.wa_drive++)
    257 		(void)config_found(self, &wa, wdprint);
    258 
    259 	TAILQ_INIT(&wdc->sc_drives);
    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 	if (wdc->sc_flags & WDCF_ACTIVE)
    520 		untimeout(wdctimeout, wdc);
    521 	else
    522 		wdc->sc_flags |= WDCF_ACTIVE;
    523 	timeout(wdctimeout, wdc, WAITTIME);
    524 
    525 	/* Do control operations specially. */
    526 	if (wd->sc_state < OPEN) {
    527 		/*
    528 		 * Actually, we want to be careful not to mess with the control
    529 		 * state if the device is currently busy, but we can assume
    530 		 * that we never get to this point if that's the case.
    531 		 */
    532 		(void) wdcontrol(wd);
    533 		return;
    534 	}
    535 
    536 	/*
    537 	 * WDCF_ERROR is set by wdcunwedge() and wdcintr() when an error is
    538 	 * encountered.  If we are in multi-sector mode, then we switch to
    539 	 * single-sector mode and retry the operation from the start.
    540 	 */
    541 	if (wdc->sc_flags & WDCF_ERROR) {
    542 		wdc->sc_flags &= ~WDCF_ERROR;
    543 		if ((wdc->sc_flags & WDCF_SINGLE) == 0) {
    544 			wdc->sc_flags |= WDCF_SINGLE;
    545 			wd->sc_skip = wd->sc_mskip = 0;
    546 		}
    547 	}
    548 
    549 	if (wd->sc_skip == 0) {
    550 #ifdef WDDEBUG
    551 		printf("\n%s: wdcstart %s %d@%d; map ", wd->sc_dev.dv_xname,
    552 		    (bp->b_flags & B_READ) ? "read" : "write", bp->b_bcount,
    553 		    bp->b_blkno);
    554 #endif
    555 		wd->sc_bcount = bp->b_bcount;
    556 #ifdef INSTRUMENT
    557 		dk_busy |= (1 << wd->sc_dev.dv_unit);
    558 		dk_wds[wd->sc_dev.dv_unit] += bp->b_bcount >> 6;
    559 #endif
    560 	} else {
    561 #ifdef WDDEBUG
    562 		printf(" %d)%x", wd->sc_skip, inb(wd->sc_iobase+wd_altsts));
    563 #endif
    564 	}
    565 
    566 	if (wd->sc_mskip == 0) {
    567 		wd->sc_mbcount = wd->sc_bcount;
    568 		/* If multi-sector, try to cluster. */
    569 		if ((wdc->sc_flags & WDCF_SINGLE) == 0) {
    570 			struct buf *oldbp, *nextbp;
    571 			oldbp = bp;
    572 			nextbp = bp->b_actf;
    573 			oldbp->b_flags |= B_XXX;
    574 			while (nextbp && oldbp->b_dev == nextbp->b_dev &&
    575 			    nextbp->b_blkno ==
    576 			    (oldbp->b_blkno + (oldbp->b_bcount / wd->sc_dk.dk_label.d_secsize)) &&
    577 			    (oldbp->b_flags & B_READ) == (nextbp->b_flags & B_READ)) {
    578 				if ((wd->sc_mbcount + nextbp->b_bcount) / wd->sc_dk.dk_label.d_secsize >= 240)
    579 					break;
    580 				wd->sc_mbcount += nextbp->b_bcount;
    581 				nextbp->b_flags |= B_XXX;
    582 				oldbp = nextbp;
    583 				nextbp = nextbp->b_actf;
    584 			}
    585 		}
    586 	}
    587 
    588 	/* If starting a multisector transfer, or doing single transfers. */
    589 	if (wd->sc_mskip == 0 || (wdc->sc_flags & WDCF_SINGLE)) {
    590 		struct disklabel *lp;
    591 		long blkno, nblks;
    592 		long cylin, head, sector;
    593 		int command;
    594 
    595 		lp = &wd->sc_dk.dk_label;
    596 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE) + wd->sc_skip;
    597 		if (WDPART(bp->b_dev) != RAW_PART)
    598 			blkno += lp->d_partitions[WDPART(bp->b_dev)].p_offset;
    599 		if (wdc->sc_flags & WDCF_SINGLE)
    600 			nblks = 1;
    601 		else
    602 			nblks = howmany(wd->sc_mbcount, lp->d_secsize);
    603 
    604 		/*
    605 		 * Check for bad sectors if we have them, and not formatting.  Only do
    606 		 * this in single-sector mode, or when starting a multiple-sector
    607 		 * transfer.
    608 		 */
    609 		if ((wd->sc_flags & WDF_BADSECT)
    610 #ifdef B_FORMAT
    611 		    && (bp->b_flags & B_FORMAT) == 0
    612 #endif
    613 		    ) {
    614 			long blkdiff;
    615 			int i;
    616 
    617 			for (i = 0; (blkdiff = wd->sc_badsect[i]) != -1; i++) {
    618 				blkdiff -= blkno;
    619 				if (blkdiff < 0)
    620 					continue;
    621 				if (blkdiff >= nblks)
    622 					break;
    623 				if (blkdiff == 0) {
    624 					/* Replace current block of transfer. */
    625 					blkno =
    626 					    lp->d_secperunit - lp->d_nsectors - i - 1;
    627 					if (wdc->sc_flags & WDCF_SINGLE)
    628 						break;
    629 				} else {
    630 					/* If clustered, try unclustering. */
    631 					if (wd->sc_mbcount > wd->sc_bcount) {
    632 						nblks = howmany(wd->sc_bcount, lp->d_secsize);
    633 						if (blkdiff >= nblks) {
    634 							/* Unclustering was enough. */
    635 							wd->sc_mbcount = wd->sc_bcount;
    636 							break;
    637 						}
    638 					}
    639 					/* Bad block inside transfer. */
    640 				}
    641 				/* Force single-sector mode. */
    642 				wd->sc_mbcount = wd->sc_bcount;
    643 				wdc->sc_flags |= WDCF_SINGLE;
    644 				nblks = 1;
    645 			}
    646 			/* Tranfer is okay now. */
    647 		}
    648 
    649 		cylin = blkno / lp->d_secpercyl;
    650 		head = (blkno % lp->d_secpercyl) / lp->d_nsectors;
    651 		sector = blkno % lp->d_nsectors;
    652 		sector++;	/* Sectors begin with 1, not 0. */
    653 
    654 #ifdef INSTRUMENT
    655 		++dk_seek[wd->sc_dev.dv_unit];
    656 		++dk_xfer[wd->sc_dev.dv_unit];
    657 #endif
    658 
    659 #ifdef B_FORMAT
    660 		if (bp->b_flags & B_FORMAT) {
    661 			sector = lp->d_gap3;
    662 			nblks = lp->d_nsectors;
    663 			command = WDCC_FORMAT;
    664 		} else
    665 #endif
    666 			command =
    667 			    (bp->b_flags & B_READ) ? WDCC_READ : WDCC_WRITE;
    668 
    669 		/* Initiate command! */
    670 		if (wdcommand(wd, cylin, head, sector, nblks, command) != 0) {
    671 			wderror(wd, NULL,
    672 			    "wdcstart: timeout waiting for unbusy");
    673 			wdcunwedge(wdc);
    674 			return;
    675 		}
    676 #ifdef WDDEBUG
    677 		printf("sector %d cylin %d head %d addr %x sts %x\n", sector,
    678 		    cylin, head, bp->b_data, inb(wd->sc_iobase+wd_altsts));
    679 #endif
    680 	}
    681 
    682 	/* If this is a read operation, just go away until it's done. */
    683 	if (bp->b_flags & B_READ)
    684 		return;
    685 
    686 	if (wait_for_drq(wdc) < 0) {
    687 		wderror(wd, NULL, "wdcstart: timeout waiting for drq");
    688 		wdcunwedge(wdc);
    689 		return;
    690 	}
    691 
    692 	/* Then send it! */
    693 	outsw(wdc->sc_iobase+wd_data, bp->b_data + wd->sc_skip * DEV_BSIZE,
    694 	    DEV_BSIZE / sizeof(short));
    695 }
    696 
    697 /*
    698  * Interrupt routine for the controller.  Acknowledge the interrupt, check for
    699  * errors on the current operation, mark it done if necessary, and start the
    700  * next request.  Also check for a partially done transfer, and continue with
    701  * the next chunk if so.
    702  */
    703 int
    704 wdcintr(wdc)
    705 	struct wdc_softc *wdc;
    706 {
    707 	struct wd_softc *wd;
    708 	struct buf *bp;
    709 
    710 	if ((wdc->sc_flags & WDCF_ACTIVE) == 0) {
    711 		/* Clear the pending interrupt. */
    712 		(void) inb(wdc->sc_iobase+wd_status);
    713 		return 0;
    714 	}
    715 
    716 	wd = wdc->sc_drives.tqh_first;
    717 	bp = wd->sc_q.b_actf;
    718 
    719 #ifdef WDDEBUG
    720 	printf("I%d ", ctrlr);
    721 #endif
    722 
    723 	if (wait_for_unbusy(wdc) < 0) {
    724 		wderror(wd, NULL, "wdcintr: timeout waiting for unbusy");
    725 		wdc->sc_status |= WDCS_ERR;	/* XXX */
    726 	}
    727 
    728 	/* Is it not a transfer, but a control operation? */
    729 	if (wd->sc_state < OPEN) {
    730 		if (wdcontrol(wd))
    731 			wdcstart(wdc);
    732 		return 1;
    733 	}
    734 
    735 	wdc->sc_flags &= ~WDCF_ACTIVE;
    736 	untimeout(wdctimeout, wdc);
    737 
    738 	/* Have we an error? */
    739 	if (wdc->sc_status & WDCS_ERR) {
    740 	lose:
    741 #ifdef WDDEBUG
    742 		wderror(wd, NULL, "wdcintr");
    743 #endif
    744 		if ((wdc->sc_flags & WDCF_SINGLE) == 0) {
    745 			wdc->sc_flags |= WDCF_ERROR;
    746 			goto restart;
    747 		}
    748 
    749 #ifdef B_FORMAT
    750 		if (bp->b_flags & B_FORMAT)
    751 			goto bad;
    752 #endif
    753 
    754 		if (++wdc->sc_errors < WDIORETRIES)
    755 			goto restart;
    756 		wderror(wd, bp, "hard error");
    757 
    758 	bad:
    759 		bp->b_error = EIO;
    760 		bp->b_flags |= B_ERROR;
    761 		goto done;
    762 	}
    763 
    764 	if (wdc->sc_status & WDCS_ECCCOR)
    765 		wderror(wd, bp, "soft ecc");
    766 
    767 	/* If this was a read, fetch the data. */
    768 	if (bp->b_flags & B_READ) {
    769 		/* Ready to receive data? */
    770 		if ((wdc->sc_status & (WDCS_READY | WDCS_SEEKCMPLT | WDCS_DRQ))
    771 		    != (WDCS_READY | WDCS_SEEKCMPLT | WDCS_DRQ)) {
    772 			wderror(wd, NULL, "wdcintr: read intr before drq");
    773 			wdcunwedge(wdc);
    774 			return 1;
    775 		}
    776 
    777 		/* Suck in data. */
    778 		insw(wdc->sc_iobase+wd_data,
    779 		    bp->b_data + wd->sc_skip * DEV_BSIZE,
    780 		    DEV_BSIZE / sizeof(short));
    781 	}
    782 
    783 	/* If we encountered any abnormalities, flag it as a soft error. */
    784 	if (wdc->sc_errors) {
    785 		wderror(wd, bp, "soft error");
    786 		wdc->sc_errors = 0;
    787 	}
    788 
    789 	/* Ready for the next block, if any. */
    790 	wd->sc_skip++;
    791 	wd->sc_mskip++;
    792 	wd->sc_bcount -= DEV_BSIZE;
    793 	wd->sc_mbcount -= DEV_BSIZE;
    794 
    795 	/* See if more to transfer. */
    796 	if (wd->sc_bcount > 0)
    797 		goto restart;
    798 
    799 done:
    800 	/* Done with this transfer, with or without error. */
    801 	wdfinish(wd, bp);
    802 
    803 restart:
    804 	/* Start the next transfer, if any. */
    805 	wdcstart(wdc);
    806 
    807 	return 1;
    808 }
    809 
    810 /*
    811  * Initialize a drive.
    812  */
    813 int
    814 wdopen(dev, flag, fmt, p)
    815 	dev_t dev;
    816 	int flag, fmt;
    817 	struct proc *p;
    818 {
    819 	int lunit;
    820 	struct wd_softc *wd;
    821 	int part = WDPART(dev);
    822 	struct partition *pp;
    823 	char *msg;
    824 	int error;
    825 
    826 	lunit = WDUNIT(dev);
    827 	if (lunit >= wdcd.cd_ndevs)
    828 		return ENXIO;
    829 	wd = wdcd.cd_devs[lunit];
    830 	if (wd == 0)
    831 		return ENXIO;
    832 
    833 	if ((wd->sc_flags & WDF_BSDLABEL) == 0) {
    834 		wd->sc_flags |= WDF_WRITEPROT;
    835 		wd->sc_q.b_actf = NULL;
    836 
    837 		/*
    838 		 * Use the default sizes until we've read the label, or longer
    839 		 * if there isn't one there.
    840 		 */
    841 		bzero(&wd->sc_dk.dk_label, sizeof(wd->sc_dk.dk_label));
    842 		wd->sc_dk.dk_label.d_type = DTYPE_ST506;
    843 		wd->sc_dk.dk_label.d_ncylinders = 1024;
    844 		wd->sc_dk.dk_label.d_secsize = DEV_BSIZE;
    845 		wd->sc_dk.dk_label.d_ntracks = 8;
    846 		wd->sc_dk.dk_label.d_nsectors = 17;
    847 		wd->sc_dk.dk_label.d_secpercyl = 17*8;
    848 		wd->sc_dk.dk_label.d_secperunit = 17*8*1024;
    849 		wd->sc_state = RECAL;
    850 
    851 		/* Read label using "raw" partition. */
    852 		msg = readdisklabel(WDLABELDEV(dev), wdstrategy,
    853 		    &wd->sc_dk.dk_label, &wd->sc_dk.dk_cpulabel);
    854 		if (msg) {
    855 			/*
    856 			 * This probably happened because the drive's default
    857 			 * geometry doesn't match the DOS geometry.  We
    858 			 * assume the DOS geometry is now in the label and try
    859 			 * again.  XXX This is a kluge.
    860 			 */
    861 			if (wd->sc_state > GEOMETRY)
    862 				wd->sc_state = GEOMETRY;
    863 			msg = readdisklabel(WDLABELDEV(dev), wdstrategy,
    864 			    &wd->sc_dk.dk_label, &wd->sc_dk.dk_cpulabel);
    865 		}
    866 		if (msg) {
    867 			log(LOG_WARNING, "%s: cannot find label (%s)\n",
    868 			    wd->sc_dev.dv_xname, msg);
    869 			if (part != RAW_PART)
    870 				return EINVAL;	/* XXX needs translation */
    871 		} else {
    872 			if (wd->sc_state > GEOMETRY)
    873 				wd->sc_state = GEOMETRY;
    874 			wd->sc_flags |= WDF_BSDLABEL;
    875 			wd->sc_flags &= ~WDF_WRITEPROT;
    876 			if (wd->sc_dk.dk_label.d_flags & D_BADSECT)
    877 				wd->sc_flags |= WDF_BADSECT;
    878 		}
    879 	}
    880 
    881 	if (wd->sc_flags & WDF_BADSECT)
    882 		bad144intern(wd);
    883 
    884 	/*
    885 	 * Warn if a partition is opened that overlaps another partition which
    886 	 * is open unless one is the "raw" partition (whole disk).
    887 	 */
    888 	if ((wd->sc_dk.dk_openmask & (1 << part)) == 0 && part != RAW_PART) {
    889 		int start, end;
    890 
    891 		pp = &wd->sc_dk.dk_label.d_partitions[part];
    892 		start = pp->p_offset;
    893 		end = pp->p_offset + pp->p_size;
    894 		for (pp = wd->sc_dk.dk_label.d_partitions;
    895 		    pp < &wd->sc_dk.dk_label.d_partitions[wd->sc_dk.dk_label.d_npartitions];
    896 		    pp++) {
    897 			if (pp->p_offset + pp->p_size <= start ||
    898 			    pp->p_offset >= end)
    899 				continue;
    900 			if (pp - wd->sc_dk.dk_label.d_partitions == RAW_PART)
    901 				continue;
    902 			if (wd->sc_dk.dk_openmask & (1 << (pp - wd->sc_dk.dk_label.d_partitions)))
    903 				log(LOG_WARNING,
    904 				    "%s%c: overlaps open partition (%c)\n",
    905 				    wd->sc_dev.dv_xname, part + 'a',
    906 				    pp - wd->sc_dk.dk_label.d_partitions + 'a');
    907 		}
    908 	}
    909 	if (part != RAW_PART &&
    910 	    (part >= wd->sc_dk.dk_label.d_npartitions ||
    911 	     wd->sc_dk.dk_label.d_partitions[part].p_fstype == FS_UNUSED)) {
    912 		error = ENXIO;
    913 		goto bad;
    914 	}
    915 
    916 	/* Insure only one open at a time. */
    917 	switch (fmt) {
    918 	case S_IFCHR:
    919 		wd->sc_dk.dk_copenmask |= (1 << part);
    920 		break;
    921 	case S_IFBLK:
    922 		wd->sc_dk.dk_bopenmask |= (1 << part);
    923 		break;
    924 	}
    925 	wd->sc_dk.dk_openmask = wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
    926 
    927 	return 0;
    928 
    929 bad:
    930 	return error;
    931 }
    932 
    933 /*
    934  * Implement operations other than read/write.
    935  * Called from wdcstart or wdcintr during opens and formats.
    936  * Uses finite-state-machine to track progress of operation in progress.
    937  * Returns 0 if operation still in progress, 1 if completed.
    938  */
    939 static int
    940 wdcontrol(wd)
    941 	struct wd_softc *wd;
    942 {
    943 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
    944 
    945 	switch (wd->sc_state) {
    946 	case RECAL:			/* Set SDH, step rate, do restore. */
    947 		if (wdcommand(wd, 0, 0, 0, 0, WDCC_RESTORE | WD_STEP) != 0) {
    948 			wderror(wd, NULL, "wdcontrol: wdcommand failed");
    949 			wdcunwedge(wdc);
    950 			return 0;
    951 		}
    952 		wd->sc_state = RECAL_WAIT;
    953 		return 0;
    954 
    955 	case RECAL_WAIT:
    956 		if (wdc->sc_status & WDCS_ERR) {
    957 			wderror(wd, NULL, "wdcontrol: recal failed");
    958 			wdcunwedge(wdc);
    959 			return 0;
    960 		}
    961 		/* fall through */
    962 	case GEOMETRY:
    963 		if (wdsetctlr(wd) != 0) {
    964 			/* Already printed a message. */
    965 			wdcunwedge(wdc);
    966 			return 0;
    967 		}
    968 		wd->sc_state = GEOMETRY_WAIT;
    969 		return 0;
    970 
    971 	case GEOMETRY_WAIT:
    972 		if (wdc->sc_status & WDCS_ERR) {
    973 			wderror(wd, NULL, "wdcontrol: geometry failed");
    974 			wdcunwedge(wdc);
    975 			return 0;
    976 		}
    977 
    978 		wdc->sc_errors = 0;
    979 		wd->sc_state = OPEN;
    980 		/*
    981 		 * The rest of the initialization can be done by normal means.
    982 		 */
    983 		return 1;
    984 	}
    985 
    986 #ifdef DIAGNOSTIC
    987 	panic("wdcontrol: impossible");
    988 #endif
    989 }
    990 
    991 /*
    992  * Send a command and wait uninterruptibly until controller is finished.
    993  * Return -1 if controller busy for too long, otherwise return non-zero if
    994  * error.  Intended for brief controller commands at critical points.
    995  * Assumes interrupts are blocked.
    996  */
    997 static int
    998 wdcommand(wd, cylin, head, sector, count, cmd)
    999 	struct wd_softc *wd;
   1000 	int cylin, head, sector, count;
   1001 	int cmd;
   1002 {
   1003 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
   1004 	int stat;
   1005 	u_short iobase;
   1006 
   1007 	/* Select drive. */
   1008 	iobase = wdc->sc_iobase;
   1009 	outb(iobase+wd_sdh, WDSD_IBM | (wd->sc_drive << 4) | head);
   1010 
   1011 	/* Wait for it to become ready to accept a command. */
   1012 	if (cmd == WDCC_DIAGNOSE || cmd == WDCC_IDC)
   1013 		stat = wait_for_unbusy(wdc);
   1014 	else
   1015 		stat = wdcwait(wdc, WDCS_READY);
   1016 	if (stat < 0)
   1017 		return -1;
   1018 
   1019 	/* Load parameters. */
   1020 	outb(iobase+wd_precomp, wd->sc_dk.dk_label.d_precompcyl / 4);
   1021 	outb(iobase+wd_cyl_lo, cylin);
   1022 	outb(iobase+wd_cyl_hi, cylin >> 8);
   1023 	outb(iobase+wd_sector, sector);
   1024 	outb(iobase+wd_seccnt, count);
   1025 
   1026 	/* Send command, await results. */
   1027 	outb(iobase+wd_command, cmd);
   1028 
   1029 	return 0;
   1030 }
   1031 
   1032 /*
   1033  * Issue IDC to drive to tell it just what geometry it is to be.
   1034  */
   1035 static int
   1036 wdsetctlr(wd)
   1037 	struct wd_softc *wd;
   1038 {
   1039 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
   1040 
   1041 #ifdef WDDEBUG
   1042 	printf("wd(%d,%d) C%dH%dS%d\n", wd->sc_ctrlr, wd->sc_drive,
   1043 	    wd->sc_dk.dk_label.d_ncylinders, wd->sc_dk.dk_label.d_ntracks,
   1044 	    wd->sc_dk.dk_label.d_nsectors);
   1045 #endif
   1046 
   1047 	if (wdcommand(wd, wd->sc_dk.dk_label.d_ncylinders,
   1048 	    wd->sc_dk.dk_label.d_ntracks - 1, 0, wd->sc_dk.dk_label.d_nsectors,
   1049 	    WDCC_IDC) != 0) {
   1050 		wderror(wd, NULL, "wdsetctlr: wdcommand failed");
   1051 		return -1;
   1052 	}
   1053 
   1054 	return 0;
   1055 }
   1056 
   1057 /*
   1058  * Issue READP to drive to ask it what it is.
   1059  */
   1060 static int
   1061 wdgetctlr(wd)
   1062 	struct wd_softc *wd;
   1063 {
   1064 	struct wdc_softc *wdc = (void *)wd->sc_dev.dv_parent;
   1065 	int i;
   1066 	char tb[DEV_BSIZE];
   1067 	struct wdparams *wp;
   1068 
   1069 	if (wdcommand(wd, 0, 0, 0, 0, WDCC_READP) != 0 ||
   1070 	    wait_for_drq(wdc) != 0) {
   1071 		/*
   1072 		 * If WDCC_READP fails then we might have an old drive so we
   1073 		 * try a seek to 0; if that passes then the drive is there but
   1074 		 * it's OLD AND KRUSTY.
   1075 		 */
   1076 		if (wdcommand(wd, 0, 0, 0, 0, WDCC_RESTORE | WD_STEP) != 0 ||
   1077 		    wait_for_ready(wdc) != 0)
   1078 			return -1;
   1079 
   1080 		strncpy(wd->sc_dk.dk_label.d_typename, "ST506",
   1081 		    sizeof wd->sc_dk.dk_label.d_typename);
   1082 		strncpy(wd->sc_params.wdp_model, "Unknown Type",
   1083 		    sizeof wd->sc_params.wdp_model);
   1084 		wd->sc_dk.dk_label.d_type = DTYPE_ST506;
   1085 	} else {
   1086 		/* Obtain parameters. */
   1087 		wp = &wd->sc_params;
   1088 		insw(wdc->sc_iobase+wd_data, tb, sizeof(tb) / sizeof(short));
   1089 		bcopy(tb, wp, sizeof(struct wdparams));
   1090 
   1091 		/* Shuffle string byte order. */
   1092 		for (i = 0; i < sizeof(wp->wdp_model); i += 2) {
   1093 			u_short *p;
   1094 			p = (u_short *)(wp->wdp_model + i);
   1095 			*p = ntohs(*p);
   1096 		}
   1097 
   1098 		strncpy(wd->sc_dk.dk_label.d_typename, "ESDI/IDE",
   1099 		    sizeof wd->sc_dk.dk_label.d_typename);
   1100 		wd->sc_dk.dk_label.d_type = DTYPE_ESDI;
   1101 		bcopy(wp->wdp_model+20, wd->sc_dk.dk_label.d_packname, 14-1);
   1102 
   1103 		/* Update disklabel given drive information. */
   1104 		wd->sc_dk.dk_label.d_ncylinders =
   1105 		    wp->wdp_fixedcyl + wp->wdp_removcyl /*+- 1*/;
   1106 		wd->sc_dk.dk_label.d_secsize = DEV_BSIZE;
   1107 		wd->sc_dk.dk_label.d_ntracks = wp->wdp_heads;
   1108 		wd->sc_dk.dk_label.d_nsectors = wp->wdp_sectors;
   1109 		wd->sc_dk.dk_label.d_secpercyl =
   1110 		    wd->sc_dk.dk_label.d_ntracks * wd->sc_dk.dk_label.d_nsectors;
   1111 		wd->sc_dk.dk_label.d_partitions[1].p_size =
   1112 		    wd->sc_dk.dk_label.d_secpercyl * wp->wdp_sectors;
   1113 		wd->sc_dk.dk_label.d_partitions[1].p_offset = 0;
   1114 	}
   1115 
   1116 #if 0
   1117 	printf("gc %x cyl %d trk %d sec %d type %d sz %d model %s\n",
   1118 	    wp->wdp_config, wp->wdp_fixedcyl + wp->wdp_removcyl, wp->wdp_heads,
   1119 	    wp->wdp_sectors, wp->wdp_cntype, wp->wdp_cnsbsz, wp->wdp_model);
   1120 #endif
   1121 
   1122 	wd->sc_dk.dk_label.d_subtype |= DSTYPE_GEOMETRY;
   1123 
   1124 	/* XXX sometimes possibly needed */
   1125 	(void) inb(wdc->sc_iobase+wd_status);
   1126 
   1127 	return 0;
   1128 }
   1129 
   1130 int
   1131 wdclose(dev, flag, fmt)
   1132 	dev_t dev;
   1133 	int flag, fmt;
   1134 {
   1135 	struct wd_softc *wd = wdcd.cd_devs[WDUNIT(dev)];
   1136 	int part = WDPART(dev);
   1137 
   1138 	switch (fmt) {
   1139 	case S_IFCHR:
   1140 		wd->sc_dk.dk_copenmask &= ~(1 << part);
   1141 		break;
   1142 	case S_IFBLK:
   1143 		wd->sc_dk.dk_bopenmask &= ~(1 << part);
   1144 		break;
   1145 	}
   1146 	wd->sc_dk.dk_openmask = wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1147 
   1148 	return 0;
   1149 }
   1150 
   1151 int
   1152 wdioctl(dev, cmd, addr, flag, p)
   1153 	dev_t dev;
   1154 	int cmd;
   1155 	caddr_t addr;
   1156 	int flag;
   1157 	struct proc *p;
   1158 {
   1159 	int lunit = WDUNIT(dev);
   1160 	struct wd_softc *wd = wdcd.cd_devs[lunit];
   1161 	int error;
   1162 
   1163 	switch (cmd) {
   1164 	case DIOCSBAD:
   1165 		if ((flag & FWRITE) == 0)
   1166 			return EBADF;
   1167 		wd->sc_dk.dk_cpulabel.bad = *(struct dkbad *)addr;
   1168 		wd->sc_flags |= WDF_BADSECT;
   1169 		bad144intern(wd);
   1170 		return 0;
   1171 
   1172 	case DIOCGDINFO:
   1173 		*(struct disklabel *)addr = wd->sc_dk.dk_label;
   1174 		return 0;
   1175 
   1176 	case DIOCGPART:
   1177 		((struct partinfo *)addr)->disklab = &wd->sc_dk.dk_label;
   1178 		((struct partinfo *)addr)->part =
   1179 		    &wd->sc_dk.dk_label.d_partitions[WDPART(dev)];
   1180 		return 0;
   1181 
   1182 	case DIOCSDINFO:
   1183 		if ((flag & FWRITE) == 0)
   1184 			return EBADF;
   1185 		error = setdisklabel(&wd->sc_dk.dk_label,
   1186 		    (struct disklabel *)addr,
   1187 		    /*(wd->sc_flags & WDF_BSDLABEL) ? wd->sc_dk.dk_openmask : */0,
   1188 		    &wd->sc_dk.dk_cpulabel);
   1189 		if (error == 0) {
   1190 			wd->sc_flags |= WDF_BSDLABEL;
   1191 			if (wd->sc_state > GEOMETRY)
   1192 				wd->sc_state = GEOMETRY;
   1193 		}
   1194 		return error;
   1195 
   1196 	case DIOCWLABEL:
   1197 		wd->sc_flags &= ~WDF_WRITEPROT;
   1198 		if ((flag & FWRITE) == 0)
   1199 			return EBADF;
   1200 		if (*(int *)addr)
   1201 			wd->sc_flags |= WDF_WLABEL;
   1202 		else
   1203 			wd->sc_flags &= ~WDF_WLABEL;
   1204 		return 0;
   1205 
   1206 	case DIOCWDINFO:
   1207 		wd->sc_flags &= ~WDF_WRITEPROT;
   1208 		if ((flag & FWRITE) == 0)
   1209 			return EBADF;
   1210 		error = setdisklabel(&wd->sc_dk.dk_label,
   1211 		    (struct disklabel *)addr,
   1212 		    /*(wd->sc_flags & WDF_BSDLABEL) ? wd->sc_dk.dk_openmask : */0,
   1213 		    &wd->sc_dk.dk_cpulabel);
   1214 		if (error == 0) {
   1215 			wd->sc_flags |= WDF_BSDLABEL;
   1216 			if (wd->sc_state > GEOMETRY)
   1217 				wd->sc_state = GEOMETRY;
   1218 
   1219 			/* Simulate opening partition 0 so write succeeds. */
   1220 			wd->sc_dk.dk_openmask |= (1 << 0);	/* XXX */
   1221 			error = writedisklabel(WDLABELDEV(dev), wdstrategy,
   1222 			    &wd->sc_dk.dk_label, &wd->sc_dk.dk_cpulabel);
   1223 			wd->sc_dk.dk_openmask =
   1224 			    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1225 		}
   1226 		return error;
   1227 
   1228 #ifdef notyet
   1229 	case DIOCGDINFOP:
   1230 		*(struct disklabel **)addr = &wd->sc_dk.dk_label;
   1231 		return 0;
   1232 
   1233 	case DIOCWFORMAT:
   1234 		if ((flag & FWRITE) == 0)
   1235 			return EBADF;
   1236 	{
   1237 		register struct format_op *fop;
   1238 		struct iovec aiov;
   1239 		struct uio auio;
   1240 
   1241 		fop = (struct format_op *)addr;
   1242 		aiov.iov_base = fop->df_buf;
   1243 		aiov.iov_len = fop->df_count;
   1244 		auio.uio_iov = &aiov;
   1245 		auio.uio_iovcnt = 1;
   1246 		auio.uio_resid = fop->df_count;
   1247 		auio.uio_segflg = 0;
   1248 		auio.uio_offset =
   1249 		    fop->df_startblk * wd->sc_dk.dk_label.d_secsize;
   1250 		auio.uio_procp = p;
   1251 		error = physio(wdformat, NULL, dev, B_WRITE, minphys,
   1252 		    &auio);
   1253 		fop->df_count -= auio.uio_resid;
   1254 		fop->df_reg[0] = wdc->sc_status;
   1255 		fop->df_reg[1] = wdc->sc_error;
   1256 		return error;
   1257 	}
   1258 #endif
   1259 
   1260 	default:
   1261 		return ENOTTY;
   1262 	}
   1263 
   1264 #ifdef DIAGNOSTIC
   1265 	panic("wdioctl: impossible");
   1266 #endif
   1267 }
   1268 
   1269 #ifdef B_FORMAT
   1270 int
   1271 wdformat(struct buf *bp)
   1272 {
   1273 
   1274 	bp->b_flags |= B_FORMAT;
   1275 	return wdstrategy(bp);
   1276 }
   1277 #endif
   1278 
   1279 int
   1280 wdsize(dev)
   1281 	dev_t dev;
   1282 {
   1283 	int lunit = WDUNIT(dev), part = WDPART(dev);
   1284 	struct wd_softc *wd;
   1285 
   1286 	if (lunit >= wdcd.cd_ndevs)
   1287 		return -1;
   1288 	wd = wdcd.cd_devs[lunit];
   1289 	if (wd == 0)
   1290 		return -1;
   1291 
   1292 	if (wd->sc_state < OPEN || (wd->sc_flags & WDF_BSDLABEL) == 0) {
   1293 		int val;
   1294 		val = wdopen(MAKEWDDEV(major(dev), lunit, RAW_PART), FREAD,
   1295 		    S_IFBLK, 0);
   1296 		/* XXX Clear the open flag? */
   1297 		if (val != 0)
   1298 			return -1;
   1299 	}
   1300 
   1301 	if ((wd->sc_flags & (WDF_WRITEPROT | WDF_BSDLABEL)) != WDF_BSDLABEL)
   1302 		return -1;
   1303 
   1304 	return (int)wd->sc_dk.dk_label.d_partitions[part].p_size;
   1305 }
   1306 
   1307 /*
   1308  * Dump core after a system crash.
   1309  */
   1310 int
   1311 wddump(dev)
   1312 	dev_t dev;
   1313 {
   1314 	struct wd_softc *wd;	/* disk unit to do the IO */
   1315 	struct wdc_softc *wdc;
   1316 	long num;		/* number of sectors to write */
   1317 	int lunit, part;
   1318 	long blkoff, blkno;
   1319 	long cylin, head, sector;
   1320 	long secpertrk, secpercyl, nblocks;
   1321 	char *addr;
   1322 	static wddoingadump = 0;
   1323 	extern caddr_t CADDR1;
   1324 	extern pt_entry_t *CMAP1;
   1325 
   1326 	addr = (char *)0;	/* starting address */
   1327 
   1328 #if DO_NOT_KNOW_HOW
   1329 	/* Toss any characters present prior to dump, ie. non-blocking getc. */
   1330 	while (cngetc())
   1331 		;
   1332 #endif
   1333 
   1334 	lunit = WDUNIT(dev);
   1335 	/* Check for acceptable drive number. */
   1336 	if (lunit >= wdcd.cd_ndevs)
   1337 		return ENXIO;
   1338 	wd = wdcd.cd_devs[lunit];
   1339 	/* Was it ever initialized? */
   1340 	if (wd == 0 || wd->sc_state < OPEN || wd->sc_flags & WDF_WRITEPROT)
   1341 		return ENXIO;
   1342 
   1343 	wdc = (void *)wd->sc_dev.dv_parent;
   1344 
   1345 	/* Convert to disk sectors. */
   1346 	num = ctob(physmem) / wd->sc_dk.dk_label.d_secsize;
   1347 
   1348 	secpertrk = wd->sc_dk.dk_label.d_nsectors;
   1349 	secpercyl = wd->sc_dk.dk_label.d_secpercyl;
   1350 	part = WDPART(dev);
   1351 	nblocks = wd->sc_dk.dk_label.d_partitions[part].p_size;
   1352 	blkoff = wd->sc_dk.dk_label.d_partitions[part].p_offset;
   1353 
   1354 	/*printf("part %x, nblocks %d, dumplo %d, num %d\n", part, nblocks,
   1355 	    dumplo, num);*/
   1356 
   1357 	/* Check transfer bounds against partition size. */
   1358 	if (dumplo < 0 || dumplo + num > nblocks)
   1359 		return EINVAL;
   1360 
   1361 	if (wddoingadump)
   1362 		return EFAULT;
   1363 	wddoingadump = 1;
   1364 
   1365 	/* Recalibrate. */
   1366 	if (wdcommand(wd, 0, 0, 0, 0, WDCC_RESTORE | WD_STEP) != 0 ||
   1367 	    wait_for_ready(wdc) != 0 || wdsetctlr(wd) != 0 ||
   1368 	    wait_for_ready(wdc) != 0) {
   1369 		wderror(wd, NULL, "wddump: recal failed");
   1370 		return EIO;
   1371 	}
   1372 
   1373 	blkno = dumplo + blkoff;
   1374 	while (num > 0) {
   1375 		/* Compute disk address. */
   1376 		cylin = blkno / secpercyl;
   1377 		head = (blkno % secpercyl) / secpertrk;
   1378 		sector = blkno % secpertrk;
   1379 
   1380 		if (wd->sc_flags & WDF_BADSECT) {
   1381 			long newblk;
   1382 			int i;
   1383 
   1384 			for (i = 0; wd->sc_badsect[i] != -1; i++) {
   1385 				if (blkno < wd->sc_badsect[i]) {
   1386 					/* Sorted list, passed our block by. */
   1387 					break;
   1388 				} else if (blkno == wd->sc_badsect[i]) {
   1389 					newblk =
   1390 					    wd->sc_dk.dk_label.d_secperunit -
   1391 					    wd->sc_dk.dk_label.d_nsectors -
   1392 					    i - 1;
   1393 					cylin = newblk / secpercyl;
   1394 					head = (newblk % secpercyl) / secpertrk;
   1395 					sector = newblk % secpertrk;
   1396 					/* Found and replaced; done. */
   1397 					break;
   1398 				}
   1399 			}
   1400 		}
   1401 		sector++;		/* origin 1 */
   1402 
   1403 #ifdef notdef
   1404 		/* Let's just talk about this first. */
   1405 		printf("cylin %d, head %d, sector %d, addr 0x%x", cylin, head,
   1406 		    sector, addr);
   1407 #endif
   1408 		if (wdcommand(wd, cylin, head, sector, 1, WDCC_WRITE) != 0) {
   1409 			wderror(wd, NULL, "wddump: wdcommand failed");
   1410 			return EIO;
   1411 		}
   1412 		if (wait_for_drq(wdc) != 0) {
   1413 			wderror(wd, NULL, "wddump: timeout waiting for drq");
   1414 			return EIO;
   1415 		}
   1416 
   1417 #ifdef notdef	/* Cannot use this since this address was mapped differently. */
   1418 		pmap_enter(kernel_pmap, CADDR1, trunc_page(addr), VM_PROT_READ, TRUE);
   1419 #else
   1420 		*CMAP1 = PG_V | PG_KW | ctob((long)addr);
   1421 		tlbflush();
   1422 #endif
   1423 
   1424 		outsw(wdc->sc_iobase+wd_data, CADDR1 + ((int)addr & PGOFSET),
   1425 		    DEV_BSIZE / sizeof(short));
   1426 
   1427 		/* Check data request (should be done). */
   1428 		if (wait_for_ready(wdc) != 0) {
   1429 			wderror(wd, NULL, "wddump: timeout waiting for ready");
   1430 			return EIO;
   1431 		}
   1432 		if (wdc->sc_status & WDCS_DRQ) {
   1433 			wderror(wd, NULL, "wddump: extra drq");
   1434 			return EIO;
   1435 		}
   1436 
   1437 		if ((unsigned)addr % 1048576 == 0)
   1438 			printf("%d ", num / (1048576 / DEV_BSIZE));
   1439 
   1440 		/* Update block count. */
   1441 		num--;
   1442 		blkno++;
   1443 		(int)addr += DEV_BSIZE;
   1444 
   1445 #if DO_NOT_KNOW_HOW
   1446 		/* Operator aborting dump? non-blocking getc() */
   1447 		if (cngetc())
   1448 			return EINTR;
   1449 #endif
   1450 	}
   1451 	return 0;
   1452 }
   1453 
   1454 /*
   1455  * Internalize the bad sector table.
   1456  */
   1457 void
   1458 bad144intern(wd)
   1459 	struct wd_softc *wd;
   1460 {
   1461 	struct dkbad *bt = &wd->sc_dk.dk_cpulabel.bad;
   1462 	struct disklabel *lp = &wd->sc_dk.dk_label;
   1463 	int i = 0;
   1464 
   1465 	for (; i < 126; i++) {
   1466 		if (bt->bt_bad[i].bt_cyl == 0xffff)
   1467 			break;
   1468 		wd->sc_badsect[i] =
   1469 		    bt->bt_bad[i].bt_cyl * lp->d_secpercyl +
   1470 		    (bt->bt_bad[i].bt_trksec >> 8) * lp->d_nsectors +
   1471 		    (bt->bt_bad[i].bt_trksec & 0xff);
   1472 	}
   1473 	for (; i < 127; i++)
   1474 		wd->sc_badsect[i] = -1;
   1475 }
   1476 
   1477 static int
   1478 wdcreset(wdc)
   1479 	struct wdc_softc *wdc;
   1480 {
   1481 	u_short iobase = wdc->sc_iobase;
   1482 
   1483 	/* Reset the device. */
   1484 	outb(iobase+wd_ctlr, WDCTL_RST | WDCTL_IDS);
   1485 	delay(1000);
   1486 	outb(iobase+wd_ctlr, WDCTL_IDS);
   1487 	delay(1000);
   1488 	(void) inb(iobase+wd_error);
   1489 	outb(iobase+wd_ctlr, WDCTL_4BIT);
   1490 
   1491 	if (wait_for_unbusy(wdc) < 0) {
   1492 		printf("%s: reset failed\n", wdc->sc_dev.dv_xname);
   1493 		return 1;
   1494 	}
   1495 
   1496 	return 0;
   1497 }
   1498 
   1499 static void
   1500 wdcrestart(arg)
   1501 	void *arg;
   1502 {
   1503 	struct wdc_softc *wdc = (struct wdc_softc *)arg;
   1504 	int s;
   1505 
   1506 	s = splbio();
   1507 	wdcstart(wdc);
   1508 	splx(s);
   1509 }
   1510 
   1511 /*
   1512  * Unwedge the controller after an unexpected error.  We do this by resetting
   1513  * it, marking all drives for recalibration, and stalling the queue for a short
   1514  * period to give the reset time to finish.
   1515  * NOTE: We use a timeout here, so this routine must not be called during
   1516  * autoconfig or dump.
   1517  */
   1518 static void
   1519 wdcunwedge(wdc)
   1520 	struct wdc_softc *wdc;
   1521 {
   1522 	int lunit;
   1523 
   1524 	untimeout(wdctimeout, wdc);
   1525 	(void) wdcreset(wdc);
   1526 
   1527 	/* Schedule recalibrate for all drives on this controller. */
   1528 	for (lunit = 0; lunit < wdcd.cd_ndevs; lunit++) {
   1529 		struct wd_softc *wd = wdcd.cd_devs[lunit];
   1530 		if (!wd || (void *)wd->sc_dev.dv_parent != wdc)
   1531 			continue;
   1532 		if (wd->sc_state > RECAL)
   1533 			wd->sc_state = RECAL;
   1534 	}
   1535 
   1536 	wdc->sc_flags |= WDCF_ERROR;
   1537 	++wdc->sc_errors;
   1538 
   1539 	/* Wake up in a little bit and restart the operation. */
   1540 	timeout(wdcrestart, wdc, RECOVERYTIME);
   1541 }
   1542 
   1543 int
   1544 wdcwait(wdc, mask)
   1545 	struct wdc_softc *wdc;
   1546 	int mask;
   1547 {
   1548 	u_short iobase = wdc->sc_iobase;
   1549 	int timeout = 0;
   1550 	u_char status;
   1551 	extern int cold;
   1552 
   1553 	for (;;) {
   1554 		wdc->sc_status = status = inb(iobase+wd_status);
   1555 		if ((status & WDCS_BUSY) == 0 && (status & mask) == mask)
   1556 			break;
   1557 		if (++timeout > WDCNDELAY)
   1558 			return -1;
   1559 		delay(WDCDELAY);
   1560 	}
   1561 	if (status & WDCS_ERR) {
   1562 		wdc->sc_error = inb(iobase+wd_error);
   1563 		return WDCS_ERR;
   1564 	}
   1565 #ifdef WDCNDELAY_DEBUG
   1566 	/* After autoconfig, there should be no long delays. */
   1567 	if (!cold && timeout > WDCNDELAY_DEBUG)
   1568 		printf("%s: warning: busy-wait took %dus\n",
   1569 		    wdc->sc_dev.dv_xname, WDCDELAY * timeout);
   1570 #endif
   1571 	return 0;
   1572 }
   1573 
   1574 static void
   1575 wdctimeout(arg)
   1576 	void *arg;
   1577 {
   1578 	struct wdc_softc *wdc = (struct wdc_softc *)arg;
   1579 	int s;
   1580 
   1581 	s = splbio();
   1582 	wderror(wdc, NULL, "lost interrupt");
   1583 	wdcunwedge(wdc);
   1584 	splx(s);
   1585 }
   1586 
   1587 static void
   1588 wderror(dev, bp, msg)
   1589 	void *dev;
   1590 	struct buf *bp;
   1591 	char *msg;
   1592 {
   1593 	struct wd_softc *wd = dev;
   1594 	struct wdc_softc *wdc = dev;
   1595 
   1596 	if (bp)
   1597 		diskerr(bp, "wd", msg, LOG_PRINTF, wd->sc_skip,
   1598 		    &wd->sc_dk.dk_label);
   1599 	else
   1600 		printf("%s: %s: status %b error %b\n", wdc->sc_dev.dv_xname,
   1601 		    msg, wdc->sc_status, WDCS_BITS, wdc->sc_error, WDERR_BITS);
   1602 }
   1603