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