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