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