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