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