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