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