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