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