Home | History | Annotate | Line # | Download | only in ata
wd.c revision 1.293
      1 /*	$NetBSD: wd.c,v 1.293 2004/09/16 20:52:43 bouyer Exp $ */
      2 
      3 /*
      4  * Copyright (c) 1998, 2001 Manuel Bouyer.  All rights reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  * 1. Redistributions of source code must retain the above copyright
     10  *	notice, this list of conditions and the following disclaimer.
     11  * 2. Redistributions in binary form must reproduce the above copyright
     12  *	notice, this list of conditions and the following disclaimer in the
     13  *	documentation and/or other materials provided with the distribution.
     14  * 3. All advertising materials mentioning features or use of this software
     15  *	must display the following acknowledgement:
     16  *  This product includes software developed by Manuel Bouyer.
     17  * 4. The name of the author may not be used to endorse or promote products
     18  *	derived from this software without specific prior written permission.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 1998, 2003, 2004 The NetBSD Foundation, Inc.
     34  * All rights reserved.
     35  *
     36  * This code is derived from software contributed to The NetBSD Foundation
     37  * by Charles M. Hannum and by Onno van der Linden.
     38  *
     39  * Redistribution and use in source and binary forms, with or without
     40  * modification, are permitted provided that the following conditions
     41  * are met:
     42  * 1. Redistributions of source code must retain the above copyright
     43  *    notice, this list of conditions and the following disclaimer.
     44  * 2. Redistributions in binary form must reproduce the above copyright
     45  *    notice, this list of conditions and the following disclaimer in the
     46  *    documentation and/or other materials provided with the distribution.
     47  * 3. All advertising materials mentioning features or use of this software
     48  *    must display the following acknowledgement:
     49  *        This product includes software developed by the NetBSD
     50  *        Foundation, Inc. and its contributors.
     51  * 4. Neither the name of The NetBSD Foundation nor the names of its
     52  *    contributors may be used to endorse or promote products derived
     53  *    from this software without specific prior written permission.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     56  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     57  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     58  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     59  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     60  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     61  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     62  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     63  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     64  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     65  * POSSIBILITY OF SUCH DAMAGE.
     66  */
     67 
     68 #include <sys/cdefs.h>
     69 __KERNEL_RCSID(0, "$NetBSD: wd.c,v 1.293 2004/09/16 20:52:43 bouyer Exp $");
     70 
     71 #ifndef ATADEBUG
     72 #define ATADEBUG
     73 #endif /* ATADEBUG */
     74 
     75 #include "rnd.h"
     76 
     77 #include <sys/param.h>
     78 #include <sys/systm.h>
     79 #include <sys/kernel.h>
     80 #include <sys/conf.h>
     81 #include <sys/file.h>
     82 #include <sys/stat.h>
     83 #include <sys/ioctl.h>
     84 #include <sys/buf.h>
     85 #include <sys/uio.h>
     86 #include <sys/malloc.h>
     87 #include <sys/device.h>
     88 #include <sys/disklabel.h>
     89 #include <sys/disk.h>
     90 #include <sys/syslog.h>
     91 #include <sys/proc.h>
     92 #include <sys/vnode.h>
     93 #if NRND > 0
     94 #include <sys/rnd.h>
     95 #endif
     96 
     97 #include <machine/intr.h>
     98 #include <machine/bus.h>
     99 
    100 #include <dev/ata/atareg.h>
    101 #include <dev/ata/atavar.h>
    102 #include <dev/ata/wdvar.h>
    103 #include <dev/ic/wdcreg.h>
    104 #include <sys/ataio.h>
    105 #include "locators.h"
    106 
    107 #define	LBA48_THRESHOLD		(0xfffffff)	/* 128GB / DEV_BSIZE */
    108 
    109 #define	WDIORETRIES_SINGLE 4	/* number of retries before single-sector */
    110 #define	WDIORETRIES	5	/* number of retries before giving up */
    111 #define	RECOVERYTIME hz/2	/* time to wait before retrying a cmd */
    112 
    113 #define	WDUNIT(dev)		DISKUNIT(dev)
    114 #define	WDPART(dev)		DISKPART(dev)
    115 #define	WDMINOR(unit, part)	DISKMINOR(unit, part)
    116 #define	MAKEWDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
    117 
    118 #define	WDLABELDEV(dev)	(MAKEWDDEV(major(dev), WDUNIT(dev), RAW_PART))
    119 
    120 #define DEBUG_INTR   0x01
    121 #define DEBUG_XFERS  0x02
    122 #define DEBUG_STATUS 0x04
    123 #define DEBUG_FUNCS  0x08
    124 #define DEBUG_PROBE  0x10
    125 #ifdef ATADEBUG
    126 int wdcdebug_wd_mask = 0x0;
    127 #define ATADEBUG_PRINT(args, level) \
    128 	if (wdcdebug_wd_mask & (level)) \
    129 		printf args
    130 #else
    131 #define ATADEBUG_PRINT(args, level)
    132 #endif
    133 
    134 int	wdprobe(struct device *, struct cfdata *, void *);
    135 void	wdattach(struct device *, struct device *, void *);
    136 int	wddetach(struct device *, int);
    137 int	wdactivate(struct device *, enum devact);
    138 int	wdprint(void *, char *);
    139 void	wdperror(const struct wd_softc *);
    140 
    141 CFATTACH_DECL(wd, sizeof(struct wd_softc),
    142     wdprobe, wdattach, wddetach, wdactivate);
    143 
    144 extern struct cfdriver wd_cd;
    145 
    146 dev_type_open(wdopen);
    147 dev_type_close(wdclose);
    148 dev_type_read(wdread);
    149 dev_type_write(wdwrite);
    150 dev_type_ioctl(wdioctl);
    151 dev_type_strategy(wdstrategy);
    152 dev_type_dump(wddump);
    153 dev_type_size(wdsize);
    154 
    155 const struct bdevsw wd_bdevsw = {
    156 	wdopen, wdclose, wdstrategy, wdioctl, wddump, wdsize, D_DISK
    157 };
    158 
    159 const struct cdevsw wd_cdevsw = {
    160 	wdopen, wdclose, wdread, wdwrite, wdioctl,
    161 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
    162 };
    163 
    164 /*
    165  * Glue necessary to hook WDCIOCCOMMAND into physio
    166  */
    167 
    168 struct wd_ioctl {
    169 	LIST_ENTRY(wd_ioctl) wi_list;
    170 	struct buf wi_bp;
    171 	struct uio wi_uio;
    172 	struct iovec wi_iov;
    173 	atareq_t wi_atareq;
    174 	struct wd_softc *wi_softc;
    175 };
    176 
    177 LIST_HEAD(, wd_ioctl) wi_head;
    178 
    179 struct	wd_ioctl *wi_find(struct buf *);
    180 void	wi_free(struct wd_ioctl *);
    181 struct	wd_ioctl *wi_get(void);
    182 void	wdioctlstrategy(struct buf *);
    183 
    184 void  wdgetdefaultlabel(struct wd_softc *, struct disklabel *);
    185 void  wdgetdisklabel(struct wd_softc *);
    186 void  wdstart(void *);
    187 void  __wdstart(struct wd_softc*, struct buf *);
    188 void  wdrestart(void *);
    189 void  wddone(void *);
    190 int   wd_get_params(struct wd_softc *, u_int8_t, struct ataparams *);
    191 int   wd_standby(struct wd_softc *, int);
    192 int   wd_flushcache(struct wd_softc *, int);
    193 void  wd_shutdown(void *);
    194 
    195 int   wd_getcache(struct wd_softc *, int *);
    196 int   wd_setcache(struct wd_softc *, int);
    197 
    198 struct dkdriver wddkdriver = { wdstrategy };
    199 
    200 #ifdef HAS_BAD144_HANDLING
    201 static void bad144intern(struct wd_softc *);
    202 #endif
    203 
    204 #define	WD_QUIRK_SPLIT_MOD15_WRITE	0x0001	/* must split certain writes */
    205 
    206 /*
    207  * Quirk table for IDE drives.  Put more-specific matches first, since
    208  * a simple globbing routine is used for matching.
    209  */
    210 static const struct wd_quirk {
    211 	const char *wdq_match;		/* inquiry pattern to match */
    212 	int wdq_quirks;			/* drive quirks */
    213 } wd_quirk_table[] = {
    214 	/*
    215 	 * Some Seagate S-ATA drives have a PHY which can get confused
    216 	 * with the way data is packetized by some S-ATA controllers.
    217 	 *
    218 	 * The work-around is to split in two any write transfer whose
    219 	 * sector count % 15 == 1 (assuming 512 byte sectors).
    220 	 *
    221 	 * XXX This is an incomplete list.  There are at least a couple
    222 	 * XXX more model numbers.  If you have trouble with such transfers
    223 	 * XXX (8K is the most common) on Seagate S-ATA drives, please
    224 	 * XXX notify thorpej (at) NetBSD.org.
    225 	 */
    226 	{ "ST3120023AS",
    227 	  WD_QUIRK_SPLIT_MOD15_WRITE },
    228 	{ "ST380023AS",
    229 	  WD_QUIRK_SPLIT_MOD15_WRITE },
    230 
    231 	{ NULL,
    232 	  0 }
    233 };
    234 
    235 static const struct wd_quirk *
    236 wd_lookup_quirks(const char *name)
    237 {
    238 	const struct wd_quirk *wdq;
    239 	const char *estr;
    240 
    241 	for (wdq = wd_quirk_table; wdq->wdq_match != NULL; wdq++) {
    242 		/*
    243 		 * We only want exact matches (which include matches
    244 		 * against globbing characters).
    245 		 */
    246 		if (pmatch(name, wdq->wdq_match, &estr) == 2)
    247 			return (wdq);
    248 	}
    249 	return (NULL);
    250 }
    251 
    252 int
    253 wdprobe(struct device *parent, struct cfdata *match, void *aux)
    254 {
    255 	struct ata_device *adev = aux;
    256 
    257 	if (adev == NULL)
    258 		return 0;
    259 	if (adev->adev_bustype->bustype_type != SCSIPI_BUSTYPE_ATA)
    260 		return 0;
    261 
    262 	if (match->cf_loc[ATA_HLCF_DRIVE] != ATA_HLCF_DRIVE_DEFAULT &&
    263 	    match->cf_loc[ATA_HLCF_DRIVE] != adev->adev_drv_data->drive)
    264 		return 0;
    265 	return 1;
    266 }
    267 
    268 void
    269 wdattach(struct device *parent, struct device *self, void *aux)
    270 {
    271 	struct wd_softc *wd = (void *)self;
    272 	struct ata_device *adev= aux;
    273 	int i, blank;
    274 	char buf[41], pbuf[9], c, *p, *q;
    275 	const struct wd_quirk *wdq;
    276 	ATADEBUG_PRINT(("wdattach\n"), DEBUG_FUNCS | DEBUG_PROBE);
    277 
    278 	lockinit(&wd->sc_lock, PRIBIO | PCATCH, "wdlock", 0, 0);
    279 
    280 	callout_init(&wd->sc_restart_ch);
    281 	bufq_alloc(&wd->sc_q, BUFQ_DISK_DEFAULT_STRAT()|BUFQ_SORT_RAWBLOCK);
    282 #ifdef WD_SOFTBADSECT
    283 	SLIST_INIT(&wd->sc_bslist);
    284 #endif
    285 	wd->atabus = adev->adev_bustype;
    286 	wd->openings = adev->adev_openings;
    287 	wd->drvp = adev->adev_drv_data;
    288 
    289 	wd->drvp->drv_done = wddone;
    290 	wd->drvp->drv_softc = &wd->sc_dev;
    291 
    292 	aprint_naive("\n");
    293 
    294 	/* read our drive info */
    295 	if (wd_get_params(wd, AT_WAIT, &wd->sc_params) != 0) {
    296 		aprint_error("\n%s: IDENTIFY failed\n", wd->sc_dev.dv_xname);
    297 		return;
    298 	}
    299 
    300 	for (blank = 0, p = wd->sc_params.atap_model, q = buf, i = 0;
    301 	    i < sizeof(wd->sc_params.atap_model); i++) {
    302 		c = *p++;
    303 		if (c == '\0')
    304 			break;
    305 		if (c != ' ') {
    306 			if (blank) {
    307 				*q++ = ' ';
    308 				blank = 0;
    309 			}
    310 			*q++ = c;
    311 		} else
    312 			blank = 1;
    313 	}
    314 	*q++ = '\0';
    315 
    316 	aprint_normal(": <%s>\n", buf);
    317 
    318 	wdq = wd_lookup_quirks(buf);
    319 	if (wdq != NULL)
    320 		wd->sc_quirks = wdq->wdq_quirks;
    321 
    322 	if ((wd->sc_params.atap_multi & 0xff) > 1) {
    323 		wd->sc_multi = wd->sc_params.atap_multi & 0xff;
    324 	} else {
    325 		wd->sc_multi = 1;
    326 	}
    327 
    328 	aprint_normal("%s: drive supports %d-sector PIO transfers,",
    329 	    wd->sc_dev.dv_xname, wd->sc_multi);
    330 
    331 	/* 48-bit LBA addressing */
    332 	if ((wd->sc_params.atap_cmd2_en & ATA_CMD2_LBA48) != 0)
    333 		wd->sc_flags |= WDF_LBA48;
    334 
    335 	/* Prior to ATA-4, LBA was optional. */
    336 	if ((wd->sc_params.atap_capabilities1 & WDC_CAP_LBA) != 0)
    337 		wd->sc_flags |= WDF_LBA;
    338 #if 0
    339 	/* ATA-4 requires LBA. */
    340 	if (wd->sc_params.atap_ataversion != 0xffff &&
    341 	    wd->sc_params.atap_ataversion >= WDC_VER_ATA4)
    342 		wd->sc_flags |= WDF_LBA;
    343 #endif
    344 
    345 	if ((wd->sc_flags & WDF_LBA48) != 0) {
    346 		aprint_normal(" LBA48 addressing\n");
    347 		wd->sc_capacity =
    348 		    ((u_int64_t) wd->sc_params.__reserved6[11] << 48) |
    349 		    ((u_int64_t) wd->sc_params.__reserved6[10] << 32) |
    350 		    ((u_int64_t) wd->sc_params.__reserved6[9]  << 16) |
    351 		    ((u_int64_t) wd->sc_params.__reserved6[8]  << 0);
    352 	} else if ((wd->sc_flags & WDF_LBA) != 0) {
    353 		aprint_normal(" LBA addressing\n");
    354 		wd->sc_capacity =
    355 		    (wd->sc_params.atap_capacity[1] << 16) |
    356 		    wd->sc_params.atap_capacity[0];
    357 	} else {
    358 		aprint_normal(" chs addressing\n");
    359 		wd->sc_capacity =
    360 		    wd->sc_params.atap_cylinders *
    361 		    wd->sc_params.atap_heads *
    362 		    wd->sc_params.atap_sectors;
    363 	}
    364 	format_bytes(pbuf, sizeof(pbuf), wd->sc_capacity * DEV_BSIZE);
    365 	aprint_normal("%s: %s, %d cyl, %d head, %d sec, "
    366 	    "%d bytes/sect x %llu sectors\n",
    367 	    self->dv_xname, pbuf,
    368 	    (wd->sc_flags & WDF_LBA) ? (int)(wd->sc_capacity /
    369 		(wd->sc_params.atap_heads * wd->sc_params.atap_sectors)) :
    370 		wd->sc_params.atap_cylinders,
    371 	    wd->sc_params.atap_heads, wd->sc_params.atap_sectors,
    372 	    DEV_BSIZE, (unsigned long long)wd->sc_capacity);
    373 
    374 	ATADEBUG_PRINT(("%s: atap_dmatiming_mimi=%d, atap_dmatiming_recom=%d\n",
    375 	    self->dv_xname, wd->sc_params.atap_dmatiming_mimi,
    376 	    wd->sc_params.atap_dmatiming_recom), DEBUG_PROBE);
    377 	/*
    378 	 * Initialize and attach the disk structure.
    379 	 */
    380 	wd->sc_dk.dk_driver = &wddkdriver;
    381 	wd->sc_dk.dk_name = wd->sc_dev.dv_xname;
    382 	disk_attach(&wd->sc_dk);
    383 	wd->sc_wdc_bio.lp = wd->sc_dk.dk_label;
    384 	wd->sc_sdhook = shutdownhook_establish(wd_shutdown, wd);
    385 	if (wd->sc_sdhook == NULL)
    386 		aprint_error("%s: WARNING: unable to establish shutdown hook\n",
    387 		    wd->sc_dev.dv_xname);
    388 #if NRND > 0
    389 	rnd_attach_source(&wd->rnd_source, wd->sc_dev.dv_xname,
    390 			  RND_TYPE_DISK, 0);
    391 #endif
    392 }
    393 
    394 int
    395 wdactivate(struct device *self, enum devact act)
    396 {
    397 	int rv = 0;
    398 
    399 	switch (act) {
    400 	case DVACT_ACTIVATE:
    401 		rv = EOPNOTSUPP;
    402 		break;
    403 
    404 	case DVACT_DEACTIVATE:
    405 		/*
    406 		 * Nothing to do; we key off the device's DVF_ACTIVATE.
    407 		 */
    408 		break;
    409 	}
    410 	return (rv);
    411 }
    412 
    413 int
    414 wddetach(struct device *self, int flags)
    415 {
    416 	struct wd_softc *sc = (struct wd_softc *)self;
    417 	struct buf *bp;
    418 	int s, bmaj, cmaj, i, mn;
    419 
    420 	/* locate the major number */
    421 	bmaj = bdevsw_lookup_major(&wd_bdevsw);
    422 	cmaj = cdevsw_lookup_major(&wd_cdevsw);
    423 
    424 	/* Nuke the vnodes for any open instances. */
    425 	for (i = 0; i < MAXPARTITIONS; i++) {
    426 		mn = WDMINOR(self->dv_unit, i);
    427 		vdevgone(bmaj, mn, mn, VBLK);
    428 		vdevgone(cmaj, mn, mn, VCHR);
    429 	}
    430 
    431 	s = splbio();
    432 
    433 	/* Kill off any queued buffers. */
    434 	while ((bp = BUFQ_GET(&sc->sc_q)) != NULL) {
    435 		bp->b_error = EIO;
    436 		bp->b_flags |= B_ERROR;
    437 		bp->b_resid = bp->b_bcount;
    438 		biodone(bp);
    439 	}
    440 
    441 	bufq_free(&sc->sc_q);
    442 	sc->atabus->ata_killpending(sc->drvp);
    443 
    444 	splx(s);
    445 
    446 	/* Detach disk. */
    447 	disk_detach(&sc->sc_dk);
    448 
    449 #ifdef WD_SOFTBADSECT
    450 	/* Clean out the bad sector list */
    451 	while (!SLIST_EMPTY(&sc->sc_bslist)) {
    452 		void *head = SLIST_FIRST(&sc->sc_bslist);
    453 		SLIST_REMOVE_HEAD(&sc->sc_bslist, dbs_next);
    454 		free(head, M_TEMP);
    455 	}
    456 	sc->sc_bscount = 0;
    457 #endif
    458 
    459 	/* Get rid of the shutdown hook. */
    460 	if (sc->sc_sdhook != NULL)
    461 		shutdownhook_disestablish(sc->sc_sdhook);
    462 
    463 #if NRND > 0
    464 	/* Unhook the entropy source. */
    465 	rnd_detach_source(&sc->rnd_source);
    466 #endif
    467 
    468 	lockmgr(&sc->sc_lock, LK_DRAIN, NULL);
    469 	sc->drvp->drive_flags = 0; /* no drive any more here */
    470 
    471 	return (0);
    472 }
    473 
    474 /*
    475  * Read/write routine for a buffer.  Validates the arguments and schedules the
    476  * transfer.  Does not wait for the transfer to complete.
    477  */
    478 void
    479 wdstrategy(struct buf *bp)
    480 {
    481 	struct wd_softc *wd = device_lookup(&wd_cd, WDUNIT(bp->b_dev));
    482 	struct disklabel *lp = wd->sc_dk.dk_label;
    483 	daddr_t blkno;
    484 	int s;
    485 
    486 	ATADEBUG_PRINT(("wdstrategy (%s)\n", wd->sc_dev.dv_xname),
    487 	    DEBUG_XFERS);
    488 
    489 	/* Valid request?  */
    490 	if (bp->b_blkno < 0 ||
    491 	    (bp->b_bcount % lp->d_secsize) != 0 ||
    492 	    (bp->b_bcount / lp->d_secsize) >= (1 << NBBY)) {
    493 		bp->b_error = EINVAL;
    494 		goto bad;
    495 	}
    496 
    497 	/* If device invalidated (e.g. media change, door open), error. */
    498 	if ((wd->sc_flags & WDF_LOADED) == 0) {
    499 		bp->b_error = EIO;
    500 		goto bad;
    501 	}
    502 
    503 	/* If it's a null transfer, return immediately. */
    504 	if (bp->b_bcount == 0)
    505 		goto done;
    506 
    507 	/*
    508 	 * Do bounds checking, adjust transfer. if error, process.
    509 	 * If end of partition, just return.
    510 	 */
    511 	if (WDPART(bp->b_dev) == RAW_PART) {
    512 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
    513 		    wd->sc_capacity) <= 0)
    514 			goto done;
    515 	} else {
    516 		if (bounds_check_with_label(&wd->sc_dk, bp,
    517 		    (wd->sc_flags & (WDF_WLABEL|WDF_LABELLING)) != 0) <= 0)
    518 			goto done;
    519 	}
    520 
    521 	/*
    522 	 * Now convert the block number to absolute and put it in
    523 	 * terms of the device's logical block size.
    524 	 */
    525 	if (lp->d_secsize >= DEV_BSIZE)
    526 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
    527 	else
    528 		blkno = bp->b_blkno * (DEV_BSIZE / lp->d_secsize);
    529 
    530 	if (WDPART(bp->b_dev) != RAW_PART)
    531 		blkno += lp->d_partitions[WDPART(bp->b_dev)].p_offset;
    532 
    533 	bp->b_rawblkno = blkno;
    534 
    535 #ifdef WD_SOFTBADSECT
    536 	/*
    537 	 * If the transfer about to be attempted contains only a block that
    538 	 * is known to be bad then return an error for the transfer without
    539 	 * even attempting to start a transfer up under the premis that we
    540 	 * will just end up doing more retries for a transfer that will end
    541 	 * up failing again.
    542 	 * XXX:SMP - mutex required to protect with DIOCBSFLUSH
    543 	 */
    544 	if (__predict_false(!SLIST_EMPTY(&wd->sc_bslist))) {
    545 		struct disk_badsectors *dbs;
    546 		daddr_t maxblk = blkno + (bp->b_bcount >> DEV_BSHIFT) - 1;
    547 
    548 		SLIST_FOREACH(dbs, &wd->sc_bslist, dbs_next)
    549 			if ((dbs->dbs_min <= blkno && blkno <= dbs->dbs_max) ||
    550 			    (dbs->dbs_min <= maxblk && maxblk <= dbs->dbs_max)){
    551 				bp->b_error = EIO;
    552 				goto bad;
    553 			}
    554 	}
    555 #endif
    556 
    557 	/* Queue transfer on drive, activate drive and controller if idle. */
    558 	s = splbio();
    559 	BUFQ_PUT(&wd->sc_q, bp);
    560 	wdstart(wd);
    561 	splx(s);
    562 	return;
    563 bad:
    564 	bp->b_flags |= B_ERROR;
    565 done:
    566 	/* Toss transfer; we're done early. */
    567 	bp->b_resid = bp->b_bcount;
    568 	biodone(bp);
    569 }
    570 
    571 /*
    572  * Queue a drive for I/O.
    573  */
    574 void
    575 wdstart(void *arg)
    576 {
    577 	struct wd_softc *wd = arg;
    578 	struct buf *bp = NULL;
    579 
    580 	ATADEBUG_PRINT(("wdstart %s\n", wd->sc_dev.dv_xname),
    581 	    DEBUG_XFERS);
    582 	while (wd->openings > 0) {
    583 
    584 		/* Is there a buf for us ? */
    585 		if ((bp = BUFQ_GET(&wd->sc_q)) == NULL)
    586 			return;
    587 
    588 		/*
    589 		 * Make the command. First lock the device
    590 		 */
    591 		wd->openings--;
    592 
    593 		wd->retries = 0;
    594 		__wdstart(wd, bp);
    595 	}
    596 }
    597 
    598 static void
    599 wd_split_mod15_write(struct buf *bp)
    600 {
    601 	struct buf *obp = bp->b_private;
    602 	struct wd_softc *sc = wd_cd.cd_devs[DISKUNIT(obp->b_dev)];
    603 
    604 	if (__predict_false(bp->b_flags & B_ERROR) != 0) {
    605 		/*
    606 		 * Propagate the error.  If this was the first half of
    607 		 * the original transfer, make sure to account for that
    608 		 * in the residual.
    609 		 */
    610 		if (bp->b_data == obp->b_data)
    611 			bp->b_resid += bp->b_bcount;
    612 		goto done;
    613 	}
    614 
    615 	/*
    616 	 * If this was the second half of the transfer, we're all done!
    617 	 */
    618 	if (bp->b_data != obp->b_data)
    619 		goto done;
    620 
    621 	/*
    622 	 * Advance the pointer to the second half and issue that command
    623 	 * using the same opening.
    624 	 */
    625 	bp->b_flags = obp->b_flags | B_CALL;
    626 	bp->b_data += bp->b_bcount;
    627 	bp->b_blkno += (bp->b_bcount / 512);
    628 	bp->b_rawblkno += (bp->b_bcount / 512);
    629 	__wdstart(sc, bp);
    630 	return;
    631 
    632  done:
    633 	obp->b_flags |= (bp->b_flags & (B_EINTR|B_ERROR));
    634 	obp->b_error = bp->b_error;
    635 	obp->b_resid = bp->b_resid;
    636 	pool_put(&bufpool, bp);
    637 	biodone(obp);
    638 	sc->openings++;
    639 	/* wddone() will call wdstart() */
    640 }
    641 
    642 void
    643 __wdstart(struct wd_softc *wd, struct buf *bp)
    644 {
    645 
    646 	/*
    647 	 * Deal with the "split mod15 write" quirk.  We just divide the
    648 	 * transfer in two, doing the first half and then then second half
    649 	 * with the same command opening.
    650 	 *
    651 	 * Note we MUST do this here, because we can't let insertion
    652 	 * into the bufq cause the transfers to be re-merged.
    653 	 */
    654 	if (__predict_false((wd->sc_quirks & WD_QUIRK_SPLIT_MOD15_WRITE) != 0 &&
    655 			    (bp->b_flags & B_READ) == 0 &&
    656 			    bp->b_bcount > 512 &&
    657 			    ((bp->b_bcount / 512) % 15) == 1)) {
    658 		struct buf *nbp;
    659 
    660 		/* already at splbio */
    661 		nbp = pool_get(&bufpool, PR_NOWAIT);
    662 		if (__predict_false(nbp == NULL)) {
    663 			/* No memory -- fail the iop. */
    664 			bp->b_error = ENOMEM;
    665 			bp->b_flags |= B_ERROR;
    666 			bp->b_resid = bp->b_bcount;
    667 			biodone(bp);
    668 			wd->openings++;
    669 			return;
    670 		}
    671 
    672 		BUF_INIT(nbp);
    673 		nbp->b_error = 0;
    674 		nbp->b_proc = bp->b_proc;
    675 		nbp->b_vp = NULLVP;
    676 		nbp->b_dev = bp->b_dev;
    677 
    678 		nbp->b_bcount = bp->b_bcount / 2;
    679 		nbp->b_bufsize = bp->b_bcount / 2;
    680 		nbp->b_data = bp->b_data;
    681 
    682 		nbp->b_blkno = bp->b_blkno;
    683 		nbp->b_rawblkno = bp->b_rawblkno;
    684 
    685 		nbp->b_flags = bp->b_flags | B_CALL;
    686 		nbp->b_iodone = wd_split_mod15_write;
    687 
    688 		/* Put ptr to orig buf in b_private and use new buf */
    689 		nbp->b_private = bp;
    690 
    691 		BIO_COPYPRIO(nbp, bp);
    692 
    693 		bp = nbp;
    694 	}
    695 
    696 	wd->sc_wdc_bio.blkno = bp->b_rawblkno;
    697 	wd->sc_wdc_bio.blkdone =0;
    698 	wd->sc_bp = bp;
    699 	/*
    700 	 * If we're retrying, retry in single-sector mode. This will give us
    701 	 * the sector number of the problem, and will eventually allow the
    702 	 * transfer to succeed.
    703 	 */
    704 	if (wd->retries >= WDIORETRIES_SINGLE)
    705 		wd->sc_wdc_bio.flags = ATA_SINGLE;
    706 	else
    707 		wd->sc_wdc_bio.flags = 0;
    708 	if (wd->sc_flags & WDF_LBA48 && wd->sc_wdc_bio.blkno > LBA48_THRESHOLD)
    709 		wd->sc_wdc_bio.flags |= ATA_LBA48;
    710 	if (wd->sc_flags & WDF_LBA)
    711 		wd->sc_wdc_bio.flags |= ATA_LBA;
    712 	if (bp->b_flags & B_READ)
    713 		wd->sc_wdc_bio.flags |= ATA_READ;
    714 	wd->sc_wdc_bio.bcount = bp->b_bcount;
    715 	wd->sc_wdc_bio.databuf = bp->b_data;
    716 	/* Instrumentation. */
    717 	disk_busy(&wd->sc_dk);
    718 	switch (wd->atabus->ata_bio(wd->drvp, &wd->sc_wdc_bio)) {
    719 	case ATACMD_TRY_AGAIN:
    720 		callout_reset(&wd->sc_restart_ch, hz, wdrestart, wd);
    721 		break;
    722 	case ATACMD_QUEUED:
    723 	case ATACMD_COMPLETE:
    724 		break;
    725 	default:
    726 		panic("__wdstart: bad return code from ata_bio()");
    727 	}
    728 }
    729 
    730 void
    731 wddone(void *v)
    732 {
    733 	struct wd_softc *wd = v;
    734 	struct buf *bp = wd->sc_bp;
    735 	const char *errmsg;
    736 	int do_perror = 0;
    737 	ATADEBUG_PRINT(("wddone %s\n", wd->sc_dev.dv_xname),
    738 	    DEBUG_XFERS);
    739 
    740 	if (bp == NULL)
    741 		return;
    742 	bp->b_resid = wd->sc_wdc_bio.bcount;
    743 	switch (wd->sc_wdc_bio.error) {
    744 	case ERR_DMA:
    745 		errmsg = "DMA error";
    746 		goto retry;
    747 	case ERR_DF:
    748 		errmsg = "device fault";
    749 		goto retry;
    750 	case TIMEOUT:
    751 		errmsg = "device timeout";
    752 		goto retry;
    753 	case ERR_RESET:
    754 		errmsg = "channel reset";
    755 		goto retry2;
    756 	case ERROR:
    757 		/* Don't care about media change bits */
    758 		if (wd->sc_wdc_bio.r_error != 0 &&
    759 		    (wd->sc_wdc_bio.r_error & ~(WDCE_MC | WDCE_MCR)) == 0)
    760 			goto noerror;
    761 		errmsg = "error";
    762 		do_perror = 1;
    763 retry:		/* Just reset and retry. Can we do more ? */
    764 		(*wd->atabus->ata_reset_drive)(wd->drvp, AT_RST_NOCMD);
    765 retry2:
    766 		diskerr(bp, "wd", errmsg, LOG_PRINTF,
    767 		    wd->sc_wdc_bio.blkdone, wd->sc_dk.dk_label);
    768 		if (wd->retries < WDIORETRIES)
    769 			printf(", retrying\n");
    770 		if (do_perror)
    771 			wdperror(wd);
    772 		if (wd->retries < WDIORETRIES) {
    773 			wd->retries++;
    774 			callout_reset(&wd->sc_restart_ch, RECOVERYTIME,
    775 			    wdrestart, wd);
    776 			return;
    777 		}
    778 		printf("\n");
    779 
    780 #ifdef WD_SOFTBADSECT
    781 		/*
    782 		 * Not all errors indicate a failed block but those that do,
    783 		 * put the block on the bad-block list for the device.  Only
    784 		 * do this for reads because the drive should do it for writes,
    785 		 * itself, according to Manuel.
    786 		 */
    787 		if ((bp->b_flags & B_READ) &&
    788 		    ((wd->drvp->ata_vers >= 4 && wd->sc_wdc_bio.r_error & 64) ||
    789 	     	     (wd->drvp->ata_vers < 4 && wd->sc_wdc_bio.r_error & 192))) {
    790 			struct disk_badsectors *dbs;
    791 
    792 			dbs = malloc(sizeof *dbs, M_TEMP, M_WAITOK);
    793 			dbs->dbs_min = bp->b_rawblkno;
    794 			dbs->dbs_max = dbs->dbs_min + (bp->b_bcount >> DEV_BSHIFT) - 1;
    795 			microtime(&dbs->dbs_failedat);
    796 			SLIST_INSERT_HEAD(&wd->sc_bslist, dbs, dbs_next);
    797 			wd->sc_bscount++;
    798 		}
    799 #endif
    800 		bp->b_flags |= B_ERROR;
    801 		bp->b_error = EIO;
    802 		break;
    803 	case NOERROR:
    804 noerror:	if ((wd->sc_wdc_bio.flags & ATA_CORR) || wd->retries > 0)
    805 			printf("%s: soft error (corrected)\n",
    806 			    wd->sc_dev.dv_xname);
    807 		break;
    808 	case ERR_NODEV:
    809 		bp->b_flags |= B_ERROR;
    810 		bp->b_error = EIO;
    811 		break;
    812 	}
    813 	disk_unbusy(&wd->sc_dk, (bp->b_bcount - bp->b_resid),
    814 	    (bp->b_flags & B_READ));
    815 #if NRND > 0
    816 	rnd_add_uint32(&wd->rnd_source, bp->b_blkno);
    817 #endif
    818 	/* XXX Yuck, but we don't want to increment openings in this case */
    819 	if (__predict_false((bp->b_flags & B_CALL) != 0 &&
    820 			    bp->b_iodone == wd_split_mod15_write))
    821 		biodone(bp);
    822 	else {
    823 		biodone(bp);
    824 		wd->openings++;
    825 	}
    826 	wdstart(wd);
    827 }
    828 
    829 void
    830 wdrestart(void *v)
    831 {
    832 	struct wd_softc *wd = v;
    833 	struct buf *bp = wd->sc_bp;
    834 	int s;
    835 	ATADEBUG_PRINT(("wdrestart %s\n", wd->sc_dev.dv_xname),
    836 	    DEBUG_XFERS);
    837 
    838 	s = splbio();
    839 	__wdstart(v, bp);
    840 	splx(s);
    841 }
    842 
    843 int
    844 wdread(dev_t dev, struct uio *uio, int flags)
    845 {
    846 
    847 	ATADEBUG_PRINT(("wdread\n"), DEBUG_XFERS);
    848 	return (physio(wdstrategy, NULL, dev, B_READ, minphys, uio));
    849 }
    850 
    851 int
    852 wdwrite(dev_t dev, struct uio *uio, int flags)
    853 {
    854 
    855 	ATADEBUG_PRINT(("wdwrite\n"), DEBUG_XFERS);
    856 	return (physio(wdstrategy, NULL, dev, B_WRITE, minphys, uio));
    857 }
    858 
    859 int
    860 wdopen(dev_t dev, int flag, int fmt, struct proc *p)
    861 {
    862 	struct wd_softc *wd;
    863 	int part, error;
    864 
    865 	ATADEBUG_PRINT(("wdopen\n"), DEBUG_FUNCS);
    866 	wd = device_lookup(&wd_cd, WDUNIT(dev));
    867 	if (wd == NULL)
    868 		return (ENXIO);
    869 
    870 	if ((wd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
    871 		return (ENODEV);
    872 
    873 	/*
    874 	 * If this is the first open of this device, add a reference
    875 	 * to the adapter.
    876 	 */
    877 	if (wd->sc_dk.dk_openmask == 0 &&
    878 	    (error = wd->atabus->ata_addref(wd->drvp)) != 0)
    879 		return (error);
    880 
    881 	if ((error = lockmgr(&wd->sc_lock, LK_EXCLUSIVE, NULL)) != 0)
    882 		goto bad4;
    883 
    884 	if (wd->sc_dk.dk_openmask != 0) {
    885 		/*
    886 		 * If any partition is open, but the disk has been invalidated,
    887 		 * disallow further opens.
    888 		 */
    889 		if ((wd->sc_flags & WDF_LOADED) == 0) {
    890 			error = EIO;
    891 			goto bad3;
    892 		}
    893 	} else {
    894 		if ((wd->sc_flags & WDF_LOADED) == 0) {
    895 			wd->sc_flags |= WDF_LOADED;
    896 
    897 			/* Load the physical device parameters. */
    898 			wd_get_params(wd, AT_WAIT, &wd->sc_params);
    899 
    900 			/* Load the partition info if not already loaded. */
    901 			wdgetdisklabel(wd);
    902 		}
    903 	}
    904 
    905 	part = WDPART(dev);
    906 
    907 	/* Check that the partition exists. */
    908 	if (part != RAW_PART &&
    909 	    (part >= wd->sc_dk.dk_label->d_npartitions ||
    910 	     wd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
    911 		error = ENXIO;
    912 		goto bad;
    913 	}
    914 
    915 	/* Insure only one open at a time. */
    916 	switch (fmt) {
    917 	case S_IFCHR:
    918 		wd->sc_dk.dk_copenmask |= (1 << part);
    919 		break;
    920 	case S_IFBLK:
    921 		wd->sc_dk.dk_bopenmask |= (1 << part);
    922 		break;
    923 	}
    924 	wd->sc_dk.dk_openmask =
    925 	    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
    926 
    927 	lockmgr(&wd->sc_lock, LK_RELEASE, NULL);
    928 	return 0;
    929 
    930 bad:
    931 	if (wd->sc_dk.dk_openmask == 0) {
    932 	}
    933 
    934 bad3:
    935 	lockmgr(&wd->sc_lock, LK_RELEASE, NULL);
    936 bad4:
    937 	if (wd->sc_dk.dk_openmask == 0)
    938 		wd->atabus->ata_delref(wd->drvp);
    939 	return error;
    940 }
    941 
    942 int
    943 wdclose(dev_t dev, int flag, int fmt, struct proc *p)
    944 {
    945 	struct wd_softc *wd = device_lookup(&wd_cd, WDUNIT(dev));
    946 	int part = WDPART(dev);
    947 	int error;
    948 
    949 	ATADEBUG_PRINT(("wdclose\n"), DEBUG_FUNCS);
    950 	if ((error = lockmgr(&wd->sc_lock, LK_EXCLUSIVE, NULL)) != 0)
    951 		return error;
    952 
    953 	switch (fmt) {
    954 	case S_IFCHR:
    955 		wd->sc_dk.dk_copenmask &= ~(1 << part);
    956 		break;
    957 	case S_IFBLK:
    958 		wd->sc_dk.dk_bopenmask &= ~(1 << part);
    959 		break;
    960 	}
    961 	wd->sc_dk.dk_openmask =
    962 	    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
    963 
    964 	if (wd->sc_dk.dk_openmask == 0) {
    965 		wd_flushcache(wd, AT_WAIT);
    966 
    967 		if (! (wd->sc_flags & WDF_KLABEL))
    968 			wd->sc_flags &= ~WDF_LOADED;
    969 
    970 		wd->atabus->ata_delref(wd->drvp);
    971 	}
    972 
    973 	lockmgr(&wd->sc_lock, LK_RELEASE, NULL);
    974 	return 0;
    975 }
    976 
    977 void
    978 wdgetdefaultlabel(struct wd_softc *wd, struct disklabel *lp)
    979 {
    980 
    981 	ATADEBUG_PRINT(("wdgetdefaultlabel\n"), DEBUG_FUNCS);
    982 	memset(lp, 0, sizeof(struct disklabel));
    983 
    984 	lp->d_secsize = DEV_BSIZE;
    985 	lp->d_ntracks = wd->sc_params.atap_heads;
    986 	lp->d_nsectors = wd->sc_params.atap_sectors;
    987 	lp->d_ncylinders = (wd->sc_flags & WDF_LBA) ? wd->sc_capacity /
    988 		(wd->sc_params.atap_heads * wd->sc_params.atap_sectors) :
    989 		wd->sc_params.atap_cylinders;
    990 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
    991 
    992 	if (strcmp(wd->sc_params.atap_model, "ST506") == 0)
    993 		lp->d_type = DTYPE_ST506;
    994 	else
    995 		lp->d_type = DTYPE_ESDI;
    996 
    997 	strncpy(lp->d_typename, wd->sc_params.atap_model, 16);
    998 	strncpy(lp->d_packname, "fictitious", 16);
    999 	if (wd->sc_capacity > UINT32_MAX)
   1000 		lp->d_secperunit = UINT32_MAX;
   1001 	else
   1002 		lp->d_secperunit = wd->sc_capacity;
   1003 	lp->d_rpm = 3600;
   1004 	lp->d_interleave = 1;
   1005 	lp->d_flags = 0;
   1006 
   1007 	lp->d_partitions[RAW_PART].p_offset = 0;
   1008 	lp->d_partitions[RAW_PART].p_size =
   1009 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
   1010 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
   1011 	lp->d_npartitions = RAW_PART + 1;
   1012 
   1013 	lp->d_magic = DISKMAGIC;
   1014 	lp->d_magic2 = DISKMAGIC;
   1015 	lp->d_checksum = dkcksum(lp);
   1016 }
   1017 
   1018 /*
   1019  * Fabricate a default disk label, and try to read the correct one.
   1020  */
   1021 void
   1022 wdgetdisklabel(struct wd_softc *wd)
   1023 {
   1024 	struct disklabel *lp = wd->sc_dk.dk_label;
   1025 	const char *errstring;
   1026 	int s;
   1027 
   1028 	ATADEBUG_PRINT(("wdgetdisklabel\n"), DEBUG_FUNCS);
   1029 
   1030 	memset(wd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
   1031 
   1032 	wdgetdefaultlabel(wd, lp);
   1033 
   1034 	wd->sc_badsect[0] = -1;
   1035 
   1036 	if (wd->drvp->state > RESET) {
   1037 		s = splbio();
   1038 		wd->drvp->drive_flags |= DRIVE_RESET;
   1039 		splx(s);
   1040 	}
   1041 	errstring = readdisklabel(MAKEWDDEV(0, wd->sc_dev.dv_unit, RAW_PART),
   1042 	    wdstrategy, lp, wd->sc_dk.dk_cpulabel);
   1043 	if (errstring) {
   1044 		/*
   1045 		 * This probably happened because the drive's default
   1046 		 * geometry doesn't match the DOS geometry.  We
   1047 		 * assume the DOS geometry is now in the label and try
   1048 		 * again.  XXX This is a kluge.
   1049 		 */
   1050 		if (wd->drvp->state > RESET) {
   1051 			s = splbio();
   1052 			wd->drvp->drive_flags |= DRIVE_RESET;
   1053 			splx(s);
   1054 		}
   1055 		errstring = readdisklabel(MAKEWDDEV(0, wd->sc_dev.dv_unit,
   1056 		    RAW_PART), wdstrategy, lp, wd->sc_dk.dk_cpulabel);
   1057 	}
   1058 	if (errstring) {
   1059 		printf("%s: %s\n", wd->sc_dev.dv_xname, errstring);
   1060 		return;
   1061 	}
   1062 
   1063 	if (wd->drvp->state > RESET) {
   1064 		s = splbio();
   1065 		wd->drvp->drive_flags |= DRIVE_RESET;
   1066 		splx(s);
   1067 	}
   1068 #ifdef HAS_BAD144_HANDLING
   1069 	if ((lp->d_flags & D_BADSECT) != 0)
   1070 		bad144intern(wd);
   1071 #endif
   1072 }
   1073 
   1074 void
   1075 wdperror(const struct wd_softc *wd)
   1076 {
   1077 	static const char *const errstr0_3[] = {"address mark not found",
   1078 	    "track 0 not found", "aborted command", "media change requested",
   1079 	    "id not found", "media changed", "uncorrectable data error",
   1080 	    "bad block detected"};
   1081 	static const char *const errstr4_5[] = {
   1082 	    "obsolete (address mark not found)",
   1083 	    "no media/write protected", "aborted command",
   1084 	    "media change requested", "id not found", "media changed",
   1085 	    "uncorrectable data error", "interface CRC error"};
   1086 	const char *const *errstr;
   1087 	int i;
   1088 	char *sep = "";
   1089 
   1090 	const char *devname = wd->sc_dev.dv_xname;
   1091 	struct ata_drive_datas *drvp = wd->drvp;
   1092 	int errno = wd->sc_wdc_bio.r_error;
   1093 
   1094 	if (drvp->ata_vers >= 4)
   1095 		errstr = errstr4_5;
   1096 	else
   1097 		errstr = errstr0_3;
   1098 
   1099 	printf("%s: (", devname);
   1100 
   1101 	if (errno == 0)
   1102 		printf("error not notified");
   1103 
   1104 	for (i = 0; i < 8; i++) {
   1105 		if (errno & (1 << i)) {
   1106 			printf("%s%s", sep, errstr[i]);
   1107 			sep = ", ";
   1108 		}
   1109 	}
   1110 	printf(")\n");
   1111 }
   1112 
   1113 int
   1114 wdioctl(dev_t dev, u_long xfer, caddr_t addr, int flag, struct proc *p)
   1115 {
   1116 	struct wd_softc *wd = device_lookup(&wd_cd, WDUNIT(dev));
   1117 	int error = 0, s;
   1118 #ifdef __HAVE_OLD_DISKLABEL
   1119 	struct disklabel *newlabel = NULL;
   1120 #endif
   1121 
   1122 	ATADEBUG_PRINT(("wdioctl\n"), DEBUG_FUNCS);
   1123 
   1124 	if ((wd->sc_flags & WDF_LOADED) == 0)
   1125 		return EIO;
   1126 
   1127 	switch (xfer) {
   1128 #ifdef HAS_BAD144_HANDLING
   1129 	case DIOCSBAD:
   1130 		if ((flag & FWRITE) == 0)
   1131 			return EBADF;
   1132 		wd->sc_dk.dk_cpulabel->bad = *(struct dkbad *)addr;
   1133 		wd->sc_dk.dk_label->d_flags |= D_BADSECT;
   1134 		bad144intern(wd);
   1135 		return 0;
   1136 #endif
   1137 #ifdef WD_SOFTBADSECT
   1138 	case DIOCBSLIST :
   1139 	{
   1140 		u_int32_t count, missing, skip;
   1141 		struct disk_badsecinfo dbsi;
   1142 		struct disk_badsectors *dbs;
   1143 		size_t available;
   1144 		caddr_t laddr;
   1145 
   1146 		dbsi = *(struct disk_badsecinfo *)addr;
   1147 		missing = wd->sc_bscount;
   1148 		count = 0;
   1149 		available = dbsi.dbsi_bufsize;
   1150 		skip = dbsi.dbsi_skip;
   1151 		laddr = dbsi.dbsi_buffer;
   1152 
   1153 		/*
   1154 		 * We start this loop with the expectation that all of the
   1155 		 * entries will be missed and decrement this counter each
   1156 		 * time we either skip over one (already copied out) or
   1157 		 * we actually copy it back to user space.  The structs
   1158 		 * holding the bad sector information are copied directly
   1159 		 * back to user space whilst the summary is returned via
   1160 		 * the struct passed in via the ioctl.
   1161 		 */
   1162 		SLIST_FOREACH(dbs, &wd->sc_bslist, dbs_next) {
   1163 			if (skip > 0) {
   1164 				missing--;
   1165 				skip--;
   1166 				continue;
   1167 			}
   1168 			if (available < sizeof(*dbs))
   1169 				break;
   1170 			available -= sizeof(*dbs);
   1171 			copyout(dbs, laddr, sizeof(*dbs));
   1172 			laddr += sizeof(*dbs);
   1173 			missing--;
   1174 			count++;
   1175 		}
   1176 		dbsi.dbsi_left = missing;
   1177 		dbsi.dbsi_copied = count;
   1178 		*(struct disk_badsecinfo *)addr = dbsi;
   1179 		return 0;
   1180 	}
   1181 
   1182 	case DIOCBSFLUSH :
   1183 		/* Clean out the bad sector list */
   1184 		while (!SLIST_EMPTY(&wd->sc_bslist)) {
   1185 			void *head = SLIST_FIRST(&wd->sc_bslist);
   1186 			SLIST_REMOVE_HEAD(&wd->sc_bslist, dbs_next);
   1187 			free(head, M_TEMP);
   1188 		}
   1189 		wd->sc_bscount = 0;
   1190 		return 0;
   1191 #endif
   1192 	case DIOCGDINFO:
   1193 		*(struct disklabel *)addr = *(wd->sc_dk.dk_label);
   1194 		return 0;
   1195 #ifdef __HAVE_OLD_DISKLABEL
   1196 	case ODIOCGDINFO:
   1197 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1198 		if (newlabel == NULL)
   1199 			return EIO;
   1200 		*newlabel = *(wd->sc_dk.dk_label);
   1201 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
   1202 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
   1203 		else
   1204 			error = ENOTTY;
   1205 		free(newlabel, M_TEMP);
   1206 		return error;
   1207 #endif
   1208 
   1209 	case DIOCGPART:
   1210 		((struct partinfo *)addr)->disklab = wd->sc_dk.dk_label;
   1211 		((struct partinfo *)addr)->part =
   1212 		    &wd->sc_dk.dk_label->d_partitions[WDPART(dev)];
   1213 		return 0;
   1214 
   1215 	case DIOCWDINFO:
   1216 	case DIOCSDINFO:
   1217 #ifdef __HAVE_OLD_DISKLABEL
   1218 	case ODIOCWDINFO:
   1219 	case ODIOCSDINFO:
   1220 #endif
   1221 	{
   1222 		struct disklabel *lp;
   1223 
   1224 		if ((flag & FWRITE) == 0)
   1225 			return EBADF;
   1226 
   1227 #ifdef __HAVE_OLD_DISKLABEL
   1228 		if (xfer == ODIOCSDINFO || xfer == ODIOCWDINFO) {
   1229 			newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1230 			if (newlabel == NULL)
   1231 				return EIO;
   1232 			memset(newlabel, 0, sizeof newlabel);
   1233 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
   1234 			lp = newlabel;
   1235 		} else
   1236 #endif
   1237 		lp = (struct disklabel *)addr;
   1238 
   1239 		if ((error = lockmgr(&wd->sc_lock, LK_EXCLUSIVE, NULL)) != 0)
   1240 			goto bad;
   1241 		wd->sc_flags |= WDF_LABELLING;
   1242 
   1243 		error = setdisklabel(wd->sc_dk.dk_label,
   1244 		    lp, /*wd->sc_dk.dk_openmask : */0,
   1245 		    wd->sc_dk.dk_cpulabel);
   1246 		if (error == 0) {
   1247 			if (wd->drvp->state > RESET) {
   1248 				s = splbio();
   1249 				wd->drvp->drive_flags |= DRIVE_RESET;
   1250 				splx(s);
   1251 			}
   1252 			if (xfer == DIOCWDINFO
   1253 #ifdef __HAVE_OLD_DISKLABEL
   1254 			    || xfer == ODIOCWDINFO
   1255 #endif
   1256 			    )
   1257 				error = writedisklabel(WDLABELDEV(dev),
   1258 				    wdstrategy, wd->sc_dk.dk_label,
   1259 				    wd->sc_dk.dk_cpulabel);
   1260 		}
   1261 
   1262 		wd->sc_flags &= ~WDF_LABELLING;
   1263 		lockmgr(&wd->sc_lock, LK_RELEASE, NULL);
   1264 bad:
   1265 #ifdef __HAVE_OLD_DISKLABEL
   1266 		if (newlabel != NULL)
   1267 			free(newlabel, M_TEMP);
   1268 #endif
   1269 		return error;
   1270 	}
   1271 
   1272 	case DIOCKLABEL:
   1273 		if (*(int *)addr)
   1274 			wd->sc_flags |= WDF_KLABEL;
   1275 		else
   1276 			wd->sc_flags &= ~WDF_KLABEL;
   1277 		return 0;
   1278 
   1279 	case DIOCWLABEL:
   1280 		if ((flag & FWRITE) == 0)
   1281 			return EBADF;
   1282 		if (*(int *)addr)
   1283 			wd->sc_flags |= WDF_WLABEL;
   1284 		else
   1285 			wd->sc_flags &= ~WDF_WLABEL;
   1286 		return 0;
   1287 
   1288 	case DIOCGDEFLABEL:
   1289 		wdgetdefaultlabel(wd, (struct disklabel *)addr);
   1290 		return 0;
   1291 #ifdef __HAVE_OLD_DISKLABEL
   1292 	case ODIOCGDEFLABEL:
   1293 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1294 		if (newlabel == NULL)
   1295 			return EIO;
   1296 		wdgetdefaultlabel(wd, newlabel);
   1297 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
   1298 			memcpy(addr, &newlabel, sizeof (struct olddisklabel));
   1299 		else
   1300 			error = ENOTTY;
   1301 		free(newlabel, M_TEMP);
   1302 		return error;
   1303 #endif
   1304 
   1305 #ifdef notyet
   1306 	case DIOCWFORMAT:
   1307 		if ((flag & FWRITE) == 0)
   1308 			return EBADF;
   1309 		{
   1310 		register struct format_op *fop;
   1311 		struct iovec aiov;
   1312 		struct uio auio;
   1313 
   1314 		fop = (struct format_op *)addr;
   1315 		aiov.iov_base = fop->df_buf;
   1316 		aiov.iov_len = fop->df_count;
   1317 		auio.uio_iov = &aiov;
   1318 		auio.uio_iovcnt = 1;
   1319 		auio.uio_resid = fop->df_count;
   1320 		auio.uio_segflg = 0;
   1321 		auio.uio_offset =
   1322 			fop->df_startblk * wd->sc_dk.dk_label->d_secsize;
   1323 		auio.uio_procp = p;
   1324 		error = physio(wdformat, NULL, dev, B_WRITE, minphys,
   1325 		    &auio);
   1326 		fop->df_count -= auio.uio_resid;
   1327 		fop->df_reg[0] = wdc->sc_status;
   1328 		fop->df_reg[1] = wdc->sc_error;
   1329 		return error;
   1330 		}
   1331 #endif
   1332 	case DIOCGCACHE:
   1333 		return wd_getcache(wd, (int *)addr);
   1334 
   1335 	case DIOCSCACHE:
   1336 		return wd_setcache(wd, *(int *)addr);
   1337 
   1338 	case DIOCCACHESYNC:
   1339 		return wd_flushcache(wd, AT_WAIT);
   1340 
   1341 	case ATAIOCCOMMAND:
   1342 		/*
   1343 		 * Make sure this command is (relatively) safe first
   1344 		 */
   1345 		if ((((atareq_t *) addr)->flags & ATACMD_READ) == 0 &&
   1346 		    (flag & FWRITE) == 0)
   1347 			return (EBADF);
   1348 		{
   1349 		struct wd_ioctl *wi;
   1350 		atareq_t *atareq = (atareq_t *) addr;
   1351 		int error;
   1352 
   1353 		wi = wi_get();
   1354 		wi->wi_softc = wd;
   1355 		wi->wi_atareq = *atareq;
   1356 
   1357 		if (atareq->datalen && atareq->flags &
   1358 		    (ATACMD_READ | ATACMD_WRITE)) {
   1359 			wi->wi_iov.iov_base = atareq->databuf;
   1360 			wi->wi_iov.iov_len = atareq->datalen;
   1361 			wi->wi_uio.uio_iov = &wi->wi_iov;
   1362 			wi->wi_uio.uio_iovcnt = 1;
   1363 			wi->wi_uio.uio_resid = atareq->datalen;
   1364 			wi->wi_uio.uio_offset = 0;
   1365 			wi->wi_uio.uio_segflg = UIO_USERSPACE;
   1366 			wi->wi_uio.uio_rw =
   1367 			    (atareq->flags & ATACMD_READ) ? B_READ : B_WRITE;
   1368 			wi->wi_uio.uio_procp = p;
   1369 			error = physio(wdioctlstrategy, &wi->wi_bp, dev,
   1370 			    (atareq->flags & ATACMD_READ) ? B_READ : B_WRITE,
   1371 			    minphys, &wi->wi_uio);
   1372 		} else {
   1373 			/* No need to call physio if we don't have any
   1374 			   user data */
   1375 			wi->wi_bp.b_flags = 0;
   1376 			wi->wi_bp.b_data = 0;
   1377 			wi->wi_bp.b_bcount = 0;
   1378 			wi->wi_bp.b_dev = 0;
   1379 			wi->wi_bp.b_proc = p;
   1380 			wdioctlstrategy(&wi->wi_bp);
   1381 			error = wi->wi_bp.b_error;
   1382 		}
   1383 		*atareq = wi->wi_atareq;
   1384 		wi_free(wi);
   1385 		return(error);
   1386 		}
   1387 
   1388 	default:
   1389 		return ENOTTY;
   1390 	}
   1391 
   1392 #ifdef DIAGNOSTIC
   1393 	panic("wdioctl: impossible");
   1394 #endif
   1395 }
   1396 
   1397 #ifdef B_FORMAT
   1398 int
   1399 wdformat(struct buf *bp)
   1400 {
   1401 
   1402 	bp->b_flags |= B_FORMAT;
   1403 	return wdstrategy(bp);
   1404 }
   1405 #endif
   1406 
   1407 int
   1408 wdsize(dev_t dev)
   1409 {
   1410 	struct wd_softc *wd;
   1411 	int part, omask;
   1412 	int size;
   1413 
   1414 	ATADEBUG_PRINT(("wdsize\n"), DEBUG_FUNCS);
   1415 
   1416 	wd = device_lookup(&wd_cd, WDUNIT(dev));
   1417 	if (wd == NULL)
   1418 		return (-1);
   1419 
   1420 	part = WDPART(dev);
   1421 	omask = wd->sc_dk.dk_openmask & (1 << part);
   1422 
   1423 	if (omask == 0 && wdopen(dev, 0, S_IFBLK, NULL) != 0)
   1424 		return (-1);
   1425 	if (wd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
   1426 		size = -1;
   1427 	else
   1428 		size = wd->sc_dk.dk_label->d_partitions[part].p_size *
   1429 		    (wd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
   1430 	if (omask == 0 && wdclose(dev, 0, S_IFBLK, NULL) != 0)
   1431 		return (-1);
   1432 	return (size);
   1433 }
   1434 
   1435 /* #define WD_DUMP_NOT_TRUSTED if you just want to watch */
   1436 static int wddoingadump = 0;
   1437 static int wddumprecalibrated = 0;
   1438 static int wddumpmulti = 1;
   1439 
   1440 /*
   1441  * Dump core after a system crash.
   1442  */
   1443 int
   1444 wddump(dev_t dev, daddr_t blkno, caddr_t va, size_t size)
   1445 {
   1446 	struct wd_softc *wd;	/* disk unit to do the I/O */
   1447 	struct disklabel *lp;   /* disk's disklabel */
   1448 	int part, err;
   1449 	int nblks;	/* total number of sectors left to write */
   1450 
   1451 	/* Check if recursive dump; if so, punt. */
   1452 	if (wddoingadump)
   1453 		return EFAULT;
   1454 	wddoingadump = 1;
   1455 
   1456 	wd = device_lookup(&wd_cd, WDUNIT(dev));
   1457 	if (wd == NULL)
   1458 		return (ENXIO);
   1459 
   1460 	part = WDPART(dev);
   1461 
   1462 	/* Convert to disk sectors.  Request must be a multiple of size. */
   1463 	lp = wd->sc_dk.dk_label;
   1464 	if ((size % lp->d_secsize) != 0)
   1465 		return EFAULT;
   1466 	nblks = size / lp->d_secsize;
   1467 	blkno = blkno / (lp->d_secsize / DEV_BSIZE);
   1468 
   1469 	/* Check transfer bounds against partition size. */
   1470 	if ((blkno < 0) || ((blkno + nblks) > lp->d_partitions[part].p_size))
   1471 		return EINVAL;
   1472 
   1473 	/* Offset block number to start of partition. */
   1474 	blkno += lp->d_partitions[part].p_offset;
   1475 
   1476 	/* Recalibrate, if first dump transfer. */
   1477 	if (wddumprecalibrated == 0) {
   1478 		wddumpmulti = wd->sc_multi;
   1479 		wddumprecalibrated = 1;
   1480 		(*wd->atabus->ata_reset_drive)(wd->drvp,
   1481 					       AT_POLL | AT_RST_EMERG);
   1482 		wd->drvp->state = RESET;
   1483 	}
   1484 
   1485 	while (nblks > 0) {
   1486 		wd->sc_bp = NULL;
   1487 		wd->sc_wdc_bio.blkno = blkno;
   1488 		wd->sc_wdc_bio.flags = ATA_POLL;
   1489 		if (wd->sc_flags & WDF_LBA48 && blkno > LBA48_THRESHOLD)
   1490 			wd->sc_wdc_bio.flags |= ATA_LBA48;
   1491 		if (wd->sc_flags & WDF_LBA)
   1492 			wd->sc_wdc_bio.flags |= ATA_LBA;
   1493 		wd->sc_wdc_bio.bcount =
   1494 			min(nblks, wddumpmulti) * lp->d_secsize;
   1495 		wd->sc_wdc_bio.databuf = va;
   1496 #ifndef WD_DUMP_NOT_TRUSTED
   1497 		switch (wd->atabus->ata_bio(wd->drvp, &wd->sc_wdc_bio)) {
   1498 		case ATACMD_TRY_AGAIN:
   1499 			panic("wddump: try again");
   1500 			break;
   1501 		case ATACMD_QUEUED:
   1502 			panic("wddump: polled command has been queued");
   1503 			break;
   1504 		case ATACMD_COMPLETE:
   1505 			break;
   1506 		}
   1507 		switch(wd->sc_wdc_bio.error) {
   1508 		case TIMEOUT:
   1509 			printf("wddump: device timed out");
   1510 			err = EIO;
   1511 			break;
   1512 		case ERR_DF:
   1513 			printf("wddump: drive fault");
   1514 			err = EIO;
   1515 			break;
   1516 		case ERR_DMA:
   1517 			printf("wddump: DMA error");
   1518 			err = EIO;
   1519 			break;
   1520 		case ERROR:
   1521 			printf("wddump: ");
   1522 			wdperror(wd);
   1523 			err = EIO;
   1524 			break;
   1525 		case NOERROR:
   1526 			err = 0;
   1527 			break;
   1528 		default:
   1529 			panic("wddump: unknown error type");
   1530 		}
   1531 		if (err != 0) {
   1532 			printf("\n");
   1533 			return err;
   1534 		}
   1535 #else	/* WD_DUMP_NOT_TRUSTED */
   1536 		/* Let's just talk about this first... */
   1537 		printf("wd%d: dump addr 0x%x, cylin %d, head %d, sector %d\n",
   1538 		    unit, va, cylin, head, sector);
   1539 		delay(500 * 1000);	/* half a second */
   1540 #endif
   1541 
   1542 		/* update block count */
   1543 		nblks -= min(nblks, wddumpmulti);
   1544 		blkno += min(nblks, wddumpmulti);
   1545 		va += min(nblks, wddumpmulti) * lp->d_secsize;
   1546 	}
   1547 
   1548 	wddoingadump = 0;
   1549 	return 0;
   1550 }
   1551 
   1552 #ifdef HAS_BAD144_HANDLING
   1553 /*
   1554  * Internalize the bad sector table.
   1555  */
   1556 void
   1557 bad144intern(struct wd_softc *wd)
   1558 {
   1559 	struct dkbad *bt = &wd->sc_dk.dk_cpulabel->bad;
   1560 	struct disklabel *lp = wd->sc_dk.dk_label;
   1561 	int i = 0;
   1562 
   1563 	ATADEBUG_PRINT(("bad144intern\n"), DEBUG_XFERS);
   1564 
   1565 	for (; i < NBT_BAD; i++) {
   1566 		if (bt->bt_bad[i].bt_cyl == 0xffff)
   1567 			break;
   1568 		wd->sc_badsect[i] =
   1569 		    bt->bt_bad[i].bt_cyl * lp->d_secpercyl +
   1570 		    (bt->bt_bad[i].bt_trksec >> 8) * lp->d_nsectors +
   1571 		    (bt->bt_bad[i].bt_trksec & 0xff);
   1572 	}
   1573 	for (; i < NBT_BAD+1; i++)
   1574 		wd->sc_badsect[i] = -1;
   1575 }
   1576 #endif
   1577 
   1578 int
   1579 wd_get_params(struct wd_softc *wd, u_int8_t flags, struct ataparams *params)
   1580 {
   1581 	switch (wd->atabus->ata_get_params(wd->drvp, flags, params)) {
   1582 	case CMD_AGAIN:
   1583 		return 1;
   1584 	case CMD_ERR:
   1585 		/*
   1586 		 * We `know' there's a drive here; just assume it's old.
   1587 		 * This geometry is only used to read the MBR and print a
   1588 		 * (false) attach message.
   1589 		 */
   1590 		strncpy(params->atap_model, "ST506",
   1591 		    sizeof params->atap_model);
   1592 		params->atap_config = ATA_CFG_FIXED;
   1593 		params->atap_cylinders = 1024;
   1594 		params->atap_heads = 8;
   1595 		params->atap_sectors = 17;
   1596 		params->atap_multi = 1;
   1597 		params->atap_capabilities1 = params->atap_capabilities2 = 0;
   1598 		wd->drvp->ata_vers = -1; /* Mark it as pre-ATA */
   1599 		return 0;
   1600 	case CMD_OK:
   1601 		return 0;
   1602 	default:
   1603 		panic("wd_get_params: bad return code from ata_get_params");
   1604 		/* NOTREACHED */
   1605 	}
   1606 }
   1607 
   1608 int
   1609 wd_getcache(struct wd_softc *wd, int *bitsp)
   1610 {
   1611 	struct ataparams params;
   1612 
   1613 	if (wd_get_params(wd, AT_WAIT, &params) != 0)
   1614 		return EIO;
   1615 	if (params.atap_cmd_set1 == 0x0000 ||
   1616 	    params.atap_cmd_set1 == 0xffff ||
   1617 	    (params.atap_cmd_set1 & WDC_CMD1_CACHE) == 0) {
   1618 		*bitsp = 0;
   1619 		return 0;
   1620 	}
   1621 	*bitsp = DKCACHE_WCHANGE | DKCACHE_READ;
   1622 	if (params.atap_cmd1_en & WDC_CMD1_CACHE)
   1623 		*bitsp |= DKCACHE_WRITE;
   1624 
   1625 	return 0;
   1626 }
   1627 
   1628 const char at_errbits[] = "\20\10ERROR\11TIMEOU\12DF";
   1629 
   1630 int
   1631 wd_setcache(struct wd_softc *wd, int bits)
   1632 {
   1633 	struct ataparams params;
   1634 	struct ata_command ata_c;
   1635 
   1636 	if (wd_get_params(wd, AT_WAIT, &params) != 0)
   1637 		return EIO;
   1638 
   1639 	if (params.atap_cmd_set1 == 0x0000 ||
   1640 	    params.atap_cmd_set1 == 0xffff ||
   1641 	    (params.atap_cmd_set1 & WDC_CMD1_CACHE) == 0)
   1642 		return EOPNOTSUPP;
   1643 
   1644 	if ((bits & DKCACHE_READ) == 0 ||
   1645 	    (bits & DKCACHE_SAVE) != 0)
   1646 		return EOPNOTSUPP;
   1647 
   1648 	memset(&ata_c, 0, sizeof(struct ata_command));
   1649 	ata_c.r_command = SET_FEATURES;
   1650 	ata_c.r_st_bmask = 0;
   1651 	ata_c.r_st_pmask = 0;
   1652 	ata_c.timeout = 30000; /* 30s timeout */
   1653 	ata_c.flags = AT_WAIT;
   1654 	if (bits & DKCACHE_WRITE)
   1655 		ata_c.r_features = WDSF_WRITE_CACHE_EN;
   1656 	else
   1657 		ata_c.r_features = WDSF_WRITE_CACHE_DS;
   1658 	if (wd->atabus->ata_exec_command(wd->drvp, &ata_c) != ATACMD_COMPLETE) {
   1659 		printf("%s: wd_setcache command not complete\n",
   1660 		    wd->sc_dev.dv_xname);
   1661 		return EIO;
   1662 	}
   1663 	if (ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1664 		char sbuf[sizeof(at_errbits) + 64];
   1665 		bitmask_snprintf(ata_c.flags, at_errbits, sbuf, sizeof(sbuf));
   1666 		printf("%s: wd_setcache: status=%s\n", wd->sc_dev.dv_xname,
   1667 		    sbuf);
   1668 		return EIO;
   1669 	}
   1670 	return 0;
   1671 }
   1672 
   1673 int
   1674 wd_standby(struct wd_softc *wd, int flags)
   1675 {
   1676 	struct ata_command ata_c;
   1677 
   1678 	memset(&ata_c, 0, sizeof(struct ata_command));
   1679 	ata_c.r_command = WDCC_STANDBY_IMMED;
   1680 	ata_c.r_st_bmask = WDCS_DRDY;
   1681 	ata_c.r_st_pmask = WDCS_DRDY;
   1682 	ata_c.flags = flags;
   1683 	ata_c.timeout = 30000; /* 30s timeout */
   1684 	if (wd->atabus->ata_exec_command(wd->drvp, &ata_c) != ATACMD_COMPLETE) {
   1685 		printf("%s: standby immediate command didn't complete\n",
   1686 		    wd->sc_dev.dv_xname);
   1687 		return EIO;
   1688 	}
   1689 	if (ata_c.flags & AT_ERROR) {
   1690 		if (ata_c.r_error == WDCE_ABRT) /* command not supported */
   1691 			return ENODEV;
   1692 	}
   1693 	if (ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1694 		char sbuf[sizeof(at_errbits) + 64];
   1695 		bitmask_snprintf(ata_c.flags, at_errbits, sbuf, sizeof(sbuf));
   1696 		printf("%s: wd_standby: status=%s\n", wd->sc_dev.dv_xname,
   1697 		    sbuf);
   1698 		return EIO;
   1699 	}
   1700 	return 0;
   1701 }
   1702 
   1703 int
   1704 wd_flushcache(struct wd_softc *wd, int flags)
   1705 {
   1706 	struct ata_command ata_c;
   1707 
   1708 	if (wd->drvp->ata_vers < 4) /* WDCC_FLUSHCACHE is here since ATA-4 */
   1709 		return ENODEV;
   1710 	memset(&ata_c, 0, sizeof(struct ata_command));
   1711 	if ((wd->sc_params.atap_cmd2_en & ATA_CMD2_LBA48) != 0 &&
   1712 	    (wd->sc_params.atap_cmd2_en & ATA_CMD2_FCE) != 0)
   1713 		ata_c.r_command = WDCC_FLUSHCACHE_EXT;
   1714 	else
   1715 		ata_c.r_command = WDCC_FLUSHCACHE;
   1716 	ata_c.r_st_bmask = WDCS_DRDY;
   1717 	ata_c.r_st_pmask = WDCS_DRDY;
   1718 	ata_c.flags = flags;
   1719 	ata_c.timeout = 30000; /* 30s timeout */
   1720 	if (wd->atabus->ata_exec_command(wd->drvp, &ata_c) != ATACMD_COMPLETE) {
   1721 		printf("%s: flush cache command didn't complete\n",
   1722 		    wd->sc_dev.dv_xname);
   1723 		return EIO;
   1724 	}
   1725 	if (ata_c.flags & AT_ERROR) {
   1726 		if (ata_c.r_error == WDCE_ABRT) /* command not supported */
   1727 			return ENODEV;
   1728 	}
   1729 	if (ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1730 		char sbuf[sizeof(at_errbits) + 64];
   1731 		bitmask_snprintf(ata_c.flags, at_errbits, sbuf, sizeof(sbuf));
   1732 		printf("%s: wd_flushcache: status=%s\n", wd->sc_dev.dv_xname,
   1733 		    sbuf);
   1734 		return EIO;
   1735 	}
   1736 	return 0;
   1737 }
   1738 
   1739 void
   1740 wd_shutdown(void *arg)
   1741 {
   1742 	struct wd_softc *wd = arg;
   1743 	wd_flushcache(wd, AT_POLL);
   1744 }
   1745 
   1746 /*
   1747  * Allocate space for a ioctl queue structure.  Mostly taken from
   1748  * scsipi_ioctl.c
   1749  */
   1750 struct wd_ioctl *
   1751 wi_get(void)
   1752 {
   1753 	struct wd_ioctl *wi;
   1754 	int s;
   1755 
   1756 	wi = malloc(sizeof(struct wd_ioctl), M_TEMP, M_WAITOK|M_ZERO);
   1757 	simple_lock_init(&wi->wi_bp.b_interlock);
   1758 	s = splbio();
   1759 	LIST_INSERT_HEAD(&wi_head, wi, wi_list);
   1760 	splx(s);
   1761 	return (wi);
   1762 }
   1763 
   1764 /*
   1765  * Free an ioctl structure and remove it from our list
   1766  */
   1767 
   1768 void
   1769 wi_free(struct wd_ioctl *wi)
   1770 {
   1771 	int s;
   1772 
   1773 	s = splbio();
   1774 	LIST_REMOVE(wi, wi_list);
   1775 	splx(s);
   1776 	free(wi, M_TEMP);
   1777 }
   1778 
   1779 /*
   1780  * Find a wd_ioctl structure based on the struct buf.
   1781  */
   1782 
   1783 struct wd_ioctl *
   1784 wi_find(struct buf *bp)
   1785 {
   1786 	struct wd_ioctl *wi;
   1787 	int s;
   1788 
   1789 	s = splbio();
   1790 	for (wi = wi_head.lh_first; wi != 0; wi = wi->wi_list.le_next)
   1791 		if (bp == &wi->wi_bp)
   1792 			break;
   1793 	splx(s);
   1794 	return (wi);
   1795 }
   1796 
   1797 /*
   1798  * Ioctl pseudo strategy routine
   1799  *
   1800  * This is mostly stolen from scsipi_ioctl.c:scsistrategy().  What
   1801  * happens here is:
   1802  *
   1803  * - wdioctl() queues a wd_ioctl structure.
   1804  *
   1805  * - wdioctl() calls physio/wdioctlstrategy based on whether or not
   1806  *   user space I/O is required.  If physio() is called, physio() eventually
   1807  *   calls wdioctlstrategy().
   1808  *
   1809  * - In either case, wdioctlstrategy() calls wd->atabus->ata_exec_command()
   1810  *   to perform the actual command
   1811  *
   1812  * The reason for the use of the pseudo strategy routine is because
   1813  * when doing I/O to/from user space, physio _really_ wants to be in
   1814  * the loop.  We could put the entire buffer into the ioctl request
   1815  * structure, but that won't scale if we want to do things like download
   1816  * microcode.
   1817  */
   1818 
   1819 void
   1820 wdioctlstrategy(struct buf *bp)
   1821 {
   1822 	struct wd_ioctl *wi;
   1823 	struct ata_command ata_c;
   1824 	int error = 0;
   1825 
   1826 	wi = wi_find(bp);
   1827 	if (wi == NULL) {
   1828 		printf("user_strat: No ioctl\n");
   1829 		error = EINVAL;
   1830 		goto bad;
   1831 	}
   1832 
   1833 	memset(&ata_c, 0, sizeof(ata_c));
   1834 
   1835 	/*
   1836 	 * Abort if physio broke up the transfer
   1837 	 */
   1838 
   1839 	if (bp->b_bcount != wi->wi_atareq.datalen) {
   1840 		printf("physio split wd ioctl request... cannot proceed\n");
   1841 		error = EIO;
   1842 		goto bad;
   1843 	}
   1844 
   1845 	/*
   1846 	 * Abort if we didn't get a buffer size that was a multiple of
   1847 	 * our sector size (or was larger than NBBY)
   1848 	 */
   1849 
   1850 	if ((bp->b_bcount % wi->wi_softc->sc_dk.dk_label->d_secsize) != 0 ||
   1851 	    (bp->b_bcount / wi->wi_softc->sc_dk.dk_label->d_secsize) >=
   1852 	     (1 << NBBY)) {
   1853 		error = EINVAL;
   1854 		goto bad;
   1855 	}
   1856 
   1857 	/*
   1858 	 * Make sure a timeout was supplied in the ioctl request
   1859 	 */
   1860 
   1861 	if (wi->wi_atareq.timeout == 0) {
   1862 		error = EINVAL;
   1863 		goto bad;
   1864 	}
   1865 
   1866 	if (wi->wi_atareq.flags & ATACMD_READ)
   1867 		ata_c.flags |= AT_READ;
   1868 	else if (wi->wi_atareq.flags & ATACMD_WRITE)
   1869 		ata_c.flags |= AT_WRITE;
   1870 
   1871 	if (wi->wi_atareq.flags & ATACMD_READREG)
   1872 		ata_c.flags |= AT_READREG;
   1873 
   1874 	ata_c.flags |= AT_WAIT;
   1875 
   1876 	ata_c.timeout = wi->wi_atareq.timeout;
   1877 	ata_c.r_command = wi->wi_atareq.command;
   1878 	ata_c.r_head = wi->wi_atareq.head & 0x0f;
   1879 	ata_c.r_cyl = wi->wi_atareq.cylinder;
   1880 	ata_c.r_sector = wi->wi_atareq.sec_num;
   1881 	ata_c.r_count = wi->wi_atareq.sec_count;
   1882 	ata_c.r_features = wi->wi_atareq.features;
   1883 	ata_c.r_st_bmask = WDCS_DRDY;
   1884 	ata_c.r_st_pmask = WDCS_DRDY;
   1885 	ata_c.data = wi->wi_bp.b_data;
   1886 	ata_c.bcount = wi->wi_bp.b_bcount;
   1887 
   1888 	if (wi->wi_softc->atabus->ata_exec_command(wi->wi_softc->drvp, &ata_c)
   1889 	    != ATACMD_COMPLETE) {
   1890 		wi->wi_atareq.retsts = ATACMD_ERROR;
   1891 		goto bad;
   1892 	}
   1893 
   1894 	if (ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1895 		if (ata_c.flags & AT_ERROR) {
   1896 			wi->wi_atareq.retsts = ATACMD_ERROR;
   1897 			wi->wi_atareq.error = ata_c.r_error;
   1898 		} else if (ata_c.flags & AT_DF)
   1899 			wi->wi_atareq.retsts = ATACMD_DF;
   1900 		else
   1901 			wi->wi_atareq.retsts = ATACMD_TIMEOUT;
   1902 	} else {
   1903 		wi->wi_atareq.retsts = ATACMD_OK;
   1904 		if (wi->wi_atareq.flags & ATACMD_READREG) {
   1905 			wi->wi_atareq.head = ata_c.r_head ;
   1906 			wi->wi_atareq.cylinder = ata_c.r_cyl;
   1907 			wi->wi_atareq.sec_num = ata_c.r_sector;
   1908 			wi->wi_atareq.sec_count = ata_c.r_count;
   1909 			wi->wi_atareq.features = ata_c.r_features;
   1910 			wi->wi_atareq.error = ata_c.r_error;
   1911 		}
   1912 	}
   1913 
   1914 	bp->b_error = 0;
   1915 	biodone(bp);
   1916 	return;
   1917 bad:
   1918 	bp->b_flags |= B_ERROR;
   1919 	bp->b_error = error;
   1920 	biodone(bp);
   1921 }
   1922