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