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