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