Home | History | Annotate | Line # | Download | only in ata
wd.c revision 1.428.2.27
      1 /*	$NetBSD: wd.c,v 1.428.2.27 2017/07/19 19:46:52 jdolecek 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  *
     15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     25  */
     26 
     27 /*-
     28  * Copyright (c) 1998, 2003, 2004 The NetBSD Foundation, Inc.
     29  * All rights reserved.
     30  *
     31  * This code is derived from software contributed to The NetBSD Foundation
     32  * by Charles M. Hannum and by Onno van der Linden.
     33  *
     34  * Redistribution and use in source and binary forms, with or without
     35  * modification, are permitted provided that the following conditions
     36  * are met:
     37  * 1. Redistributions of source code must retain the above copyright
     38  *    notice, this list of conditions and the following disclaimer.
     39  * 2. Redistributions in binary form must reproduce the above copyright
     40  *    notice, this list of conditions and the following disclaimer in the
     41  *    documentation and/or other materials provided with the distribution.
     42  *
     43  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     44  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     45  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     46  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     47  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     48  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     49  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     50  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     51  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     52  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     53  * POSSIBILITY OF SUCH DAMAGE.
     54  */
     55 
     56 #include <sys/cdefs.h>
     57 __KERNEL_RCSID(0, "$NetBSD: wd.c,v 1.428.2.27 2017/07/19 19:46:52 jdolecek Exp $");
     58 
     59 #include "opt_ata.h"
     60 #include "opt_wd.h"
     61 
     62 #include <sys/param.h>
     63 #include <sys/systm.h>
     64 #include <sys/kernel.h>
     65 #include <sys/conf.h>
     66 #include <sys/file.h>
     67 #include <sys/stat.h>
     68 #include <sys/ioctl.h>
     69 #include <sys/buf.h>
     70 #include <sys/bufq.h>
     71 #include <sys/uio.h>
     72 #include <sys/malloc.h>
     73 #include <sys/device.h>
     74 #include <sys/disklabel.h>
     75 #include <sys/disk.h>
     76 #include <sys/syslog.h>
     77 #include <sys/proc.h>
     78 #include <sys/reboot.h>
     79 #include <sys/vnode.h>
     80 #include <sys/rndsource.h>
     81 
     82 #include <sys/intr.h>
     83 #include <sys/bus.h>
     84 
     85 #include <dev/ata/atareg.h>
     86 #include <dev/ata/atavar.h>
     87 #include <dev/ata/wdvar.h>
     88 #include <dev/ic/wdcreg.h>
     89 #include <sys/ataio.h>
     90 #include "locators.h"
     91 
     92 #include <prop/proplib.h>
     93 
     94 #define	WDIORETRIES_SINGLE 4	/* number of retries for single-sector */
     95 #define	WDIORETRIES	5	/* number of retries before giving up */
     96 #define	RECOVERYTIME hz/2	/* time to wait before retrying a cmd */
     97 
     98 #define	WDUNIT(dev)		DISKUNIT(dev)
     99 #define	WDPART(dev)		DISKPART(dev)
    100 #define	WDMINOR(unit, part)	DISKMINOR(unit, part)
    101 #define	MAKEWDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
    102 
    103 #define	WDLABELDEV(dev)	(MAKEWDDEV(major(dev), WDUNIT(dev), RAW_PART))
    104 
    105 #define DEBUG_INTR   0x01
    106 #define DEBUG_XFERS  0x02
    107 #define DEBUG_STATUS 0x04
    108 #define DEBUG_FUNCS  0x08
    109 #define DEBUG_PROBE  0x10
    110 #ifdef ATADEBUG
    111 int wdcdebug_wd_mask = 0x0;
    112 #define ATADEBUG_PRINT(args, level) \
    113 	if (wdcdebug_wd_mask & (level)) \
    114 		printf args
    115 #else
    116 #define ATADEBUG_PRINT(args, level)
    117 #endif
    118 
    119 #ifdef WD_CHAOS_MONKEY
    120 int wdcdebug_wd_cnt = 200;
    121 int wdcdebug_wd_chaos = 0;
    122 #endif
    123 
    124 int	wdprobe(device_t, cfdata_t, void *);
    125 void	wdattach(device_t, device_t, void *);
    126 int	wddetach(device_t, int);
    127 int	wdprint(void *, char *);
    128 void	wdperror(const struct wd_softc *, struct ata_xfer *);
    129 
    130 static void	wdminphys(struct buf *);
    131 
    132 static int	wdlastclose(device_t);
    133 static bool	wd_suspend(device_t, const pmf_qual_t *);
    134 static int	wd_standby(struct wd_softc *, int);
    135 
    136 CFATTACH_DECL3_NEW(wd, sizeof(struct wd_softc),
    137     wdprobe, wdattach, wddetach, NULL, NULL, NULL, DVF_DETACH_SHUTDOWN);
    138 
    139 extern struct cfdriver wd_cd;
    140 
    141 dev_type_open(wdopen);
    142 dev_type_close(wdclose);
    143 dev_type_read(wdread);
    144 dev_type_write(wdwrite);
    145 dev_type_ioctl(wdioctl);
    146 dev_type_strategy(wdstrategy);
    147 dev_type_dump(wddump);
    148 dev_type_size(wdsize);
    149 static dev_type_discard(wddiscard);
    150 
    151 const struct bdevsw wd_bdevsw = {
    152 	.d_open = wdopen,
    153 	.d_close = wdclose,
    154 	.d_strategy = wdstrategy,
    155 	.d_ioctl = wdioctl,
    156 	.d_dump = wddump,
    157 	.d_psize = wdsize,
    158 	.d_discard = wddiscard,
    159 	.d_flag = D_DISK
    160 };
    161 
    162 const struct cdevsw wd_cdevsw = {
    163 	.d_open = wdopen,
    164 	.d_close = wdclose,
    165 	.d_read = wdread,
    166 	.d_write = wdwrite,
    167 	.d_ioctl = wdioctl,
    168 	.d_stop = nostop,
    169 	.d_tty = notty,
    170 	.d_poll = nopoll,
    171 	.d_mmap = nommap,
    172 	.d_kqfilter = nokqfilter,
    173 	.d_discard = wddiscard,
    174 	.d_flag = D_DISK
    175 };
    176 
    177 /* #define WD_DUMP_NOT_TRUSTED if you just want to watch */
    178 static int wddoingadump = 0;
    179 static int wddumprecalibrated = 0;
    180 
    181 /*
    182  * Glue necessary to hook WDCIOCCOMMAND into physio
    183  */
    184 
    185 struct wd_ioctl {
    186 	LIST_ENTRY(wd_ioctl) wi_list;
    187 	struct buf wi_bp;
    188 	struct uio wi_uio;
    189 	struct iovec wi_iov;
    190 	atareq_t wi_atareq;
    191 	struct wd_softc *wi_softc;
    192 };
    193 
    194 struct	wd_ioctl *wi_find(struct buf *);
    195 void	wi_free(struct wd_ioctl *);
    196 struct	wd_ioctl *wi_get(struct wd_softc *);
    197 void	wdioctlstrategy(struct buf *);
    198 
    199 void  wdgetdefaultlabel(struct wd_softc *, struct disklabel *);
    200 void  wdgetdisklabel(struct wd_softc *);
    201 void  wdstart(device_t);
    202 void  wdstart1(struct wd_softc *, struct buf *, struct ata_xfer *);
    203 static void  wdbiorestart(void *);
    204 void  wddone(device_t, struct ata_xfer *);
    205 static void wd_params_to_properties(struct wd_softc *);
    206 int   wd_get_params(struct wd_softc *, uint8_t, struct ataparams *);
    207 int   wd_flushcache(struct wd_softc *, int, bool);
    208 int   wd_trim(struct wd_softc *, int, daddr_t, long);
    209 bool  wd_shutdown(device_t, int);
    210 
    211 int   wd_getcache(struct wd_softc *, int *);
    212 int   wd_setcache(struct wd_softc *, int);
    213 
    214 struct dkdriver wddkdriver = {
    215 	.d_strategy = wdstrategy,
    216 	.d_minphys = wdminphys
    217 };
    218 
    219 #ifdef HAS_BAD144_HANDLING
    220 static void bad144intern(struct wd_softc *);
    221 #endif
    222 
    223 #define	WD_QUIRK_SPLIT_MOD15_WRITE	0x0001	/* must split certain writes */
    224 
    225 #define	WD_QUIRK_FMT "\20\1SPLIT_MOD15_WRITE\2FORCE_LBA48"
    226 
    227 /*
    228  * Quirk table for IDE drives.  Put more-specific matches first, since
    229  * a simple globing routine is used for matching.
    230  */
    231 static const struct wd_quirk {
    232 	const char *wdq_match;		/* inquiry pattern to match */
    233 	int wdq_quirks;			/* drive quirks */
    234 } wd_quirk_table[] = {
    235 	/*
    236 	 * Some Seagate S-ATA drives have a PHY which can get confused
    237 	 * with the way data is packetized by some S-ATA controllers.
    238 	 *
    239 	 * The work-around is to split in two any write transfer whose
    240 	 * sector count % 15 == 1 (assuming 512 byte sectors).
    241 	 *
    242 	 * XXX This is an incomplete list.  There are at least a couple
    243 	 * XXX more model numbers.  If you have trouble with such transfers
    244 	 * XXX (8K is the most common) on Seagate S-ATA drives, please
    245 	 * XXX notify thorpej (at) NetBSD.org.
    246 	 *
    247 	 * The ST360015AS has not yet been confirmed to have this
    248 	 * issue, however, it is the only other drive in the
    249 	 * Seagate Barracuda Serial ATA V family.
    250 	 *
    251 	 */
    252 	{ "ST3120023AS",
    253 	  WD_QUIRK_SPLIT_MOD15_WRITE },
    254 	{ "ST380023AS",
    255 	  WD_QUIRK_SPLIT_MOD15_WRITE },
    256 	{ "ST360015AS",
    257 	  WD_QUIRK_SPLIT_MOD15_WRITE },
    258 	{ NULL,
    259 	  0 }
    260 };
    261 
    262 static const struct wd_quirk *
    263 wd_lookup_quirks(const char *name)
    264 {
    265 	const struct wd_quirk *wdq;
    266 	const char *estr;
    267 
    268 	for (wdq = wd_quirk_table; wdq->wdq_match != NULL; wdq++) {
    269 		/*
    270 		 * We only want exact matches (which include matches
    271 		 * against globbing characters).
    272 		 */
    273 		if (pmatch(name, wdq->wdq_match, &estr) == 2)
    274 			return (wdq);
    275 	}
    276 	return (NULL);
    277 }
    278 
    279 int
    280 wdprobe(device_t parent, cfdata_t match, void *aux)
    281 {
    282 	struct ata_device *adev = aux;
    283 
    284 	if (adev == NULL)
    285 		return 0;
    286 	if (adev->adev_bustype->bustype_type != SCSIPI_BUSTYPE_ATA)
    287 		return 0;
    288 
    289 	if (match->cf_loc[ATA_HLCF_DRIVE] != ATA_HLCF_DRIVE_DEFAULT &&
    290 	    match->cf_loc[ATA_HLCF_DRIVE] != adev->adev_drv_data->drive)
    291 		return 0;
    292 	return 1;
    293 }
    294 
    295 void
    296 wdattach(device_t parent, device_t self, void *aux)
    297 {
    298 	struct wd_softc *wd = device_private(self);
    299 	struct ata_device *adev= aux;
    300 	int i, blank;
    301 	char tbuf[41], pbuf[9], c, *p, *q;
    302 	const struct wd_quirk *wdq;
    303 
    304 	wd->sc_dev = self;
    305 
    306 	ATADEBUG_PRINT(("wdattach\n"), DEBUG_FUNCS | DEBUG_PROBE);
    307 	mutex_init(&wd->sc_lock, MUTEX_DEFAULT, IPL_BIO);
    308 	bufq_alloc(&wd->sc_q, BUFQ_DISK_DEFAULT_STRAT, BUFQ_SORT_RAWBLOCK);
    309 #ifdef WD_SOFTBADSECT
    310 	SLIST_INIT(&wd->sc_bslist);
    311 #endif
    312 	wd->atabus = adev->adev_bustype;
    313 	wd->drvp = adev->adev_drv_data;
    314 
    315 	wd->drvp->drv_openings = 1;
    316 	wd->drvp->drv_start = wdstart;
    317 	wd->drvp->drv_done = wddone;
    318 	wd->drvp->drv_softc = wd->sc_dev; /* done in atabusconfig_thread()
    319 					     but too late */
    320 
    321 	aprint_naive("\n");
    322 	aprint_normal("\n");
    323 
    324 	/* read our drive info */
    325 	if (wd_get_params(wd, AT_WAIT, &wd->sc_params) != 0) {
    326 		aprint_error_dev(self, "IDENTIFY failed\n");
    327 		goto out;
    328 	}
    329 
    330 	for (blank = 0, p = wd->sc_params.atap_model, q = tbuf, i = 0;
    331 	    i < sizeof(wd->sc_params.atap_model); i++) {
    332 		c = *p++;
    333 		if (c == '\0')
    334 			break;
    335 		if (c != ' ') {
    336 			if (blank) {
    337 				*q++ = ' ';
    338 				blank = 0;
    339 			}
    340 			*q++ = c;
    341 		} else
    342 			blank = 1;
    343 	}
    344 	*q++ = '\0';
    345 
    346 	aprint_normal_dev(self, "<%s>\n", tbuf);
    347 
    348 	wdq = wd_lookup_quirks(tbuf);
    349 	if (wdq != NULL)
    350 		wd->sc_quirks = wdq->wdq_quirks;
    351 
    352 	if (wd->sc_quirks != 0) {
    353 		char sbuf[sizeof(WD_QUIRK_FMT) + 64];
    354 		snprintb(sbuf, sizeof(sbuf), WD_QUIRK_FMT, wd->sc_quirks);
    355 		aprint_normal_dev(self, "quirks %s\n", sbuf);
    356 
    357 		if (wd->sc_quirks & WD_QUIRK_SPLIT_MOD15_WRITE) {
    358 			aprint_error_dev(self, "drive corrupts write transfers with certain controllers, consider replacing\n");
    359 		}
    360 	}
    361 
    362 	if ((wd->sc_params.atap_multi & 0xff) > 1) {
    363 		wd->drvp->multi = wd->sc_params.atap_multi & 0xff;
    364 	} else {
    365 		wd->drvp->multi = 1;
    366 	}
    367 
    368 	aprint_verbose_dev(self, "drive supports %d-sector PIO transfers,",
    369 	    wd->drvp->multi);
    370 
    371 	/* 48-bit LBA addressing */
    372 	if ((wd->sc_params.atap_cmd2_en & ATA_CMD2_LBA48) != 0)
    373 		wd->sc_flags |= WDF_LBA48;
    374 
    375 	/* Prior to ATA-4, LBA was optional. */
    376 	if ((wd->sc_params.atap_capabilities1 & WDC_CAP_LBA) != 0)
    377 		wd->sc_flags |= WDF_LBA;
    378 #if 0
    379 	/* ATA-4 requires LBA. */
    380 	if (wd->sc_params.atap_ataversion != 0xffff &&
    381 	    wd->sc_params.atap_ataversion >= WDC_VER_ATA4)
    382 		wd->sc_flags |= WDF_LBA;
    383 #endif
    384 
    385 	if ((wd->sc_flags & WDF_LBA48) != 0) {
    386 		aprint_verbose(" LBA48 addressing\n");
    387 		wd->sc_capacity =
    388 		    ((uint64_t) wd->sc_params.atap_max_lba[3] << 48) |
    389 		    ((uint64_t) wd->sc_params.atap_max_lba[2] << 32) |
    390 		    ((uint64_t) wd->sc_params.atap_max_lba[1] << 16) |
    391 		    ((uint64_t) wd->sc_params.atap_max_lba[0] <<  0);
    392 		wd->sc_capacity28 =
    393 		    (wd->sc_params.atap_capacity[1] << 16) |
    394 		    wd->sc_params.atap_capacity[0];
    395 	} else if ((wd->sc_flags & WDF_LBA) != 0) {
    396 		aprint_verbose(" LBA addressing\n");
    397 		wd->sc_capacity28 = wd->sc_capacity =
    398 		    (wd->sc_params.atap_capacity[1] << 16) |
    399 		    wd->sc_params.atap_capacity[0];
    400 	} else {
    401 		aprint_verbose(" chs addressing\n");
    402 		wd->sc_capacity28 = wd->sc_capacity =
    403 		    wd->sc_params.atap_cylinders *
    404 		    wd->sc_params.atap_heads *
    405 		    wd->sc_params.atap_sectors;
    406 	}
    407 	if ((wd->sc_params.atap_secsz & ATA_SECSZ_VALID_MASK) == ATA_SECSZ_VALID
    408 	    && ((wd->sc_params.atap_secsz & ATA_SECSZ_LLS) != 0)) {
    409 		wd->sc_blksize = 2ULL *
    410 		    ((uint32_t)((wd->sc_params.atap_lls_secsz[1] << 16) |
    411 		    wd->sc_params.atap_lls_secsz[0]));
    412 	} else {
    413 		wd->sc_blksize = 512;
    414 	}
    415 	wd->sc_capacity512 = (wd->sc_capacity * wd->sc_blksize) / DEV_BSIZE;
    416 	format_bytes(pbuf, sizeof(pbuf), wd->sc_capacity * wd->sc_blksize);
    417 	aprint_normal_dev(self, "%s, %d cyl, %d head, %d sec, "
    418 	    "%d bytes/sect x %llu sectors\n",
    419 	    pbuf,
    420 	    (wd->sc_flags & WDF_LBA) ? (int)(wd->sc_capacity /
    421 		(wd->sc_params.atap_heads * wd->sc_params.atap_sectors)) :
    422 		wd->sc_params.atap_cylinders,
    423 	    wd->sc_params.atap_heads, wd->sc_params.atap_sectors,
    424 	    wd->sc_blksize, (unsigned long long)wd->sc_capacity);
    425 
    426 	ATADEBUG_PRINT(("%s: atap_dmatiming_mimi=%d, atap_dmatiming_recom=%d\n",
    427 	    device_xname(self), wd->sc_params.atap_dmatiming_mimi,
    428 	    wd->sc_params.atap_dmatiming_recom), DEBUG_PROBE);
    429 
    430 	if (wd->sc_blksize <= 0 || !powerof2(wd->sc_blksize) ||
    431 	    wd->sc_blksize < DEV_BSIZE || wd->sc_blksize > MAXPHYS) {
    432 		aprint_normal_dev(self, "WARNING: block size %u "
    433 		    "might not actually work\n", wd->sc_blksize);
    434 	}
    435 
    436 out:
    437 	/*
    438 	 * Initialize and attach the disk structure.
    439 	 */
    440 	/* we fill in dk_info later */
    441 	disk_init(&wd->sc_dk, device_xname(wd->sc_dev), &wddkdriver);
    442 	disk_attach(&wd->sc_dk);
    443 	wd->drvp->lp = wd->sc_dk.dk_label;
    444 	wd_params_to_properties(wd);
    445 	rnd_attach_source(&wd->rnd_source, device_xname(wd->sc_dev),
    446 			  RND_TYPE_DISK, RND_FLAG_DEFAULT);
    447 
    448 	/* Discover wedges on this disk. */
    449 	dkwedge_discover(&wd->sc_dk);
    450 
    451 	if (!pmf_device_register1(self, wd_suspend, NULL, wd_shutdown))
    452 		aprint_error_dev(self, "couldn't establish power handler\n");
    453 }
    454 
    455 static bool
    456 wd_suspend(device_t dv, const pmf_qual_t *qual)
    457 {
    458 	struct wd_softc *sc = device_private(dv);
    459 
    460 	/* the adapter needs to be enabled */
    461 	if (sc->atabus->ata_addref(sc->drvp))
    462 		return true; /* no need to complain */
    463 
    464 	wd_flushcache(sc, AT_WAIT, false);
    465 	wd_standby(sc, AT_WAIT);
    466 
    467 	sc->atabus->ata_delref(sc->drvp);
    468 	return true;
    469 }
    470 
    471 int
    472 wddetach(device_t self, int flags)
    473 {
    474 	struct wd_softc *sc = device_private(self);
    475 	int bmaj, cmaj, i, mn, rc;
    476 
    477 	if ((rc = disk_begindetach(&sc->sc_dk, wdlastclose, self, flags)) != 0)
    478 		return rc;
    479 
    480 	/* locate the major number */
    481 	bmaj = bdevsw_lookup_major(&wd_bdevsw);
    482 	cmaj = cdevsw_lookup_major(&wd_cdevsw);
    483 
    484 	/* Nuke the vnodes for any open instances. */
    485 	for (i = 0; i < MAXPARTITIONS; i++) {
    486 		mn = WDMINOR(device_unit(self), i);
    487 		vdevgone(bmaj, mn, mn, VBLK);
    488 		vdevgone(cmaj, mn, mn, VCHR);
    489 	}
    490 
    491 	/* Delete all of our wedges. */
    492 	dkwedge_delall(&sc->sc_dk);
    493 
    494 	mutex_enter(&sc->sc_lock);
    495 
    496 	/* Kill off any queued buffers. */
    497 	bufq_drain(sc->sc_q);
    498 
    499 	sc->atabus->ata_killpending(sc->drvp);
    500 	mutex_exit(&sc->sc_lock);
    501 
    502 	if (flags & DETACH_POWEROFF)
    503 		wd_standby(sc, AT_POLL);
    504 
    505 	bufq_free(sc->sc_q);
    506 
    507 	/* Detach disk. */
    508 	disk_detach(&sc->sc_dk);
    509 	disk_destroy(&sc->sc_dk);
    510 
    511 #ifdef WD_SOFTBADSECT
    512 	/* Clean out the bad sector list */
    513 	while (!SLIST_EMPTY(&sc->sc_bslist)) {
    514 		void *head = SLIST_FIRST(&sc->sc_bslist);
    515 		SLIST_REMOVE_HEAD(&sc->sc_bslist, dbs_next);
    516 		free(head, M_TEMP);
    517 	}
    518 	sc->sc_bscount = 0;
    519 #endif
    520 
    521 	pmf_device_deregister(self);
    522 
    523 	/* Unhook the entropy source. */
    524 	rnd_detach_source(&sc->rnd_source);
    525 
    526 	mutex_destroy(&sc->sc_lock);
    527 
    528 	sc->drvp->drive_type = ATA_DRIVET_NONE; /* no drive any more here */
    529 	sc->drvp->drive_flags = 0;
    530 
    531 	return (0);
    532 }
    533 
    534 /*
    535  * Read/write routine for a buffer.  Validates the arguments and schedules the
    536  * transfer.  Does not wait for the transfer to complete.
    537  */
    538 void
    539 wdstrategy(struct buf *bp)
    540 {
    541 	struct wd_softc *wd =
    542 	    device_lookup_private(&wd_cd, WDUNIT(bp->b_dev));
    543 	struct disklabel *lp = wd->sc_dk.dk_label;
    544 	daddr_t blkno;
    545 
    546 	ATADEBUG_PRINT(("wdstrategy (%s)\n", device_xname(wd->sc_dev)),
    547 	    DEBUG_XFERS);
    548 
    549 	/* Valid request?  */
    550 	if (bp->b_blkno < 0 ||
    551 	    (bp->b_bcount % lp->d_secsize) != 0 ||
    552 	    (bp->b_bcount / lp->d_secsize) >= (1 << NBBY)) {
    553 		bp->b_error = EINVAL;
    554 		goto done;
    555 	}
    556 
    557 	/* If device invalidated (e.g. media change, door open,
    558 	 * device detachment), then error.
    559 	 */
    560 	if ((wd->sc_flags & WDF_LOADED) == 0 ||
    561 	    !device_is_enabled(wd->sc_dev)) {
    562 		bp->b_error = EIO;
    563 		goto done;
    564 	}
    565 
    566 	/* If it's a null transfer, return immediately. */
    567 	if (bp->b_bcount == 0)
    568 		goto done;
    569 
    570 	/*
    571 	 * Do bounds checking, adjust transfer. if error, process.
    572 	 * If end of partition, just return.
    573 	 */
    574 	if (WDPART(bp->b_dev) == RAW_PART) {
    575 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
    576 		    wd->sc_capacity512) <= 0)
    577 			goto done;
    578 	} else {
    579 		if (bounds_check_with_label(&wd->sc_dk, bp,
    580 		    (wd->sc_flags & (WDF_WLABEL|WDF_LABELLING)) != 0) <= 0)
    581 			goto done;
    582 	}
    583 
    584 	/*
    585 	 * Now convert the block number to absolute and put it in
    586 	 * terms of the device's logical block size.
    587 	 */
    588 	if (lp->d_secsize >= DEV_BSIZE)
    589 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
    590 	else
    591 		blkno = bp->b_blkno * (DEV_BSIZE / lp->d_secsize);
    592 
    593 	if (WDPART(bp->b_dev) != RAW_PART)
    594 		blkno += lp->d_partitions[WDPART(bp->b_dev)].p_offset;
    595 
    596 	bp->b_rawblkno = blkno;
    597 
    598 #ifdef WD_SOFTBADSECT
    599 	/*
    600 	 * If the transfer about to be attempted contains only a block that
    601 	 * is known to be bad then return an error for the transfer without
    602 	 * even attempting to start a transfer up under the premis that we
    603 	 * will just end up doing more retries for a transfer that will end
    604 	 * up failing again.
    605 	 */
    606 	if (__predict_false(!SLIST_EMPTY(&wd->sc_bslist))) {
    607 		struct disk_badsectors *dbs;
    608 		daddr_t maxblk = blkno + (bp->b_bcount / wd->sc_blksize) - 1;
    609 
    610 		mutex_enter(&wd->sc_lock);
    611 		SLIST_FOREACH(dbs, &wd->sc_bslist, dbs_next)
    612 			if ((dbs->dbs_min <= blkno && blkno <= dbs->dbs_max) ||
    613 			    (dbs->dbs_min <= maxblk && maxblk <= dbs->dbs_max)){
    614 				bp->b_error = EIO;
    615 				mutex_exit(&wd->sc_lock);
    616 				goto done;
    617 			}
    618 		mutex_exit(&wd->sc_lock);
    619 	}
    620 #endif
    621 
    622 	/* Queue transfer on drive, activate drive and controller if idle. */
    623 	mutex_enter(&wd->sc_lock);
    624 	disk_wait(&wd->sc_dk);
    625 	bufq_put(wd->sc_q, bp);
    626 	mutex_exit(&wd->sc_lock);
    627 
    628 	/* Try to queue on the current drive only */
    629 	wdstart(wd->sc_dev);
    630 	return;
    631 done:
    632 	/* Toss transfer; we're done early. */
    633 	bp->b_resid = bp->b_bcount;
    634 	biodone(bp);
    635 }
    636 
    637 /*
    638  * Queue a drive for I/O.
    639  */
    640 void
    641 wdstart(device_t self)
    642 {
    643 	struct wd_softc *wd = device_private(self);
    644 	struct buf *bp;
    645 	struct ata_xfer *xfer;
    646 
    647 	ATADEBUG_PRINT(("wdstart %s\n", device_xname(wd->sc_dev)),
    648 	    DEBUG_XFERS);
    649 
    650 	if (!device_is_active(wd->sc_dev))
    651 		return;
    652 
    653 	mutex_enter(&wd->sc_lock);
    654 
    655 	/*
    656 	 * Do not queue any transfers until flush is finished, so that
    657 	 * once flush is pending, it will get handled as soon as xfer
    658 	 * is available.
    659 	 */
    660 	if (ISSET(wd->sc_flags, WDF_FLUSH_PEND))
    661 		goto out;
    662 
    663 	while (bufq_peek(wd->sc_q) != NULL) {
    664 		/* First try to get xfer. Limit to drive openings iff NCQ. */
    665 		xfer = ata_get_xfer_ext(wd->drvp->chnl_softc, false,
    666 		    ISSET(wd->drvp->drive_flags, ATA_DRIVE_NCQ)
    667 		        ? wd->drvp->drv_openings : 0);
    668 		if (xfer == NULL)
    669 			break;
    670 
    671 		/* There is got to be a buf for us */
    672 		bp = bufq_get(wd->sc_q);
    673 		KASSERT(bp != NULL);
    674 
    675 		xfer->c_retries = 0;
    676 		wdstart1(wd, bp, xfer);
    677 	}
    678 
    679 out:
    680 	mutex_exit(&wd->sc_lock);
    681 }
    682 
    683 void
    684 wdstart1(struct wd_softc *wd, struct buf *bp, struct ata_xfer *xfer)
    685 {
    686 	/* must be locked on entry */
    687 	KASSERT(mutex_owned(&wd->sc_lock));
    688 
    689 	KASSERT(bp == xfer->c_bio.bp || xfer->c_bio.bp == NULL);
    690 	KASSERT((xfer->c_flags & (C_WAITACT|C_FREE)) == 0);
    691 
    692 	/* Reset state, so that retries don't use stale info */
    693 	if (__predict_false(xfer->c_retries > 0)) {
    694 		xfer->c_flags = 0;
    695 		memset(&xfer->c_bio, 0, sizeof(xfer->c_bio));
    696 	}
    697 
    698 	xfer->c_bio.blkno = bp->b_rawblkno;
    699 	xfer->c_bio.bcount = bp->b_bcount;
    700 	xfer->c_bio.databuf = bp->b_data;
    701 	xfer->c_bio.blkdone = 0;
    702 	xfer->c_bio.bp = bp;
    703 
    704 #ifdef WD_CHAOS_MONKEY
    705 	/*
    706 	 * Override blkno to be over device capacity to trigger error,
    707 	 * but only if it's read, to avoid trashing disk contents should
    708 	 * the command be clipped, or otherwise misinterpreted, by the
    709 	 * driver or controller.
    710 	 */
    711 	if (BUF_ISREAD(bp) && xfer->c_retries == 0 && wdcdebug_wd_cnt > 0 &&
    712 	    (++wdcdebug_wd_chaos % wdcdebug_wd_cnt) == 0) {
    713 		aprint_normal_dev(wd->sc_dev, "%s: chaos xfer %d\n",
    714 		    __func__, xfer->c_slot);
    715 		xfer->c_bio.blkno = 7777777 + wd->sc_capacity;
    716 	}
    717 #endif
    718 
    719 	/*
    720 	 * If we're retrying, retry in single-sector mode. This will give us
    721 	 * the sector number of the problem, and will eventually allow the
    722 	 * transfer to succeed.
    723 	 */
    724 	if (xfer->c_retries >= WDIORETRIES_SINGLE)
    725 		xfer->c_bio.flags = ATA_SINGLE;
    726 	else
    727 		xfer->c_bio.flags = 0;
    728 	if (wd->sc_flags & WDF_LBA48 &&
    729 	    (((xfer->c_bio.blkno +
    730 	     xfer->c_bio.bcount / wd->sc_dk.dk_label->d_secsize) >
    731 	    wd->sc_capacity28) ||
    732 	    ((xfer->c_bio.bcount / wd->sc_dk.dk_label->d_secsize) > 128)))
    733 		xfer->c_bio.flags |= ATA_LBA48;
    734 
    735 	/*
    736 	 * If NCQ was negotiated, always use it for the first attempt.
    737 	 * Since device cancels all outstanding requests on error, downgrade
    738 	 * to non-NCQ on retry, so that the retried transfer would not cause
    739 	 * cascade failure for the other transfers if it fails again.
    740 	 * If FUA was requested, we can't downgrade, as that would violate
    741 	 * the semantics - FUA would not be honored. In that case, continue
    742 	 * retrying with NCQ.
    743 	 */
    744 	if (wd->drvp->drive_flags & ATA_DRIVE_NCQ &&
    745 	    (xfer->c_retries == 0 || (bp->b_flags & B_MEDIA_FUA))) {
    746 		xfer->c_bio.flags |= ATA_LBA48;
    747 		xfer->c_flags |= C_NCQ;
    748 
    749 		if ((wd->drvp->drive_flags & ATA_DRIVE_NCQ_PRIO) &&
    750 		    BIO_GETPRIO(bp) == BPRIO_TIMECRITICAL)
    751 			xfer->c_bio.flags |= ATA_PRIO_HIGH;
    752 	}
    753 
    754 	if (wd->sc_flags & WDF_LBA)
    755 		xfer->c_bio.flags |= ATA_LBA;
    756 	if (bp->b_flags & B_READ)
    757 		xfer->c_bio.flags |= ATA_READ;
    758 	if (bp->b_flags & B_MEDIA_FUA) {
    759 		/* If not using NCQ, the command WRITE DMA FUA EXT is LBA48 */
    760 		KASSERT((wd->sc_flags & WDF_LBA48) != 0);
    761 		if ((xfer->c_flags & C_NCQ) == 0)
    762 			xfer->c_bio.flags |= ATA_LBA48;
    763 
    764 		xfer->c_bio.flags |= ATA_FUA;
    765 	}
    766 
    767 	/* Instrumentation. */
    768 	disk_busy(&wd->sc_dk);
    769 	switch (wd->atabus->ata_bio(wd->drvp, xfer)) {
    770 	case ATACMD_TRY_AGAIN:
    771 		panic("wdstart1: try again");
    772 		break;
    773 	case ATACMD_QUEUED:
    774 	case ATACMD_COMPLETE:
    775 		break;
    776 	default:
    777 		panic("wdstart1: bad return code from ata_bio()");
    778 	}
    779 }
    780 
    781 void
    782 wddone(device_t self, struct ata_xfer *xfer)
    783 {
    784 	struct wd_softc *wd = device_private(self);
    785 	const char *errmsg;
    786 	int do_perror = 0;
    787 	struct buf *bp;
    788 
    789 	ATADEBUG_PRINT(("wddone %s\n", device_xname(wd->sc_dev)),
    790 	    DEBUG_XFERS);
    791 
    792 	if (__predict_false(wddoingadump)) {
    793 		/* just drop it to the floor */
    794 		ata_free_xfer(wd->drvp->chnl_softc, xfer);
    795 		return;
    796 	}
    797 
    798 	bp = xfer->c_bio.bp;
    799 	KASSERT(bp != NULL);
    800 
    801 	bp->b_resid = xfer->c_bio.bcount;
    802 	switch (xfer->c_bio.error) {
    803 	case ERR_DMA:
    804 		errmsg = "DMA error";
    805 		goto retry;
    806 	case ERR_DF:
    807 		errmsg = "device fault";
    808 		goto retry;
    809 	case TIMEOUT:
    810 		errmsg = "device timeout";
    811 		goto retry;
    812 	case REQUEUE:
    813 		errmsg = "requeue";
    814 		goto retry2;
    815 	case ERR_RESET:
    816 		errmsg = "channel reset";
    817 		goto retry2;
    818 	case ERROR:
    819 		/* Don't care about media change bits */
    820 		if (xfer->c_bio.r_error != 0 &&
    821 		    (xfer->c_bio.r_error & ~(WDCE_MC | WDCE_MCR)) == 0)
    822 			goto noerror;
    823 		errmsg = "error";
    824 		do_perror = 1;
    825 retry:		/* Just reset and retry. Can we do more ? */
    826 		(*wd->atabus->ata_reset_drive)(wd->drvp, AT_POLL, NULL);
    827 retry2:
    828 		mutex_enter(&wd->sc_lock);
    829 
    830 		diskerr(bp, "wd", errmsg, LOG_PRINTF,
    831 		    xfer->c_bio.blkdone, wd->sc_dk.dk_label);
    832 		if (xfer->c_retries < WDIORETRIES)
    833 			printf(", slot %d, retry %d", xfer->c_slot,
    834 			    xfer->c_retries + 1);
    835 		printf("\n");
    836 		if (do_perror)
    837 			wdperror(wd, xfer);
    838 
    839 		if (xfer->c_retries < WDIORETRIES) {
    840 			int timo;
    841 
    842 			if (xfer->c_bio.error == REQUEUE) {
    843 				/* rerun ASAP, and do not count as retry */
    844 				timo = 1;
    845 			} else {
    846 				xfer->c_retries++;
    847 				timo = RECOVERYTIME;
    848 			}
    849 
    850 			callout_reset(&xfer->c_retry_callout, timo,
    851 			    wdbiorestart, xfer);
    852 
    853 			mutex_exit(&wd->sc_lock);
    854 			return;
    855 		}
    856 
    857 		mutex_exit(&wd->sc_lock);
    858 
    859 #ifdef WD_SOFTBADSECT
    860 		/*
    861 		 * Not all errors indicate a failed block but those that do,
    862 		 * put the block on the bad-block list for the device.  Only
    863 		 * do this for reads because the drive should do it for writes,
    864 		 * itself, according to Manuel.
    865 		 */
    866 		if ((bp->b_flags & B_READ) &&
    867 		    ((wd->drvp->ata_vers >= 4 && xfer->c_bio.r_error & 64) ||
    868 		     (wd->drvp->ata_vers < 4 && xfer->c_bio.r_error & 192))) {
    869 			struct disk_badsectors *dbs;
    870 
    871 			dbs = malloc(sizeof *dbs, M_TEMP, M_NOWAIT);
    872 			if (dbs == NULL) {
    873 				aprint_error_dev(wd->sc_dev,
    874 				    "failed to add bad block to list\n");
    875 				goto out;
    876 			}
    877 
    878 			dbs->dbs_min = bp->b_rawblkno;
    879 			dbs->dbs_max = dbs->dbs_min +
    880 			    (bp->b_bcount /wd->sc_blksize) - 1;
    881 			microtime(&dbs->dbs_failedat);
    882 
    883 			mutex_enter(&wd->sc_lock);
    884 			SLIST_INSERT_HEAD(&wd->sc_bslist, dbs, dbs_next);
    885 			wd->sc_bscount++;
    886 			mutex_exit(&wd->sc_lock);
    887 		}
    888 out:
    889 #endif
    890 		bp->b_error = EIO;
    891 		break;
    892 	case NOERROR:
    893 noerror:	if ((xfer->c_bio.flags & ATA_CORR) || xfer->c_retries > 0)
    894 			aprint_error_dev(wd->sc_dev,
    895 			    "soft error (corrected)\n");
    896 		break;
    897 	case ERR_NODEV:
    898 		bp->b_error = EIO;
    899 		break;
    900 	}
    901 	if (__predict_false(bp->b_error != 0) && bp->b_resid == 0) {
    902 		/*
    903 		 * the disk or controller sometimes report a complete
    904 		 * xfer, when there has been an error. This is wrong,
    905 		 * assume nothing got transfered in this case
    906 		 */
    907 		bp->b_resid = bp->b_bcount;
    908 	}
    909 	disk_unbusy(&wd->sc_dk, (bp->b_bcount - bp->b_resid),
    910 	    (bp->b_flags & B_READ));
    911 	rnd_add_uint32(&wd->rnd_source, bp->b_blkno);
    912 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
    913 	biodone(bp);
    914 	ata_channel_start(wd->drvp->chnl_softc, wd->drvp->drive);
    915 }
    916 
    917 static void
    918 wdbiorestart(void *v)
    919 {
    920 	struct ata_xfer *xfer = v;
    921 	struct buf *bp = xfer->c_bio.bp;
    922 	struct wd_softc *wd = device_lookup_private(&wd_cd, WDUNIT(bp->b_dev));
    923 
    924 	ATADEBUG_PRINT(("wdrestart %s\n", device_xname(wd->sc_dev)),
    925 	    DEBUG_XFERS);
    926 
    927 	mutex_enter(&wd->sc_lock);
    928 	wdstart1(wd, bp, xfer);
    929 	mutex_exit(&wd->sc_lock);
    930 }
    931 
    932 static void
    933 wdminphys(struct buf *bp)
    934 {
    935 	const struct wd_softc * const wd =
    936 	    device_lookup_private(&wd_cd, WDUNIT(bp->b_dev));
    937 	uint32_t maxsectors;
    938 
    939 	/*
    940 	 * The limit is actually 65536 for LBA48 and 256 for non-LBA48,
    941 	 * but that requires to set the count for the ATA command
    942 	 * to 0, which is somewhat error prone, so better stay safe.
    943 	 */
    944 	if (wd->sc_flags & WDF_LBA48)
    945 		maxsectors = 65535;
    946 	else
    947 		maxsectors = 128;
    948 
    949 	if (bp->b_bcount > (wd->sc_blksize * maxsectors))
    950 		bp->b_bcount = (wd->sc_blksize * maxsectors);
    951 
    952 	minphys(bp);
    953 }
    954 
    955 int
    956 wdread(dev_t dev, struct uio *uio, int flags)
    957 {
    958 
    959 	ATADEBUG_PRINT(("wdread\n"), DEBUG_XFERS);
    960 	return (physio(wdstrategy, NULL, dev, B_READ, wdminphys, uio));
    961 }
    962 
    963 int
    964 wdwrite(dev_t dev, struct uio *uio, int flags)
    965 {
    966 
    967 	ATADEBUG_PRINT(("wdwrite\n"), DEBUG_XFERS);
    968 	return (physio(wdstrategy, NULL, dev, B_WRITE, wdminphys, uio));
    969 }
    970 
    971 int
    972 wdopen(dev_t dev, int flag, int fmt, struct lwp *l)
    973 {
    974 	struct wd_softc *wd;
    975 	int part, error;
    976 
    977 	ATADEBUG_PRINT(("wdopen\n"), DEBUG_FUNCS);
    978 	wd = device_lookup_private(&wd_cd, WDUNIT(dev));
    979 	if (wd == NULL)
    980 		return (ENXIO);
    981 
    982 	if (! device_is_active(wd->sc_dev))
    983 		return (ENODEV);
    984 
    985 	if (wd->sc_capacity == 0)
    986 		return (ENODEV);
    987 
    988 	part = WDPART(dev);
    989 
    990 	mutex_enter(&wd->sc_dk.dk_openlock);
    991 
    992 	/*
    993 	 * If there are wedges, and this is not RAW_PART, then we
    994 	 * need to fail.
    995 	 */
    996 	if (wd->sc_dk.dk_nwedges != 0 && part != RAW_PART) {
    997 		error = EBUSY;
    998 		goto bad1;
    999 	}
   1000 
   1001 	/*
   1002 	 * If this is the first open of this device, add a reference
   1003 	 * to the adapter.
   1004 	 */
   1005 	if (wd->sc_dk.dk_openmask == 0 &&
   1006 	    (error = wd->atabus->ata_addref(wd->drvp)) != 0)
   1007 		goto bad1;
   1008 
   1009 	if (wd->sc_dk.dk_openmask != 0) {
   1010 		/*
   1011 		 * If any partition is open, but the disk has been invalidated,
   1012 		 * disallow further opens.
   1013 		 */
   1014 		if ((wd->sc_flags & WDF_LOADED) == 0) {
   1015 			error = EIO;
   1016 			goto bad2;
   1017 		}
   1018 	} else {
   1019 		if ((wd->sc_flags & WDF_LOADED) == 0) {
   1020 
   1021 			/* Load the physical device parameters. */
   1022 			if (wd_get_params(wd, AT_WAIT, &wd->sc_params) != 0) {
   1023 				aprint_error_dev(wd->sc_dev,
   1024 				"IDENTIFY failed\n");
   1025 				error = EIO;
   1026 				goto bad2;
   1027 			}
   1028 			wd->sc_flags |= WDF_LOADED;
   1029 			/* Load the partition info if not already loaded. */
   1030 			wdgetdisklabel(wd);
   1031 		}
   1032 	}
   1033 
   1034 	/* Check that the partition exists. */
   1035 	if (part != RAW_PART &&
   1036 	    (part >= wd->sc_dk.dk_label->d_npartitions ||
   1037 	     wd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
   1038 		error = ENXIO;
   1039 		goto bad2;
   1040 	}
   1041 
   1042 	/* Insure only one open at a time. */
   1043 	switch (fmt) {
   1044 	case S_IFCHR:
   1045 		wd->sc_dk.dk_copenmask |= (1 << part);
   1046 		break;
   1047 	case S_IFBLK:
   1048 		wd->sc_dk.dk_bopenmask |= (1 << part);
   1049 		break;
   1050 	}
   1051 	wd->sc_dk.dk_openmask =
   1052 	    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1053 
   1054 	mutex_exit(&wd->sc_dk.dk_openlock);
   1055 	return 0;
   1056 
   1057  bad2:
   1058 	if (wd->sc_dk.dk_openmask == 0)
   1059 		wd->atabus->ata_delref(wd->drvp);
   1060  bad1:
   1061 	mutex_exit(&wd->sc_dk.dk_openlock);
   1062 	return error;
   1063 }
   1064 
   1065 /*
   1066  * Caller must hold wd->sc_dk.dk_openlock.
   1067  */
   1068 static int
   1069 wdlastclose(device_t self)
   1070 {
   1071 	struct wd_softc *wd = device_private(self);
   1072 
   1073 	wd_flushcache(wd, AT_WAIT, false);
   1074 
   1075 	if (! (wd->sc_flags & WDF_KLABEL))
   1076 		wd->sc_flags &= ~WDF_LOADED;
   1077 
   1078 	wd->atabus->ata_delref(wd->drvp);
   1079 
   1080 	return 0;
   1081 }
   1082 
   1083 int
   1084 wdclose(dev_t dev, int flag, int fmt, struct lwp *l)
   1085 {
   1086 	struct wd_softc *wd =
   1087 	    device_lookup_private(&wd_cd, WDUNIT(dev));
   1088 	int part = WDPART(dev);
   1089 
   1090 	ATADEBUG_PRINT(("wdclose\n"), DEBUG_FUNCS);
   1091 
   1092 	mutex_enter(&wd->sc_dk.dk_openlock);
   1093 
   1094 	switch (fmt) {
   1095 	case S_IFCHR:
   1096 		wd->sc_dk.dk_copenmask &= ~(1 << part);
   1097 		break;
   1098 	case S_IFBLK:
   1099 		wd->sc_dk.dk_bopenmask &= ~(1 << part);
   1100 		break;
   1101 	}
   1102 	wd->sc_dk.dk_openmask =
   1103 	    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1104 
   1105 	if (wd->sc_dk.dk_openmask == 0)
   1106 		wdlastclose(wd->sc_dev);
   1107 
   1108 	mutex_exit(&wd->sc_dk.dk_openlock);
   1109 	return 0;
   1110 }
   1111 
   1112 void
   1113 wdgetdefaultlabel(struct wd_softc *wd, struct disklabel *lp)
   1114 {
   1115 
   1116 	ATADEBUG_PRINT(("wdgetdefaultlabel\n"), DEBUG_FUNCS);
   1117 	memset(lp, 0, sizeof(struct disklabel));
   1118 
   1119 	lp->d_secsize = wd->sc_blksize;
   1120 	lp->d_ntracks = wd->sc_params.atap_heads;
   1121 	lp->d_nsectors = wd->sc_params.atap_sectors;
   1122 	lp->d_ncylinders = (wd->sc_flags & WDF_LBA) ? wd->sc_capacity /
   1123 		(wd->sc_params.atap_heads * wd->sc_params.atap_sectors) :
   1124 		wd->sc_params.atap_cylinders;
   1125 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
   1126 
   1127 	if (strcmp(wd->sc_params.atap_model, "ST506") == 0)
   1128 		lp->d_type = DKTYPE_ST506;
   1129 	else
   1130 		lp->d_type = DKTYPE_ESDI;
   1131 
   1132 	strncpy(lp->d_typename, wd->sc_params.atap_model, 16);
   1133 	strncpy(lp->d_packname, "fictitious", 16);
   1134 	if (wd->sc_capacity > UINT32_MAX)
   1135 		lp->d_secperunit = UINT32_MAX;
   1136 	else
   1137 		lp->d_secperunit = wd->sc_capacity;
   1138 	lp->d_rpm = 3600;
   1139 	lp->d_interleave = 1;
   1140 	lp->d_flags = 0;
   1141 
   1142 	lp->d_partitions[RAW_PART].p_offset = 0;
   1143 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
   1144 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
   1145 	lp->d_npartitions = RAW_PART + 1;
   1146 
   1147 	lp->d_magic = DISKMAGIC;
   1148 	lp->d_magic2 = DISKMAGIC;
   1149 	lp->d_checksum = dkcksum(lp);
   1150 }
   1151 
   1152 /*
   1153  * Fabricate a default disk label, and try to read the correct one.
   1154  */
   1155 void
   1156 wdgetdisklabel(struct wd_softc *wd)
   1157 {
   1158 	struct disklabel *lp = wd->sc_dk.dk_label;
   1159 	const char *errstring;
   1160 
   1161 	ATADEBUG_PRINT(("wdgetdisklabel\n"), DEBUG_FUNCS);
   1162 
   1163 	memset(wd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
   1164 
   1165 	wdgetdefaultlabel(wd, lp);
   1166 
   1167 	wd->drvp->badsect[0] = -1;
   1168 
   1169 	if (wd->drvp->state > RESET) {
   1170 		mutex_enter(&wd->sc_lock);
   1171 		wd->drvp->drive_flags |= ATA_DRIVE_RESET;
   1172 		mutex_exit(&wd->sc_lock);
   1173 	}
   1174 	errstring = readdisklabel(MAKEWDDEV(0, device_unit(wd->sc_dev),
   1175 				  RAW_PART), wdstrategy, lp,
   1176 				  wd->sc_dk.dk_cpulabel);
   1177 	if (errstring) {
   1178 		/*
   1179 		 * This probably happened because the drive's default
   1180 		 * geometry doesn't match the DOS geometry.  We
   1181 		 * assume the DOS geometry is now in the label and try
   1182 		 * again.  XXX This is a kluge.
   1183 		 */
   1184 		if (wd->drvp->state > RESET) {
   1185 			mutex_enter(&wd->sc_lock);
   1186 			wd->drvp->drive_flags |= ATA_DRIVE_RESET;
   1187 			mutex_exit(&wd->sc_lock);
   1188 		}
   1189 		errstring = readdisklabel(MAKEWDDEV(0, device_unit(wd->sc_dev),
   1190 		    RAW_PART), wdstrategy, lp, wd->sc_dk.dk_cpulabel);
   1191 	}
   1192 	if (errstring) {
   1193 		aprint_error_dev(wd->sc_dev, "%s\n", errstring);
   1194 		return;
   1195 	}
   1196 
   1197 	if (wd->drvp->state > RESET) {
   1198 		mutex_enter(&wd->sc_lock);
   1199 		wd->drvp->drive_flags |= ATA_DRIVE_RESET;
   1200 		mutex_exit(&wd->sc_lock);
   1201 	}
   1202 #ifdef HAS_BAD144_HANDLING
   1203 	if ((lp->d_flags & D_BADSECT) != 0)
   1204 		bad144intern(wd);
   1205 #endif
   1206 }
   1207 
   1208 void
   1209 wdperror(const struct wd_softc *wd, struct ata_xfer *xfer)
   1210 {
   1211 	static const char *const errstr0_3[] = {"address mark not found",
   1212 	    "track 0 not found", "aborted command", "media change requested",
   1213 	    "id not found", "media changed", "uncorrectable data error",
   1214 	    "bad block detected"};
   1215 	static const char *const errstr4_5[] = {
   1216 	    "obsolete (address mark not found)",
   1217 	    "no media/write protected", "aborted command",
   1218 	    "media change requested", "id not found", "media changed",
   1219 	    "uncorrectable data error", "interface CRC error"};
   1220 	const char *const *errstr;
   1221 	int i;
   1222 	const char *sep = "";
   1223 
   1224 	const char *devname = device_xname(wd->sc_dev);
   1225 	struct ata_drive_datas *drvp = wd->drvp;
   1226 	int errno = xfer->c_bio.r_error;
   1227 
   1228 	if (drvp->ata_vers >= 4)
   1229 		errstr = errstr4_5;
   1230 	else
   1231 		errstr = errstr0_3;
   1232 
   1233 	printf("%s: (", devname);
   1234 
   1235 	if (errno == 0)
   1236 		printf("error not notified");
   1237 
   1238 	for (i = 0; i < 8; i++) {
   1239 		if (errno & (1 << i)) {
   1240 			printf("%s%s", sep, errstr[i]);
   1241 			sep = ", ";
   1242 		}
   1243 	}
   1244 	printf(")\n");
   1245 }
   1246 
   1247 int
   1248 wdioctl(dev_t dev, u_long xfer, void *addr, int flag, struct lwp *l)
   1249 {
   1250 	struct wd_softc *wd =
   1251 	    device_lookup_private(&wd_cd, WDUNIT(dev));
   1252 	int error;
   1253 #ifdef __HAVE_OLD_DISKLABEL
   1254 	struct disklabel *newlabel = NULL;
   1255 #endif
   1256 
   1257 	ATADEBUG_PRINT(("wdioctl\n"), DEBUG_FUNCS);
   1258 
   1259 	if ((wd->sc_flags & WDF_LOADED) == 0)
   1260 		return EIO;
   1261 
   1262 	error = disk_ioctl(&wd->sc_dk, dev, xfer, addr, flag, l);
   1263 	if (error != EPASSTHROUGH)
   1264 		return error;
   1265 
   1266 	error = 0;
   1267 	switch (xfer) {
   1268 #ifdef HAS_BAD144_HANDLING
   1269 	case DIOCSBAD:
   1270 		if ((flag & FWRITE) == 0)
   1271 			return EBADF;
   1272 		wd->sc_dk.dk_cpulabel->bad = *(struct dkbad *)addr;
   1273 		wd->sc_dk.dk_label->d_flags |= D_BADSECT;
   1274 		bad144intern(wd);
   1275 		return 0;
   1276 #endif
   1277 #ifdef WD_SOFTBADSECT
   1278 	case DIOCBSLIST :
   1279 	{
   1280 		uint32_t count, missing, skip;
   1281 		struct disk_badsecinfo dbsi;
   1282 		struct disk_badsectors *dbs;
   1283 		size_t available;
   1284 		uint8_t *laddr;
   1285 
   1286 		dbsi = *(struct disk_badsecinfo *)addr;
   1287 		missing = wd->sc_bscount;
   1288 		count = 0;
   1289 		available = dbsi.dbsi_bufsize;
   1290 		skip = dbsi.dbsi_skip;
   1291 		laddr = (uint8_t *)dbsi.dbsi_buffer;
   1292 
   1293 		/*
   1294 		 * We start this loop with the expectation that all of the
   1295 		 * entries will be missed and decrement this counter each
   1296 		 * time we either skip over one (already copied out) or
   1297 		 * we actually copy it back to user space.  The structs
   1298 		 * holding the bad sector information are copied directly
   1299 		 * back to user space whilst the summary is returned via
   1300 		 * the struct passed in via the ioctl.
   1301 		 */
   1302 		SLIST_FOREACH(dbs, &wd->sc_bslist, dbs_next) {
   1303 			if (skip > 0) {
   1304 				missing--;
   1305 				skip--;
   1306 				continue;
   1307 			}
   1308 			if (available < sizeof(*dbs))
   1309 				break;
   1310 			available -= sizeof(*dbs);
   1311 			copyout(dbs, laddr, sizeof(*dbs));
   1312 			laddr += sizeof(*dbs);
   1313 			missing--;
   1314 			count++;
   1315 		}
   1316 		dbsi.dbsi_left = missing;
   1317 		dbsi.dbsi_copied = count;
   1318 		*(struct disk_badsecinfo *)addr = dbsi;
   1319 		return 0;
   1320 	}
   1321 
   1322 	case DIOCBSFLUSH :
   1323 		/* Clean out the bad sector list */
   1324 		while (!SLIST_EMPTY(&wd->sc_bslist)) {
   1325 			void *head = SLIST_FIRST(&wd->sc_bslist);
   1326 			SLIST_REMOVE_HEAD(&wd->sc_bslist, dbs_next);
   1327 			free(head, M_TEMP);
   1328 		}
   1329 		wd->sc_bscount = 0;
   1330 		return 0;
   1331 #endif
   1332 
   1333 	case DIOCWDINFO:
   1334 	case DIOCSDINFO:
   1335 #ifdef __HAVE_OLD_DISKLABEL
   1336 	case ODIOCWDINFO:
   1337 	case ODIOCSDINFO:
   1338 #endif
   1339 	{
   1340 		struct disklabel *lp;
   1341 
   1342 		if ((flag & FWRITE) == 0)
   1343 			return EBADF;
   1344 
   1345 #ifdef __HAVE_OLD_DISKLABEL
   1346 		if (xfer == ODIOCSDINFO || xfer == ODIOCWDINFO) {
   1347 			newlabel = malloc(sizeof *newlabel, M_TEMP,
   1348 			    M_WAITOK | M_ZERO);
   1349 			if (newlabel == NULL)
   1350 				return EIO;
   1351 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
   1352 			lp = newlabel;
   1353 		} else
   1354 #endif
   1355 		lp = (struct disklabel *)addr;
   1356 
   1357 		mutex_enter(&wd->sc_dk.dk_openlock);
   1358 		wd->sc_flags |= WDF_LABELLING;
   1359 
   1360 		error = setdisklabel(wd->sc_dk.dk_label,
   1361 		    lp, /*wd->sc_dk.dk_openmask : */0,
   1362 		    wd->sc_dk.dk_cpulabel);
   1363 		if (error == 0) {
   1364 			if (wd->drvp->state > RESET) {
   1365 				mutex_enter(&wd->sc_lock);
   1366 				wd->drvp->drive_flags |= ATA_DRIVE_RESET;
   1367 				mutex_exit(&wd->sc_lock);
   1368 			}
   1369 			if (xfer == DIOCWDINFO
   1370 #ifdef __HAVE_OLD_DISKLABEL
   1371 			    || xfer == ODIOCWDINFO
   1372 #endif
   1373 			    )
   1374 				error = writedisklabel(WDLABELDEV(dev),
   1375 				    wdstrategy, wd->sc_dk.dk_label,
   1376 				    wd->sc_dk.dk_cpulabel);
   1377 		}
   1378 
   1379 		wd->sc_flags &= ~WDF_LABELLING;
   1380 		mutex_exit(&wd->sc_dk.dk_openlock);
   1381 #ifdef __HAVE_OLD_DISKLABEL
   1382 		if (newlabel != NULL)
   1383 			free(newlabel, M_TEMP);
   1384 #endif
   1385 		return error;
   1386 	}
   1387 
   1388 	case DIOCKLABEL:
   1389 		if (*(int *)addr)
   1390 			wd->sc_flags |= WDF_KLABEL;
   1391 		else
   1392 			wd->sc_flags &= ~WDF_KLABEL;
   1393 		return 0;
   1394 
   1395 	case DIOCWLABEL:
   1396 		if ((flag & FWRITE) == 0)
   1397 			return EBADF;
   1398 		if (*(int *)addr)
   1399 			wd->sc_flags |= WDF_WLABEL;
   1400 		else
   1401 			wd->sc_flags &= ~WDF_WLABEL;
   1402 		return 0;
   1403 
   1404 	case DIOCGDEFLABEL:
   1405 		wdgetdefaultlabel(wd, (struct disklabel *)addr);
   1406 		return 0;
   1407 #ifdef __HAVE_OLD_DISKLABEL
   1408 	case ODIOCGDEFLABEL:
   1409 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1410 		if (newlabel == NULL)
   1411 			return EIO;
   1412 		wdgetdefaultlabel(wd, newlabel);
   1413 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
   1414 			memcpy(addr, &newlabel, sizeof (struct olddisklabel));
   1415 		else
   1416 			error = ENOTTY;
   1417 		free(newlabel, M_TEMP);
   1418 		return error;
   1419 #endif
   1420 
   1421 #ifdef notyet
   1422 	case DIOCWFORMAT:
   1423 		if ((flag & FWRITE) == 0)
   1424 			return EBADF;
   1425 		{
   1426 		register struct format_op *fop;
   1427 		struct iovec aiov;
   1428 		struct uio auio;
   1429 
   1430 		fop = (struct format_op *)addr;
   1431 		aiov.iov_base = fop->df_buf;
   1432 		aiov.iov_len = fop->df_count;
   1433 		auio.uio_iov = &aiov;
   1434 		auio.uio_iovcnt = 1;
   1435 		auio.uio_resid = fop->df_count;
   1436 		auio.uio_offset =
   1437 			fop->df_startblk * wd->sc_dk.dk_label->d_secsize;
   1438 		auio.uio_vmspace = l->l_proc->p_vmspace;
   1439 		error = physio(wdformat, NULL, dev, B_WRITE, wdminphys,
   1440 		    &auio);
   1441 		fop->df_count -= auio.uio_resid;
   1442 		fop->df_reg[0] = wdc->sc_status;
   1443 		fop->df_reg[1] = wdc->sc_error;
   1444 		return error;
   1445 		}
   1446 #endif
   1447 	case DIOCGCACHE:
   1448 		return wd_getcache(wd, (int *)addr);
   1449 
   1450 	case DIOCSCACHE:
   1451 		return wd_setcache(wd, *(int *)addr);
   1452 
   1453 	case DIOCCACHESYNC:
   1454 		return wd_flushcache(wd, AT_WAIT, true);
   1455 
   1456 	case ATAIOCCOMMAND:
   1457 		/*
   1458 		 * Make sure this command is (relatively) safe first
   1459 		 */
   1460 		if ((((atareq_t *) addr)->flags & ATACMD_READ) == 0 &&
   1461 		    (flag & FWRITE) == 0)
   1462 			return (EBADF);
   1463 		{
   1464 		struct wd_ioctl *wi;
   1465 		atareq_t *atareq = (atareq_t *) addr;
   1466 		int error1;
   1467 
   1468 		wi = wi_get(wd);
   1469 		wi->wi_atareq = *atareq;
   1470 
   1471 		if (atareq->datalen && atareq->flags &
   1472 		    (ATACMD_READ | ATACMD_WRITE)) {
   1473 			void *tbuf;
   1474 			if (atareq->datalen < DEV_BSIZE
   1475 			    && atareq->command == WDCC_IDENTIFY) {
   1476 				tbuf = malloc(DEV_BSIZE, M_TEMP, M_WAITOK);
   1477 				wi->wi_iov.iov_base = tbuf;
   1478 				wi->wi_iov.iov_len = DEV_BSIZE;
   1479 				UIO_SETUP_SYSSPACE(&wi->wi_uio);
   1480 			} else {
   1481 				tbuf = NULL;
   1482 				wi->wi_iov.iov_base = atareq->databuf;
   1483 				wi->wi_iov.iov_len = atareq->datalen;
   1484 				wi->wi_uio.uio_vmspace = l->l_proc->p_vmspace;
   1485 			}
   1486 			wi->wi_uio.uio_iov = &wi->wi_iov;
   1487 			wi->wi_uio.uio_iovcnt = 1;
   1488 			wi->wi_uio.uio_resid = atareq->datalen;
   1489 			wi->wi_uio.uio_offset = 0;
   1490 			wi->wi_uio.uio_rw =
   1491 			    (atareq->flags & ATACMD_READ) ? B_READ : B_WRITE;
   1492 			error1 = physio(wdioctlstrategy, &wi->wi_bp, dev,
   1493 			    (atareq->flags & ATACMD_READ) ? B_READ : B_WRITE,
   1494 			    wdminphys, &wi->wi_uio);
   1495 			if (tbuf != NULL && error1 == 0) {
   1496 				error1 = copyout(tbuf, atareq->databuf,
   1497 				    atareq->datalen);
   1498 				free(tbuf, M_TEMP);
   1499 			}
   1500 		} else {
   1501 			/* No need to call physio if we don't have any
   1502 			   user data */
   1503 			wi->wi_bp.b_flags = 0;
   1504 			wi->wi_bp.b_data = 0;
   1505 			wi->wi_bp.b_bcount = 0;
   1506 			wi->wi_bp.b_dev = dev;
   1507 			wi->wi_bp.b_proc = l->l_proc;
   1508 			wdioctlstrategy(&wi->wi_bp);
   1509 			error1 = wi->wi_bp.b_error;
   1510 		}
   1511 		*atareq = wi->wi_atareq;
   1512 		wi_free(wi);
   1513 		return(error1);
   1514 		}
   1515 
   1516 	case DIOCGSTRATEGY:
   1517 	    {
   1518 		struct disk_strategy *dks = (void *)addr;
   1519 
   1520 		mutex_enter(&wd->sc_lock);
   1521 		strlcpy(dks->dks_name, bufq_getstrategyname(wd->sc_q),
   1522 		    sizeof(dks->dks_name));
   1523 		mutex_exit(&wd->sc_lock);
   1524 		dks->dks_paramlen = 0;
   1525 
   1526 		return 0;
   1527 	    }
   1528 
   1529 	case DIOCSSTRATEGY:
   1530 	    {
   1531 		struct disk_strategy *dks = (void *)addr;
   1532 		struct bufq_state *new;
   1533 		struct bufq_state *old;
   1534 
   1535 		if ((flag & FWRITE) == 0) {
   1536 			return EBADF;
   1537 		}
   1538 		if (dks->dks_param != NULL) {
   1539 			return EINVAL;
   1540 		}
   1541 		dks->dks_name[sizeof(dks->dks_name) - 1] = 0; /* ensure term */
   1542 		error = bufq_alloc(&new, dks->dks_name,
   1543 		    BUFQ_EXACT|BUFQ_SORT_RAWBLOCK);
   1544 		if (error) {
   1545 			return error;
   1546 		}
   1547 		mutex_enter(&wd->sc_lock);
   1548 		old = wd->sc_q;
   1549 		bufq_move(new, old);
   1550 		wd->sc_q = new;
   1551 		mutex_exit(&wd->sc_lock);
   1552 		bufq_free(old);
   1553 
   1554 		return 0;
   1555 	    }
   1556 
   1557 	default:
   1558 		return ENOTTY;
   1559 	}
   1560 
   1561 #ifdef DIAGNOSTIC
   1562 	panic("wdioctl: impossible");
   1563 #endif
   1564 }
   1565 
   1566 static int
   1567 wddiscard(dev_t dev, off_t pos, off_t len)
   1568 {
   1569 	struct wd_softc *wd = device_lookup_private(&wd_cd, WDUNIT(dev));
   1570 	daddr_t bno;
   1571 	long size, done;
   1572 	long maxatonce, amount;
   1573 	int result;
   1574 
   1575 	if (!(wd->sc_params.atap_ata_major & WDC_VER_ATA7)
   1576 	    || !(wd->sc_params.support_dsm & ATA_SUPPORT_DSM_TRIM)) {
   1577 		/* not supported; ignore request */
   1578 		ATADEBUG_PRINT(("wddiscard (unsupported)\n"), DEBUG_FUNCS);
   1579 		return 0;
   1580 	}
   1581 	maxatonce = 0xffff; /*wd->sc_params.max_dsm_blocks*/
   1582 
   1583 	ATADEBUG_PRINT(("wddiscard\n"), DEBUG_FUNCS);
   1584 
   1585 	if ((wd->sc_flags & WDF_LOADED) == 0)
   1586 		return EIO;
   1587 
   1588 	/* round the start up and the end down */
   1589 	bno = (pos + wd->sc_blksize - 1) / wd->sc_blksize;
   1590 	size = ((pos + len) / wd->sc_blksize) - bno;
   1591 
   1592 	done = 0;
   1593 	while (done < size) {
   1594 	     amount = size - done;
   1595 	     if (amount > maxatonce) {
   1596 		     amount = maxatonce;
   1597 	     }
   1598 	     result = wd_trim(wd, WDPART(dev), bno + done, amount);
   1599 	     if (result) {
   1600 		     return result;
   1601 	     }
   1602 	     done += amount;
   1603 	}
   1604 	return 0;
   1605 }
   1606 
   1607 #ifdef B_FORMAT
   1608 int
   1609 wdformat(struct buf *bp)
   1610 {
   1611 
   1612 	bp->b_flags |= B_FORMAT;
   1613 	return wdstrategy(bp);
   1614 }
   1615 #endif
   1616 
   1617 int
   1618 wdsize(dev_t dev)
   1619 {
   1620 	struct wd_softc *wd;
   1621 	int part, omask;
   1622 	int size;
   1623 
   1624 	ATADEBUG_PRINT(("wdsize\n"), DEBUG_FUNCS);
   1625 
   1626 	wd = device_lookup_private(&wd_cd, WDUNIT(dev));
   1627 	if (wd == NULL)
   1628 		return (-1);
   1629 
   1630 	part = WDPART(dev);
   1631 	omask = wd->sc_dk.dk_openmask & (1 << part);
   1632 
   1633 	if (omask == 0 && wdopen(dev, 0, S_IFBLK, NULL) != 0)
   1634 		return (-1);
   1635 	if (wd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
   1636 		size = -1;
   1637 	else
   1638 		size = wd->sc_dk.dk_label->d_partitions[part].p_size *
   1639 		    (wd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
   1640 	if (omask == 0 && wdclose(dev, 0, S_IFBLK, NULL) != 0)
   1641 		return (-1);
   1642 	return (size);
   1643 }
   1644 
   1645 /*
   1646  * Dump core after a system crash.
   1647  */
   1648 int
   1649 wddump(dev_t dev, daddr_t blkno, void *va, size_t size)
   1650 {
   1651 	struct wd_softc *wd;	/* disk unit to do the I/O */
   1652 	struct disklabel *lp;   /* disk's disklabel */
   1653 	int part, err;
   1654 	int nblks;	/* total number of sectors left to write */
   1655 	struct ata_xfer *xfer;
   1656 
   1657 	/* Check if recursive dump; if so, punt. */
   1658 	if (wddoingadump)
   1659 		return EFAULT;
   1660 	wddoingadump = 1;
   1661 
   1662 	wd = device_lookup_private(&wd_cd, WDUNIT(dev));
   1663 	if (wd == NULL)
   1664 		return (ENXIO);
   1665 
   1666 	part = WDPART(dev);
   1667 
   1668 	/* Convert to disk sectors.  Request must be a multiple of size. */
   1669 	lp = wd->sc_dk.dk_label;
   1670 	if ((size % lp->d_secsize) != 0)
   1671 		return EFAULT;
   1672 	nblks = size / lp->d_secsize;
   1673 	blkno = blkno / (lp->d_secsize / DEV_BSIZE);
   1674 
   1675 	/* Check transfer bounds against partition size. */
   1676 	if ((blkno < 0) || ((blkno + nblks) > lp->d_partitions[part].p_size))
   1677 		return EINVAL;
   1678 
   1679 	/* Offset block number to start of partition. */
   1680 	blkno += lp->d_partitions[part].p_offset;
   1681 
   1682 	/* Recalibrate, if first dump transfer. */
   1683 	if (wddumprecalibrated == 0) {
   1684 		wddumprecalibrated = 1;
   1685 		(*wd->atabus->ata_reset_drive)(wd->drvp,
   1686 					       AT_POLL | AT_RST_EMERG, NULL);
   1687 		wd->drvp->state = RESET;
   1688 	}
   1689 
   1690 	xfer = ata_get_xfer_ext(wd->drvp->chnl_softc, false, 0);
   1691 	if (xfer == NULL) {
   1692 		printf("%s: no xfer\n", __func__);
   1693 		return EAGAIN;
   1694 	}
   1695 
   1696 	xfer->c_bio.blkno = blkno;
   1697 	xfer->c_bio.flags = ATA_POLL;
   1698 	if (wd->sc_flags & WDF_LBA48 &&
   1699 	    (xfer->c_bio.blkno + nblks) > wd->sc_capacity28)
   1700 		xfer->c_bio.flags |= ATA_LBA48;
   1701 	if (wd->sc_flags & WDF_LBA)
   1702 		xfer->c_bio.flags |= ATA_LBA;
   1703 	xfer->c_bio.bcount = nblks * lp->d_secsize;
   1704 	xfer->c_bio.databuf = va;
   1705 #ifndef WD_DUMP_NOT_TRUSTED
   1706 	switch (err = wd->atabus->ata_bio(wd->drvp, xfer)) {
   1707 	case ATACMD_TRY_AGAIN:
   1708 		panic("wddump: try again");
   1709 		break;
   1710 	case ATACMD_QUEUED:
   1711 		panic("wddump: polled command has been queued");
   1712 		break;
   1713 	case ATACMD_COMPLETE:
   1714 		break;
   1715 	default:
   1716 		panic("wddump: unknown atacmd code %d", err);
   1717 	}
   1718 	switch(err = xfer->c_bio.error) {
   1719 	case TIMEOUT:
   1720 		printf("wddump: device timed out");
   1721 		err = EIO;
   1722 		break;
   1723 	case ERR_DF:
   1724 		printf("wddump: drive fault");
   1725 		err = EIO;
   1726 		break;
   1727 	case ERR_DMA:
   1728 		printf("wddump: DMA error");
   1729 		err = EIO;
   1730 		break;
   1731 	case ERROR:
   1732 		printf("wddump: ");
   1733 		wdperror(wd, xfer);
   1734 		err = EIO;
   1735 		break;
   1736 	case NOERROR:
   1737 		err = 0;
   1738 		break;
   1739 	default:
   1740 		panic("wddump: unknown error type %d", err);
   1741 	}
   1742 
   1743 	if (err != 0) {
   1744 		printf("\n");
   1745 		return err;
   1746 	}
   1747 #else	/* WD_DUMP_NOT_TRUSTED */
   1748 	/* Let's just talk about this first... */
   1749 	printf("wd%d: dump addr 0x%x, cylin %d, head %d, sector %d\n",
   1750 	    unit, va, cylin, head, sector);
   1751 	delay(500 * 1000);	/* half a second */
   1752 #endif
   1753 
   1754 	wddoingadump = 0;
   1755 	return 0;
   1756 }
   1757 
   1758 #ifdef HAS_BAD144_HANDLING
   1759 /*
   1760  * Internalize the bad sector table.
   1761  */
   1762 void
   1763 bad144intern(struct wd_softc *wd)
   1764 {
   1765 	struct dkbad *bt = &wd->sc_dk.dk_cpulabel->bad;
   1766 	struct disklabel *lp = wd->sc_dk.dk_label;
   1767 	int i = 0;
   1768 
   1769 	ATADEBUG_PRINT(("bad144intern\n"), DEBUG_XFERS);
   1770 
   1771 	for (; i < NBT_BAD; i++) {
   1772 		if (bt->bt_bad[i].bt_cyl == 0xffff)
   1773 			break;
   1774 		wd->drvp->badsect[i] =
   1775 		    bt->bt_bad[i].bt_cyl * lp->d_secpercyl +
   1776 		    (bt->bt_bad[i].bt_trksec >> 8) * lp->d_nsectors +
   1777 		    (bt->bt_bad[i].bt_trksec & 0xff);
   1778 	}
   1779 	for (; i < NBT_BAD+1; i++)
   1780 		wd->drvp->badsect[i] = -1;
   1781 }
   1782 #endif
   1783 
   1784 static void
   1785 wd_params_to_properties(struct wd_softc *wd)
   1786 {
   1787 	struct disk_geom *dg = &wd->sc_dk.dk_geom;
   1788 
   1789 	memset(dg, 0, sizeof(*dg));
   1790 
   1791 	dg->dg_secperunit = wd->sc_capacity;
   1792 	dg->dg_secsize = wd->sc_blksize;
   1793 	dg->dg_nsectors = wd->sc_params.atap_sectors;
   1794 	dg->dg_ntracks = wd->sc_params.atap_heads;
   1795 	if ((wd->sc_flags & WDF_LBA) == 0)
   1796 		dg->dg_ncylinders = wd->sc_params.atap_cylinders;
   1797 
   1798 	/* XXX Should have a case for ATA here, too. */
   1799 	const char *cp = strcmp(wd->sc_params.atap_model, "ST506") ?
   1800 	    "ST506" : "ESDI";
   1801 
   1802 	disk_set_info(wd->sc_dev, &wd->sc_dk, cp);
   1803 }
   1804 
   1805 int
   1806 wd_get_params(struct wd_softc *wd, uint8_t flags, struct ataparams *params)
   1807 {
   1808 
   1809 	switch (wd->atabus->ata_get_params(wd->drvp, flags, params)) {
   1810 	case CMD_AGAIN:
   1811 		return 1;
   1812 	case CMD_ERR:
   1813 		if (wd->drvp->drive_type != ATA_DRIVET_OLD)
   1814 			return 1;
   1815 		/*
   1816 		 * We `know' there's a drive here; just assume it's old.
   1817 		 * This geometry is only used to read the MBR and print a
   1818 		 * (false) attach message.
   1819 		 */
   1820 		strncpy(params->atap_model, "ST506",
   1821 		    sizeof params->atap_model);
   1822 		params->atap_config = ATA_CFG_FIXED;
   1823 		params->atap_cylinders = 1024;
   1824 		params->atap_heads = 8;
   1825 		params->atap_sectors = 17;
   1826 		params->atap_multi = 1;
   1827 		params->atap_capabilities1 = params->atap_capabilities2 = 0;
   1828 		wd->drvp->ata_vers = -1; /* Mark it as pre-ATA */
   1829 		/* FALLTHROUGH */
   1830 	case CMD_OK:
   1831 		return 0;
   1832 	default:
   1833 		panic("wd_get_params: bad return code from ata_get_params");
   1834 		/* NOTREACHED */
   1835 	}
   1836 }
   1837 
   1838 int
   1839 wd_getcache(struct wd_softc *wd, int *bitsp)
   1840 {
   1841 	struct ataparams params;
   1842 
   1843 	if (wd_get_params(wd, AT_WAIT, &params) != 0)
   1844 		return EIO;
   1845 	if (params.atap_cmd_set1 == 0x0000 ||
   1846 	    params.atap_cmd_set1 == 0xffff ||
   1847 	    (params.atap_cmd_set1 & WDC_CMD1_CACHE) == 0) {
   1848 		*bitsp = 0;
   1849 		return 0;
   1850 	}
   1851 	*bitsp = DKCACHE_WCHANGE | DKCACHE_READ;
   1852 	if (params.atap_cmd1_en & WDC_CMD1_CACHE)
   1853 		*bitsp |= DKCACHE_WRITE;
   1854 
   1855 	if (wd->drvp->drive_flags & (ATA_DRIVE_NCQ|ATA_DRIVE_WFUA))
   1856 		*bitsp |= DKCACHE_FUA;
   1857 
   1858 	return 0;
   1859 }
   1860 
   1861 const char at_errbits[] = "\20\10ERROR\11TIMEOU\12DF";
   1862 
   1863 int
   1864 wd_setcache(struct wd_softc *wd, int bits)
   1865 {
   1866 	struct ataparams params;
   1867 	struct ata_xfer *xfer;
   1868 	int error;
   1869 
   1870 	if (wd_get_params(wd, AT_WAIT, &params) != 0)
   1871 		return EIO;
   1872 
   1873 	if (params.atap_cmd_set1 == 0x0000 ||
   1874 	    params.atap_cmd_set1 == 0xffff ||
   1875 	    (params.atap_cmd_set1 & WDC_CMD1_CACHE) == 0)
   1876 		return EOPNOTSUPP;
   1877 
   1878 	if ((bits & DKCACHE_READ) == 0 ||
   1879 	    (bits & DKCACHE_SAVE) != 0)
   1880 		return EOPNOTSUPP;
   1881 
   1882 	xfer = ata_get_xfer(wd->drvp->chnl_softc);
   1883 	if (xfer == NULL)
   1884 		return EINTR;
   1885 
   1886 	xfer->c_ata_c.r_command = SET_FEATURES;
   1887 	xfer->c_ata_c.r_st_bmask = 0;
   1888 	xfer->c_ata_c.r_st_pmask = 0;
   1889 	xfer->c_ata_c.timeout = 30000; /* 30s timeout */
   1890 	xfer->c_ata_c.flags = AT_WAIT;
   1891 	if (bits & DKCACHE_WRITE)
   1892 		xfer->c_ata_c.r_features = WDSF_WRITE_CACHE_EN;
   1893 	else
   1894 		xfer->c_ata_c.r_features = WDSF_WRITE_CACHE_DS;
   1895 	if (wd->atabus->ata_exec_command(wd->drvp, xfer) != ATACMD_COMPLETE) {
   1896 		aprint_error_dev(wd->sc_dev,
   1897 		    "wd_setcache command not complete\n");
   1898 		error = EIO;
   1899 		goto out;
   1900 	}
   1901 
   1902 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1903 		char sbuf[sizeof(at_errbits) + 64];
   1904 		snprintb(sbuf, sizeof(sbuf), at_errbits, xfer->c_ata_c.flags);
   1905 		aprint_error_dev(wd->sc_dev, "wd_setcache: status=%s\n", sbuf);
   1906 		error = EIO;
   1907 		goto out;
   1908 	}
   1909 
   1910 	error = 0;
   1911 
   1912 out:
   1913 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
   1914 	ata_channel_start(wd->drvp->chnl_softc, wd->drvp->drive);
   1915 	return error;
   1916 }
   1917 
   1918 static int
   1919 wd_standby(struct wd_softc *wd, int flags)
   1920 {
   1921 	struct ata_xfer *xfer;
   1922 	int error;
   1923 
   1924 	xfer = ata_get_xfer(wd->drvp->chnl_softc);
   1925 	if (xfer == NULL)
   1926 		return EINTR;
   1927 
   1928 	xfer->c_ata_c.r_command = WDCC_STANDBY_IMMED;
   1929 	xfer->c_ata_c.r_st_bmask = WDCS_DRDY;
   1930 	xfer->c_ata_c.r_st_pmask = WDCS_DRDY;
   1931 	xfer->c_ata_c.flags = flags;
   1932 	xfer->c_ata_c.timeout = 30000; /* 30s timeout */
   1933 	if (wd->atabus->ata_exec_command(wd->drvp, xfer) != ATACMD_COMPLETE) {
   1934 		aprint_error_dev(wd->sc_dev,
   1935 		    "standby immediate command didn't complete\n");
   1936 		error = EIO;
   1937 		goto out;
   1938 	}
   1939 	if (xfer->c_ata_c.flags & AT_ERROR) {
   1940 		if (xfer->c_ata_c.r_error == WDCE_ABRT) {
   1941 			/* command not supported */
   1942 			error = ENODEV;
   1943 			goto out;
   1944 		}
   1945 	}
   1946 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1947 		char sbuf[sizeof(at_errbits) + 64];
   1948 		snprintb(sbuf, sizeof(sbuf), at_errbits, xfer->c_ata_c.flags);
   1949 		aprint_error_dev(wd->sc_dev, "wd_standby: status=%s\n", sbuf);
   1950 		error = EIO;
   1951 		goto out;
   1952 	}
   1953 	error = 0;
   1954 
   1955 out:
   1956 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
   1957 	/* drive is supposed to go idle, do not call ata_channel_start() */
   1958 	return error;
   1959 }
   1960 
   1961 int
   1962 wd_flushcache(struct wd_softc *wd, int flags, bool start)
   1963 {
   1964 	struct ata_xfer *xfer;
   1965 	int error;
   1966 
   1967 	/*
   1968 	 * WDCC_FLUSHCACHE is here since ATA-4, but some drives report
   1969 	 * only ATA-2 and still support it.
   1970 	 */
   1971 	if (wd->drvp->ata_vers < 4 &&
   1972 	    ((wd->sc_params.atap_cmd_set2 & WDC_CMD2_FC) == 0 ||
   1973 	    wd->sc_params.atap_cmd_set2 == 0xffff))
   1974 		return ENODEV;
   1975 
   1976 	mutex_enter(&wd->sc_lock);
   1977 	SET(wd->sc_flags, WDF_FLUSH_PEND);
   1978 	mutex_exit(&wd->sc_lock);
   1979 
   1980 	xfer = ata_get_xfer(wd->drvp->chnl_softc);
   1981 
   1982 	mutex_enter(&wd->sc_lock);
   1983 	CLR(wd->sc_flags, WDF_FLUSH_PEND);
   1984 	mutex_exit(&wd->sc_lock);
   1985 
   1986 	if (xfer == NULL) {
   1987 		error = EINTR;
   1988 		goto out;
   1989 	}
   1990 
   1991 	if ((wd->sc_params.atap_cmd2_en & ATA_CMD2_LBA48) != 0 &&
   1992 	    (wd->sc_params.atap_cmd2_en & ATA_CMD2_FCE) != 0) {
   1993 		xfer->c_ata_c.r_command = WDCC_FLUSHCACHE_EXT;
   1994 		flags |= AT_LBA48;
   1995 	} else
   1996 		xfer->c_ata_c.r_command = WDCC_FLUSHCACHE;
   1997 	xfer->c_ata_c.r_st_bmask = WDCS_DRDY;
   1998 	xfer->c_ata_c.r_st_pmask = WDCS_DRDY;
   1999 	xfer->c_ata_c.flags = flags | AT_READREG;
   2000 	xfer->c_ata_c.timeout = 300000; /* 5m timeout */
   2001 	if (wd->atabus->ata_exec_command(wd->drvp, xfer) != ATACMD_COMPLETE) {
   2002 		aprint_error_dev(wd->sc_dev,
   2003 		    "flush cache command didn't complete\n");
   2004 		error = EIO;
   2005 		goto out_xfer;
   2006 	}
   2007 	if (xfer->c_ata_c.flags & AT_ERROR) {
   2008 		if (xfer->c_ata_c.r_error == WDCE_ABRT) {
   2009 			/* command not supported */
   2010 			error = ENODEV;
   2011 			goto out_xfer;
   2012 		}
   2013 	}
   2014 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   2015 		char sbuf[sizeof(at_errbits) + 64];
   2016 		snprintb(sbuf, sizeof(sbuf), at_errbits, xfer->c_ata_c.flags);
   2017 		aprint_error_dev(wd->sc_dev, "wd_flushcache: status=%s\n",
   2018 		    sbuf);
   2019 		error = EIO;
   2020 		goto out_xfer;
   2021 	}
   2022 	error = 0;
   2023 
   2024 out_xfer:
   2025 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
   2026 
   2027 out:
   2028 	/* kick queue processing blocked while waiting for flush xfer */
   2029 	if (start)
   2030 		ata_channel_start(wd->drvp->chnl_softc, wd->drvp->drive);
   2031 
   2032 	return error;
   2033 }
   2034 
   2035 int
   2036 wd_trim(struct wd_softc *wd, int part, daddr_t bno, long size)
   2037 {
   2038 	struct ata_xfer *xfer;
   2039 	int error;
   2040 	unsigned char *req;
   2041 
   2042 	if (part != RAW_PART)
   2043 		bno += wd->sc_dk.dk_label->d_partitions[part].p_offset;;
   2044 
   2045 	xfer = ata_get_xfer(wd->drvp->chnl_softc);
   2046 	if (xfer == NULL)
   2047 		return EINTR;
   2048 
   2049 	req = kmem_zalloc(512, KM_SLEEP);
   2050 	req[0] = bno & 0xff;
   2051 	req[1] = (bno >> 8) & 0xff;
   2052 	req[2] = (bno >> 16) & 0xff;
   2053 	req[3] = (bno >> 24) & 0xff;
   2054 	req[4] = (bno >> 32) & 0xff;
   2055 	req[5] = (bno >> 40) & 0xff;
   2056 	req[6] = size & 0xff;
   2057 	req[7] = (size >> 8) & 0xff;
   2058 
   2059 	xfer->c_ata_c.r_command = ATA_DATA_SET_MANAGEMENT;
   2060 	xfer->c_ata_c.r_count = 1;
   2061 	xfer->c_ata_c.r_features = ATA_SUPPORT_DSM_TRIM;
   2062 	xfer->c_ata_c.r_st_bmask = WDCS_DRDY;
   2063 	xfer->c_ata_c.r_st_pmask = WDCS_DRDY;
   2064 	xfer->c_ata_c.timeout = 30000; /* 30s timeout */
   2065 	xfer->c_ata_c.data = req;
   2066 	xfer->c_ata_c.bcount = 512;
   2067 	xfer->c_ata_c.flags |= AT_WRITE | AT_WAIT;
   2068 	if (wd->atabus->ata_exec_command(wd->drvp, xfer) != ATACMD_COMPLETE) {
   2069 		aprint_error_dev(wd->sc_dev,
   2070 		    "trim command didn't complete\n");
   2071 		kmem_free(req, 512);
   2072 		error = EIO;
   2073 		goto out;
   2074 	}
   2075 	kmem_free(req, 512);
   2076 	if (xfer->c_ata_c.flags & AT_ERROR) {
   2077 		if (xfer->c_ata_c.r_error == WDCE_ABRT) {
   2078 			/* command not supported */
   2079 			error = ENODEV;
   2080 			goto out;
   2081 		}
   2082 	}
   2083 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   2084 		char sbuf[sizeof(at_errbits) + 64];
   2085 		snprintb(sbuf, sizeof(sbuf), at_errbits, xfer->c_ata_c.flags);
   2086 		aprint_error_dev(wd->sc_dev, "wd_trim: status=%s\n",
   2087 		    sbuf);
   2088 		error = EIO;
   2089 		goto out;
   2090 	}
   2091 	error = 0;
   2092 
   2093 out:
   2094 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
   2095 	ata_channel_start(wd->drvp->chnl_softc, wd->drvp->drive);
   2096 	return error;
   2097 }
   2098 
   2099 bool
   2100 wd_shutdown(device_t dev, int how)
   2101 {
   2102 	struct wd_softc *wd = device_private(dev);
   2103 
   2104 	/* the adapter needs to be enabled */
   2105 	if (wd->atabus->ata_addref(wd->drvp))
   2106 		return true; /* no need to complain */
   2107 
   2108 	wd_flushcache(wd, AT_POLL, false);
   2109 	if ((how & RB_POWERDOWN) == RB_POWERDOWN)
   2110 		wd_standby(wd, AT_POLL);
   2111 	return true;
   2112 }
   2113 
   2114 /*
   2115  * Allocate space for a ioctl queue structure.  Mostly taken from
   2116  * scsipi_ioctl.c
   2117  */
   2118 struct wd_ioctl *
   2119 wi_get(struct wd_softc *wd)
   2120 {
   2121 	struct wd_ioctl *wi;
   2122 
   2123 	wi = malloc(sizeof(struct wd_ioctl), M_TEMP, M_WAITOK|M_ZERO);
   2124 	wi->wi_softc = wd;
   2125 	buf_init(&wi->wi_bp);
   2126 
   2127 	return (wi);
   2128 }
   2129 
   2130 /*
   2131  * Free an ioctl structure and remove it from our list
   2132  */
   2133 
   2134 void
   2135 wi_free(struct wd_ioctl *wi)
   2136 {
   2137 	buf_destroy(&wi->wi_bp);
   2138 	free(wi, M_TEMP);
   2139 }
   2140 
   2141 /*
   2142  * Find a wd_ioctl structure based on the struct buf.
   2143  */
   2144 
   2145 struct wd_ioctl *
   2146 wi_find(struct buf *bp)
   2147 {
   2148 	return container_of(bp, struct wd_ioctl, wi_bp);
   2149 }
   2150 
   2151 static uint
   2152 wi_sector_size(const struct wd_ioctl * const wi)
   2153 {
   2154 	switch (wi->wi_atareq.command) {
   2155 	case WDCC_READ:
   2156 	case WDCC_WRITE:
   2157 	case WDCC_READMULTI:
   2158 	case WDCC_WRITEMULTI:
   2159 	case WDCC_READDMA:
   2160 	case WDCC_WRITEDMA:
   2161 	case WDCC_READ_EXT:
   2162 	case WDCC_WRITE_EXT:
   2163 	case WDCC_READMULTI_EXT:
   2164 	case WDCC_WRITEMULTI_EXT:
   2165 	case WDCC_READDMA_EXT:
   2166 	case WDCC_WRITEDMA_EXT:
   2167 	case WDCC_READ_FPDMA_QUEUED:
   2168 	case WDCC_WRITE_FPDMA_QUEUED:
   2169 		return wi->wi_softc->sc_blksize;
   2170 	default:
   2171 		return 512;
   2172 	}
   2173 }
   2174 
   2175 /*
   2176  * Ioctl pseudo strategy routine
   2177  *
   2178  * This is mostly stolen from scsipi_ioctl.c:scsistrategy().  What
   2179  * happens here is:
   2180  *
   2181  * - wdioctl() queues a wd_ioctl structure.
   2182  *
   2183  * - wdioctl() calls physio/wdioctlstrategy based on whether or not
   2184  *   user space I/O is required.  If physio() is called, physio() eventually
   2185  *   calls wdioctlstrategy().
   2186  *
   2187  * - In either case, wdioctlstrategy() calls wd->atabus->ata_exec_command()
   2188  *   to perform the actual command
   2189  *
   2190  * The reason for the use of the pseudo strategy routine is because
   2191  * when doing I/O to/from user space, physio _really_ wants to be in
   2192  * the loop.  We could put the entire buffer into the ioctl request
   2193  * structure, but that won't scale if we want to do things like download
   2194  * microcode.
   2195  */
   2196 
   2197 void
   2198 wdioctlstrategy(struct buf *bp)
   2199 {
   2200 	struct wd_ioctl *wi;
   2201 	struct ata_xfer *xfer;
   2202 	int error = 0;
   2203 
   2204 	wi = wi_find(bp);
   2205 	if (wi == NULL) {
   2206 		printf("wdioctlstrategy: "
   2207 		    "No matching ioctl request found in queue\n");
   2208 		error = EINVAL;
   2209 		goto out2;
   2210 	}
   2211 
   2212 	xfer = ata_get_xfer(wi->wi_softc->drvp->chnl_softc);
   2213 	if (xfer == NULL) {
   2214 		error = EINTR;
   2215 		goto out2;
   2216 	}
   2217 
   2218 	/*
   2219 	 * Abort if physio broke up the transfer
   2220 	 */
   2221 
   2222 	if (bp->b_bcount != wi->wi_atareq.datalen) {
   2223 		printf("physio split wd ioctl request... cannot proceed\n");
   2224 		error = EIO;
   2225 		goto out;
   2226 	}
   2227 
   2228 	/*
   2229 	 * Abort if we didn't get a buffer size that was a multiple of
   2230 	 * our sector size (or overflows CHS/LBA28 sector count)
   2231 	 */
   2232 
   2233 	if ((bp->b_bcount % wi_sector_size(wi)) != 0 ||
   2234 	    (bp->b_bcount / wi_sector_size(wi)) >=
   2235 	     (1 << NBBY)) {
   2236 		error = EINVAL;
   2237 		goto out;
   2238 	}
   2239 
   2240 	/*
   2241 	 * Make sure a timeout was supplied in the ioctl request
   2242 	 */
   2243 
   2244 	if (wi->wi_atareq.timeout == 0) {
   2245 		error = EINVAL;
   2246 		goto out;
   2247 	}
   2248 
   2249 	if (wi->wi_atareq.flags & ATACMD_READ)
   2250 		xfer->c_ata_c.flags |= AT_READ;
   2251 	else if (wi->wi_atareq.flags & ATACMD_WRITE)
   2252 		xfer->c_ata_c.flags |= AT_WRITE;
   2253 
   2254 	if (wi->wi_atareq.flags & ATACMD_READREG)
   2255 		xfer->c_ata_c.flags |= AT_READREG;
   2256 
   2257 	if ((wi->wi_atareq.flags & ATACMD_LBA) != 0)
   2258 		xfer->c_ata_c.flags |= AT_LBA;
   2259 
   2260 	xfer->c_ata_c.flags |= AT_WAIT;
   2261 
   2262 	xfer->c_ata_c.timeout = wi->wi_atareq.timeout;
   2263 	xfer->c_ata_c.r_command = wi->wi_atareq.command;
   2264 	xfer->c_ata_c.r_lba = ((wi->wi_atareq.head & 0x0f) << 24) |
   2265 	    (wi->wi_atareq.cylinder << 8) |
   2266 	    wi->wi_atareq.sec_num;
   2267 	xfer->c_ata_c.r_count = wi->wi_atareq.sec_count;
   2268 	xfer->c_ata_c.r_features = wi->wi_atareq.features;
   2269 	xfer->c_ata_c.r_st_bmask = WDCS_DRDY;
   2270 	xfer->c_ata_c.r_st_pmask = WDCS_DRDY;
   2271 	xfer->c_ata_c.data = wi->wi_bp.b_data;
   2272 	xfer->c_ata_c.bcount = wi->wi_bp.b_bcount;
   2273 
   2274 	if (wi->wi_softc->atabus->ata_exec_command(wi->wi_softc->drvp, xfer)
   2275 	    != ATACMD_COMPLETE) {
   2276 		wi->wi_atareq.retsts = ATACMD_ERROR;
   2277 		error = EIO;
   2278 		goto out;
   2279 	}
   2280 
   2281 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   2282 		if (xfer->c_ata_c.flags & AT_ERROR) {
   2283 			wi->wi_atareq.retsts = ATACMD_ERROR;
   2284 			wi->wi_atareq.error = xfer->c_ata_c.r_error;
   2285 		} else if (xfer->c_ata_c.flags & AT_DF)
   2286 			wi->wi_atareq.retsts = ATACMD_DF;
   2287 		else
   2288 			wi->wi_atareq.retsts = ATACMD_TIMEOUT;
   2289 	} else {
   2290 		wi->wi_atareq.retsts = ATACMD_OK;
   2291 		if (wi->wi_atareq.flags & ATACMD_READREG) {
   2292 			wi->wi_atareq.command = xfer->c_ata_c.r_status;
   2293 			wi->wi_atareq.features = xfer->c_ata_c.r_error;
   2294 			wi->wi_atareq.sec_count = xfer->c_ata_c.r_count;
   2295 			wi->wi_atareq.sec_num = xfer->c_ata_c.r_lba & 0xff;
   2296 			wi->wi_atareq.head = (xfer->c_ata_c.r_device & 0xf0) |
   2297 			    ((xfer->c_ata_c.r_lba >> 24) & 0x0f);
   2298 			wi->wi_atareq.cylinder =
   2299 			    (xfer->c_ata_c.r_lba >> 8) & 0xffff;
   2300 			wi->wi_atareq.error = xfer->c_ata_c.r_error;
   2301 		}
   2302 	}
   2303 
   2304 out:
   2305 	ata_free_xfer(wi->wi_softc->drvp->chnl_softc, xfer);
   2306 	ata_channel_start(wi->wi_softc->drvp->chnl_softc,
   2307 	    wi->wi_softc->drvp->drive);
   2308 out2:
   2309 	bp->b_error = error;
   2310 	if (error)
   2311 		bp->b_resid = bp->b_bcount;
   2312 	biodone(bp);
   2313 }
   2314