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