xref: /openbsd/sys/dev/ata/wd.c (revision d415bd75)
1 /*	$OpenBSD: wd.c,v 1.130 2022/10/23 14:39:19 krw Exp $ */
2 /*	$NetBSD: wd.c,v 1.193 1999/02/28 17:15:27 explorer Exp $ */
3 
4 /*
5  * Copyright (c) 1998, 2001 Manuel Bouyer.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *	notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *	notice, this list of conditions and the following disclaimer in the
14  *	documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 /*-
29  * Copyright (c) 1998, 2003, 2004 The NetBSD Foundation, Inc.
30  * All rights reserved.
31  *
32  * This code is derived from software contributed to The NetBSD Foundation
33  * by Charles M. Hannum and by Onno van der Linden.
34  *
35  * Redistribution and use in source and binary forms, with or without
36  * modification, are permitted provided that the following conditions
37  * are met:
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  *
44  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
45  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
46  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
47  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
48  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
49  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
50  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
51  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
52  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
53  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
54  * POSSIBILITY OF SUCH DAMAGE.
55  */
56 
57 #if 0
58 #include "rnd.h"
59 #endif
60 
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/kernel.h>
64 #include <sys/conf.h>
65 #include <sys/fcntl.h>
66 #include <sys/stat.h>
67 #include <sys/ioctl.h>
68 #include <sys/mutex.h>
69 #include <sys/buf.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/timeout.h>
77 #include <sys/vnode.h>
78 #include <sys/dkio.h>
79 #include <sys/reboot.h>
80 
81 #include <machine/intr.h>
82 #include <machine/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 <dev/ic/wdcvar.h>
89 #if 0
90 #include "locators.h"
91 #endif
92 
93 #define	LBA48_THRESHOLD		(0xfffffff)	/* 128GB / DEV_BSIZE */
94 
95 #define	WDIORETRIES_SINGLE 4	/* number of retries before single-sector */
96 #define	WDIORETRIES	5	/* number of retries before giving up */
97 #define	RECOVERYTIME_MSEC 500	/* time to wait before retrying a cmd */
98 
99 #define DEBUG_INTR   0x01
100 #define DEBUG_XFERS  0x02
101 #define DEBUG_STATUS 0x04
102 #define DEBUG_FUNCS  0x08
103 #define DEBUG_PROBE  0x10
104 #ifdef WDCDEBUG
105 extern int wdcdebug_wd_mask; /* init'ed in ata_wdc.c */
106 #define WDCDEBUG_PRINT(args, level) do {	\
107 	if ((wdcdebug_wd_mask & (level)) != 0)	\
108 		printf args;			\
109 } while (0)
110 #else
111 #define WDCDEBUG_PRINT(args, level)
112 #endif
113 
114 
115 #define sc_drive sc_wdc_bio.drive
116 #define sc_mode sc_wdc_bio.mode
117 #define sc_multi sc_wdc_bio.multi
118 
119 int	wdprobe(struct device *, void *, void *);
120 void	wdattach(struct device *, struct device *, void *);
121 int	wddetach(struct device *, int);
122 int	wdactivate(struct device *, int);
123 int	wdprint(void *, char *);
124 
125 const struct cfattach wd_ca = {
126 	sizeof(struct wd_softc), wdprobe, wdattach,
127 	wddetach, wdactivate
128 };
129 
130 struct cfdriver wd_cd = {
131 	NULL, "wd", DV_DISK
132 };
133 
134 void  wdgetdefaultlabel(struct wd_softc *, struct disklabel *);
135 int   wdgetdisklabel(dev_t dev, struct wd_softc *, struct disklabel *, int);
136 void  wdstrategy(struct buf *);
137 void  wdstart(void *);
138 void  __wdstart(struct wd_softc*, struct buf *);
139 void  wdrestart(void *);
140 int   wd_get_params(struct wd_softc *, u_int8_t, struct ataparams *);
141 int   wd_flushcache(struct wd_softc *, int);
142 void  wd_standby(struct wd_softc *, int);
143 
144 /* XXX: these should go elsewhere */
145 cdev_decl(wd);
146 bdev_decl(wd);
147 
148 #define wdlookup(unit) (struct wd_softc *)disk_lookup(&wd_cd, (unit))
149 
150 
151 int
152 wdprobe(struct device *parent, void *match_, void *aux)
153 {
154 	struct ata_atapi_attach *aa_link = aux;
155 	struct cfdata *match = match_;
156 
157 	if (aa_link == NULL)
158 		return 0;
159 	if (aa_link->aa_type != T_ATA)
160 		return 0;
161 
162 	if (match->cf_loc[0] != -1 &&
163 	    match->cf_loc[0] != aa_link->aa_channel)
164 		return 0;
165 
166 	if (match->cf_loc[1] != -1 &&
167 	    match->cf_loc[1] != aa_link->aa_drv_data->drive)
168 		return 0;
169 
170 	return 1;
171 }
172 
173 void
174 wdattach(struct device *parent, struct device *self, void *aux)
175 {
176 	struct wd_softc *wd = (void *)self;
177 	struct ata_atapi_attach *aa_link= aux;
178 	struct wdc_command wdc_c;
179 	int i, blank;
180 	char buf[41], c, *p, *q;
181 	WDCDEBUG_PRINT(("wdattach\n"), DEBUG_FUNCS | DEBUG_PROBE);
182 
183 	wd->openings = aa_link->aa_openings;
184 	wd->drvp = aa_link->aa_drv_data;
185 
186 	strlcpy(wd->drvp->drive_name, wd->sc_dev.dv_xname,
187 	    sizeof(wd->drvp->drive_name));
188 	wd->drvp->cf_flags = wd->sc_dev.dv_cfdata->cf_flags;
189 
190 	if ((NERRS_MAX - 2) > 0)
191 		wd->drvp->n_dmaerrs = NERRS_MAX - 2;
192 	else
193 		wd->drvp->n_dmaerrs = 0;
194 
195 	/* read our drive info */
196 	if (wd_get_params(wd, at_poll, &wd->sc_params) != 0) {
197 		printf("%s: IDENTIFY failed\n", wd->sc_dev.dv_xname);
198 		return;
199 	}
200 
201 	for (blank = 0, p = wd->sc_params.atap_model, q = buf, i = 0;
202 	    i < sizeof(wd->sc_params.atap_model); i++) {
203 		c = *p++;
204 		if (c == '\0')
205 			break;
206 		if (c != ' ') {
207 			if (blank) {
208 				*q++ = ' ';
209 				blank = 0;
210 			}
211 			*q++ = c;
212 		} else
213 			blank = 1;
214 		}
215 	*q++ = '\0';
216 
217 	printf(": <%s>\n", buf);
218 
219 	wdc_probe_caps(wd->drvp, &wd->sc_params);
220 	wdc_print_caps(wd->drvp);
221 
222 	if ((wd->sc_params.atap_multi & 0xff) > 1) {
223 		wd->sc_multi = wd->sc_params.atap_multi & 0xff;
224 	} else {
225 		wd->sc_multi = 1;
226 	}
227 
228 	printf("%s: %d-sector PIO,", wd->sc_dev.dv_xname, wd->sc_multi);
229 
230 	/* use 48-bit LBA if enabled */
231 	if ((wd->sc_params.atap_cmd2_en & ATAPI_CMD2_48AD) != 0)
232 		wd->sc_flags |= WDF_LBA48;
233 
234 	/* Prior to ATA-4, LBA was optional. */
235 	if ((wd->sc_params.atap_capabilities1 & WDC_CAP_LBA) != 0)
236 		wd->sc_flags |= WDF_LBA;
237 #if 0
238 	/* ATA-4 requires LBA. */
239 	if (wd->sc_params.atap_ataversion != 0xffff &&
240 	    wd->sc_params.atap_ataversion >= WDC_VER_ATA4)
241 		wd->sc_flags |= WDF_LBA;
242 #endif
243 
244 	if ((wd->sc_flags & WDF_LBA48) != 0) {
245 		wd->sc_capacity =
246 		    (((u_int64_t)wd->sc_params.atap_max_lba[3] << 48) |
247 		     ((u_int64_t)wd->sc_params.atap_max_lba[2] << 32) |
248 		     ((u_int64_t)wd->sc_params.atap_max_lba[1] << 16) |
249 		      (u_int64_t)wd->sc_params.atap_max_lba[0]);
250 		printf(" LBA48, %lluMB, %llu sectors\n",
251 		    wd->sc_capacity / (1048576 / DEV_BSIZE),
252 		    wd->sc_capacity);
253 	} else if ((wd->sc_flags & WDF_LBA) != 0) {
254 		wd->sc_capacity =
255 		    (wd->sc_params.atap_capacity[1] << 16) |
256 		    wd->sc_params.atap_capacity[0];
257 		printf(" LBA, %lluMB, %llu sectors\n",
258 		    wd->sc_capacity / (1048576 / DEV_BSIZE),
259 		    wd->sc_capacity);
260 	} else {
261 		wd->sc_capacity =
262 		    wd->sc_params.atap_cylinders *
263 		    wd->sc_params.atap_heads *
264 		    wd->sc_params.atap_sectors;
265 		printf(" CHS, %lluMB, %d cyl, %d head, %d sec, %llu sectors\n",
266 		    wd->sc_capacity / (1048576 / DEV_BSIZE),
267 		    wd->sc_params.atap_cylinders,
268 		    wd->sc_params.atap_heads,
269 		    wd->sc_params.atap_sectors,
270 		    wd->sc_capacity);
271 	}
272 	WDCDEBUG_PRINT(("%s: atap_dmatiming_mimi=%d, atap_dmatiming_recom=%d\n",
273 	    self->dv_xname, wd->sc_params.atap_dmatiming_mimi,
274 	    wd->sc_params.atap_dmatiming_recom), DEBUG_PROBE);
275 
276 	/* use read look ahead if supported */
277 	if (wd->sc_params.atap_cmd_set1 & WDC_CMD1_AHEAD) {
278 		bzero(&wdc_c, sizeof(struct wdc_command));
279 		wdc_c.r_command = SET_FEATURES;
280 		wdc_c.r_features = WDSF_READAHEAD_EN;
281 		wdc_c.timeout = 1000;
282 		wdc_c.flags = at_poll;
283 
284 		if (wdc_exec_command(wd->drvp, &wdc_c) != WDC_COMPLETE) {
285 			printf("%s: enable look ahead command didn't "
286 			    "complete\n", wd->sc_dev.dv_xname);
287 		}
288 	}
289 
290 	/* use write cache if supported */
291 	if (wd->sc_params.atap_cmd_set1 & WDC_CMD1_CACHE) {
292 		bzero(&wdc_c, sizeof(struct wdc_command));
293 		wdc_c.r_command = SET_FEATURES;
294 		wdc_c.r_features = WDSF_EN_WR_CACHE;
295 		wdc_c.timeout = 1000;
296 		wdc_c.flags = at_poll;
297 
298 		if (wdc_exec_command(wd->drvp, &wdc_c) != WDC_COMPLETE) {
299 			printf("%s: enable write cache command didn't "
300 			    "complete\n", wd->sc_dev.dv_xname);
301 		}
302 	}
303 
304 	/*
305 	 * FREEZE LOCK the drive so malicious users can't lock it on us.
306 	 * As there is no harm in issuing this to drives that don't
307 	 * support the security feature set we just send it, and don't
308 	 * bother checking if the drive sends a command abort to tell us it
309 	 * doesn't support it.
310 	 */
311 	bzero(&wdc_c, sizeof(struct wdc_command));
312 
313 	wdc_c.r_command = WDCC_SEC_FREEZE_LOCK;
314 	wdc_c.timeout = 1000;
315 	wdc_c.flags = at_poll;
316 	if (wdc_exec_command(wd->drvp, &wdc_c) != WDC_COMPLETE) {
317 		printf("%s: freeze lock command didn't complete\n",
318 		    wd->sc_dev.dv_xname);
319 	}
320 
321 	/*
322 	 * Initialize disk structures.
323 	 */
324 	wd->sc_dk.dk_name = wd->sc_dev.dv_xname;
325 	bufq_init(&wd->sc_bufq, BUFQ_DEFAULT);
326 	timeout_set(&wd->sc_restart_timeout, wdrestart, wd);
327 
328 	/* Attach disk. */
329 	disk_attach(&wd->sc_dev, &wd->sc_dk);
330 	wd->sc_wdc_bio.lp = wd->sc_dk.dk_label;
331 }
332 
333 int
334 wdactivate(struct device *self, int act)
335 {
336 	struct wd_softc *wd = (void *)self;
337 	int rv = 0;
338 
339 	switch (act) {
340 	case DVACT_SUSPEND:
341 		break;
342 	case DVACT_POWERDOWN:
343 		wd_flushcache(wd, AT_POLL);
344 		if (boothowto & RB_POWERDOWN)
345 			wd_standby(wd, AT_POLL);
346 		break;
347 	case DVACT_RESUME:
348 		/*
349 		 * Do two resets separated by a small delay. The
350 		 * first wakes the controller, the second resets
351 		 * the channel.
352 		 */
353 		wdc_disable_intr(wd->drvp->chnl_softc);
354 		wdc_reset_channel(wd->drvp, 1);
355 		delay(10000);
356 		wdc_reset_channel(wd->drvp, 0);
357 		wdc_enable_intr(wd->drvp->chnl_softc);
358 		wd_get_params(wd, at_poll, &wd->sc_params);
359 		break;
360 	}
361 	return (rv);
362 }
363 
364 int
365 wddetach(struct device *self, int flags)
366 {
367 	struct wd_softc *sc = (struct wd_softc *)self;
368 
369 	timeout_del(&sc->sc_restart_timeout);
370 
371 	bufq_drain(&sc->sc_bufq);
372 
373 	disk_gone(wdopen, self->dv_unit);
374 
375 	/* Detach disk. */
376 	bufq_destroy(&sc->sc_bufq);
377 	disk_detach(&sc->sc_dk);
378 
379 	return (0);
380 }
381 
382 /*
383  * Read/write routine for a buffer.  Validates the arguments and schedules the
384  * transfer.  Does not wait for the transfer to complete.
385  */
386 void
387 wdstrategy(struct buf *bp)
388 {
389 	struct wd_softc *wd;
390 	int s;
391 
392 	wd = wdlookup(DISKUNIT(bp->b_dev));
393 	if (wd == NULL) {
394 		bp->b_error = ENXIO;
395 		goto bad;
396 	}
397 
398 	WDCDEBUG_PRINT(("wdstrategy (%s)\n", wd->sc_dev.dv_xname),
399 	    DEBUG_XFERS);
400 
401 	/* If device invalidated (e.g. media change, door open), error. */
402 	if ((wd->sc_flags & WDF_LOADED) == 0) {
403 		bp->b_error = EIO;
404 		goto bad;
405 	}
406 
407 	/* Validate the request. */
408 	if (bounds_check_with_label(bp, wd->sc_dk.dk_label) == -1)
409 		goto done;
410 
411 	/* Check that the number of sectors can fit in a byte. */
412 	if ((bp->b_bcount / wd->sc_dk.dk_label->d_secsize) >= (1 << NBBY)) {
413 		bp->b_error = EINVAL;
414 		goto bad;
415 	}
416 
417 	/* Queue transfer on drive, activate drive and controller if idle. */
418 	bufq_queue(&wd->sc_bufq, bp);
419 	s = splbio();
420 	wdstart(wd);
421 	splx(s);
422 	device_unref(&wd->sc_dev);
423 	return;
424 
425  bad:
426 	bp->b_flags |= B_ERROR;
427 	bp->b_resid = bp->b_bcount;
428  done:
429 	s = splbio();
430 	biodone(bp);
431 	splx(s);
432 	if (wd != NULL)
433 		device_unref(&wd->sc_dev);
434 }
435 
436 /*
437  * Queue a drive for I/O.
438  */
439 void
440 wdstart(void *arg)
441 {
442 	struct wd_softc *wd = arg;
443 	struct buf *bp = NULL;
444 
445 	WDCDEBUG_PRINT(("wdstart %s\n", wd->sc_dev.dv_xname),
446 	    DEBUG_XFERS);
447 	while (wd->openings > 0) {
448 
449 		/* Is there a buf for us ? */
450 		if ((bp = bufq_dequeue(&wd->sc_bufq)) == NULL)
451 			return;
452 		/*
453 		 * Make the command. First lock the device
454 		 */
455 		wd->openings--;
456 
457 		wd->retries = 0;
458 		__wdstart(wd, bp);
459 	}
460 }
461 
462 void
463 __wdstart(struct wd_softc *wd, struct buf *bp)
464 {
465 	struct disklabel *lp;
466 	u_int64_t nsecs;
467 
468 	lp = wd->sc_dk.dk_label;
469 	wd->sc_wdc_bio.blkno = DL_BLKTOSEC(lp, bp->b_blkno + DL_SECTOBLK(lp,
470 	    DL_GETPOFFSET(&lp->d_partitions[DISKPART(bp->b_dev)])));
471 	wd->sc_wdc_bio.blkdone =0;
472 	wd->sc_bp = bp;
473 	/*
474 	 * If we're retrying, retry in single-sector mode. This will give us
475 	 * the sector number of the problem, and will eventually allow the
476 	 * transfer to succeed.
477 	 */
478 	if (wd->retries >= WDIORETRIES_SINGLE)
479 		wd->sc_wdc_bio.flags = ATA_SINGLE;
480 	else
481 		wd->sc_wdc_bio.flags = 0;
482 	nsecs = howmany(bp->b_bcount, lp->d_secsize);
483 	if ((wd->sc_flags & WDF_LBA48) &&
484 	    /* use LBA48 only if really need */
485 	    ((wd->sc_wdc_bio.blkno + nsecs - 1 >= LBA48_THRESHOLD) ||
486 	     (nsecs > 0xff)))
487 		wd->sc_wdc_bio.flags |= ATA_LBA48;
488 	if (wd->sc_flags & WDF_LBA)
489 		wd->sc_wdc_bio.flags |= ATA_LBA;
490 	if (bp->b_flags & B_READ)
491 		wd->sc_wdc_bio.flags |= ATA_READ;
492 	wd->sc_wdc_bio.bcount = bp->b_bcount;
493 	wd->sc_wdc_bio.databuf = bp->b_data;
494 	wd->sc_wdc_bio.wd = wd;
495 	/* Instrumentation. */
496 	disk_busy(&wd->sc_dk);
497 	switch (wdc_ata_bio(wd->drvp, &wd->sc_wdc_bio)) {
498 	case WDC_TRY_AGAIN:
499 		timeout_add_sec(&wd->sc_restart_timeout, 1);
500 		break;
501 	case WDC_QUEUED:
502 		break;
503 	case WDC_COMPLETE:
504 		/*
505 		 * This code is never executed because we never set
506 		 * the ATA_POLL flag above
507 		 */
508 #if 0
509 		if (wd->sc_wdc_bio.flags & ATA_POLL)
510 			wddone(wd);
511 #endif
512 		break;
513 	default:
514 		panic("__wdstart: bad return code from wdc_ata_bio()");
515 	}
516 }
517 
518 void
519 wddone(void *v)
520 {
521 	struct wd_softc *wd = v;
522 	struct buf *bp = wd->sc_bp;
523 	char buf[256], *errbuf = buf;
524 	WDCDEBUG_PRINT(("wddone %s\n", wd->sc_dev.dv_xname),
525 	    DEBUG_XFERS);
526 
527 	bp->b_resid = wd->sc_wdc_bio.bcount;
528 	errbuf[0] = '\0';
529 	switch (wd->sc_wdc_bio.error) {
530 	case ERR_NODEV:
531 		bp->b_flags |= B_ERROR;
532 		bp->b_error = ENXIO;
533 		break;
534 	case ERR_DMA:
535 		errbuf = "DMA error";
536 		goto retry;
537 	case ERR_DF:
538 		errbuf = "device fault";
539 		goto retry;
540 	case TIMEOUT:
541 		errbuf = "device timeout";
542 		goto retry;
543 	case ERROR:
544 		/* Don't care about media change bits */
545 		if (wd->sc_wdc_bio.r_error != 0 &&
546 		    (wd->sc_wdc_bio.r_error & ~(WDCE_MC | WDCE_MCR)) == 0)
547 			goto noerror;
548 		ata_perror(wd->drvp, wd->sc_wdc_bio.r_error, errbuf,
549 		    sizeof buf);
550 retry:
551 		/* Just reset and retry. Can we do more ? */
552 		wdc_reset_channel(wd->drvp, 0);
553 		diskerr(bp, "wd", errbuf, LOG_PRINTF,
554 		    wd->sc_wdc_bio.blkdone, wd->sc_dk.dk_label);
555 		if (wd->retries++ < WDIORETRIES) {
556 			printf(", retrying\n");
557 			timeout_add_msec(&wd->sc_restart_timeout,
558 			    RECOVERYTIME_MSEC);
559 			return;
560 		}
561 		printf("\n");
562 		bp->b_flags |= B_ERROR;
563 		bp->b_error = EIO;
564 		break;
565 	case NOERROR:
566 noerror:	if ((wd->sc_wdc_bio.flags & ATA_CORR) || wd->retries > 0)
567 			printf("%s: soft error (corrected)\n",
568 			    wd->sc_dev.dv_xname);
569 	}
570 	disk_unbusy(&wd->sc_dk, (bp->b_bcount - bp->b_resid),
571 	    bp->b_blkno, (bp->b_flags & B_READ));
572 	biodone(bp);
573 	wd->openings++;
574 	wdstart(wd);
575 }
576 
577 void
578 wdrestart(void *v)
579 {
580 	struct wd_softc *wd = v;
581 	struct buf *bp = wd->sc_bp;
582 	struct channel_softc *chnl;
583 	int s;
584 	WDCDEBUG_PRINT(("wdrestart %s\n", wd->sc_dev.dv_xname),
585 	    DEBUG_XFERS);
586 
587 	chnl = (struct channel_softc *)(wd->drvp->chnl_softc);
588 	if (chnl->dying)
589 		return;
590 
591 	s = splbio();
592 	disk_unbusy(&wd->sc_dk, 0, 0, (bp->b_flags & B_READ));
593 	__wdstart(v, bp);
594 	splx(s);
595 }
596 
597 int
598 wdread(dev_t dev, struct uio *uio, int flags)
599 {
600 
601 	WDCDEBUG_PRINT(("wdread\n"), DEBUG_XFERS);
602 	return (physio(wdstrategy, dev, B_READ, minphys, uio));
603 }
604 
605 int
606 wdwrite(dev_t dev, struct uio *uio, int flags)
607 {
608 
609 	WDCDEBUG_PRINT(("wdwrite\n"), DEBUG_XFERS);
610 	return (physio(wdstrategy, dev, B_WRITE, minphys, uio));
611 }
612 
613 int
614 wdopen(dev_t dev, int flag, int fmt, struct proc *p)
615 {
616 	struct wd_softc *wd;
617 	struct channel_softc *chnl;
618 	int unit, part;
619 	int error;
620 
621 	WDCDEBUG_PRINT(("wdopen\n"), DEBUG_FUNCS);
622 
623 	unit = DISKUNIT(dev);
624 	wd = wdlookup(unit);
625 	if (wd == NULL)
626 		return ENXIO;
627 	chnl = (struct channel_softc *)(wd->drvp->chnl_softc);
628 	if (chnl->dying)
629 		return (ENXIO);
630 
631 	/*
632 	 * If this is the first open of this device, add a reference
633 	 * to the adapter.
634 	 */
635 	if ((error = disk_lock(&wd->sc_dk)) != 0)
636 		goto bad4;
637 
638 	if (wd->sc_dk.dk_openmask != 0) {
639 		/*
640 		 * If any partition is open, but the disk has been invalidated,
641 		 * disallow further opens.
642 		 */
643 		if ((wd->sc_flags & WDF_LOADED) == 0) {
644 			error = EIO;
645 			goto bad3;
646 		}
647 	} else {
648 		if ((wd->sc_flags & WDF_LOADED) == 0) {
649 			wd->sc_flags |= WDF_LOADED;
650 
651 			/* Load the physical device parameters. */
652 			wd_get_params(wd, AT_WAIT, &wd->sc_params);
653 
654 			/* Load the partition info if not already loaded. */
655 			if (wdgetdisklabel(dev, wd,
656 			    wd->sc_dk.dk_label, 0) == EIO) {
657 				error = EIO;
658 				goto bad;
659 			}
660 		}
661 	}
662 
663 	part = DISKPART(dev);
664 
665 	if ((error = disk_openpart(&wd->sc_dk, part, fmt, 1)) != 0)
666 		goto bad;
667 
668 	disk_unlock(&wd->sc_dk);
669 	device_unref(&wd->sc_dev);
670 	return 0;
671 
672 bad:
673 	if (wd->sc_dk.dk_openmask == 0) {
674 	}
675 
676 bad3:
677 	disk_unlock(&wd->sc_dk);
678 bad4:
679 	device_unref(&wd->sc_dev);
680 	return error;
681 }
682 
683 int
684 wdclose(dev_t dev, int flag, int fmt, struct proc *p)
685 {
686 	struct wd_softc *wd;
687 	int part = DISKPART(dev);
688 
689 	wd = wdlookup(DISKUNIT(dev));
690 	if (wd == NULL)
691 		return ENXIO;
692 
693 	WDCDEBUG_PRINT(("wdclose\n"), DEBUG_FUNCS);
694 
695 	disk_lock_nointr(&wd->sc_dk);
696 
697 	disk_closepart(&wd->sc_dk, part, fmt);
698 
699 	if (wd->sc_dk.dk_openmask == 0) {
700 		wd_flushcache(wd, AT_WAIT);
701 		/* XXXX Must wait for I/O to complete! */
702 	}
703 
704 	disk_unlock(&wd->sc_dk);
705 
706 	device_unref(&wd->sc_dev);
707 	return (0);
708 }
709 
710 void
711 wdgetdefaultlabel(struct wd_softc *wd, struct disklabel *lp)
712 {
713 	WDCDEBUG_PRINT(("wdgetdefaultlabel\n"), DEBUG_FUNCS);
714 	bzero(lp, sizeof(struct disklabel));
715 
716 	lp->d_secsize = DEV_BSIZE;
717 	DL_SETDSIZE(lp, wd->sc_capacity);
718 	lp->d_ntracks = wd->sc_params.atap_heads;
719 	lp->d_nsectors = wd->sc_params.atap_sectors;
720 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
721 	lp->d_ncylinders = DL_GETDSIZE(lp) / lp->d_secpercyl;
722 	if (wd->drvp->ata_vers == -1) {
723 		lp->d_type = DTYPE_ST506;
724 		strncpy(lp->d_typename, "ST506/MFM/RLL", sizeof lp->d_typename);
725 	} else {
726 		lp->d_type = DTYPE_ESDI;
727 		strncpy(lp->d_typename, "ESDI/IDE disk", sizeof lp->d_typename);
728 	}
729 	/* XXX - user viscopy() like sd.c */
730 	strncpy(lp->d_packname, wd->sc_params.atap_model, sizeof lp->d_packname);
731 	lp->d_version = 1;
732 
733 	lp->d_magic = DISKMAGIC;
734 	lp->d_magic2 = DISKMAGIC;
735 	lp->d_checksum = dkcksum(lp);
736 }
737 
738 /*
739  * Fabricate a default disk label, and try to read the correct one.
740  */
741 int
742 wdgetdisklabel(dev_t dev, struct wd_softc *wd, struct disklabel *lp,
743     int spoofonly)
744 {
745 	int error;
746 
747 	WDCDEBUG_PRINT(("wdgetdisklabel\n"), DEBUG_FUNCS);
748 
749 	wdgetdefaultlabel(wd, lp);
750 
751 	if (wd->drvp->state > RECAL)
752 		wd->drvp->drive_flags |= DRIVE_RESET;
753 	error = readdisklabel(DISKLABELDEV(dev), wdstrategy, lp,
754 	    spoofonly);
755 	if (wd->drvp->state > RECAL)
756 		wd->drvp->drive_flags |= DRIVE_RESET;
757 	return (error);
758 }
759 
760 int
761 wdioctl(dev_t dev, u_long xfer, caddr_t addr, int flag, struct proc *p)
762 {
763 	struct wd_softc *wd;
764 	struct disklabel *lp;
765 	int error = 0;
766 
767 	WDCDEBUG_PRINT(("wdioctl\n"), DEBUG_FUNCS);
768 
769 	wd = wdlookup(DISKUNIT(dev));
770 	if (wd == NULL)
771 		return ENXIO;
772 
773 	if ((wd->sc_flags & WDF_LOADED) == 0) {
774 		error = EIO;
775 		goto exit;
776 	}
777 
778 	switch (xfer) {
779 	case DIOCRLDINFO:
780 		lp = malloc(sizeof(*lp), M_TEMP, M_WAITOK);
781 		wdgetdisklabel(dev, wd, lp, 0);
782 		bcopy(lp, wd->sc_dk.dk_label, sizeof(*lp));
783 		free(lp, M_TEMP, sizeof(*lp));
784 		goto exit;
785 
786 	case DIOCGPDINFO:
787 		wdgetdisklabel(dev, wd, (struct disklabel *)addr, 1);
788 		goto exit;
789 
790 	case DIOCGDINFO:
791 		*(struct disklabel *)addr = *(wd->sc_dk.dk_label);
792 		goto exit;
793 
794 	case DIOCGPART:
795 		((struct partinfo *)addr)->disklab = wd->sc_dk.dk_label;
796 		((struct partinfo *)addr)->part =
797 		    &wd->sc_dk.dk_label->d_partitions[DISKPART(dev)];
798 		goto exit;
799 
800 	case DIOCWDINFO:
801 	case DIOCSDINFO:
802 		if ((flag & FWRITE) == 0) {
803 			error = EBADF;
804 			goto exit;
805 		}
806 
807 		if ((error = disk_lock(&wd->sc_dk)) != 0)
808 			goto exit;
809 
810 		error = setdisklabel(wd->sc_dk.dk_label,
811 		    (struct disklabel *)addr, wd->sc_dk.dk_openmask);
812 		if (error == 0) {
813 			if (wd->drvp->state > RECAL)
814 				wd->drvp->drive_flags |= DRIVE_RESET;
815 			if (xfer == DIOCWDINFO)
816 				error = writedisklabel(DISKLABELDEV(dev),
817 				    wdstrategy, wd->sc_dk.dk_label);
818 		}
819 
820 		disk_unlock(&wd->sc_dk);
821 		goto exit;
822 
823 	case DIOCCACHESYNC:
824 		if ((flag & FWRITE) == 0) {
825 			error = EBADF;
826 			goto exit;
827 		}
828 		error = wd_flushcache(wd, AT_WAIT);
829 		goto exit;
830 
831 	default:
832 		error = wdc_ioctl(wd->drvp, xfer, addr, flag, p);
833 		goto exit;
834 	}
835 
836 #ifdef DIAGNOSTIC
837 	panic("wdioctl: impossible");
838 #endif
839 
840  exit:
841 	device_unref(&wd->sc_dev);
842 	return (error);
843 }
844 
845 #ifdef B_FORMAT
846 int
847 wdformat(struct buf *bp)
848 {
849 
850 	bp->b_flags |= B_FORMAT;
851 	return wdstrategy(bp);
852 }
853 #endif
854 
855 daddr_t
856 wdsize(dev_t dev)
857 {
858 	struct wd_softc *wd;
859 	struct disklabel *lp;
860 	int part, omask;
861 	daddr_t size;
862 
863 	WDCDEBUG_PRINT(("wdsize\n"), DEBUG_FUNCS);
864 
865 	wd = wdlookup(DISKUNIT(dev));
866 	if (wd == NULL)
867 		return (-1);
868 
869 	part = DISKPART(dev);
870 	omask = wd->sc_dk.dk_openmask & (1 << part);
871 
872 	if (omask == 0 && wdopen(dev, 0, S_IFBLK, NULL) != 0) {
873 		size = -1;
874 		goto exit;
875 	}
876 
877 	lp = wd->sc_dk.dk_label;
878 	size = DL_SECTOBLK(lp, DL_GETPSIZE(&lp->d_partitions[part]));
879 	if (omask == 0 && wdclose(dev, 0, S_IFBLK, NULL) != 0)
880 		size = -1;
881 
882  exit:
883 	device_unref(&wd->sc_dev);
884 	return (size);
885 }
886 
887 /* #define WD_DUMP_NOT_TRUSTED if you just want to watch */
888 static int wddoingadump = 0;
889 static int wddumprecalibrated = 0;
890 static int wddumpmulti = 1;
891 
892 /*
893  * Dump core after a system crash.
894  */
895 int
896 wddump(dev_t dev, daddr_t blkno, caddr_t va, size_t size)
897 {
898 	struct wd_softc *wd;	/* disk unit to do the I/O */
899 	struct disklabel *lp;   /* disk's disklabel */
900 	int unit, part;
901 	int nblks;	/* total number of sectors left to write */
902 	int nwrt;	/* sectors to write with current i/o. */
903 	int err;
904 	char errbuf[256];
905 
906 	/* Check if recursive dump; if so, punt. */
907 	if (wddoingadump)
908 		return EFAULT;
909 	wddoingadump = 1;
910 
911 	unit = DISKUNIT(dev);
912 	wd = wdlookup(unit);
913 	if (wd == NULL)
914 		return ENXIO;
915 
916 	part = DISKPART(dev);
917 
918 	/* Make sure it was initialized. */
919 	if (wd->drvp->state < READY)
920 		return ENXIO;
921 
922 	/* Convert to disk sectors.  Request must be a multiple of size. */
923 	lp = wd->sc_dk.dk_label;
924 	if ((size % lp->d_secsize) != 0)
925 		return EFAULT;
926 	nblks = size / lp->d_secsize;
927 	blkno = blkno / (lp->d_secsize / DEV_BSIZE);
928 
929 	/* Check transfer bounds against partition size. */
930 	if ((blkno < 0) || ((blkno + nblks) > DL_GETPSIZE(&lp->d_partitions[part])))
931 		return EINVAL;
932 
933 	/* Offset block number to start of partition. */
934 	blkno += DL_GETPOFFSET(&lp->d_partitions[part]);
935 
936 	/* Recalibrate, if first dump transfer. */
937 	if (wddumprecalibrated == 0) {
938 		wddumpmulti = wd->sc_multi;
939 		wddumprecalibrated = 1;
940 		wd->drvp->state = RECAL;
941 	}
942 
943 	while (nblks > 0) {
944 		nwrt = min(nblks, wddumpmulti);
945 		wd->sc_wdc_bio.blkno = blkno;
946 		wd->sc_wdc_bio.flags = ATA_POLL;
947 		if (wd->sc_flags & WDF_LBA48)
948 			wd->sc_wdc_bio.flags |= ATA_LBA48;
949 		if (wd->sc_flags & WDF_LBA)
950 			wd->sc_wdc_bio.flags |= ATA_LBA;
951 		wd->sc_wdc_bio.bcount = nwrt * lp->d_secsize;
952 		wd->sc_wdc_bio.databuf = va;
953 		wd->sc_wdc_bio.wd = wd;
954 #ifndef WD_DUMP_NOT_TRUSTED
955 		switch (wdc_ata_bio(wd->drvp, &wd->sc_wdc_bio)) {
956 		case WDC_TRY_AGAIN:
957 			panic("wddump: try again");
958 			break;
959 		case WDC_QUEUED:
960 			panic("wddump: polled command has been queued");
961 			break;
962 		case WDC_COMPLETE:
963 			break;
964 		}
965 		switch(wd->sc_wdc_bio.error) {
966 		case TIMEOUT:
967 			printf("wddump: device timed out");
968 			err = EIO;
969 			break;
970 		case ERR_DF:
971 			printf("wddump: drive fault");
972 			err = EIO;
973 			break;
974 		case ERR_DMA:
975 			printf("wddump: DMA error");
976 			err = EIO;
977 			break;
978 		case ERROR:
979 			errbuf[0] = '\0';
980 			ata_perror(wd->drvp, wd->sc_wdc_bio.r_error, errbuf,
981 			    sizeof errbuf);
982 			printf("wddump: %s", errbuf);
983 			err = EIO;
984 			break;
985 		case NOERROR:
986 			err = 0;
987 			break;
988 		default:
989 			panic("wddump: unknown error type");
990 		}
991 		if (err != 0) {
992 			printf("\n");
993 			return err;
994 		}
995 #else	/* WD_DUMP_NOT_TRUSTED */
996 		/* Let's just talk about this first... */
997 		printf("wd%d: dump addr 0x%x, cylin %d, head %d, sector %d\n",
998 		    unit, va, cylin, head, sector);
999 		delay(500 * 1000);	/* half a second */
1000 #endif
1001 
1002 		/* update block count */
1003 		nblks -= nwrt;
1004 		blkno += nwrt;
1005 		va += nwrt * lp->d_secsize;
1006 	}
1007 
1008 	wddoingadump = 0;
1009 	return 0;
1010 }
1011 
1012 int
1013 wd_get_params(struct wd_softc *wd, u_int8_t flags, struct ataparams *params)
1014 {
1015 	switch (ata_get_params(wd->drvp, flags, params)) {
1016 	case CMD_AGAIN:
1017 		return 1;
1018 	case CMD_ERR:
1019 		/* If we already have drive parameters, reuse them. */
1020 		if (wd->sc_params.atap_cylinders != 0) {
1021 			if (params != &wd->sc_params)
1022 				bcopy(&wd->sc_params, params,
1023 				    sizeof(struct ataparams));
1024 			return 0;
1025 		}
1026 		/*
1027 		 * We `know' there's a drive here; just assume it's old.
1028 		 * This geometry is only used to read the MBR and print a
1029 		 * (false) attach message.
1030 		 */
1031 		bzero(params, sizeof(struct ataparams));
1032 		strncpy(params->atap_model, "ST506",
1033 		    sizeof params->atap_model);
1034 		params->atap_config = ATA_CFG_FIXED;
1035 		params->atap_cylinders = 1024;
1036 		params->atap_heads = 8;
1037 		params->atap_sectors = 17;
1038 		params->atap_multi = 1;
1039 		params->atap_capabilities1 = params->atap_capabilities2 = 0;
1040 		wd->drvp->ata_vers = -1; /* Mark it as pre-ATA */
1041 		return 0;
1042 	case CMD_OK:
1043 		return 0;
1044 	default:
1045 		panic("wd_get_params: bad return code from ata_get_params");
1046 		/* NOTREACHED */
1047 	}
1048 }
1049 
1050 int
1051 wd_flushcache(struct wd_softc *wd, int flags)
1052 {
1053 	struct wdc_command wdc_c;
1054 
1055 	if (wd->drvp->ata_vers < 4) /* WDCC_FLUSHCACHE is here since ATA-4 */
1056 		return EIO;
1057 	bzero(&wdc_c, sizeof(struct wdc_command));
1058 	wdc_c.r_command = (wd->sc_flags & WDF_LBA48 ? WDCC_FLUSHCACHE_EXT :
1059 	    WDCC_FLUSHCACHE);
1060 	wdc_c.r_st_bmask = WDCS_DRDY;
1061 	wdc_c.r_st_pmask = WDCS_DRDY;
1062 	wdc_c.flags = flags;
1063 	wdc_c.timeout = 30000; /* 30s timeout */
1064 	if (wdc_exec_command(wd->drvp, &wdc_c) != WDC_COMPLETE) {
1065 		printf("%s: flush cache command didn't complete\n",
1066 		    wd->sc_dev.dv_xname);
1067 		return EIO;
1068 	}
1069 	if (wdc_c.flags & ERR_NODEV)
1070 		return ENODEV;
1071 	if (wdc_c.flags & AT_TIMEOU) {
1072 		printf("%s: flush cache command timeout\n",
1073 		    wd->sc_dev.dv_xname);
1074 		return EIO;
1075 	}
1076 	if (wdc_c.flags & AT_ERROR) {
1077 		if (wdc_c.r_error == WDCE_ABRT) /* command not supported */
1078 			return ENODEV;
1079 		printf("%s: flush cache command: error 0x%x\n",
1080 		    wd->sc_dev.dv_xname, wdc_c.r_error);
1081 		return EIO;
1082 	}
1083 	if (wdc_c.flags & AT_DF) {
1084 		printf("%s: flush cache command: drive fault\n",
1085 		    wd->sc_dev.dv_xname);
1086 		return EIO;
1087 	}
1088 	return 0;
1089 }
1090 
1091 void
1092 wd_standby(struct wd_softc *wd, int flags)
1093 {
1094 	struct wdc_command wdc_c;
1095 
1096 	bzero(&wdc_c, sizeof(struct wdc_command));
1097 	wdc_c.r_command = WDCC_STANDBY_IMMED;
1098 	wdc_c.r_st_bmask = WDCS_DRDY;
1099 	wdc_c.r_st_pmask = WDCS_DRDY;
1100 	wdc_c.flags = flags;
1101 	wdc_c.timeout = 30000; /* 30s timeout */
1102 	if (wdc_exec_command(wd->drvp, &wdc_c) != WDC_COMPLETE) {
1103 		printf("%s: standby command didn't complete\n",
1104 		    wd->sc_dev.dv_xname);
1105 	}
1106 	if (wdc_c.flags & AT_TIMEOU) {
1107 		printf("%s: standby command timeout\n",
1108 		    wd->sc_dev.dv_xname);
1109 	}
1110 	if (wdc_c.flags & AT_DF) {
1111 		printf("%s: standby command: drive fault\n",
1112 		    wd->sc_dev.dv_xname);
1113 	}
1114 	/*
1115 	 * Ignore error register, it shouldn't report anything else
1116 	 * than COMMAND ABORTED, which means the device doesn't support
1117 	 * standby
1118 	 */
1119 }
1120