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