Home | History | Annotate | Line # | Download | only in ata
wd.c revision 1.428.2.31
      1 /*	$NetBSD: wd.c,v 1.428.2.31 2017/07/30 20:16:29 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.31 2017/07/30 20:16:29 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, 0,
    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 		xfer->c_flags |= C_CHAOS;
    717 	}
    718 #endif
    719 
    720 	/*
    721 	 * If we're retrying, retry in single-sector mode. This will give us
    722 	 * the sector number of the problem, and will eventually allow the
    723 	 * transfer to succeed.
    724 	 */
    725 	if (xfer->c_retries >= WDIORETRIES_SINGLE)
    726 		xfer->c_bio.flags = ATA_SINGLE;
    727 	else
    728 		xfer->c_bio.flags = 0;
    729 	if (wd->sc_flags & WDF_LBA48 &&
    730 	    (((xfer->c_bio.blkno +
    731 	     xfer->c_bio.bcount / wd->sc_dk.dk_label->d_secsize) >
    732 	    wd->sc_capacity28) ||
    733 	    ((xfer->c_bio.bcount / wd->sc_dk.dk_label->d_secsize) > 128)))
    734 		xfer->c_bio.flags |= ATA_LBA48;
    735 
    736 	/*
    737 	 * If NCQ was negotiated, always use it. Some drives return random
    738 	 * errors when switching between NCQ and non-NCQ I/O too often.
    739 	 */
    740 	if (wd->drvp->drive_flags & ATA_DRIVE_NCQ) {
    741 		xfer->c_bio.flags |= ATA_LBA48;
    742 		xfer->c_flags |= C_NCQ;
    743 
    744 		if ((wd->drvp->drive_flags & ATA_DRIVE_NCQ_PRIO) &&
    745 		    BIO_GETPRIO(bp) == BPRIO_TIMECRITICAL)
    746 			xfer->c_bio.flags |= ATA_PRIO_HIGH;
    747 	}
    748 
    749 	if (wd->sc_flags & WDF_LBA)
    750 		xfer->c_bio.flags |= ATA_LBA;
    751 	if (bp->b_flags & B_READ)
    752 		xfer->c_bio.flags |= ATA_READ;
    753 	if (bp->b_flags & B_MEDIA_FUA) {
    754 		/* If not using NCQ, the command WRITE DMA FUA EXT is LBA48 */
    755 		KASSERT((wd->sc_flags & WDF_LBA48) != 0);
    756 		if ((xfer->c_flags & C_NCQ) == 0)
    757 			xfer->c_bio.flags |= ATA_LBA48;
    758 
    759 		xfer->c_bio.flags |= ATA_FUA;
    760 	}
    761 
    762 	/* Instrumentation. */
    763 	if (xfer->c_retries == 0)
    764 		disk_busy(&wd->sc_dk);
    765 	switch (wd->atabus->ata_bio(wd->drvp, xfer)) {
    766 	case ATACMD_TRY_AGAIN:
    767 		panic("wdstart1: try again");
    768 		break;
    769 	case ATACMD_QUEUED:
    770 	case ATACMD_COMPLETE:
    771 		break;
    772 	default:
    773 		panic("wdstart1: bad return code from ata_bio()");
    774 	}
    775 }
    776 
    777 void
    778 wddone(device_t self, struct ata_xfer *xfer)
    779 {
    780 	struct wd_softc *wd = device_private(self);
    781 	const char *errmsg;
    782 	int do_perror = 0;
    783 	struct buf *bp;
    784 
    785 	ATADEBUG_PRINT(("wddone %s\n", device_xname(wd->sc_dev)),
    786 	    DEBUG_XFERS);
    787 
    788 	if (__predict_false(wddoingadump)) {
    789 		/* just drop it to the floor */
    790 		ata_free_xfer(wd->drvp->chnl_softc, xfer);
    791 		return;
    792 	}
    793 
    794 	bp = xfer->c_bio.bp;
    795 	KASSERT(bp != NULL);
    796 
    797 	bp->b_resid = xfer->c_bio.bcount;
    798 	switch (xfer->c_bio.error) {
    799 	case ERR_DMA:
    800 		errmsg = "DMA error";
    801 		goto retry;
    802 	case ERR_DF:
    803 		errmsg = "device fault";
    804 		goto retry;
    805 	case TIMEOUT:
    806 		errmsg = "device timeout";
    807 		goto retry;
    808 	case REQUEUE:
    809 		errmsg = "requeue";
    810 		goto retry2;
    811 	case ERR_RESET:
    812 		errmsg = "channel reset";
    813 		goto retry2;
    814 	case ERROR:
    815 		/* Don't care about media change bits */
    816 		if (xfer->c_bio.r_error != 0 &&
    817 		    (xfer->c_bio.r_error & ~(WDCE_MC | WDCE_MCR)) == 0)
    818 			goto noerror;
    819 		errmsg = "error";
    820 		do_perror = 1;
    821 retry:		/* Just reset and retry. Can we do more ? */
    822 		(*wd->atabus->ata_reset_drive)(wd->drvp, AT_POLL, NULL);
    823 retry2:
    824 		mutex_enter(&wd->sc_lock);
    825 
    826 		diskerr(bp, "wd", errmsg, LOG_PRINTF,
    827 		    xfer->c_bio.blkdone, wd->sc_dk.dk_label);
    828 		if (xfer->c_retries < WDIORETRIES)
    829 			printf(", slot %d, retry %d", xfer->c_slot,
    830 			    xfer->c_retries + 1);
    831 		printf("\n");
    832 		if (do_perror)
    833 			wdperror(wd, xfer);
    834 
    835 		if (xfer->c_retries < WDIORETRIES) {
    836 			xfer->c_retries++;
    837 
    838 			/* Rerun ASAP if just requeued */
    839 			callout_reset(&xfer->c_retry_callout,
    840 			    (xfer->c_bio.error == REQUEUE) ? 1 : RECOVERYTIME,
    841 			    wdbiorestart, xfer);
    842 
    843 			mutex_exit(&wd->sc_lock);
    844 			return;
    845 		}
    846 
    847 		mutex_exit(&wd->sc_lock);
    848 
    849 #ifdef WD_SOFTBADSECT
    850 		/*
    851 		 * Not all errors indicate a failed block but those that do,
    852 		 * put the block on the bad-block list for the device.  Only
    853 		 * do this for reads because the drive should do it for writes,
    854 		 * itself, according to Manuel.
    855 		 */
    856 		if ((bp->b_flags & B_READ) &&
    857 		    ((wd->drvp->ata_vers >= 4 && xfer->c_bio.r_error & 64) ||
    858 		     (wd->drvp->ata_vers < 4 && xfer->c_bio.r_error & 192))) {
    859 			struct disk_badsectors *dbs;
    860 
    861 			dbs = malloc(sizeof *dbs, M_TEMP, M_NOWAIT);
    862 			if (dbs == NULL) {
    863 				aprint_error_dev(wd->sc_dev,
    864 				    "failed to add bad block to list\n");
    865 				goto out;
    866 			}
    867 
    868 			dbs->dbs_min = bp->b_rawblkno;
    869 			dbs->dbs_max = dbs->dbs_min +
    870 			    (bp->b_bcount /wd->sc_blksize) - 1;
    871 			microtime(&dbs->dbs_failedat);
    872 
    873 			mutex_enter(&wd->sc_lock);
    874 			SLIST_INSERT_HEAD(&wd->sc_bslist, dbs, dbs_next);
    875 			wd->sc_bscount++;
    876 			mutex_exit(&wd->sc_lock);
    877 		}
    878 out:
    879 #endif
    880 		bp->b_error = EIO;
    881 		break;
    882 	case NOERROR:
    883 noerror:	if ((xfer->c_bio.flags & ATA_CORR) || xfer->c_retries > 0)
    884 			aprint_error_dev(wd->sc_dev,
    885 			    "soft error (corrected) slot %d\n", xfer->c_slot);
    886 #ifdef WD_CHAOS_MONKEY
    887 		KASSERT((xfer->c_flags & C_CHAOS) == 0);
    888 #endif
    889 		break;
    890 	case ERR_NODEV:
    891 		bp->b_error = EIO;
    892 		break;
    893 	}
    894 	if (__predict_false(bp->b_error != 0) && bp->b_resid == 0) {
    895 		/*
    896 		 * the disk or controller sometimes report a complete
    897 		 * xfer, when there has been an error. This is wrong,
    898 		 * assume nothing got transfered in this case
    899 		 */
    900 		bp->b_resid = bp->b_bcount;
    901 	}
    902 	disk_unbusy(&wd->sc_dk, (bp->b_bcount - bp->b_resid),
    903 	    (bp->b_flags & B_READ));
    904 	rnd_add_uint32(&wd->rnd_source, bp->b_blkno);
    905 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
    906 	biodone(bp);
    907 	ata_channel_start(wd->drvp->chnl_softc, wd->drvp->drive);
    908 }
    909 
    910 static void
    911 wdbiorestart(void *v)
    912 {
    913 	struct ata_xfer *xfer = v;
    914 	struct buf *bp = xfer->c_bio.bp;
    915 	struct wd_softc *wd = device_lookup_private(&wd_cd, WDUNIT(bp->b_dev));
    916 
    917 	ATADEBUG_PRINT(("wdrestart %s\n", device_xname(wd->sc_dev)),
    918 	    DEBUG_XFERS);
    919 
    920 	mutex_enter(&wd->sc_lock);
    921 	wdstart1(wd, bp, xfer);
    922 	mutex_exit(&wd->sc_lock);
    923 }
    924 
    925 static void
    926 wdminphys(struct buf *bp)
    927 {
    928 	const struct wd_softc * const wd =
    929 	    device_lookup_private(&wd_cd, WDUNIT(bp->b_dev));
    930 	uint32_t maxsectors;
    931 
    932 	/*
    933 	 * The limit is actually 65536 for LBA48 and 256 for non-LBA48,
    934 	 * but that requires to set the count for the ATA command
    935 	 * to 0, which is somewhat error prone, so better stay safe.
    936 	 */
    937 	if (wd->sc_flags & WDF_LBA48)
    938 		maxsectors = 65535;
    939 	else
    940 		maxsectors = 128;
    941 
    942 	if (bp->b_bcount > (wd->sc_blksize * maxsectors))
    943 		bp->b_bcount = (wd->sc_blksize * maxsectors);
    944 
    945 	minphys(bp);
    946 }
    947 
    948 int
    949 wdread(dev_t dev, struct uio *uio, int flags)
    950 {
    951 
    952 	ATADEBUG_PRINT(("wdread\n"), DEBUG_XFERS);
    953 	return (physio(wdstrategy, NULL, dev, B_READ, wdminphys, uio));
    954 }
    955 
    956 int
    957 wdwrite(dev_t dev, struct uio *uio, int flags)
    958 {
    959 
    960 	ATADEBUG_PRINT(("wdwrite\n"), DEBUG_XFERS);
    961 	return (physio(wdstrategy, NULL, dev, B_WRITE, wdminphys, uio));
    962 }
    963 
    964 int
    965 wdopen(dev_t dev, int flag, int fmt, struct lwp *l)
    966 {
    967 	struct wd_softc *wd;
    968 	int part, error;
    969 
    970 	ATADEBUG_PRINT(("wdopen\n"), DEBUG_FUNCS);
    971 	wd = device_lookup_private(&wd_cd, WDUNIT(dev));
    972 	if (wd == NULL)
    973 		return (ENXIO);
    974 
    975 	if (! device_is_active(wd->sc_dev))
    976 		return (ENODEV);
    977 
    978 	if (wd->sc_capacity == 0)
    979 		return (ENODEV);
    980 
    981 	part = WDPART(dev);
    982 
    983 	mutex_enter(&wd->sc_dk.dk_openlock);
    984 
    985 	/*
    986 	 * If there are wedges, and this is not RAW_PART, then we
    987 	 * need to fail.
    988 	 */
    989 	if (wd->sc_dk.dk_nwedges != 0 && part != RAW_PART) {
    990 		error = EBUSY;
    991 		goto bad1;
    992 	}
    993 
    994 	/*
    995 	 * If this is the first open of this device, add a reference
    996 	 * to the adapter.
    997 	 */
    998 	if (wd->sc_dk.dk_openmask == 0 &&
    999 	    (error = wd->atabus->ata_addref(wd->drvp)) != 0)
   1000 		goto bad1;
   1001 
   1002 	if (wd->sc_dk.dk_openmask != 0) {
   1003 		/*
   1004 		 * If any partition is open, but the disk has been invalidated,
   1005 		 * disallow further opens.
   1006 		 */
   1007 		if ((wd->sc_flags & WDF_LOADED) == 0) {
   1008 			error = EIO;
   1009 			goto bad2;
   1010 		}
   1011 	} else {
   1012 		if ((wd->sc_flags & WDF_LOADED) == 0) {
   1013 
   1014 			/* Load the physical device parameters. */
   1015 			if (wd_get_params(wd, AT_WAIT, &wd->sc_params) != 0) {
   1016 				aprint_error_dev(wd->sc_dev,
   1017 				"IDENTIFY failed\n");
   1018 				error = EIO;
   1019 				goto bad2;
   1020 			}
   1021 			wd->sc_flags |= WDF_LOADED;
   1022 			/* Load the partition info if not already loaded. */
   1023 			wdgetdisklabel(wd);
   1024 		}
   1025 	}
   1026 
   1027 	/* Check that the partition exists. */
   1028 	if (part != RAW_PART &&
   1029 	    (part >= wd->sc_dk.dk_label->d_npartitions ||
   1030 	     wd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
   1031 		error = ENXIO;
   1032 		goto bad2;
   1033 	}
   1034 
   1035 	/* Insure only one open at a time. */
   1036 	switch (fmt) {
   1037 	case S_IFCHR:
   1038 		wd->sc_dk.dk_copenmask |= (1 << part);
   1039 		break;
   1040 	case S_IFBLK:
   1041 		wd->sc_dk.dk_bopenmask |= (1 << part);
   1042 		break;
   1043 	}
   1044 	wd->sc_dk.dk_openmask =
   1045 	    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1046 
   1047 	mutex_exit(&wd->sc_dk.dk_openlock);
   1048 	return 0;
   1049 
   1050  bad2:
   1051 	if (wd->sc_dk.dk_openmask == 0)
   1052 		wd->atabus->ata_delref(wd->drvp);
   1053  bad1:
   1054 	mutex_exit(&wd->sc_dk.dk_openlock);
   1055 	return error;
   1056 }
   1057 
   1058 /*
   1059  * Caller must hold wd->sc_dk.dk_openlock.
   1060  */
   1061 static int
   1062 wdlastclose(device_t self)
   1063 {
   1064 	struct wd_softc *wd = device_private(self);
   1065 
   1066 	wd_flushcache(wd, AT_WAIT, false);
   1067 
   1068 	if (! (wd->sc_flags & WDF_KLABEL))
   1069 		wd->sc_flags &= ~WDF_LOADED;
   1070 
   1071 	wd->atabus->ata_delref(wd->drvp);
   1072 
   1073 	return 0;
   1074 }
   1075 
   1076 int
   1077 wdclose(dev_t dev, int flag, int fmt, struct lwp *l)
   1078 {
   1079 	struct wd_softc *wd =
   1080 	    device_lookup_private(&wd_cd, WDUNIT(dev));
   1081 	int part = WDPART(dev);
   1082 
   1083 	ATADEBUG_PRINT(("wdclose\n"), DEBUG_FUNCS);
   1084 
   1085 	mutex_enter(&wd->sc_dk.dk_openlock);
   1086 
   1087 	switch (fmt) {
   1088 	case S_IFCHR:
   1089 		wd->sc_dk.dk_copenmask &= ~(1 << part);
   1090 		break;
   1091 	case S_IFBLK:
   1092 		wd->sc_dk.dk_bopenmask &= ~(1 << part);
   1093 		break;
   1094 	}
   1095 	wd->sc_dk.dk_openmask =
   1096 	    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1097 
   1098 	if (wd->sc_dk.dk_openmask == 0)
   1099 		wdlastclose(wd->sc_dev);
   1100 
   1101 	mutex_exit(&wd->sc_dk.dk_openlock);
   1102 	return 0;
   1103 }
   1104 
   1105 void
   1106 wdgetdefaultlabel(struct wd_softc *wd, struct disklabel *lp)
   1107 {
   1108 
   1109 	ATADEBUG_PRINT(("wdgetdefaultlabel\n"), DEBUG_FUNCS);
   1110 	memset(lp, 0, sizeof(struct disklabel));
   1111 
   1112 	lp->d_secsize = wd->sc_blksize;
   1113 	lp->d_ntracks = wd->sc_params.atap_heads;
   1114 	lp->d_nsectors = wd->sc_params.atap_sectors;
   1115 	lp->d_ncylinders = (wd->sc_flags & WDF_LBA) ? wd->sc_capacity /
   1116 		(wd->sc_params.atap_heads * wd->sc_params.atap_sectors) :
   1117 		wd->sc_params.atap_cylinders;
   1118 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
   1119 
   1120 	if (strcmp(wd->sc_params.atap_model, "ST506") == 0)
   1121 		lp->d_type = DKTYPE_ST506;
   1122 	else
   1123 		lp->d_type = DKTYPE_ESDI;
   1124 
   1125 	strncpy(lp->d_typename, wd->sc_params.atap_model, 16);
   1126 	strncpy(lp->d_packname, "fictitious", 16);
   1127 	if (wd->sc_capacity > UINT32_MAX)
   1128 		lp->d_secperunit = UINT32_MAX;
   1129 	else
   1130 		lp->d_secperunit = wd->sc_capacity;
   1131 	lp->d_rpm = 3600;
   1132 	lp->d_interleave = 1;
   1133 	lp->d_flags = 0;
   1134 
   1135 	lp->d_partitions[RAW_PART].p_offset = 0;
   1136 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
   1137 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
   1138 	lp->d_npartitions = RAW_PART + 1;
   1139 
   1140 	lp->d_magic = DISKMAGIC;
   1141 	lp->d_magic2 = DISKMAGIC;
   1142 	lp->d_checksum = dkcksum(lp);
   1143 }
   1144 
   1145 /*
   1146  * Fabricate a default disk label, and try to read the correct one.
   1147  */
   1148 void
   1149 wdgetdisklabel(struct wd_softc *wd)
   1150 {
   1151 	struct disklabel *lp = wd->sc_dk.dk_label;
   1152 	const char *errstring;
   1153 
   1154 	ATADEBUG_PRINT(("wdgetdisklabel\n"), DEBUG_FUNCS);
   1155 
   1156 	memset(wd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
   1157 
   1158 	wdgetdefaultlabel(wd, lp);
   1159 
   1160 	wd->drvp->badsect[0] = -1;
   1161 
   1162 	if (wd->drvp->state > RESET) {
   1163 		mutex_enter(&wd->sc_lock);
   1164 		wd->drvp->drive_flags |= ATA_DRIVE_RESET;
   1165 		mutex_exit(&wd->sc_lock);
   1166 	}
   1167 	errstring = readdisklabel(MAKEWDDEV(0, device_unit(wd->sc_dev),
   1168 				  RAW_PART), wdstrategy, lp,
   1169 				  wd->sc_dk.dk_cpulabel);
   1170 	if (errstring) {
   1171 		/*
   1172 		 * This probably happened because the drive's default
   1173 		 * geometry doesn't match the DOS geometry.  We
   1174 		 * assume the DOS geometry is now in the label and try
   1175 		 * again.  XXX This is a kluge.
   1176 		 */
   1177 		if (wd->drvp->state > RESET) {
   1178 			mutex_enter(&wd->sc_lock);
   1179 			wd->drvp->drive_flags |= ATA_DRIVE_RESET;
   1180 			mutex_exit(&wd->sc_lock);
   1181 		}
   1182 		errstring = readdisklabel(MAKEWDDEV(0, device_unit(wd->sc_dev),
   1183 		    RAW_PART), wdstrategy, lp, wd->sc_dk.dk_cpulabel);
   1184 	}
   1185 	if (errstring) {
   1186 		aprint_error_dev(wd->sc_dev, "%s\n", errstring);
   1187 		return;
   1188 	}
   1189 
   1190 	if (wd->drvp->state > RESET) {
   1191 		mutex_enter(&wd->sc_lock);
   1192 		wd->drvp->drive_flags |= ATA_DRIVE_RESET;
   1193 		mutex_exit(&wd->sc_lock);
   1194 	}
   1195 #ifdef HAS_BAD144_HANDLING
   1196 	if ((lp->d_flags & D_BADSECT) != 0)
   1197 		bad144intern(wd);
   1198 #endif
   1199 }
   1200 
   1201 void
   1202 wdperror(const struct wd_softc *wd, struct ata_xfer *xfer)
   1203 {
   1204 	static const char *const errstr0_3[] = {"address mark not found",
   1205 	    "track 0 not found", "aborted command", "media change requested",
   1206 	    "id not found", "media changed", "uncorrectable data error",
   1207 	    "bad block detected"};
   1208 	static const char *const errstr4_5[] = {
   1209 	    "obsolete (address mark not found)",
   1210 	    "no media/write protected", "aborted command",
   1211 	    "media change requested", "id not found", "media changed",
   1212 	    "uncorrectable data error", "interface CRC error"};
   1213 	const char *const *errstr;
   1214 	int i;
   1215 	const char *sep = "";
   1216 
   1217 	const char *devname = device_xname(wd->sc_dev);
   1218 	struct ata_drive_datas *drvp = wd->drvp;
   1219 	int errno = xfer->c_bio.r_error;
   1220 
   1221 	if (drvp->ata_vers >= 4)
   1222 		errstr = errstr4_5;
   1223 	else
   1224 		errstr = errstr0_3;
   1225 
   1226 	printf("%s: (", devname);
   1227 
   1228 	if (errno == 0)
   1229 		printf("error not notified");
   1230 
   1231 	for (i = 0; i < 8; i++) {
   1232 		if (errno & (1 << i)) {
   1233 			printf("%s%s", sep, errstr[i]);
   1234 			sep = ", ";
   1235 		}
   1236 	}
   1237 	printf(")\n");
   1238 }
   1239 
   1240 int
   1241 wdioctl(dev_t dev, u_long xfer, void *addr, int flag, struct lwp *l)
   1242 {
   1243 	struct wd_softc *wd =
   1244 	    device_lookup_private(&wd_cd, WDUNIT(dev));
   1245 	int error;
   1246 #ifdef __HAVE_OLD_DISKLABEL
   1247 	struct disklabel *newlabel = NULL;
   1248 #endif
   1249 
   1250 	ATADEBUG_PRINT(("wdioctl\n"), DEBUG_FUNCS);
   1251 
   1252 	if ((wd->sc_flags & WDF_LOADED) == 0)
   1253 		return EIO;
   1254 
   1255 	error = disk_ioctl(&wd->sc_dk, dev, xfer, addr, flag, l);
   1256 	if (error != EPASSTHROUGH)
   1257 		return error;
   1258 
   1259 	error = 0;
   1260 	switch (xfer) {
   1261 #ifdef HAS_BAD144_HANDLING
   1262 	case DIOCSBAD:
   1263 		if ((flag & FWRITE) == 0)
   1264 			return EBADF;
   1265 		wd->sc_dk.dk_cpulabel->bad = *(struct dkbad *)addr;
   1266 		wd->sc_dk.dk_label->d_flags |= D_BADSECT;
   1267 		bad144intern(wd);
   1268 		return 0;
   1269 #endif
   1270 #ifdef WD_SOFTBADSECT
   1271 	case DIOCBSLIST :
   1272 	{
   1273 		uint32_t count, missing, skip;
   1274 		struct disk_badsecinfo dbsi;
   1275 		struct disk_badsectors *dbs;
   1276 		size_t available;
   1277 		uint8_t *laddr;
   1278 
   1279 		dbsi = *(struct disk_badsecinfo *)addr;
   1280 		missing = wd->sc_bscount;
   1281 		count = 0;
   1282 		available = dbsi.dbsi_bufsize;
   1283 		skip = dbsi.dbsi_skip;
   1284 		laddr = (uint8_t *)dbsi.dbsi_buffer;
   1285 
   1286 		/*
   1287 		 * We start this loop with the expectation that all of the
   1288 		 * entries will be missed and decrement this counter each
   1289 		 * time we either skip over one (already copied out) or
   1290 		 * we actually copy it back to user space.  The structs
   1291 		 * holding the bad sector information are copied directly
   1292 		 * back to user space whilst the summary is returned via
   1293 		 * the struct passed in via the ioctl.
   1294 		 */
   1295 		SLIST_FOREACH(dbs, &wd->sc_bslist, dbs_next) {
   1296 			if (skip > 0) {
   1297 				missing--;
   1298 				skip--;
   1299 				continue;
   1300 			}
   1301 			if (available < sizeof(*dbs))
   1302 				break;
   1303 			available -= sizeof(*dbs);
   1304 			copyout(dbs, laddr, sizeof(*dbs));
   1305 			laddr += sizeof(*dbs);
   1306 			missing--;
   1307 			count++;
   1308 		}
   1309 		dbsi.dbsi_left = missing;
   1310 		dbsi.dbsi_copied = count;
   1311 		*(struct disk_badsecinfo *)addr = dbsi;
   1312 		return 0;
   1313 	}
   1314 
   1315 	case DIOCBSFLUSH :
   1316 		/* Clean out the bad sector list */
   1317 		while (!SLIST_EMPTY(&wd->sc_bslist)) {
   1318 			void *head = SLIST_FIRST(&wd->sc_bslist);
   1319 			SLIST_REMOVE_HEAD(&wd->sc_bslist, dbs_next);
   1320 			free(head, M_TEMP);
   1321 		}
   1322 		wd->sc_bscount = 0;
   1323 		return 0;
   1324 #endif
   1325 
   1326 	case DIOCWDINFO:
   1327 	case DIOCSDINFO:
   1328 #ifdef __HAVE_OLD_DISKLABEL
   1329 	case ODIOCWDINFO:
   1330 	case ODIOCSDINFO:
   1331 #endif
   1332 	{
   1333 		struct disklabel *lp;
   1334 
   1335 		if ((flag & FWRITE) == 0)
   1336 			return EBADF;
   1337 
   1338 #ifdef __HAVE_OLD_DISKLABEL
   1339 		if (xfer == ODIOCSDINFO || xfer == ODIOCWDINFO) {
   1340 			newlabel = malloc(sizeof *newlabel, M_TEMP,
   1341 			    M_WAITOK | M_ZERO);
   1342 			if (newlabel == NULL)
   1343 				return EIO;
   1344 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
   1345 			lp = newlabel;
   1346 		} else
   1347 #endif
   1348 		lp = (struct disklabel *)addr;
   1349 
   1350 		mutex_enter(&wd->sc_dk.dk_openlock);
   1351 		wd->sc_flags |= WDF_LABELLING;
   1352 
   1353 		error = setdisklabel(wd->sc_dk.dk_label,
   1354 		    lp, /*wd->sc_dk.dk_openmask : */0,
   1355 		    wd->sc_dk.dk_cpulabel);
   1356 		if (error == 0) {
   1357 			if (wd->drvp->state > RESET) {
   1358 				mutex_enter(&wd->sc_lock);
   1359 				wd->drvp->drive_flags |= ATA_DRIVE_RESET;
   1360 				mutex_exit(&wd->sc_lock);
   1361 			}
   1362 			if (xfer == DIOCWDINFO
   1363 #ifdef __HAVE_OLD_DISKLABEL
   1364 			    || xfer == ODIOCWDINFO
   1365 #endif
   1366 			    )
   1367 				error = writedisklabel(WDLABELDEV(dev),
   1368 				    wdstrategy, wd->sc_dk.dk_label,
   1369 				    wd->sc_dk.dk_cpulabel);
   1370 		}
   1371 
   1372 		wd->sc_flags &= ~WDF_LABELLING;
   1373 		mutex_exit(&wd->sc_dk.dk_openlock);
   1374 #ifdef __HAVE_OLD_DISKLABEL
   1375 		if (newlabel != NULL)
   1376 			free(newlabel, M_TEMP);
   1377 #endif
   1378 		return error;
   1379 	}
   1380 
   1381 	case DIOCKLABEL:
   1382 		if (*(int *)addr)
   1383 			wd->sc_flags |= WDF_KLABEL;
   1384 		else
   1385 			wd->sc_flags &= ~WDF_KLABEL;
   1386 		return 0;
   1387 
   1388 	case DIOCWLABEL:
   1389 		if ((flag & FWRITE) == 0)
   1390 			return EBADF;
   1391 		if (*(int *)addr)
   1392 			wd->sc_flags |= WDF_WLABEL;
   1393 		else
   1394 			wd->sc_flags &= ~WDF_WLABEL;
   1395 		return 0;
   1396 
   1397 	case DIOCGDEFLABEL:
   1398 		wdgetdefaultlabel(wd, (struct disklabel *)addr);
   1399 		return 0;
   1400 #ifdef __HAVE_OLD_DISKLABEL
   1401 	case ODIOCGDEFLABEL:
   1402 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1403 		if (newlabel == NULL)
   1404 			return EIO;
   1405 		wdgetdefaultlabel(wd, newlabel);
   1406 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
   1407 			memcpy(addr, &newlabel, sizeof (struct olddisklabel));
   1408 		else
   1409 			error = ENOTTY;
   1410 		free(newlabel, M_TEMP);
   1411 		return error;
   1412 #endif
   1413 
   1414 #ifdef notyet
   1415 	case DIOCWFORMAT:
   1416 		if ((flag & FWRITE) == 0)
   1417 			return EBADF;
   1418 		{
   1419 		register struct format_op *fop;
   1420 		struct iovec aiov;
   1421 		struct uio auio;
   1422 
   1423 		fop = (struct format_op *)addr;
   1424 		aiov.iov_base = fop->df_buf;
   1425 		aiov.iov_len = fop->df_count;
   1426 		auio.uio_iov = &aiov;
   1427 		auio.uio_iovcnt = 1;
   1428 		auio.uio_resid = fop->df_count;
   1429 		auio.uio_offset =
   1430 			fop->df_startblk * wd->sc_dk.dk_label->d_secsize;
   1431 		auio.uio_vmspace = l->l_proc->p_vmspace;
   1432 		error = physio(wdformat, NULL, dev, B_WRITE, wdminphys,
   1433 		    &auio);
   1434 		fop->df_count -= auio.uio_resid;
   1435 		fop->df_reg[0] = wdc->sc_status;
   1436 		fop->df_reg[1] = wdc->sc_error;
   1437 		return error;
   1438 		}
   1439 #endif
   1440 	case DIOCGCACHE:
   1441 		return wd_getcache(wd, (int *)addr);
   1442 
   1443 	case DIOCSCACHE:
   1444 		return wd_setcache(wd, *(int *)addr);
   1445 
   1446 	case DIOCCACHESYNC:
   1447 		return wd_flushcache(wd, AT_WAIT, true);
   1448 
   1449 	case ATAIOCCOMMAND:
   1450 		/*
   1451 		 * Make sure this command is (relatively) safe first
   1452 		 */
   1453 		if ((((atareq_t *) addr)->flags & ATACMD_READ) == 0 &&
   1454 		    (flag & FWRITE) == 0)
   1455 			return (EBADF);
   1456 		{
   1457 		struct wd_ioctl *wi;
   1458 		atareq_t *atareq = (atareq_t *) addr;
   1459 		int error1;
   1460 
   1461 		wi = wi_get(wd);
   1462 		wi->wi_atareq = *atareq;
   1463 
   1464 		if (atareq->datalen && atareq->flags &
   1465 		    (ATACMD_READ | ATACMD_WRITE)) {
   1466 			void *tbuf;
   1467 			if (atareq->datalen < DEV_BSIZE
   1468 			    && atareq->command == WDCC_IDENTIFY) {
   1469 				tbuf = malloc(DEV_BSIZE, M_TEMP, M_WAITOK);
   1470 				wi->wi_iov.iov_base = tbuf;
   1471 				wi->wi_iov.iov_len = DEV_BSIZE;
   1472 				UIO_SETUP_SYSSPACE(&wi->wi_uio);
   1473 			} else {
   1474 				tbuf = NULL;
   1475 				wi->wi_iov.iov_base = atareq->databuf;
   1476 				wi->wi_iov.iov_len = atareq->datalen;
   1477 				wi->wi_uio.uio_vmspace = l->l_proc->p_vmspace;
   1478 			}
   1479 			wi->wi_uio.uio_iov = &wi->wi_iov;
   1480 			wi->wi_uio.uio_iovcnt = 1;
   1481 			wi->wi_uio.uio_resid = atareq->datalen;
   1482 			wi->wi_uio.uio_offset = 0;
   1483 			wi->wi_uio.uio_rw =
   1484 			    (atareq->flags & ATACMD_READ) ? B_READ : B_WRITE;
   1485 			error1 = physio(wdioctlstrategy, &wi->wi_bp, dev,
   1486 			    (atareq->flags & ATACMD_READ) ? B_READ : B_WRITE,
   1487 			    wdminphys, &wi->wi_uio);
   1488 			if (tbuf != NULL && error1 == 0) {
   1489 				error1 = copyout(tbuf, atareq->databuf,
   1490 				    atareq->datalen);
   1491 				free(tbuf, M_TEMP);
   1492 			}
   1493 		} else {
   1494 			/* No need to call physio if we don't have any
   1495 			   user data */
   1496 			wi->wi_bp.b_flags = 0;
   1497 			wi->wi_bp.b_data = 0;
   1498 			wi->wi_bp.b_bcount = 0;
   1499 			wi->wi_bp.b_dev = dev;
   1500 			wi->wi_bp.b_proc = l->l_proc;
   1501 			wdioctlstrategy(&wi->wi_bp);
   1502 			error1 = wi->wi_bp.b_error;
   1503 		}
   1504 		*atareq = wi->wi_atareq;
   1505 		wi_free(wi);
   1506 		return(error1);
   1507 		}
   1508 
   1509 	case DIOCGSTRATEGY:
   1510 	    {
   1511 		struct disk_strategy *dks = (void *)addr;
   1512 
   1513 		mutex_enter(&wd->sc_lock);
   1514 		strlcpy(dks->dks_name, bufq_getstrategyname(wd->sc_q),
   1515 		    sizeof(dks->dks_name));
   1516 		mutex_exit(&wd->sc_lock);
   1517 		dks->dks_paramlen = 0;
   1518 
   1519 		return 0;
   1520 	    }
   1521 
   1522 	case DIOCSSTRATEGY:
   1523 	    {
   1524 		struct disk_strategy *dks = (void *)addr;
   1525 		struct bufq_state *new;
   1526 		struct bufq_state *old;
   1527 
   1528 		if ((flag & FWRITE) == 0) {
   1529 			return EBADF;
   1530 		}
   1531 		if (dks->dks_param != NULL) {
   1532 			return EINVAL;
   1533 		}
   1534 		dks->dks_name[sizeof(dks->dks_name) - 1] = 0; /* ensure term */
   1535 		error = bufq_alloc(&new, dks->dks_name,
   1536 		    BUFQ_EXACT|BUFQ_SORT_RAWBLOCK);
   1537 		if (error) {
   1538 			return error;
   1539 		}
   1540 		mutex_enter(&wd->sc_lock);
   1541 		old = wd->sc_q;
   1542 		bufq_move(new, old);
   1543 		wd->sc_q = new;
   1544 		mutex_exit(&wd->sc_lock);
   1545 		bufq_free(old);
   1546 
   1547 		return 0;
   1548 	    }
   1549 
   1550 	default:
   1551 		return ENOTTY;
   1552 	}
   1553 
   1554 #ifdef DIAGNOSTIC
   1555 	panic("wdioctl: impossible");
   1556 #endif
   1557 }
   1558 
   1559 static int
   1560 wddiscard(dev_t dev, off_t pos, off_t len)
   1561 {
   1562 	struct wd_softc *wd = device_lookup_private(&wd_cd, WDUNIT(dev));
   1563 	daddr_t bno;
   1564 	long size, done;
   1565 	long maxatonce, amount;
   1566 	int result;
   1567 
   1568 	if (!(wd->sc_params.atap_ata_major & WDC_VER_ATA7)
   1569 	    || !(wd->sc_params.support_dsm & ATA_SUPPORT_DSM_TRIM)) {
   1570 		/* not supported; ignore request */
   1571 		ATADEBUG_PRINT(("wddiscard (unsupported)\n"), DEBUG_FUNCS);
   1572 		return 0;
   1573 	}
   1574 	maxatonce = 0xffff; /*wd->sc_params.max_dsm_blocks*/
   1575 
   1576 	ATADEBUG_PRINT(("wddiscard\n"), DEBUG_FUNCS);
   1577 
   1578 	if ((wd->sc_flags & WDF_LOADED) == 0)
   1579 		return EIO;
   1580 
   1581 	/* round the start up and the end down */
   1582 	bno = (pos + wd->sc_blksize - 1) / wd->sc_blksize;
   1583 	size = ((pos + len) / wd->sc_blksize) - bno;
   1584 
   1585 	done = 0;
   1586 	while (done < size) {
   1587 	     amount = size - done;
   1588 	     if (amount > maxatonce) {
   1589 		     amount = maxatonce;
   1590 	     }
   1591 	     result = wd_trim(wd, WDPART(dev), bno + done, amount);
   1592 	     if (result) {
   1593 		     return result;
   1594 	     }
   1595 	     done += amount;
   1596 	}
   1597 	return 0;
   1598 }
   1599 
   1600 #ifdef B_FORMAT
   1601 int
   1602 wdformat(struct buf *bp)
   1603 {
   1604 
   1605 	bp->b_flags |= B_FORMAT;
   1606 	return wdstrategy(bp);
   1607 }
   1608 #endif
   1609 
   1610 int
   1611 wdsize(dev_t dev)
   1612 {
   1613 	struct wd_softc *wd;
   1614 	int part, omask;
   1615 	int size;
   1616 
   1617 	ATADEBUG_PRINT(("wdsize\n"), DEBUG_FUNCS);
   1618 
   1619 	wd = device_lookup_private(&wd_cd, WDUNIT(dev));
   1620 	if (wd == NULL)
   1621 		return (-1);
   1622 
   1623 	part = WDPART(dev);
   1624 	omask = wd->sc_dk.dk_openmask & (1 << part);
   1625 
   1626 	if (omask == 0 && wdopen(dev, 0, S_IFBLK, NULL) != 0)
   1627 		return (-1);
   1628 	if (wd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
   1629 		size = -1;
   1630 	else
   1631 		size = wd->sc_dk.dk_label->d_partitions[part].p_size *
   1632 		    (wd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
   1633 	if (omask == 0 && wdclose(dev, 0, S_IFBLK, NULL) != 0)
   1634 		return (-1);
   1635 	return (size);
   1636 }
   1637 
   1638 /*
   1639  * Dump core after a system crash.
   1640  */
   1641 int
   1642 wddump(dev_t dev, daddr_t blkno, void *va, size_t size)
   1643 {
   1644 	struct wd_softc *wd;	/* disk unit to do the I/O */
   1645 	struct disklabel *lp;   /* disk's disklabel */
   1646 	int part, err;
   1647 	int nblks;	/* total number of sectors left to write */
   1648 	struct ata_xfer *xfer;
   1649 
   1650 	/* Check if recursive dump; if so, punt. */
   1651 	if (wddoingadump)
   1652 		return EFAULT;
   1653 	wddoingadump = 1;
   1654 
   1655 	wd = device_lookup_private(&wd_cd, WDUNIT(dev));
   1656 	if (wd == NULL)
   1657 		return (ENXIO);
   1658 
   1659 	part = WDPART(dev);
   1660 
   1661 	/* Convert to disk sectors.  Request must be a multiple of size. */
   1662 	lp = wd->sc_dk.dk_label;
   1663 	if ((size % lp->d_secsize) != 0)
   1664 		return EFAULT;
   1665 	nblks = size / lp->d_secsize;
   1666 	blkno = blkno / (lp->d_secsize / DEV_BSIZE);
   1667 
   1668 	/* Check transfer bounds against partition size. */
   1669 	if ((blkno < 0) || ((blkno + nblks) > lp->d_partitions[part].p_size))
   1670 		return EINVAL;
   1671 
   1672 	/* Offset block number to start of partition. */
   1673 	blkno += lp->d_partitions[part].p_offset;
   1674 
   1675 	/* Recalibrate, if first dump transfer. */
   1676 	if (wddumprecalibrated == 0) {
   1677 		wddumprecalibrated = 1;
   1678 		(*wd->atabus->ata_reset_drive)(wd->drvp,
   1679 					       AT_POLL | AT_RST_EMERG, NULL);
   1680 		wd->drvp->state = RESET;
   1681 	}
   1682 
   1683 	xfer = ata_get_xfer_ext(wd->drvp->chnl_softc, 0, 0);
   1684 	if (xfer == NULL) {
   1685 		printf("%s: no xfer\n", __func__);
   1686 		return EAGAIN;
   1687 	}
   1688 
   1689 	xfer->c_bio.blkno = blkno;
   1690 	xfer->c_bio.flags = ATA_POLL;
   1691 	if (wd->sc_flags & WDF_LBA48 &&
   1692 	    (xfer->c_bio.blkno + nblks) > wd->sc_capacity28)
   1693 		xfer->c_bio.flags |= ATA_LBA48;
   1694 	if (wd->sc_flags & WDF_LBA)
   1695 		xfer->c_bio.flags |= ATA_LBA;
   1696 	xfer->c_bio.bcount = nblks * lp->d_secsize;
   1697 	xfer->c_bio.databuf = va;
   1698 #ifndef WD_DUMP_NOT_TRUSTED
   1699 	switch (err = wd->atabus->ata_bio(wd->drvp, xfer)) {
   1700 	case ATACMD_TRY_AGAIN:
   1701 		panic("wddump: try again");
   1702 		break;
   1703 	case ATACMD_QUEUED:
   1704 		panic("wddump: polled command has been queued");
   1705 		break;
   1706 	case ATACMD_COMPLETE:
   1707 		break;
   1708 	default:
   1709 		panic("wddump: unknown atacmd code %d", err);
   1710 	}
   1711 	switch(err = xfer->c_bio.error) {
   1712 	case TIMEOUT:
   1713 		printf("wddump: device timed out");
   1714 		err = EIO;
   1715 		break;
   1716 	case ERR_DF:
   1717 		printf("wddump: drive fault");
   1718 		err = EIO;
   1719 		break;
   1720 	case ERR_DMA:
   1721 		printf("wddump: DMA error");
   1722 		err = EIO;
   1723 		break;
   1724 	case ERROR:
   1725 		printf("wddump: ");
   1726 		wdperror(wd, xfer);
   1727 		err = EIO;
   1728 		break;
   1729 	case NOERROR:
   1730 		err = 0;
   1731 		break;
   1732 	default:
   1733 		panic("wddump: unknown error type %d", err);
   1734 	}
   1735 
   1736 	if (err != 0) {
   1737 		printf("\n");
   1738 		return err;
   1739 	}
   1740 #else	/* WD_DUMP_NOT_TRUSTED */
   1741 	/* Let's just talk about this first... */
   1742 	printf("wd%d: dump addr 0x%x, cylin %d, head %d, sector %d\n",
   1743 	    unit, va, cylin, head, sector);
   1744 	delay(500 * 1000);	/* half a second */
   1745 #endif
   1746 
   1747 	wddoingadump = 0;
   1748 	return 0;
   1749 }
   1750 
   1751 #ifdef HAS_BAD144_HANDLING
   1752 /*
   1753  * Internalize the bad sector table.
   1754  */
   1755 void
   1756 bad144intern(struct wd_softc *wd)
   1757 {
   1758 	struct dkbad *bt = &wd->sc_dk.dk_cpulabel->bad;
   1759 	struct disklabel *lp = wd->sc_dk.dk_label;
   1760 	int i = 0;
   1761 
   1762 	ATADEBUG_PRINT(("bad144intern\n"), DEBUG_XFERS);
   1763 
   1764 	for (; i < NBT_BAD; i++) {
   1765 		if (bt->bt_bad[i].bt_cyl == 0xffff)
   1766 			break;
   1767 		wd->drvp->badsect[i] =
   1768 		    bt->bt_bad[i].bt_cyl * lp->d_secpercyl +
   1769 		    (bt->bt_bad[i].bt_trksec >> 8) * lp->d_nsectors +
   1770 		    (bt->bt_bad[i].bt_trksec & 0xff);
   1771 	}
   1772 	for (; i < NBT_BAD+1; i++)
   1773 		wd->drvp->badsect[i] = -1;
   1774 }
   1775 #endif
   1776 
   1777 static void
   1778 wd_params_to_properties(struct wd_softc *wd)
   1779 {
   1780 	struct disk_geom *dg = &wd->sc_dk.dk_geom;
   1781 
   1782 	memset(dg, 0, sizeof(*dg));
   1783 
   1784 	dg->dg_secperunit = wd->sc_capacity;
   1785 	dg->dg_secsize = wd->sc_blksize;
   1786 	dg->dg_nsectors = wd->sc_params.atap_sectors;
   1787 	dg->dg_ntracks = wd->sc_params.atap_heads;
   1788 	if ((wd->sc_flags & WDF_LBA) == 0)
   1789 		dg->dg_ncylinders = wd->sc_params.atap_cylinders;
   1790 
   1791 	/* XXX Should have a case for ATA here, too. */
   1792 	const char *cp = strcmp(wd->sc_params.atap_model, "ST506") ?
   1793 	    "ST506" : "ESDI";
   1794 
   1795 	disk_set_info(wd->sc_dev, &wd->sc_dk, cp);
   1796 }
   1797 
   1798 int
   1799 wd_get_params(struct wd_softc *wd, uint8_t flags, struct ataparams *params)
   1800 {
   1801 
   1802 	switch (wd->atabus->ata_get_params(wd->drvp, flags, params)) {
   1803 	case CMD_AGAIN:
   1804 		return 1;
   1805 	case CMD_ERR:
   1806 		if (wd->drvp->drive_type != ATA_DRIVET_OLD)
   1807 			return 1;
   1808 		/*
   1809 		 * We `know' there's a drive here; just assume it's old.
   1810 		 * This geometry is only used to read the MBR and print a
   1811 		 * (false) attach message.
   1812 		 */
   1813 		strncpy(params->atap_model, "ST506",
   1814 		    sizeof params->atap_model);
   1815 		params->atap_config = ATA_CFG_FIXED;
   1816 		params->atap_cylinders = 1024;
   1817 		params->atap_heads = 8;
   1818 		params->atap_sectors = 17;
   1819 		params->atap_multi = 1;
   1820 		params->atap_capabilities1 = params->atap_capabilities2 = 0;
   1821 		wd->drvp->ata_vers = -1; /* Mark it as pre-ATA */
   1822 		/* FALLTHROUGH */
   1823 	case CMD_OK:
   1824 		return 0;
   1825 	default:
   1826 		panic("wd_get_params: bad return code from ata_get_params");
   1827 		/* NOTREACHED */
   1828 	}
   1829 }
   1830 
   1831 int
   1832 wd_getcache(struct wd_softc *wd, int *bitsp)
   1833 {
   1834 	struct ataparams params;
   1835 
   1836 	if (wd_get_params(wd, AT_WAIT, &params) != 0)
   1837 		return EIO;
   1838 	if (params.atap_cmd_set1 == 0x0000 ||
   1839 	    params.atap_cmd_set1 == 0xffff ||
   1840 	    (params.atap_cmd_set1 & WDC_CMD1_CACHE) == 0) {
   1841 		*bitsp = 0;
   1842 		return 0;
   1843 	}
   1844 	*bitsp = DKCACHE_WCHANGE | DKCACHE_READ;
   1845 	if (params.atap_cmd1_en & WDC_CMD1_CACHE)
   1846 		*bitsp |= DKCACHE_WRITE;
   1847 
   1848 	if (wd->drvp->drive_flags & (ATA_DRIVE_NCQ|ATA_DRIVE_WFUA))
   1849 		*bitsp |= DKCACHE_FUA;
   1850 
   1851 	return 0;
   1852 }
   1853 
   1854 const char at_errbits[] = "\20\10ERROR\11TIMEOU\12DF";
   1855 
   1856 int
   1857 wd_setcache(struct wd_softc *wd, int bits)
   1858 {
   1859 	struct ataparams params;
   1860 	struct ata_xfer *xfer;
   1861 	int error;
   1862 
   1863 	if (wd_get_params(wd, AT_WAIT, &params) != 0)
   1864 		return EIO;
   1865 
   1866 	if (params.atap_cmd_set1 == 0x0000 ||
   1867 	    params.atap_cmd_set1 == 0xffff ||
   1868 	    (params.atap_cmd_set1 & WDC_CMD1_CACHE) == 0)
   1869 		return EOPNOTSUPP;
   1870 
   1871 	if ((bits & DKCACHE_READ) == 0 ||
   1872 	    (bits & DKCACHE_SAVE) != 0)
   1873 		return EOPNOTSUPP;
   1874 
   1875 	xfer = ata_get_xfer(wd->drvp->chnl_softc);
   1876 	if (xfer == NULL)
   1877 		return EINTR;
   1878 
   1879 	xfer->c_ata_c.r_command = SET_FEATURES;
   1880 	xfer->c_ata_c.r_st_bmask = 0;
   1881 	xfer->c_ata_c.r_st_pmask = 0;
   1882 	xfer->c_ata_c.timeout = 30000; /* 30s timeout */
   1883 	xfer->c_ata_c.flags = AT_WAIT;
   1884 	if (bits & DKCACHE_WRITE)
   1885 		xfer->c_ata_c.r_features = WDSF_WRITE_CACHE_EN;
   1886 	else
   1887 		xfer->c_ata_c.r_features = WDSF_WRITE_CACHE_DS;
   1888 	if (wd->atabus->ata_exec_command(wd->drvp, xfer) != ATACMD_COMPLETE) {
   1889 		aprint_error_dev(wd->sc_dev,
   1890 		    "wd_setcache command not complete\n");
   1891 		error = EIO;
   1892 		goto out;
   1893 	}
   1894 
   1895 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1896 		char sbuf[sizeof(at_errbits) + 64];
   1897 		snprintb(sbuf, sizeof(sbuf), at_errbits, xfer->c_ata_c.flags);
   1898 		aprint_error_dev(wd->sc_dev, "wd_setcache: status=%s\n", sbuf);
   1899 		error = EIO;
   1900 		goto out;
   1901 	}
   1902 
   1903 	error = 0;
   1904 
   1905 out:
   1906 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
   1907 	ata_channel_start(wd->drvp->chnl_softc, wd->drvp->drive);
   1908 	return error;
   1909 }
   1910 
   1911 static int
   1912 wd_standby(struct wd_softc *wd, int flags)
   1913 {
   1914 	struct ata_xfer *xfer;
   1915 	int error;
   1916 
   1917 	xfer = ata_get_xfer(wd->drvp->chnl_softc);
   1918 	if (xfer == NULL)
   1919 		return EINTR;
   1920 
   1921 	xfer->c_ata_c.r_command = WDCC_STANDBY_IMMED;
   1922 	xfer->c_ata_c.r_st_bmask = WDCS_DRDY;
   1923 	xfer->c_ata_c.r_st_pmask = WDCS_DRDY;
   1924 	xfer->c_ata_c.flags = flags;
   1925 	xfer->c_ata_c.timeout = 30000; /* 30s timeout */
   1926 	if (wd->atabus->ata_exec_command(wd->drvp, xfer) != ATACMD_COMPLETE) {
   1927 		aprint_error_dev(wd->sc_dev,
   1928 		    "standby immediate command didn't complete\n");
   1929 		error = EIO;
   1930 		goto out;
   1931 	}
   1932 	if (xfer->c_ata_c.flags & AT_ERROR) {
   1933 		if (xfer->c_ata_c.r_error == WDCE_ABRT) {
   1934 			/* command not supported */
   1935 			error = ENODEV;
   1936 			goto out;
   1937 		}
   1938 	}
   1939 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1940 		char sbuf[sizeof(at_errbits) + 64];
   1941 		snprintb(sbuf, sizeof(sbuf), at_errbits, xfer->c_ata_c.flags);
   1942 		aprint_error_dev(wd->sc_dev, "wd_standby: status=%s\n", sbuf);
   1943 		error = EIO;
   1944 		goto out;
   1945 	}
   1946 	error = 0;
   1947 
   1948 out:
   1949 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
   1950 	/* drive is supposed to go idle, do not call ata_channel_start() */
   1951 	return error;
   1952 }
   1953 
   1954 int
   1955 wd_flushcache(struct wd_softc *wd, int flags, bool start)
   1956 {
   1957 	struct ata_xfer *xfer;
   1958 	int error;
   1959 
   1960 	/*
   1961 	 * WDCC_FLUSHCACHE is here since ATA-4, but some drives report
   1962 	 * only ATA-2 and still support it.
   1963 	 */
   1964 	if (wd->drvp->ata_vers < 4 &&
   1965 	    ((wd->sc_params.atap_cmd_set2 & WDC_CMD2_FC) == 0 ||
   1966 	    wd->sc_params.atap_cmd_set2 == 0xffff))
   1967 		return ENODEV;
   1968 
   1969 	mutex_enter(&wd->sc_lock);
   1970 	SET(wd->sc_flags, WDF_FLUSH_PEND);
   1971 	mutex_exit(&wd->sc_lock);
   1972 
   1973 	xfer = ata_get_xfer(wd->drvp->chnl_softc);
   1974 
   1975 	mutex_enter(&wd->sc_lock);
   1976 	CLR(wd->sc_flags, WDF_FLUSH_PEND);
   1977 	mutex_exit(&wd->sc_lock);
   1978 
   1979 	if (xfer == NULL) {
   1980 		error = EINTR;
   1981 		goto out;
   1982 	}
   1983 
   1984 	if ((wd->sc_params.atap_cmd2_en & ATA_CMD2_LBA48) != 0 &&
   1985 	    (wd->sc_params.atap_cmd2_en & ATA_CMD2_FCE) != 0) {
   1986 		xfer->c_ata_c.r_command = WDCC_FLUSHCACHE_EXT;
   1987 		flags |= AT_LBA48;
   1988 	} else
   1989 		xfer->c_ata_c.r_command = WDCC_FLUSHCACHE;
   1990 	xfer->c_ata_c.r_st_bmask = WDCS_DRDY;
   1991 	xfer->c_ata_c.r_st_pmask = WDCS_DRDY;
   1992 	xfer->c_ata_c.flags = flags | AT_READREG;
   1993 	xfer->c_ata_c.timeout = 300000; /* 5m timeout */
   1994 	if (wd->atabus->ata_exec_command(wd->drvp, xfer) != ATACMD_COMPLETE) {
   1995 		aprint_error_dev(wd->sc_dev,
   1996 		    "flush cache command didn't complete\n");
   1997 		error = EIO;
   1998 		goto out_xfer;
   1999 	}
   2000 	if (xfer->c_ata_c.flags & AT_ERROR) {
   2001 		if (xfer->c_ata_c.r_error == WDCE_ABRT) {
   2002 			/* command not supported */
   2003 			error = ENODEV;
   2004 			goto out_xfer;
   2005 		}
   2006 	}
   2007 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   2008 		char sbuf[sizeof(at_errbits) + 64];
   2009 		snprintb(sbuf, sizeof(sbuf), at_errbits, xfer->c_ata_c.flags);
   2010 		aprint_error_dev(wd->sc_dev, "wd_flushcache: status=%s\n",
   2011 		    sbuf);
   2012 		error = EIO;
   2013 		goto out_xfer;
   2014 	}
   2015 	error = 0;
   2016 
   2017 out_xfer:
   2018 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
   2019 
   2020 out:
   2021 	/* kick queue processing blocked while waiting for flush xfer */
   2022 	if (start)
   2023 		ata_channel_start(wd->drvp->chnl_softc, wd->drvp->drive);
   2024 
   2025 	return error;
   2026 }
   2027 
   2028 int
   2029 wd_trim(struct wd_softc *wd, int part, daddr_t bno, long size)
   2030 {
   2031 	struct ata_xfer *xfer;
   2032 	int error;
   2033 	unsigned char *req;
   2034 
   2035 	if (part != RAW_PART)
   2036 		bno += wd->sc_dk.dk_label->d_partitions[part].p_offset;;
   2037 
   2038 	xfer = ata_get_xfer(wd->drvp->chnl_softc);
   2039 	if (xfer == NULL)
   2040 		return EINTR;
   2041 
   2042 	req = kmem_zalloc(512, KM_SLEEP);
   2043 	req[0] = bno & 0xff;
   2044 	req[1] = (bno >> 8) & 0xff;
   2045 	req[2] = (bno >> 16) & 0xff;
   2046 	req[3] = (bno >> 24) & 0xff;
   2047 	req[4] = (bno >> 32) & 0xff;
   2048 	req[5] = (bno >> 40) & 0xff;
   2049 	req[6] = size & 0xff;
   2050 	req[7] = (size >> 8) & 0xff;
   2051 
   2052 	xfer->c_ata_c.r_command = ATA_DATA_SET_MANAGEMENT;
   2053 	xfer->c_ata_c.r_count = 1;
   2054 	xfer->c_ata_c.r_features = ATA_SUPPORT_DSM_TRIM;
   2055 	xfer->c_ata_c.r_st_bmask = WDCS_DRDY;
   2056 	xfer->c_ata_c.r_st_pmask = WDCS_DRDY;
   2057 	xfer->c_ata_c.timeout = 30000; /* 30s timeout */
   2058 	xfer->c_ata_c.data = req;
   2059 	xfer->c_ata_c.bcount = 512;
   2060 	xfer->c_ata_c.flags |= AT_WRITE | AT_WAIT;
   2061 	if (wd->atabus->ata_exec_command(wd->drvp, xfer) != ATACMD_COMPLETE) {
   2062 		aprint_error_dev(wd->sc_dev,
   2063 		    "trim command didn't complete\n");
   2064 		kmem_free(req, 512);
   2065 		error = EIO;
   2066 		goto out;
   2067 	}
   2068 	kmem_free(req, 512);
   2069 	if (xfer->c_ata_c.flags & AT_ERROR) {
   2070 		if (xfer->c_ata_c.r_error == WDCE_ABRT) {
   2071 			/* command not supported */
   2072 			error = ENODEV;
   2073 			goto out;
   2074 		}
   2075 	}
   2076 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   2077 		char sbuf[sizeof(at_errbits) + 64];
   2078 		snprintb(sbuf, sizeof(sbuf), at_errbits, xfer->c_ata_c.flags);
   2079 		aprint_error_dev(wd->sc_dev, "wd_trim: status=%s\n",
   2080 		    sbuf);
   2081 		error = EIO;
   2082 		goto out;
   2083 	}
   2084 	error = 0;
   2085 
   2086 out:
   2087 	ata_free_xfer(wd->drvp->chnl_softc, xfer);
   2088 	ata_channel_start(wd->drvp->chnl_softc, wd->drvp->drive);
   2089 	return error;
   2090 }
   2091 
   2092 bool
   2093 wd_shutdown(device_t dev, int how)
   2094 {
   2095 	struct wd_softc *wd = device_private(dev);
   2096 
   2097 	/* the adapter needs to be enabled */
   2098 	if (wd->atabus->ata_addref(wd->drvp))
   2099 		return true; /* no need to complain */
   2100 
   2101 	wd_flushcache(wd, AT_POLL, false);
   2102 	if ((how & RB_POWERDOWN) == RB_POWERDOWN)
   2103 		wd_standby(wd, AT_POLL);
   2104 	return true;
   2105 }
   2106 
   2107 /*
   2108  * Allocate space for a ioctl queue structure.  Mostly taken from
   2109  * scsipi_ioctl.c
   2110  */
   2111 struct wd_ioctl *
   2112 wi_get(struct wd_softc *wd)
   2113 {
   2114 	struct wd_ioctl *wi;
   2115 
   2116 	wi = malloc(sizeof(struct wd_ioctl), M_TEMP, M_WAITOK|M_ZERO);
   2117 	wi->wi_softc = wd;
   2118 	buf_init(&wi->wi_bp);
   2119 
   2120 	return (wi);
   2121 }
   2122 
   2123 /*
   2124  * Free an ioctl structure and remove it from our list
   2125  */
   2126 
   2127 void
   2128 wi_free(struct wd_ioctl *wi)
   2129 {
   2130 	buf_destroy(&wi->wi_bp);
   2131 	free(wi, M_TEMP);
   2132 }
   2133 
   2134 /*
   2135  * Find a wd_ioctl structure based on the struct buf.
   2136  */
   2137 
   2138 struct wd_ioctl *
   2139 wi_find(struct buf *bp)
   2140 {
   2141 	return container_of(bp, struct wd_ioctl, wi_bp);
   2142 }
   2143 
   2144 static uint
   2145 wi_sector_size(const struct wd_ioctl * const wi)
   2146 {
   2147 	switch (wi->wi_atareq.command) {
   2148 	case WDCC_READ:
   2149 	case WDCC_WRITE:
   2150 	case WDCC_READMULTI:
   2151 	case WDCC_WRITEMULTI:
   2152 	case WDCC_READDMA:
   2153 	case WDCC_WRITEDMA:
   2154 	case WDCC_READ_EXT:
   2155 	case WDCC_WRITE_EXT:
   2156 	case WDCC_READMULTI_EXT:
   2157 	case WDCC_WRITEMULTI_EXT:
   2158 	case WDCC_READDMA_EXT:
   2159 	case WDCC_WRITEDMA_EXT:
   2160 	case WDCC_READ_FPDMA_QUEUED:
   2161 	case WDCC_WRITE_FPDMA_QUEUED:
   2162 		return wi->wi_softc->sc_blksize;
   2163 	default:
   2164 		return 512;
   2165 	}
   2166 }
   2167 
   2168 /*
   2169  * Ioctl pseudo strategy routine
   2170  *
   2171  * This is mostly stolen from scsipi_ioctl.c:scsistrategy().  What
   2172  * happens here is:
   2173  *
   2174  * - wdioctl() queues a wd_ioctl structure.
   2175  *
   2176  * - wdioctl() calls physio/wdioctlstrategy based on whether or not
   2177  *   user space I/O is required.  If physio() is called, physio() eventually
   2178  *   calls wdioctlstrategy().
   2179  *
   2180  * - In either case, wdioctlstrategy() calls wd->atabus->ata_exec_command()
   2181  *   to perform the actual command
   2182  *
   2183  * The reason for the use of the pseudo strategy routine is because
   2184  * when doing I/O to/from user space, physio _really_ wants to be in
   2185  * the loop.  We could put the entire buffer into the ioctl request
   2186  * structure, but that won't scale if we want to do things like download
   2187  * microcode.
   2188  */
   2189 
   2190 void
   2191 wdioctlstrategy(struct buf *bp)
   2192 {
   2193 	struct wd_ioctl *wi;
   2194 	struct ata_xfer *xfer;
   2195 	int error = 0;
   2196 
   2197 	wi = wi_find(bp);
   2198 	if (wi == NULL) {
   2199 		printf("wdioctlstrategy: "
   2200 		    "No matching ioctl request found in queue\n");
   2201 		error = EINVAL;
   2202 		goto out2;
   2203 	}
   2204 
   2205 	xfer = ata_get_xfer(wi->wi_softc->drvp->chnl_softc);
   2206 	if (xfer == NULL) {
   2207 		error = EINTR;
   2208 		goto out2;
   2209 	}
   2210 
   2211 	/*
   2212 	 * Abort if physio broke up the transfer
   2213 	 */
   2214 
   2215 	if (bp->b_bcount != wi->wi_atareq.datalen) {
   2216 		printf("physio split wd ioctl request... cannot proceed\n");
   2217 		error = EIO;
   2218 		goto out;
   2219 	}
   2220 
   2221 	/*
   2222 	 * Abort if we didn't get a buffer size that was a multiple of
   2223 	 * our sector size (or overflows CHS/LBA28 sector count)
   2224 	 */
   2225 
   2226 	if ((bp->b_bcount % wi_sector_size(wi)) != 0 ||
   2227 	    (bp->b_bcount / wi_sector_size(wi)) >=
   2228 	     (1 << NBBY)) {
   2229 		error = EINVAL;
   2230 		goto out;
   2231 	}
   2232 
   2233 	/*
   2234 	 * Make sure a timeout was supplied in the ioctl request
   2235 	 */
   2236 
   2237 	if (wi->wi_atareq.timeout == 0) {
   2238 		error = EINVAL;
   2239 		goto out;
   2240 	}
   2241 
   2242 	if (wi->wi_atareq.flags & ATACMD_READ)
   2243 		xfer->c_ata_c.flags |= AT_READ;
   2244 	else if (wi->wi_atareq.flags & ATACMD_WRITE)
   2245 		xfer->c_ata_c.flags |= AT_WRITE;
   2246 
   2247 	if (wi->wi_atareq.flags & ATACMD_READREG)
   2248 		xfer->c_ata_c.flags |= AT_READREG;
   2249 
   2250 	if ((wi->wi_atareq.flags & ATACMD_LBA) != 0)
   2251 		xfer->c_ata_c.flags |= AT_LBA;
   2252 
   2253 	xfer->c_ata_c.flags |= AT_WAIT;
   2254 
   2255 	xfer->c_ata_c.timeout = wi->wi_atareq.timeout;
   2256 	xfer->c_ata_c.r_command = wi->wi_atareq.command;
   2257 	xfer->c_ata_c.r_lba = ((wi->wi_atareq.head & 0x0f) << 24) |
   2258 	    (wi->wi_atareq.cylinder << 8) |
   2259 	    wi->wi_atareq.sec_num;
   2260 	xfer->c_ata_c.r_count = wi->wi_atareq.sec_count;
   2261 	xfer->c_ata_c.r_features = wi->wi_atareq.features;
   2262 	xfer->c_ata_c.r_st_bmask = WDCS_DRDY;
   2263 	xfer->c_ata_c.r_st_pmask = WDCS_DRDY;
   2264 	xfer->c_ata_c.data = wi->wi_bp.b_data;
   2265 	xfer->c_ata_c.bcount = wi->wi_bp.b_bcount;
   2266 
   2267 	if (wi->wi_softc->atabus->ata_exec_command(wi->wi_softc->drvp, xfer)
   2268 	    != ATACMD_COMPLETE) {
   2269 		wi->wi_atareq.retsts = ATACMD_ERROR;
   2270 		error = EIO;
   2271 		goto out;
   2272 	}
   2273 
   2274 	if (xfer->c_ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   2275 		if (xfer->c_ata_c.flags & AT_ERROR) {
   2276 			wi->wi_atareq.retsts = ATACMD_ERROR;
   2277 			wi->wi_atareq.error = xfer->c_ata_c.r_error;
   2278 		} else if (xfer->c_ata_c.flags & AT_DF)
   2279 			wi->wi_atareq.retsts = ATACMD_DF;
   2280 		else
   2281 			wi->wi_atareq.retsts = ATACMD_TIMEOUT;
   2282 	} else {
   2283 		wi->wi_atareq.retsts = ATACMD_OK;
   2284 		if (wi->wi_atareq.flags & ATACMD_READREG) {
   2285 			wi->wi_atareq.command = xfer->c_ata_c.r_status;
   2286 			wi->wi_atareq.features = xfer->c_ata_c.r_error;
   2287 			wi->wi_atareq.sec_count = xfer->c_ata_c.r_count;
   2288 			wi->wi_atareq.sec_num = xfer->c_ata_c.r_lba & 0xff;
   2289 			wi->wi_atareq.head = (xfer->c_ata_c.r_device & 0xf0) |
   2290 			    ((xfer->c_ata_c.r_lba >> 24) & 0x0f);
   2291 			wi->wi_atareq.cylinder =
   2292 			    (xfer->c_ata_c.r_lba >> 8) & 0xffff;
   2293 			wi->wi_atareq.error = xfer->c_ata_c.r_error;
   2294 		}
   2295 	}
   2296 
   2297 out:
   2298 	ata_free_xfer(wi->wi_softc->drvp->chnl_softc, xfer);
   2299 	ata_channel_start(wi->wi_softc->drvp->chnl_softc,
   2300 	    wi->wi_softc->drvp->drive);
   2301 out2:
   2302 	bp->b_error = error;
   2303 	if (error)
   2304 		bp->b_resid = bp->b_bcount;
   2305 	biodone(bp);
   2306 }
   2307