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