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