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