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