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