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