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