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