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