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