Home | History | Annotate | Line # | Download | only in ata
wd.c revision 1.355.6.2
      1 /*	$NetBSD: wd.c,v 1.355.6.2 2008/04/03 12:42:38 mjf 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.355.6.2 2008/04/03 12:42:38 mjf 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/reboot.h>
     92 #include <sys/vnode.h>
     93 #if NRND > 0
     94 #include <sys/rnd.h>
     95 #endif
     96 
     97 #include <sys/intr.h>
     98 #include <sys/bus.h>
     99 
    100 #include <dev/ata/atareg.h>
    101 #include <dev/ata/atavar.h>
    102 #include <dev/ata/wdvar.h>
    103 #include <dev/ic/wdcreg.h>
    104 #include <sys/ataio.h>
    105 #include "locators.h"
    106 
    107 #include <prop/proplib.h>
    108 
    109 #define	LBA48_THRESHOLD		(0xfffffff)	/* 128GB / DEV_BSIZE */
    110 
    111 #define	WDIORETRIES_SINGLE 4	/* number of retries before single-sector */
    112 #define	WDIORETRIES	5	/* number of retries before giving up */
    113 #define	RECOVERYTIME hz/2	/* time to wait before retrying a cmd */
    114 
    115 #define	WDUNIT(dev)		DISKUNIT(dev)
    116 #define	WDPART(dev)		DISKPART(dev)
    117 #define	WDMINOR(unit, part)	DISKMINOR(unit, part)
    118 #define	MAKEWDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
    119 
    120 #define	WDLABELDEV(dev)	(MAKEWDDEV(major(dev), WDUNIT(dev), RAW_PART))
    121 
    122 #define DEBUG_INTR   0x01
    123 #define DEBUG_XFERS  0x02
    124 #define DEBUG_STATUS 0x04
    125 #define DEBUG_FUNCS  0x08
    126 #define DEBUG_PROBE  0x10
    127 #ifdef ATADEBUG
    128 int wdcdebug_wd_mask = 0x0;
    129 #define ATADEBUG_PRINT(args, level) \
    130 	if (wdcdebug_wd_mask & (level)) \
    131 		printf args
    132 #else
    133 #define ATADEBUG_PRINT(args, level)
    134 #endif
    135 
    136 int	wdprobe(struct device *, struct cfdata *, void *);
    137 void	wdattach(struct device *, struct device *, void *);
    138 int	wddetach(struct device *, int);
    139 int	wdactivate(struct device *, enum devact);
    140 int	wdprint(void *, char *);
    141 void	wdperror(const struct wd_softc *);
    142 
    143 static bool	wd_suspend(device_t PMF_FN_PROTO);
    144 static int	wd_standby(struct wd_softc *, int);
    145 
    146 CFATTACH_DECL_NEW(wd, sizeof(struct wd_softc),
    147     wdprobe, wdattach, wddetach, wdactivate);
    148 
    149 extern struct cfdriver wd_cd;
    150 
    151 dev_type_open(wdopen);
    152 dev_type_close(wdclose);
    153 dev_type_read(wdread);
    154 dev_type_write(wdwrite);
    155 dev_type_ioctl(wdioctl);
    156 dev_type_strategy(wdstrategy);
    157 dev_type_dump(wddump);
    158 dev_type_size(wdsize);
    159 
    160 const struct bdevsw wd_bdevsw = {
    161 	wdopen, wdclose, wdstrategy, wdioctl, wddump, wdsize, D_DISK
    162 };
    163 
    164 const struct cdevsw wd_cdevsw = {
    165 	wdopen, wdclose, wdread, wdwrite, wdioctl,
    166 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
    167 };
    168 
    169 /*
    170  * Glue necessary to hook WDCIOCCOMMAND into physio
    171  */
    172 
    173 struct wd_ioctl {
    174 	LIST_ENTRY(wd_ioctl) wi_list;
    175 	struct buf wi_bp;
    176 	struct uio wi_uio;
    177 	struct iovec wi_iov;
    178 	atareq_t wi_atareq;
    179 	struct wd_softc *wi_softc;
    180 };
    181 
    182 LIST_HEAD(, wd_ioctl) wi_head;
    183 
    184 struct	wd_ioctl *wi_find(struct buf *);
    185 void	wi_free(struct wd_ioctl *);
    186 struct	wd_ioctl *wi_get(void);
    187 void	wdioctlstrategy(struct buf *);
    188 
    189 void  wdgetdefaultlabel(struct wd_softc *, struct disklabel *);
    190 void  wdgetdisklabel(struct wd_softc *);
    191 void  wdstart(void *);
    192 void  __wdstart(struct wd_softc*, struct buf *);
    193 void  wdrestart(void *);
    194 void  wddone(void *);
    195 int   wd_get_params(struct wd_softc *, u_int8_t, struct ataparams *);
    196 int   wd_flushcache(struct wd_softc *, int);
    197 bool  wd_shutdown(device_t, int);
    198 
    199 int   wd_getcache(struct wd_softc *, int *);
    200 int   wd_setcache(struct wd_softc *, int);
    201 
    202 struct dkdriver wddkdriver = { wdstrategy, minphys };
    203 
    204 #ifdef HAS_BAD144_HANDLING
    205 static void bad144intern(struct wd_softc *);
    206 #endif
    207 
    208 #define	WD_QUIRK_SPLIT_MOD15_WRITE	0x0001	/* must split certain writes */
    209 #define	WD_QUIRK_FORCE_LBA48		0x0002	/* must use LBA48 commands */
    210 
    211 #define	WD_QUIRK_FMT "\20\1SPLIT_MOD15_WRITE\2FORCE_LBA48"
    212 
    213 /*
    214  * Quirk table for IDE drives.  Put more-specific matches first, since
    215  * a simple globbing routine is used for matching.
    216  */
    217 static const struct wd_quirk {
    218 	const char *wdq_match;		/* inquiry pattern to match */
    219 	int wdq_quirks;			/* drive quirks */
    220 } wd_quirk_table[] = {
    221 	/*
    222 	 * Some Seagate S-ATA drives have a PHY which can get confused
    223 	 * with the way data is packetized by some S-ATA controllers.
    224 	 *
    225 	 * The work-around is to split in two any write transfer whose
    226 	 * sector count % 15 == 1 (assuming 512 byte sectors).
    227 	 *
    228 	 * XXX This is an incomplete list.  There are at least a couple
    229 	 * XXX more model numbers.  If you have trouble with such transfers
    230 	 * XXX (8K is the most common) on Seagate S-ATA drives, please
    231 	 * XXX notify thorpej (at) NetBSD.org.
    232 	 */
    233 	{ "ST3120023AS",
    234 	  WD_QUIRK_SPLIT_MOD15_WRITE },
    235 	{ "ST380023AS",
    236 	  WD_QUIRK_SPLIT_MOD15_WRITE },
    237 
    238 	/*
    239 	 * These seagate drives seems to have issue addressing sector 0xfffffff
    240 	 * (aka LBA48_THRESHOLD) in LBA mode. The workaround is to force
    241 	 * LBA48
    242 	 * Note that we can't just change the code to always use LBA48 for
    243 	 * sector 0xfffffff, because this would break valid and working
    244 	 * setups using LBA48 drives on non-LBA48-capable controllers
    245 	 * (and it's hard to get a list of such controllers)
    246 	 */
    247 	{ "ST3160021A*",
    248 	  WD_QUIRK_FORCE_LBA48 },
    249 	{ "ST3160811A*",
    250 	  WD_QUIRK_FORCE_LBA48 },
    251 	{ "ST3160812A*",
    252 	  WD_QUIRK_FORCE_LBA48 },
    253 	{ "ST3160023A*",
    254 	  WD_QUIRK_FORCE_LBA48 },
    255 	{ "ST3160827A*",
    256 	  WD_QUIRK_FORCE_LBA48 },
    257 	/* Attempt to catch all seagate drives larger than 200GB */
    258 	{ "ST3[2-9][0-9][0-9][0-9][0-9][0-9][A-Z]*",
    259 	  WD_QUIRK_FORCE_LBA48 },
    260 	{ "ST3[1-9][0-9][0-9][0-9][0-9][0-9][0-9][A-Z]*",
    261 	  WD_QUIRK_FORCE_LBA48 },
    262 	{ NULL,
    263 	  0 }
    264 };
    265 
    266 static const struct wd_quirk *
    267 wd_lookup_quirks(const char *name)
    268 {
    269 	const struct wd_quirk *wdq;
    270 	const char *estr;
    271 
    272 	for (wdq = wd_quirk_table; wdq->wdq_match != NULL; wdq++) {
    273 		/*
    274 		 * We only want exact matches (which include matches
    275 		 * against globbing characters).
    276 		 */
    277 		if (pmatch(name, wdq->wdq_match, &estr) == 2)
    278 			return (wdq);
    279 	}
    280 	return (NULL);
    281 }
    282 
    283 int
    284 wdprobe(struct device *parent, struct cfdata *match, void *aux)
    285 {
    286 	struct ata_device *adev = aux;
    287 
    288 	if (adev == NULL)
    289 		return 0;
    290 	if (adev->adev_bustype->bustype_type != SCSIPI_BUSTYPE_ATA)
    291 		return 0;
    292 
    293 	if (match->cf_loc[ATA_HLCF_DRIVE] != ATA_HLCF_DRIVE_DEFAULT &&
    294 	    match->cf_loc[ATA_HLCF_DRIVE] != adev->adev_drv_data->drive)
    295 		return 0;
    296 	return 1;
    297 }
    298 
    299 void
    300 wdattach(struct device *parent, struct device *self, void *aux)
    301 {
    302 	struct wd_softc *wd = device_private(self);
    303 	struct ata_device *adev= aux;
    304 	int i, blank;
    305 	char tbuf[41], pbuf[9], c, *p, *q;
    306 	const struct wd_quirk *wdq;
    307 	uint16_t np;
    308 	int bmajor, cmajor;
    309 
    310 	wd->sc_dev = self;
    311 
    312 	ATADEBUG_PRINT(("wdattach\n"), DEBUG_FUNCS | DEBUG_PROBE);
    313 	callout_init(&wd->sc_restart_ch, 0);
    314 	bufq_alloc(&wd->sc_q, BUFQ_DISK_DEFAULT_STRAT, BUFQ_SORT_RAWBLOCK);
    315 #ifdef WD_SOFTBADSECT
    316 	SLIST_INIT(&wd->sc_bslist);
    317 #endif
    318 	wd->atabus = adev->adev_bustype;
    319 	wd->openings = adev->adev_openings;
    320 	wd->drvp = adev->adev_drv_data;
    321 
    322 	wd->drvp->drv_done = wddone;
    323 	wd->drvp->drv_softc = wd->sc_dev;
    324 
    325 	aprint_naive("\n");
    326 
    327 	/* read our drive info */
    328 	if (wd_get_params(wd, AT_WAIT, &wd->sc_params) != 0) {
    329 		aprint_error("\n%s: IDENTIFY failed\n", device_xname(self));
    330 		return;
    331 	}
    332 
    333 	for (blank = 0, p = wd->sc_params.atap_model, q = tbuf, i = 0;
    334 	    i < sizeof(wd->sc_params.atap_model); i++) {
    335 		c = *p++;
    336 		if (c == '\0')
    337 			break;
    338 		if (c != ' ') {
    339 			if (blank) {
    340 				*q++ = ' ';
    341 				blank = 0;
    342 			}
    343 			*q++ = c;
    344 		} else
    345 			blank = 1;
    346 	}
    347 	*q++ = '\0';
    348 
    349 	aprint_normal(": <%s>\n", tbuf);
    350 
    351 	wdq = wd_lookup_quirks(tbuf);
    352 	if (wdq != NULL)
    353 		wd->sc_quirks = wdq->wdq_quirks;
    354 
    355 	if (wd->sc_quirks != 0) {
    356 		char sbuf[sizeof(WD_QUIRK_FMT) + 64];
    357 		bitmask_snprintf(wd->sc_quirks, WD_QUIRK_FMT,
    358 		    sbuf, sizeof(sbuf));
    359 		aprint_normal_dev(self, "quirks %s\n", sbuf);
    360 	}
    361 
    362 	if ((wd->sc_params.atap_multi & 0xff) > 1) {
    363 		wd->sc_multi = wd->sc_params.atap_multi & 0xff;
    364 	} else {
    365 		wd->sc_multi = 1;
    366 	}
    367 
    368 	aprint_verbose_dev(self, "drive supports %d-sector PIO transfers,",
    369 	    wd->sc_multi);
    370 
    371 	/* 48-bit LBA addressing */
    372 	if ((wd->sc_params.atap_cmd2_en & ATA_CMD2_LBA48) != 0)
    373 		wd->sc_flags |= WDF_LBA48;
    374 
    375 	/* Prior to ATA-4, LBA was optional. */
    376 	if ((wd->sc_params.atap_capabilities1 & WDC_CAP_LBA) != 0)
    377 		wd->sc_flags |= WDF_LBA;
    378 #if 0
    379 	/* ATA-4 requires LBA. */
    380 	if (wd->sc_params.atap_ataversion != 0xffff &&
    381 	    wd->sc_params.atap_ataversion >= WDC_VER_ATA4)
    382 		wd->sc_flags |= WDF_LBA;
    383 #endif
    384 
    385 	if ((wd->sc_flags & WDF_LBA48) != 0) {
    386 		aprint_verbose(" LBA48 addressing\n");
    387 		wd->sc_capacity =
    388 		    ((u_int64_t) wd->sc_params.__reserved6[11] << 48) |
    389 		    ((u_int64_t) wd->sc_params.__reserved6[10] << 32) |
    390 		    ((u_int64_t) wd->sc_params.__reserved6[9]  << 16) |
    391 		    ((u_int64_t) wd->sc_params.__reserved6[8]  << 0);
    392 	} else if ((wd->sc_flags & WDF_LBA) != 0) {
    393 		aprint_verbose(" LBA addressing\n");
    394 		wd->sc_capacity =
    395 		    ((u_int64_t)wd->sc_params.atap_capacity[1] << 16) |
    396 		    wd->sc_params.atap_capacity[0];
    397 	} else {
    398 		aprint_verbose(" chs addressing\n");
    399 		wd->sc_capacity =
    400 		    wd->sc_params.atap_cylinders *
    401 		    wd->sc_params.atap_heads *
    402 		    wd->sc_params.atap_sectors;
    403 	}
    404 	format_bytes(pbuf, sizeof(pbuf), wd->sc_capacity * DEV_BSIZE);
    405 	aprint_normal_dev(self, "%s, %d cyl, %d head, %d sec, "
    406 	    "%d bytes/sect x %llu sectors\n",
    407 	    pbuf,
    408 	    (wd->sc_flags & WDF_LBA) ? (int)(wd->sc_capacity /
    409 		(wd->sc_params.atap_heads * wd->sc_params.atap_sectors)) :
    410 		wd->sc_params.atap_cylinders,
    411 	    wd->sc_params.atap_heads, wd->sc_params.atap_sectors,
    412 	    DEV_BSIZE, (unsigned long long)wd->sc_capacity);
    413 
    414 	ATADEBUG_PRINT(("%s: atap_dmatiming_mimi=%d, atap_dmatiming_recom=%d\n",
    415 	    device_xname(self), wd->sc_params.atap_dmatiming_mimi,
    416 	    wd->sc_params.atap_dmatiming_recom), DEBUG_PROBE);
    417 	/*
    418 	 * Initialize and attach the disk structure.
    419 	 */
    420 	/* we fill in dk_info later */
    421 	disk_init(&wd->sc_dk, device_xname(wd->sc_dev), &wddkdriver);
    422 	disk_attach(&wd->sc_dk);
    423 	wd->sc_wdc_bio.lp = wd->sc_dk.dk_label;
    424 #if NRND > 0
    425 	rnd_attach_source(&wd->rnd_source, device_xname(wd->sc_dev),
    426 			  RND_TYPE_DISK, 0);
    427 #endif
    428 
    429 	/* Discover wedges on this disk. */
    430 	dkwedge_discover(&wd->sc_dk);
    431 
    432 	if (!pmf_device_register1(self, wd_suspend, NULL, wd_shutdown))
    433 		aprint_error_dev(self, "couldn't establish power handler\n");
    434 
    435 	bmajor = bdevsw_lookup_major(&wd_bdevsw);
    436 	cmajor = cdevsw_lookup_major(&wd_cdevsw);
    437 
    438 	np = wd->sc_dk.dk_label->d_npartitions;
    439 
    440 	for (i = 0; i < np; i++) {
    441 		device_register_name(
    442 	    	    MAKEDISKDEV(bmajor, device_unit(&wd->sc_dev), i),
    443 	    	    self, false, DEV_DISK,
    444 		    "wd%d%c", device_unit(&wd->sc_dev), 'a' + i);
    445 
    446 		device_register_name(
    447 	    	    MAKEDISKDEV(cmajor, device_unit(&wd->sc_dev), i),
    448 	    	    self, true, DEV_DISK,
    449 		    "rwd%d%c", device_unit(&wd->sc_dev), 'a' + i);
    450 	}
    451 }
    452 
    453 static bool
    454 wd_suspend(device_t dv PMF_FN_ARGS)
    455 {
    456 	struct wd_softc *sc = device_private(dv);
    457 
    458 	wd_flushcache(sc, AT_WAIT);
    459 	wd_standby(sc, AT_WAIT);
    460 	return true;
    461 }
    462 
    463 int
    464 wdactivate(struct device *self, enum devact act)
    465 {
    466 	int rv = 0;
    467 
    468 	switch (act) {
    469 	case DVACT_ACTIVATE:
    470 		rv = EOPNOTSUPP;
    471 		break;
    472 
    473 	case DVACT_DEACTIVATE:
    474 		/*
    475 		 * Nothing to do; we key off the device's DVF_ACTIVATE.
    476 		 */
    477 		break;
    478 	}
    479 	return (rv);
    480 }
    481 
    482 int
    483 wddetach(struct device *self, int flags)
    484 {
    485 	struct wd_softc *sc = device_private(self);
    486 	int s, bmaj, cmaj, i, mn, unit;
    487 
    488 	/* locate the major number */
    489 	bmaj = bdevsw_lookup_major(&wd_bdevsw);
    490 	cmaj = cdevsw_lookup_major(&wd_cdevsw);
    491 
    492 	/* Nuke the vnodes for any open instances. */
    493 	for (i = 0; i < MAXPARTITIONS; i++) {
    494 		unit = device_unit(self);
    495 		mn = WDMINOR(unit, i);
    496 		vdevgone(bmaj, mn, mn, VBLK);
    497 		vdevgone(cmaj, mn, mn, VCHR);
    498 
    499 		device_unregister_name(makedev(bmaj, mn),
    500 		    "wd%d%c", unit, 'a' + i);
    501 		device_unregister_name(makedev(cmaj, mn),
    502 		    "rwd%d%c", unit, 'a' + i);
    503 	}
    504 
    505 	/* Delete all of our wedges. */
    506 	dkwedge_delall(&sc->sc_dk);
    507 
    508 	s = splbio();
    509 
    510 	/* Kill off any queued buffers. */
    511 	bufq_drain(sc->sc_q);
    512 
    513 	bufq_free(sc->sc_q);
    514 	sc->atabus->ata_killpending(sc->drvp);
    515 
    516 	splx(s);
    517 
    518 	/* Detach disk. */
    519 	disk_detach(&sc->sc_dk);
    520 
    521 #ifdef WD_SOFTBADSECT
    522 	/* Clean out the bad sector list */
    523 	while (!SLIST_EMPTY(&sc->sc_bslist)) {
    524 		void *head = SLIST_FIRST(&sc->sc_bslist);
    525 		SLIST_REMOVE_HEAD(&sc->sc_bslist, dbs_next);
    526 		free(head, M_TEMP);
    527 	}
    528 	sc->sc_bscount = 0;
    529 #endif
    530 
    531 	pmf_device_deregister(self);
    532 
    533 #if NRND > 0
    534 	/* Unhook the entropy source. */
    535 	rnd_detach_source(&sc->rnd_source);
    536 #endif
    537 
    538 	sc->drvp->drive_flags = 0; /* no drive any more here */
    539 
    540 	return (0);
    541 }
    542 
    543 /*
    544  * Read/write routine for a buffer.  Validates the arguments and schedules the
    545  * transfer.  Does not wait for the transfer to complete.
    546  */
    547 void
    548 wdstrategy(struct buf *bp)
    549 {
    550 	struct wd_softc *wd =
    551 	    device_private(device_lookup(&wd_cd, WDUNIT(bp->b_dev)));
    552 	struct disklabel *lp = wd->sc_dk.dk_label;
    553 	daddr_t blkno;
    554 	int s;
    555 
    556 	ATADEBUG_PRINT(("wdstrategy (%s)\n", device_xname(wd->sc_dev)),
    557 	    DEBUG_XFERS);
    558 
    559 	/* Valid request?  */
    560 	if (bp->b_blkno < 0 ||
    561 	    (bp->b_bcount % lp->d_secsize) != 0 ||
    562 	    (bp->b_bcount / lp->d_secsize) >= (1 << NBBY)) {
    563 		bp->b_error = EINVAL;
    564 		goto done;
    565 	}
    566 
    567 	/* If device invalidated (e.g. media change, door open), error. */
    568 	if ((wd->sc_flags & WDF_LOADED) == 0) {
    569 		bp->b_error = EIO;
    570 		goto done;
    571 	}
    572 
    573 	/* If it's a null transfer, return immediately. */
    574 	if (bp->b_bcount == 0)
    575 		goto done;
    576 
    577 	/*
    578 	 * Do bounds checking, adjust transfer. if error, process.
    579 	 * If end of partition, just return.
    580 	 */
    581 	if (WDPART(bp->b_dev) == RAW_PART) {
    582 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
    583 		    wd->sc_capacity) <= 0)
    584 			goto done;
    585 	} else {
    586 		if (bounds_check_with_label(&wd->sc_dk, bp,
    587 		    (wd->sc_flags & (WDF_WLABEL|WDF_LABELLING)) != 0) <= 0)
    588 			goto done;
    589 	}
    590 
    591 	/*
    592 	 * Now convert the block number to absolute and put it in
    593 	 * terms of the device's logical block size.
    594 	 */
    595 	if (lp->d_secsize >= DEV_BSIZE)
    596 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
    597 	else
    598 		blkno = bp->b_blkno * (DEV_BSIZE / lp->d_secsize);
    599 
    600 	if (WDPART(bp->b_dev) != RAW_PART)
    601 		blkno += lp->d_partitions[WDPART(bp->b_dev)].p_offset;
    602 
    603 	bp->b_rawblkno = blkno;
    604 
    605 #ifdef WD_SOFTBADSECT
    606 	/*
    607 	 * If the transfer about to be attempted contains only a block that
    608 	 * is known to be bad then return an error for the transfer without
    609 	 * even attempting to start a transfer up under the premis that we
    610 	 * will just end up doing more retries for a transfer that will end
    611 	 * up failing again.
    612 	 * XXX:SMP - mutex required to protect with DIOCBSFLUSH
    613 	 */
    614 	if (__predict_false(!SLIST_EMPTY(&wd->sc_bslist))) {
    615 		struct disk_badsectors *dbs;
    616 		daddr_t maxblk = blkno + (bp->b_bcount >> DEV_BSHIFT) - 1;
    617 
    618 		SLIST_FOREACH(dbs, &wd->sc_bslist, dbs_next)
    619 			if ((dbs->dbs_min <= blkno && blkno <= dbs->dbs_max) ||
    620 			    (dbs->dbs_min <= maxblk && maxblk <= dbs->dbs_max)){
    621 				bp->b_error = EIO;
    622 				goto done;
    623 			}
    624 	}
    625 #endif
    626 
    627 	/* Queue transfer on drive, activate drive and controller if idle. */
    628 	s = splbio();
    629 	BUFQ_PUT(wd->sc_q, bp);
    630 	wdstart(wd);
    631 	splx(s);
    632 	return;
    633 done:
    634 	/* Toss transfer; we're done early. */
    635 	bp->b_resid = bp->b_bcount;
    636 	biodone(bp);
    637 }
    638 
    639 /*
    640  * Queue a drive for I/O.
    641  */
    642 void
    643 wdstart(void *arg)
    644 {
    645 	struct wd_softc *wd = arg;
    646 	struct buf *bp = NULL;
    647 
    648 	ATADEBUG_PRINT(("wdstart %s\n", device_xname(wd->sc_dev)),
    649 	    DEBUG_XFERS);
    650 	while (wd->openings > 0) {
    651 
    652 		/* Is there a buf for us ? */
    653 		if ((bp = BUFQ_GET(wd->sc_q)) == NULL)
    654 			return;
    655 
    656 		/*
    657 		 * Make the command. First lock the device
    658 		 */
    659 		wd->openings--;
    660 
    661 		wd->retries = 0;
    662 		__wdstart(wd, bp);
    663 	}
    664 }
    665 
    666 static void
    667 wd_split_mod15_write(struct buf *bp)
    668 {
    669 	struct buf *obp = bp->b_private;
    670 	struct wd_softc *sc =
    671 	    device_private(wd_cd.cd_devs[DISKUNIT(obp->b_dev)]);
    672 
    673 	if (__predict_false(bp->b_error != 0)) {
    674 		/*
    675 		 * Propagate the error.  If this was the first half of
    676 		 * the original transfer, make sure to account for that
    677 		 * in the residual.
    678 		 */
    679 		if (bp->b_data == obp->b_data)
    680 			bp->b_resid += bp->b_bcount;
    681 		goto done;
    682 	}
    683 
    684 	/*
    685 	 * If this was the second half of the transfer, we're all done!
    686 	 */
    687 	if (bp->b_data != obp->b_data)
    688 		goto done;
    689 
    690 	/*
    691 	 * Advance the pointer to the second half and issue that command
    692 	 * using the same opening.
    693 	 */
    694 	bp->b_flags = obp->b_flags;
    695 	bp->b_oflags = obp->b_oflags;
    696 	bp->b_cflags = obp->b_cflags;
    697 	bp->b_data = (char *)bp->b_data + bp->b_bcount;
    698 	bp->b_blkno += (bp->b_bcount / 512);
    699 	bp->b_rawblkno += (bp->b_bcount / 512);
    700 	__wdstart(sc, bp);
    701 	return;
    702 
    703  done:
    704 	obp->b_error = bp->b_error;
    705 	obp->b_resid = bp->b_resid;
    706 	putiobuf(bp);
    707 	biodone(obp);
    708 	sc->openings++;
    709 	/* wddone() will call wdstart() */
    710 }
    711 
    712 void
    713 __wdstart(struct wd_softc *wd, struct buf *bp)
    714 {
    715 
    716 	/*
    717 	 * Deal with the "split mod15 write" quirk.  We just divide the
    718 	 * transfer in two, doing the first half and then then second half
    719 	 * with the same command opening.
    720 	 *
    721 	 * Note we MUST do this here, because we can't let insertion
    722 	 * into the bufq cause the transfers to be re-merged.
    723 	 */
    724 	if (__predict_false((wd->sc_quirks & WD_QUIRK_SPLIT_MOD15_WRITE) != 0 &&
    725 			    (bp->b_flags & B_READ) == 0 &&
    726 			    bp->b_bcount > 512 &&
    727 			    ((bp->b_bcount / 512) % 15) == 1)) {
    728 		struct buf *nbp;
    729 
    730 		/* already at splbio */
    731 		nbp = getiobuf(NULL, false);
    732 		if (__predict_false(nbp == NULL)) {
    733 			/* No memory -- fail the iop. */
    734 			bp->b_error = ENOMEM;
    735 			bp->b_resid = bp->b_bcount;
    736 			biodone(bp);
    737 			wd->openings++;
    738 			return;
    739 		}
    740 
    741 		nbp->b_error = 0;
    742 		nbp->b_proc = bp->b_proc;
    743 		nbp->b_dev = bp->b_dev;
    744 
    745 		nbp->b_bcount = bp->b_bcount / 2;
    746 		nbp->b_bufsize = bp->b_bcount / 2;
    747 		nbp->b_data = bp->b_data;
    748 
    749 		nbp->b_blkno = bp->b_blkno;
    750 		nbp->b_rawblkno = bp->b_rawblkno;
    751 
    752 		nbp->b_flags = bp->b_flags;
    753 		nbp->b_oflags = bp->b_oflags;
    754 		nbp->b_cflags = bp->b_cflags;
    755 		nbp->b_iodone = wd_split_mod15_write;
    756 
    757 		/* Put ptr to orig buf in b_private and use new buf */
    758 		nbp->b_private = bp;
    759 
    760 		BIO_COPYPRIO(nbp, bp);
    761 
    762 		bp = nbp;
    763 	}
    764 
    765 	wd->sc_wdc_bio.blkno = bp->b_rawblkno;
    766 	wd->sc_wdc_bio.blkdone =0;
    767 	wd->sc_bp = bp;
    768 	/*
    769 	 * If we're retrying, retry in single-sector mode. This will give us
    770 	 * the sector number of the problem, and will eventually allow the
    771 	 * transfer to succeed.
    772 	 */
    773 	if (wd->retries >= WDIORETRIES_SINGLE)
    774 		wd->sc_wdc_bio.flags = ATA_SINGLE;
    775 	else
    776 		wd->sc_wdc_bio.flags = 0;
    777 	if (wd->sc_flags & WDF_LBA48 &&
    778 	    (wd->sc_wdc_bio.blkno > LBA48_THRESHOLD ||
    779 	    (wd->sc_quirks & WD_QUIRK_FORCE_LBA48) != 0))
    780 		wd->sc_wdc_bio.flags |= ATA_LBA48;
    781 	if (wd->sc_flags & WDF_LBA)
    782 		wd->sc_wdc_bio.flags |= ATA_LBA;
    783 	if (bp->b_flags & B_READ)
    784 		wd->sc_wdc_bio.flags |= ATA_READ;
    785 	wd->sc_wdc_bio.bcount = bp->b_bcount;
    786 	wd->sc_wdc_bio.databuf = bp->b_data;
    787 	/* Instrumentation. */
    788 	disk_busy(&wd->sc_dk);
    789 	switch (wd->atabus->ata_bio(wd->drvp, &wd->sc_wdc_bio)) {
    790 	case ATACMD_TRY_AGAIN:
    791 		callout_reset(&wd->sc_restart_ch, hz, wdrestart, wd);
    792 		break;
    793 	case ATACMD_QUEUED:
    794 	case ATACMD_COMPLETE:
    795 		break;
    796 	default:
    797 		panic("__wdstart: bad return code from ata_bio()");
    798 	}
    799 }
    800 
    801 void
    802 wddone(void *v)
    803 {
    804 	struct wd_softc *wd = device_private(v);
    805 	struct buf *bp = wd->sc_bp;
    806 	const char *errmsg;
    807 	int do_perror = 0;
    808 	int nblks;
    809 
    810 	ATADEBUG_PRINT(("wddone %s\n", device_xname(wd->sc_dev)),
    811 	    DEBUG_XFERS);
    812 	if (bp == NULL)
    813 		return;
    814 	bp->b_resid = wd->sc_wdc_bio.bcount;
    815 	switch (wd->sc_wdc_bio.error) {
    816 	case ERR_DMA:
    817 		errmsg = "DMA error";
    818 		goto retry;
    819 	case ERR_DF:
    820 		errmsg = "device fault";
    821 		goto retry;
    822 	case TIMEOUT:
    823 		errmsg = "device timeout";
    824 		goto retry;
    825 	case ERR_RESET:
    826 		errmsg = "channel reset";
    827 		goto retry2;
    828 	case ERROR:
    829 		/* Don't care about media change bits */
    830 		if (wd->sc_wdc_bio.r_error != 0 &&
    831 		    (wd->sc_wdc_bio.r_error & ~(WDCE_MC | WDCE_MCR)) == 0)
    832 			goto noerror;
    833 		errmsg = "error";
    834 		do_perror = 1;
    835 		if ((wd->sc_wdc_bio.r_error & (WDCE_IDNF | WDCE_ABRT)) &&
    836 		    (wd->sc_quirks & WD_QUIRK_FORCE_LBA48) == 0) {
    837 			nblks = wd->sc_wdc_bio.bcount /
    838 			    wd->sc_dk.dk_label->d_secsize;
    839 			/*
    840 			 * If we get a "id not found" when crossing the
    841 			 * LBA48_THRESHOLD, and the drive is larger than
    842 			 * 128GB, then we can assume the drive has the
    843 			 * LBA48 bug and we switch to LBA48.
    844 			 */
    845 			if (wd->sc_wdc_bio.blkno <= LBA48_THRESHOLD &&
    846 			    wd->sc_wdc_bio.blkno + nblks > LBA48_THRESHOLD &&
    847 			    wd->sc_capacity > LBA48_THRESHOLD + 1) {
    848 				errmsg = "LBA48 bug";
    849 				wd->sc_quirks |= WD_QUIRK_FORCE_LBA48;
    850 				do_perror = 0;
    851 				goto retry2;
    852 			}
    853 		}
    854 retry:		/* Just reset and retry. Can we do more ? */
    855 		(*wd->atabus->ata_reset_drive)(wd->drvp, AT_RST_NOCMD);
    856 retry2:
    857 		diskerr(bp, "wd", errmsg, LOG_PRINTF,
    858 		    wd->sc_wdc_bio.blkdone, wd->sc_dk.dk_label);
    859 		if (wd->retries < WDIORETRIES)
    860 			printf(", retrying");
    861 		printf("\n");
    862 		if (do_perror)
    863 			wdperror(wd);
    864 		if (wd->retries < WDIORETRIES) {
    865 			wd->retries++;
    866 			callout_reset(&wd->sc_restart_ch, RECOVERYTIME,
    867 			    wdrestart, wd);
    868 			return;
    869 		}
    870 
    871 #ifdef WD_SOFTBADSECT
    872 		/*
    873 		 * Not all errors indicate a failed block but those that do,
    874 		 * put the block on the bad-block list for the device.  Only
    875 		 * do this for reads because the drive should do it for writes,
    876 		 * itself, according to Manuel.
    877 		 */
    878 		if ((bp->b_flags & B_READ) &&
    879 		    ((wd->drvp->ata_vers >= 4 && wd->sc_wdc_bio.r_error & 64) ||
    880 	     	     (wd->drvp->ata_vers < 4 && wd->sc_wdc_bio.r_error & 192))) {
    881 			struct disk_badsectors *dbs;
    882 
    883 			dbs = malloc(sizeof *dbs, M_TEMP, M_WAITOK);
    884 			dbs->dbs_min = bp->b_rawblkno;
    885 			dbs->dbs_max = dbs->dbs_min + (bp->b_bcount >> DEV_BSHIFT) - 1;
    886 			microtime(&dbs->dbs_failedat);
    887 			SLIST_INSERT_HEAD(&wd->sc_bslist, dbs, dbs_next);
    888 			wd->sc_bscount++;
    889 		}
    890 #endif
    891 		bp->b_error = EIO;
    892 		break;
    893 	case NOERROR:
    894 noerror:	if ((wd->sc_wdc_bio.flags & ATA_CORR) || wd->retries > 0)
    895 			aprint_error_dev(wd->sc_dev,
    896 			    "soft error (corrected)\n");
    897 		break;
    898 	case ERR_NODEV:
    899 		bp->b_error = EIO;
    900 		break;
    901 	}
    902 	disk_unbusy(&wd->sc_dk, (bp->b_bcount - bp->b_resid),
    903 	    (bp->b_flags & B_READ));
    904 #if NRND > 0
    905 	rnd_add_uint32(&wd->rnd_source, bp->b_blkno);
    906 #endif
    907 	/* XXX Yuck, but we don't want to increment openings in this case */
    908 	if (__predict_false(bp->b_iodone == wd_split_mod15_write))
    909 		biodone(bp);
    910 	else {
    911 		biodone(bp);
    912 		wd->openings++;
    913 	}
    914 	wdstart(wd);
    915 }
    916 
    917 void
    918 wdrestart(void *v)
    919 {
    920 	struct wd_softc *wd = v;
    921 	struct buf *bp = wd->sc_bp;
    922 	int s;
    923 
    924 	ATADEBUG_PRINT(("wdrestart %s\n", device_xname(wd->sc_dev)),
    925 	    DEBUG_XFERS);
    926 	s = splbio();
    927 	__wdstart(v, bp);
    928 	splx(s);
    929 }
    930 
    931 int
    932 wdread(dev_t dev, struct uio *uio, int flags)
    933 {
    934 
    935 	ATADEBUG_PRINT(("wdread\n"), DEBUG_XFERS);
    936 	return (physio(wdstrategy, NULL, dev, B_READ, minphys, uio));
    937 }
    938 
    939 int
    940 wdwrite(dev_t dev, struct uio *uio, int flags)
    941 {
    942 
    943 	ATADEBUG_PRINT(("wdwrite\n"), DEBUG_XFERS);
    944 	return (physio(wdstrategy, NULL, dev, B_WRITE, minphys, uio));
    945 }
    946 
    947 int
    948 wdopen(dev_t dev, int flag, int fmt, struct lwp *l)
    949 {
    950 	struct wd_softc *wd;
    951 	int part, error;
    952 
    953 	ATADEBUG_PRINT(("wdopen\n"), DEBUG_FUNCS);
    954 	wd = device_private(device_lookup(&wd_cd, WDUNIT(dev)));
    955 	if (wd == NULL)
    956 		return (ENXIO);
    957 
    958 	if (! device_is_active(wd->sc_dev))
    959 		return (ENODEV);
    960 
    961 	part = WDPART(dev);
    962 
    963 	mutex_enter(&wd->sc_dk.dk_openlock);
    964 
    965 	/*
    966 	 * If there are wedges, and this is not RAW_PART, then we
    967 	 * need to fail.
    968 	 */
    969 	if (wd->sc_dk.dk_nwedges != 0 && part != RAW_PART) {
    970 		error = EBUSY;
    971 		goto bad1;
    972 	}
    973 
    974 	/*
    975 	 * If this is the first open of this device, add a reference
    976 	 * to the adapter.
    977 	 */
    978 	if (wd->sc_dk.dk_openmask == 0 &&
    979 	    (error = wd->atabus->ata_addref(wd->drvp)) != 0)
    980 		goto bad1;
    981 
    982 	if (wd->sc_dk.dk_openmask != 0) {
    983 		/*
    984 		 * If any partition is open, but the disk has been invalidated,
    985 		 * disallow further opens.
    986 		 */
    987 		if ((wd->sc_flags & WDF_LOADED) == 0) {
    988 			error = EIO;
    989 			goto bad2;
    990 		}
    991 	} else {
    992 		if ((wd->sc_flags & WDF_LOADED) == 0) {
    993 			wd->sc_flags |= WDF_LOADED;
    994 
    995 			/* Load the physical device parameters. */
    996 			wd_get_params(wd, AT_WAIT, &wd->sc_params);
    997 
    998 			/* Load the partition info if not already loaded. */
    999 			wdgetdisklabel(wd);
   1000 		}
   1001 	}
   1002 
   1003 	/* Check that the partition exists. */
   1004 	if (part != RAW_PART &&
   1005 	    (part >= wd->sc_dk.dk_label->d_npartitions ||
   1006 	     wd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
   1007 		error = ENXIO;
   1008 		goto bad2;
   1009 	}
   1010 
   1011 	/* Insure only one open at a time. */
   1012 	switch (fmt) {
   1013 	case S_IFCHR:
   1014 		wd->sc_dk.dk_copenmask |= (1 << part);
   1015 		break;
   1016 	case S_IFBLK:
   1017 		wd->sc_dk.dk_bopenmask |= (1 << part);
   1018 		break;
   1019 	}
   1020 	wd->sc_dk.dk_openmask =
   1021 	    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1022 
   1023 	mutex_exit(&wd->sc_dk.dk_openlock);
   1024 	return 0;
   1025 
   1026  bad2:
   1027 	if (wd->sc_dk.dk_openmask == 0)
   1028 		wd->atabus->ata_delref(wd->drvp);
   1029  bad1:
   1030 	mutex_exit(&wd->sc_dk.dk_openlock);
   1031 	return error;
   1032 }
   1033 
   1034 int
   1035 wdclose(dev_t dev, int flag, int fmt, struct lwp *l)
   1036 {
   1037 	struct wd_softc *wd =
   1038 	    device_private(device_lookup(&wd_cd, WDUNIT(dev)));
   1039 	int part = WDPART(dev);
   1040 
   1041 	ATADEBUG_PRINT(("wdclose\n"), DEBUG_FUNCS);
   1042 
   1043 	mutex_enter(&wd->sc_dk.dk_openlock);
   1044 
   1045 	switch (fmt) {
   1046 	case S_IFCHR:
   1047 		wd->sc_dk.dk_copenmask &= ~(1 << part);
   1048 		break;
   1049 	case S_IFBLK:
   1050 		wd->sc_dk.dk_bopenmask &= ~(1 << part);
   1051 		break;
   1052 	}
   1053 	wd->sc_dk.dk_openmask =
   1054 	    wd->sc_dk.dk_copenmask | wd->sc_dk.dk_bopenmask;
   1055 
   1056 	if (wd->sc_dk.dk_openmask == 0) {
   1057 		wd_flushcache(wd, AT_WAIT);
   1058 
   1059 		if (! (wd->sc_flags & WDF_KLABEL))
   1060 			wd->sc_flags &= ~WDF_LOADED;
   1061 
   1062 		wd->atabus->ata_delref(wd->drvp);
   1063 	}
   1064 
   1065 	mutex_exit(&wd->sc_dk.dk_openlock);
   1066 	return 0;
   1067 }
   1068 
   1069 void
   1070 wdgetdefaultlabel(struct wd_softc *wd, struct disklabel *lp)
   1071 {
   1072 
   1073 	ATADEBUG_PRINT(("wdgetdefaultlabel\n"), DEBUG_FUNCS);
   1074 	memset(lp, 0, sizeof(struct disklabel));
   1075 
   1076 	lp->d_secsize = DEV_BSIZE;
   1077 	lp->d_ntracks = wd->sc_params.atap_heads;
   1078 	lp->d_nsectors = wd->sc_params.atap_sectors;
   1079 	lp->d_ncylinders = (wd->sc_flags & WDF_LBA) ? wd->sc_capacity /
   1080 		(wd->sc_params.atap_heads * wd->sc_params.atap_sectors) :
   1081 		wd->sc_params.atap_cylinders;
   1082 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
   1083 
   1084 	if (strcmp(wd->sc_params.atap_model, "ST506") == 0)
   1085 		lp->d_type = DTYPE_ST506;
   1086 	else
   1087 		lp->d_type = DTYPE_ESDI;
   1088 
   1089 	strncpy(lp->d_typename, wd->sc_params.atap_model, 16);
   1090 	strncpy(lp->d_packname, "fictitious", 16);
   1091 	if (wd->sc_capacity > UINT32_MAX)
   1092 		lp->d_secperunit = UINT32_MAX;
   1093 	else
   1094 		lp->d_secperunit = wd->sc_capacity;
   1095 	lp->d_rpm = 3600;
   1096 	lp->d_interleave = 1;
   1097 	lp->d_flags = 0;
   1098 
   1099 	lp->d_partitions[RAW_PART].p_offset = 0;
   1100 	lp->d_partitions[RAW_PART].p_size =
   1101 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
   1102 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
   1103 	lp->d_npartitions = RAW_PART + 1;
   1104 
   1105 	lp->d_magic = DISKMAGIC;
   1106 	lp->d_magic2 = DISKMAGIC;
   1107 	lp->d_checksum = dkcksum(lp);
   1108 }
   1109 
   1110 /*
   1111  * Fabricate a default disk label, and try to read the correct one.
   1112  */
   1113 void
   1114 wdgetdisklabel(struct wd_softc *wd)
   1115 {
   1116 	struct disklabel *lp = wd->sc_dk.dk_label;
   1117 	const char *errstring;
   1118 	int s;
   1119 
   1120 	ATADEBUG_PRINT(("wdgetdisklabel\n"), DEBUG_FUNCS);
   1121 
   1122 	memset(wd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
   1123 
   1124 	wdgetdefaultlabel(wd, lp);
   1125 
   1126 	wd->sc_badsect[0] = -1;
   1127 
   1128 	if (wd->drvp->state > RESET) {
   1129 		s = splbio();
   1130 		wd->drvp->drive_flags |= DRIVE_RESET;
   1131 		splx(s);
   1132 	}
   1133 	errstring = readdisklabel(MAKEWDDEV(0, device_unit(wd->sc_dev),
   1134 				  RAW_PART), wdstrategy, lp,
   1135 				  wd->sc_dk.dk_cpulabel);
   1136 	if (errstring) {
   1137 		/*
   1138 		 * This probably happened because the drive's default
   1139 		 * geometry doesn't match the DOS geometry.  We
   1140 		 * assume the DOS geometry is now in the label and try
   1141 		 * again.  XXX This is a kluge.
   1142 		 */
   1143 		if (wd->drvp->state > RESET) {
   1144 			s = splbio();
   1145 			wd->drvp->drive_flags |= DRIVE_RESET;
   1146 			splx(s);
   1147 		}
   1148 		errstring = readdisklabel(MAKEWDDEV(0, device_unit(wd->sc_dev),
   1149 		    RAW_PART), wdstrategy, lp, wd->sc_dk.dk_cpulabel);
   1150 	}
   1151 	if (errstring) {
   1152 		aprint_error_dev(wd->sc_dev, "%s\n", errstring);
   1153 		return;
   1154 	}
   1155 
   1156 	if (wd->drvp->state > RESET) {
   1157 		s = splbio();
   1158 		wd->drvp->drive_flags |= DRIVE_RESET;
   1159 		splx(s);
   1160 	}
   1161 #ifdef HAS_BAD144_HANDLING
   1162 	if ((lp->d_flags & D_BADSECT) != 0)
   1163 		bad144intern(wd);
   1164 #endif
   1165 }
   1166 
   1167 void
   1168 wdperror(const struct wd_softc *wd)
   1169 {
   1170 	static const char *const errstr0_3[] = {"address mark not found",
   1171 	    "track 0 not found", "aborted command", "media change requested",
   1172 	    "id not found", "media changed", "uncorrectable data error",
   1173 	    "bad block detected"};
   1174 	static const char *const errstr4_5[] = {
   1175 	    "obsolete (address mark not found)",
   1176 	    "no media/write protected", "aborted command",
   1177 	    "media change requested", "id not found", "media changed",
   1178 	    "uncorrectable data error", "interface CRC error"};
   1179 	const char *const *errstr;
   1180 	int i;
   1181 	const char *sep = "";
   1182 
   1183 	const char *devname = device_xname(wd->sc_dev);
   1184 	struct ata_drive_datas *drvp = wd->drvp;
   1185 	int errno = wd->sc_wdc_bio.r_error;
   1186 
   1187 	if (drvp->ata_vers >= 4)
   1188 		errstr = errstr4_5;
   1189 	else
   1190 		errstr = errstr0_3;
   1191 
   1192 	printf("%s: (", devname);
   1193 
   1194 	if (errno == 0)
   1195 		printf("error not notified");
   1196 
   1197 	for (i = 0; i < 8; i++) {
   1198 		if (errno & (1 << i)) {
   1199 			printf("%s%s", sep, errstr[i]);
   1200 			sep = ", ";
   1201 		}
   1202 	}
   1203 	printf(")\n");
   1204 }
   1205 
   1206 int
   1207 wdioctl(dev_t dev, u_long xfer, void *addr, int flag, struct lwp *l)
   1208 {
   1209 	struct wd_softc *wd =
   1210 	    device_private(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, device_xname(wd->sc_dev));
   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, device_xname(wd->sc_dev));
   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_private(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_private(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 
   1810 	switch (wd->atabus->ata_get_params(wd->drvp, flags, params)) {
   1811 	case CMD_AGAIN:
   1812 		return 1;
   1813 	case CMD_ERR:
   1814 		/*
   1815 		 * We `know' there's a drive here; just assume it's old.
   1816 		 * This geometry is only used to read the MBR and print a
   1817 		 * (false) attach message.
   1818 		 */
   1819 		strncpy(params->atap_model, "ST506",
   1820 		    sizeof params->atap_model);
   1821 		params->atap_config = ATA_CFG_FIXED;
   1822 		params->atap_cylinders = 1024;
   1823 		params->atap_heads = 8;
   1824 		params->atap_sectors = 17;
   1825 		params->atap_multi = 1;
   1826 		params->atap_capabilities1 = params->atap_capabilities2 = 0;
   1827 		wd->drvp->ata_vers = -1; /* Mark it as pre-ATA */
   1828 		/* FALLTHROUGH */
   1829 	case CMD_OK:
   1830 		wd_params_to_properties(wd, params);
   1831 		return 0;
   1832 	default:
   1833 		panic("wd_get_params: bad return code from ata_get_params");
   1834 		/* NOTREACHED */
   1835 	}
   1836 }
   1837 
   1838 int
   1839 wd_getcache(struct wd_softc *wd, int *bitsp)
   1840 {
   1841 	struct ataparams params;
   1842 
   1843 	if (wd_get_params(wd, AT_WAIT, &params) != 0)
   1844 		return EIO;
   1845 	if (params.atap_cmd_set1 == 0x0000 ||
   1846 	    params.atap_cmd_set1 == 0xffff ||
   1847 	    (params.atap_cmd_set1 & WDC_CMD1_CACHE) == 0) {
   1848 		*bitsp = 0;
   1849 		return 0;
   1850 	}
   1851 	*bitsp = DKCACHE_WCHANGE | DKCACHE_READ;
   1852 	if (params.atap_cmd1_en & WDC_CMD1_CACHE)
   1853 		*bitsp |= DKCACHE_WRITE;
   1854 
   1855 	return 0;
   1856 }
   1857 
   1858 const char at_errbits[] = "\20\10ERROR\11TIMEOU\12DF";
   1859 
   1860 int
   1861 wd_setcache(struct wd_softc *wd, int bits)
   1862 {
   1863 	struct ataparams params;
   1864 	struct ata_command ata_c;
   1865 
   1866 	if (wd_get_params(wd, AT_WAIT, &params) != 0)
   1867 		return EIO;
   1868 
   1869 	if (params.atap_cmd_set1 == 0x0000 ||
   1870 	    params.atap_cmd_set1 == 0xffff ||
   1871 	    (params.atap_cmd_set1 & WDC_CMD1_CACHE) == 0)
   1872 		return EOPNOTSUPP;
   1873 
   1874 	if ((bits & DKCACHE_READ) == 0 ||
   1875 	    (bits & DKCACHE_SAVE) != 0)
   1876 		return EOPNOTSUPP;
   1877 
   1878 	memset(&ata_c, 0, sizeof(struct ata_command));
   1879 	ata_c.r_command = SET_FEATURES;
   1880 	ata_c.r_st_bmask = 0;
   1881 	ata_c.r_st_pmask = 0;
   1882 	ata_c.timeout = 30000; /* 30s timeout */
   1883 	ata_c.flags = AT_WAIT;
   1884 	if (bits & DKCACHE_WRITE)
   1885 		ata_c.r_features = WDSF_WRITE_CACHE_EN;
   1886 	else
   1887 		ata_c.r_features = WDSF_WRITE_CACHE_DS;
   1888 	if (wd->atabus->ata_exec_command(wd->drvp, &ata_c) != ATACMD_COMPLETE) {
   1889 		aprint_error_dev(wd->sc_dev,
   1890 		    "wd_setcache command not complete\n");
   1891 		return EIO;
   1892 	}
   1893 	if (ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1894 		char sbuf[sizeof(at_errbits) + 64];
   1895 		bitmask_snprintf(ata_c.flags, at_errbits, sbuf, sizeof(sbuf));
   1896 		aprint_error_dev(wd->sc_dev, "wd_setcache: status=%s\n", sbuf);
   1897 		return EIO;
   1898 	}
   1899 	return 0;
   1900 }
   1901 
   1902 static 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 		aprint_error_dev(wd->sc_dev,
   1915 		    "standby immediate command didn't complete\n");
   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 		aprint_error_dev(wd->sc_dev, "wd_standby: status=%s\n", sbuf);
   1926 		return EIO;
   1927 	}
   1928 	return 0;
   1929 }
   1930 
   1931 int
   1932 wd_flushcache(struct wd_softc *wd, int flags)
   1933 {
   1934 	struct ata_command ata_c;
   1935 
   1936 	/*
   1937 	 * WDCC_FLUSHCACHE is here since ATA-4, but some drives report
   1938 	 * only ATA-2 and still support it.
   1939 	 */
   1940 	if (wd->drvp->ata_vers < 4 &&
   1941 	    ((wd->sc_params.atap_cmd_set2 & WDC_CMD2_FC) == 0 ||
   1942 	    wd->sc_params.atap_cmd_set2 == 0xffff))
   1943 		return ENODEV;
   1944 	memset(&ata_c, 0, sizeof(struct ata_command));
   1945 	if ((wd->sc_params.atap_cmd2_en & ATA_CMD2_LBA48) != 0 &&
   1946 	    (wd->sc_params.atap_cmd2_en & ATA_CMD2_FCE) != 0)
   1947 		ata_c.r_command = WDCC_FLUSHCACHE_EXT;
   1948 	else
   1949 		ata_c.r_command = WDCC_FLUSHCACHE;
   1950 	ata_c.r_st_bmask = WDCS_DRDY;
   1951 	ata_c.r_st_pmask = WDCS_DRDY;
   1952 	ata_c.flags = flags;
   1953 	ata_c.timeout = 30000; /* 30s timeout */
   1954 	if (wd->atabus->ata_exec_command(wd->drvp, &ata_c) != ATACMD_COMPLETE) {
   1955 		aprint_error_dev(wd->sc_dev,
   1956 		    "flush cache command didn't complete\n");
   1957 		return EIO;
   1958 	}
   1959 	if (ata_c.flags & AT_ERROR) {
   1960 		if (ata_c.r_error == WDCE_ABRT) /* command not supported */
   1961 			return ENODEV;
   1962 	}
   1963 	if (ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   1964 		char sbuf[sizeof(at_errbits) + 64];
   1965 		bitmask_snprintf(ata_c.flags, at_errbits, sbuf, sizeof(sbuf));
   1966 		aprint_error_dev(wd->sc_dev, "wd_flushcache: status=%s\n",
   1967 		    sbuf);
   1968 		return EIO;
   1969 	}
   1970 	return 0;
   1971 }
   1972 
   1973 bool
   1974 wd_shutdown(device_t dev, int how)
   1975 {
   1976 
   1977 	struct wd_softc *wd = device_private(dev);
   1978 	wd_flushcache(wd, AT_POLL);
   1979 	if ((how & RB_POWERDOWN) == RB_POWERDOWN)
   1980 		wd_standby(wd, AT_POLL);
   1981 	return true;
   1982 }
   1983 
   1984 /*
   1985  * Allocate space for a ioctl queue structure.  Mostly taken from
   1986  * scsipi_ioctl.c
   1987  */
   1988 struct wd_ioctl *
   1989 wi_get(void)
   1990 {
   1991 	struct wd_ioctl *wi;
   1992 	int s;
   1993 
   1994 	wi = malloc(sizeof(struct wd_ioctl), M_TEMP, M_WAITOK|M_ZERO);
   1995 	buf_init(&wi->wi_bp);
   1996 	s = splbio();
   1997 	LIST_INSERT_HEAD(&wi_head, wi, wi_list);
   1998 	splx(s);
   1999 	return (wi);
   2000 }
   2001 
   2002 /*
   2003  * Free an ioctl structure and remove it from our list
   2004  */
   2005 
   2006 void
   2007 wi_free(struct wd_ioctl *wi)
   2008 {
   2009 	int s;
   2010 
   2011 	s = splbio();
   2012 	LIST_REMOVE(wi, wi_list);
   2013 	splx(s);
   2014 	buf_destroy(&wi->wi_bp);
   2015 	free(wi, M_TEMP);
   2016 }
   2017 
   2018 /*
   2019  * Find a wd_ioctl structure based on the struct buf.
   2020  */
   2021 
   2022 struct wd_ioctl *
   2023 wi_find(struct buf *bp)
   2024 {
   2025 	struct wd_ioctl *wi;
   2026 	int s;
   2027 
   2028 	s = splbio();
   2029 	for (wi = wi_head.lh_first; wi != 0; wi = wi->wi_list.le_next)
   2030 		if (bp == &wi->wi_bp)
   2031 			break;
   2032 	splx(s);
   2033 	return (wi);
   2034 }
   2035 
   2036 /*
   2037  * Ioctl pseudo strategy routine
   2038  *
   2039  * This is mostly stolen from scsipi_ioctl.c:scsistrategy().  What
   2040  * happens here is:
   2041  *
   2042  * - wdioctl() queues a wd_ioctl structure.
   2043  *
   2044  * - wdioctl() calls physio/wdioctlstrategy based on whether or not
   2045  *   user space I/O is required.  If physio() is called, physio() eventually
   2046  *   calls wdioctlstrategy().
   2047  *
   2048  * - In either case, wdioctlstrategy() calls wd->atabus->ata_exec_command()
   2049  *   to perform the actual command
   2050  *
   2051  * The reason for the use of the pseudo strategy routine is because
   2052  * when doing I/O to/from user space, physio _really_ wants to be in
   2053  * the loop.  We could put the entire buffer into the ioctl request
   2054  * structure, but that won't scale if we want to do things like download
   2055  * microcode.
   2056  */
   2057 
   2058 void
   2059 wdioctlstrategy(struct buf *bp)
   2060 {
   2061 	struct wd_ioctl *wi;
   2062 	struct ata_command ata_c;
   2063 	int error = 0;
   2064 
   2065 	wi = wi_find(bp);
   2066 	if (wi == NULL) {
   2067 		printf("wdioctlstrategy: "
   2068 		    "No matching ioctl request found in queue\n");
   2069 		error = EINVAL;
   2070 		goto bad;
   2071 	}
   2072 
   2073 	memset(&ata_c, 0, sizeof(ata_c));
   2074 
   2075 	/*
   2076 	 * Abort if physio broke up the transfer
   2077 	 */
   2078 
   2079 	if (bp->b_bcount != wi->wi_atareq.datalen) {
   2080 		printf("physio split wd ioctl request... cannot proceed\n");
   2081 		error = EIO;
   2082 		goto bad;
   2083 	}
   2084 
   2085 	/*
   2086 	 * Abort if we didn't get a buffer size that was a multiple of
   2087 	 * our sector size (or was larger than NBBY)
   2088 	 */
   2089 
   2090 	if ((bp->b_bcount % wi->wi_softc->sc_dk.dk_label->d_secsize) != 0 ||
   2091 	    (bp->b_bcount / wi->wi_softc->sc_dk.dk_label->d_secsize) >=
   2092 	     (1 << NBBY)) {
   2093 		error = EINVAL;
   2094 		goto bad;
   2095 	}
   2096 
   2097 	/*
   2098 	 * Make sure a timeout was supplied in the ioctl request
   2099 	 */
   2100 
   2101 	if (wi->wi_atareq.timeout == 0) {
   2102 		error = EINVAL;
   2103 		goto bad;
   2104 	}
   2105 
   2106 	if (wi->wi_atareq.flags & ATACMD_READ)
   2107 		ata_c.flags |= AT_READ;
   2108 	else if (wi->wi_atareq.flags & ATACMD_WRITE)
   2109 		ata_c.flags |= AT_WRITE;
   2110 
   2111 	if (wi->wi_atareq.flags & ATACMD_READREG)
   2112 		ata_c.flags |= AT_READREG;
   2113 
   2114 	ata_c.flags |= AT_WAIT;
   2115 
   2116 	ata_c.timeout = wi->wi_atareq.timeout;
   2117 	ata_c.r_command = wi->wi_atareq.command;
   2118 	ata_c.r_head = wi->wi_atareq.head & 0x0f;
   2119 	ata_c.r_cyl = wi->wi_atareq.cylinder;
   2120 	ata_c.r_sector = wi->wi_atareq.sec_num;
   2121 	ata_c.r_count = wi->wi_atareq.sec_count;
   2122 	ata_c.r_features = wi->wi_atareq.features;
   2123 	ata_c.r_st_bmask = WDCS_DRDY;
   2124 	ata_c.r_st_pmask = WDCS_DRDY;
   2125 	ata_c.data = wi->wi_bp.b_data;
   2126 	ata_c.bcount = wi->wi_bp.b_bcount;
   2127 
   2128 	if (wi->wi_softc->atabus->ata_exec_command(wi->wi_softc->drvp, &ata_c)
   2129 	    != ATACMD_COMPLETE) {
   2130 		wi->wi_atareq.retsts = ATACMD_ERROR;
   2131 		goto bad;
   2132 	}
   2133 
   2134 	if (ata_c.flags & (AT_ERROR | AT_TIMEOU | AT_DF)) {
   2135 		if (ata_c.flags & AT_ERROR) {
   2136 			wi->wi_atareq.retsts = ATACMD_ERROR;
   2137 			wi->wi_atareq.error = ata_c.r_error;
   2138 		} else if (ata_c.flags & AT_DF)
   2139 			wi->wi_atareq.retsts = ATACMD_DF;
   2140 		else
   2141 			wi->wi_atareq.retsts = ATACMD_TIMEOUT;
   2142 	} else {
   2143 		wi->wi_atareq.retsts = ATACMD_OK;
   2144 		if (wi->wi_atareq.flags & ATACMD_READREG) {
   2145 			wi->wi_atareq.head = ata_c.r_head ;
   2146 			wi->wi_atareq.cylinder = ata_c.r_cyl;
   2147 			wi->wi_atareq.sec_num = ata_c.r_sector;
   2148 			wi->wi_atareq.sec_count = ata_c.r_count;
   2149 			wi->wi_atareq.features = ata_c.r_features;
   2150 			wi->wi_atareq.error = ata_c.r_error;
   2151 		}
   2152 	}
   2153 
   2154 	bp->b_error = 0;
   2155 	biodone(bp);
   2156 	return;
   2157 bad:
   2158 	bp->b_error = error;
   2159 	biodone(bp);
   2160 }
   2161