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