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