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