xref: /netbsd-src/sys/dev/scsipi/sd.c (revision 3cec974c61d7fac0a37c0377723a33214a458c8b)
1 /*	$NetBSD: sd.c,v 1.170 2001/03/09 16:07:39 explorer Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Charles M. Hannum.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*
40  * Originally written by Julian Elischer (julian@dialix.oz.au)
41  * for TRW Financial Systems for use under the MACH(2.5) operating system.
42  *
43  * TRW Financial Systems, in accordance with their agreement with Carnegie
44  * Mellon University, makes this software available to CMU to distribute
45  * or use in any manner that they see fit as long as this message is kept with
46  * the software. For this reason TFS also grants any other persons or
47  * organisations permission to use or modify this software.
48  *
49  * TFS supplies this software to be publicly redistributed
50  * on the understanding that TFS is not responsible for the correct
51  * functioning of this software in any circumstances.
52  *
53  * Ported to run under 386BSD by Julian Elischer (julian@dialix.oz.au) Sept 1992
54  */
55 
56 #include "opt_scsi.h"
57 #include "rnd.h"
58 
59 #include <sys/types.h>
60 #include <sys/param.h>
61 #include <sys/systm.h>
62 #include <sys/kernel.h>
63 #include <sys/file.h>
64 #include <sys/stat.h>
65 #include <sys/ioctl.h>
66 #include <sys/scsiio.h>
67 #include <sys/buf.h>
68 #include <sys/uio.h>
69 #include <sys/malloc.h>
70 #include <sys/errno.h>
71 #include <sys/device.h>
72 #include <sys/disklabel.h>
73 #include <sys/disk.h>
74 #include <sys/proc.h>
75 #include <sys/conf.h>
76 #include <sys/vnode.h>
77 #if NRND > 0
78 #include <sys/rnd.h>
79 #endif
80 
81 #include <dev/scsipi/scsipi_all.h>
82 #include <dev/scsipi/scsi_all.h>
83 #include <dev/scsipi/scsipi_disk.h>
84 #include <dev/scsipi/scsi_disk.h>
85 #include <dev/scsipi/scsiconf.h>
86 #include <dev/scsipi/sdvar.h>
87 
88 #include "sd.h"		/* NSD_SCSIBUS and NSD_ATAPIBUS come from here */
89 
90 #ifndef	SDOUTSTANDING
91 #define	SDOUTSTANDING	4
92 #endif
93 
94 #define	SDUNIT(dev)			DISKUNIT(dev)
95 #define	SDPART(dev)			DISKPART(dev)
96 #define	SDMINOR(unit, part)		DISKMINOR(unit, part)
97 #define	MAKESDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
98 
99 #define	SDLABELDEV(dev)	(MAKESDDEV(major(dev), SDUNIT(dev), RAW_PART))
100 
101 int	sdlock __P((struct sd_softc *));
102 void	sdunlock __P((struct sd_softc *));
103 void	sdminphys __P((struct buf *));
104 void	sdgetdefaultlabel __P((struct sd_softc *, struct disklabel *));
105 void	sdgetdisklabel __P((struct sd_softc *));
106 void	sdstart __P((void *));
107 void	sddone __P((struct scsipi_xfer *));
108 void	sd_shutdown __P((void *));
109 int	sd_reassign_blocks __P((struct sd_softc *, u_long));
110 int	sd_interpret_sense __P((struct scsipi_xfer *));
111 
112 extern struct cfdriver sd_cd;
113 
114 struct dkdriver sddkdriver = { sdstrategy };
115 
116 struct scsipi_device sd_switch = {
117 	sd_interpret_sense,	/* check our error handler first */
118 	sdstart,		/* have a queue, served by this */
119 	NULL,			/* have no async handler */
120 	sddone,			/* deal with stats at interrupt time */
121 };
122 
123 /*
124  * The routine called by the low level scsi routine when it discovers
125  * a device suitable for this driver.
126  */
127 void
128 sdattach(parent, sd, sc_link, ops)
129 	struct device *parent;
130 	struct sd_softc *sd;
131 	struct scsipi_link *sc_link;
132 	const struct sd_ops *ops;
133 {
134 	int error, result;
135 	struct disk_parms *dp = &sd->params;
136 	char pbuf[9];
137 
138 	SC_DEBUG(sc_link, SDEV_DB2, ("sdattach: "));
139 
140 	BUFQ_INIT(&sd->buf_queue);
141 
142 	/*
143 	 * Store information needed to contact our base driver
144 	 */
145 	sd->sc_link = sc_link;
146 	sd->sc_ops = ops;
147 	sc_link->device = &sd_switch;
148 	sc_link->device_softc = sd;
149 	if (sc_link->openings > SDOUTSTANDING)
150 		sc_link->openings = SDOUTSTANDING;
151 
152 	/*
153 	 * Initialize and attach the disk structure.
154 	 */
155 	sd->sc_dk.dk_driver = &sddkdriver;
156 	sd->sc_dk.dk_name = sd->sc_dev.dv_xname;
157 	disk_attach(&sd->sc_dk);
158 
159 #ifdef __BROKEN_DK_ESTABLISH
160 	dk_establish(&sd->sc_dk, &sd->sc_dev);		/* XXX */
161 #endif
162 
163 	/*
164 	 * Use the subdriver to request information regarding the drive.
165 	 */
166 	printf("\n");
167 
168 	error = scsipi_start(sd->sc_link, SSS_START,
169 	    XS_CTL_DISCOVERY | XS_CTL_IGNORE_ILLEGAL_REQUEST |
170 	    XS_CTL_IGNORE_MEDIA_CHANGE | XS_CTL_SILENT);
171 
172 	if (error)
173 		result = SDGP_RESULT_OFFLINE;
174 	else
175 		result = (*sd->sc_ops->sdo_get_parms)(sd, &sd->params,
176 		    XS_CTL_DISCOVERY);
177 	printf("%s: ", sd->sc_dev.dv_xname);
178 	switch (result) {
179 	case SDGP_RESULT_OK:
180 		format_bytes(pbuf, sizeof(pbuf),
181 		    (u_int64_t)dp->disksize * dp->blksize);
182 	        printf(
183 		"%s, %ld cyl, %ld head, %ld sec, %ld bytes/sect x %ld sectors",
184 		    pbuf, dp->cyls, dp->heads, dp->sectors, dp->blksize,
185 		    dp->disksize);
186 		break;
187 
188 	case SDGP_RESULT_OFFLINE:
189 		printf("drive offline");
190 		break;
191 
192 	case SDGP_RESULT_UNFORMATTED:
193 		printf("unformatted media");
194 		break;
195 
196 #ifdef DIAGNOSTIC
197 	default:
198 		panic("sdattach: unknown result from get_parms");
199 		break;
200 #endif
201 	}
202 	printf("\n");
203 
204 	/*
205 	 * Establish a shutdown hook so that we can ensure that
206 	 * our data has actually made it onto the platter at
207 	 * shutdown time.  Note that this relies on the fact
208 	 * that the shutdown hook code puts us at the head of
209 	 * the list (thus guaranteeing that our hook runs before
210 	 * our ancestors').
211 	 */
212 	if ((sd->sc_sdhook =
213 	    shutdownhook_establish(sd_shutdown, sd)) == NULL)
214 		printf("%s: WARNING: unable to establish shutdown hook\n",
215 		    sd->sc_dev.dv_xname);
216 
217 #if NRND > 0
218 	/*
219 	 * attach the device into the random source list
220 	 */
221 	rnd_attach_source(&sd->rnd_source, sd->sc_dev.dv_xname,
222 			  RND_TYPE_DISK, 0);
223 #endif
224 }
225 
226 int
227 sdactivate(self, act)
228 	struct device *self;
229 	enum devact act;
230 {
231 	int rv = 0;
232 
233 	switch (act) {
234 	case DVACT_ACTIVATE:
235 		rv = EOPNOTSUPP;
236 		break;
237 
238 	case DVACT_DEACTIVATE:
239 		/*
240 		 * Nothing to do; we key off the device's DVF_ACTIVE.
241 		 */
242 		break;
243 	}
244 	return (rv);
245 }
246 
247 int
248 sddetach(self, flags)
249 	struct device *self;
250 	int flags;
251 {
252 	struct sd_softc *sd = (struct sd_softc *) self;
253 	struct buf *bp;
254 	int s, bmaj, cmaj, mn;
255 
256 	/* locate the major number */
257 	for (bmaj = 0; bmaj <= nblkdev; bmaj++)
258 		if (bdevsw[bmaj].d_open == sdopen)
259 			break;
260 	for (cmaj = 0; cmaj <= nchrdev; cmaj++)
261 		if (cdevsw[cmaj].d_open == sdopen)
262 			break;
263 
264 	s = splbio();
265 
266 	/* Kill off any queued buffers. */
267 	while ((bp = BUFQ_FIRST(&sd->buf_queue)) != NULL) {
268 		BUFQ_REMOVE(&sd->buf_queue, bp);
269 		bp->b_error = EIO;
270 		bp->b_flags |= B_ERROR;
271 		bp->b_resid = bp->b_bcount;
272 		biodone(bp);
273 	}
274 
275 	/* Kill off any pending commands. */
276 	scsipi_kill_pending(sd->sc_link);
277 
278 	splx(s);
279 
280 	/* Nuke the vnodes for any open instances */
281 	mn = SDMINOR(self->dv_unit, 0);
282 	vdevgone(bmaj, mn, mn + (MAXPARTITIONS - 1), VBLK);
283 	vdevgone(cmaj, mn, mn + (MAXPARTITIONS - 1), VCHR);
284 
285 	/* Detach from the disk list. */
286 	disk_detach(&sd->sc_dk);
287 
288 	/* Get rid of the shutdown hook. */
289 	shutdownhook_disestablish(sd->sc_sdhook);
290 
291 #if NRND > 0
292 	/* Unhook the entropy source. */
293 	rnd_detach_source(&sd->rnd_source);
294 #endif
295 
296 	return (0);
297 }
298 
299 /*
300  * Wait interruptibly for an exclusive lock.
301  *
302  * XXX
303  * Several drivers do this; it should be abstracted and made MP-safe.
304  */
305 int
306 sdlock(sd)
307 	struct sd_softc *sd;
308 {
309 	int error;
310 
311 	while ((sd->flags & SDF_LOCKED) != 0) {
312 		sd->flags |= SDF_WANTED;
313 		if ((error = tsleep(sd, PRIBIO | PCATCH, "sdlck", 0)) != 0)
314 			return (error);
315 	}
316 	sd->flags |= SDF_LOCKED;
317 	return (0);
318 }
319 
320 /*
321  * Unlock and wake up any waiters.
322  */
323 void
324 sdunlock(sd)
325 	struct sd_softc *sd;
326 {
327 
328 	sd->flags &= ~SDF_LOCKED;
329 	if ((sd->flags & SDF_WANTED) != 0) {
330 		sd->flags &= ~SDF_WANTED;
331 		wakeup(sd);
332 	}
333 }
334 
335 /*
336  * open the device. Make sure the partition info is a up-to-date as can be.
337  */
338 int
339 sdopen(dev, flag, fmt, p)
340 	dev_t dev;
341 	int flag, fmt;
342 	struct proc *p;
343 {
344 	struct sd_softc *sd;
345 	struct scsipi_link *sc_link;
346 	int unit, part;
347 	int error;
348 
349 	unit = SDUNIT(dev);
350 	if (unit >= sd_cd.cd_ndevs)
351 		return (ENXIO);
352 	sd = sd_cd.cd_devs[unit];
353 	if (sd == NULL)
354 		return (ENXIO);
355 
356 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
357 		return (ENODEV);
358 
359 	sc_link = sd->sc_link;
360 	part = SDPART(dev);
361 
362 	SC_DEBUG(sc_link, SDEV_DB1,
363 	    ("sdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev, unit,
364 	    sd_cd.cd_ndevs, part));
365 
366 	/*
367 	 * If this is the first open of this device, add a reference
368 	 * to the adapter.
369 	 */
370 	if (sd->sc_dk.dk_openmask == 0 &&
371 	    (error = scsipi_adapter_addref(sc_link)) != 0)
372 		return (error);
373 
374 	if ((error = sdlock(sd)) != 0)
375 		goto bad4;
376 
377 	if ((sc_link->flags & SDEV_OPEN) != 0) {
378 		/*
379 		 * If any partition is open, but the disk has been invalidated,
380 		 * disallow further opens of non-raw partition
381 		 */
382 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0 &&
383 		    (part != RAW_PART || fmt != S_IFCHR)) {
384 			error = EIO;
385 			goto bad3;
386 		}
387 	} else {
388 		/* Check that it is still responding and ok. */
389 		error = scsipi_test_unit_ready(sc_link,
390 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
391 		    XS_CTL_IGNORE_NOT_READY);
392 		if (error)
393 			goto bad3;
394 
395 		/*
396 		 * Start the pack spinning if necessary. Always allow the
397 		 * raw parition to be opened, for raw IOCTLs. Data transfers
398 		 * will check for SDEV_MEDIA_LOADED.
399 		 */
400 		error = scsipi_start(sc_link, SSS_START,
401 		    XS_CTL_IGNORE_ILLEGAL_REQUEST |
402 		    XS_CTL_IGNORE_MEDIA_CHANGE | XS_CTL_SILENT);
403 		if (error) {
404 			if (part != RAW_PART || fmt != S_IFCHR)
405 				goto bad3;
406 			else
407 				goto out;
408 		}
409 
410 		sc_link->flags |= SDEV_OPEN;
411 
412 		if (sd->sc_link->flags & SDEV_REMOVABLE) {
413 			/* Lock the pack in. */
414 			error = scsipi_prevent(sc_link, PR_PREVENT,
415 					       XS_CTL_IGNORE_ILLEGAL_REQUEST
416 					       | XS_CTL_IGNORE_MEDIA_CHANGE);
417 			if (error)
418 				goto bad;
419 		}
420 
421 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
422 			sc_link->flags |= SDEV_MEDIA_LOADED;
423 
424 			/*
425 			 * Load the physical device parameters.
426 			 *
427 			 * Note that if media is present but unformatted,
428 			 * we allow the open (so that it can be formatted!).
429 			 * The drive should refuse real I/O, if the media is
430 			 * unformatted.
431 			 */
432 			if ((*sd->sc_ops->sdo_get_parms)(sd, &sd->params,
433 			    0) == SDGP_RESULT_OFFLINE) {
434 				error = ENXIO;
435 				goto bad2;
436 			}
437 			SC_DEBUG(sc_link, SDEV_DB3, ("Params loaded "));
438 
439 			/* Load the partition info if not already loaded. */
440 			sdgetdisklabel(sd);
441 			SC_DEBUG(sc_link, SDEV_DB3, ("Disklabel loaded "));
442 		}
443 	}
444 
445 	/* Check that the partition exists. */
446 	if (part != RAW_PART &&
447 	    (part >= sd->sc_dk.dk_label->d_npartitions ||
448 	     sd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
449 		error = ENXIO;
450 		goto bad;
451 	}
452 
453 out:	/* Insure only one open at a time. */
454 	switch (fmt) {
455 	case S_IFCHR:
456 		sd->sc_dk.dk_copenmask |= (1 << part);
457 		break;
458 	case S_IFBLK:
459 		sd->sc_dk.dk_bopenmask |= (1 << part);
460 		break;
461 	}
462 	sd->sc_dk.dk_openmask =
463 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
464 
465 	SC_DEBUG(sc_link, SDEV_DB3, ("open complete\n"));
466 	sdunlock(sd);
467 	return (0);
468 
469 bad2:
470 	sc_link->flags &= ~SDEV_MEDIA_LOADED;
471 
472 bad:
473 	if (sd->sc_dk.dk_openmask == 0) {
474 		scsipi_prevent(sc_link, PR_ALLOW,
475 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
476 		sc_link->flags &= ~SDEV_OPEN;
477 	}
478 
479 bad3:
480 	sdunlock(sd);
481 bad4:
482 	if (sd->sc_dk.dk_openmask == 0)
483 		scsipi_adapter_delref(sc_link);
484 	return (error);
485 }
486 
487 /*
488  * close the device.. only called if we are the LAST occurence of an open
489  * device.  Convenient now but usually a pain.
490  */
491 int
492 sdclose(dev, flag, fmt, p)
493 	dev_t dev;
494 	int flag, fmt;
495 	struct proc *p;
496 {
497 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
498 	int part = SDPART(dev);
499 	int error;
500 
501 	if ((error = sdlock(sd)) != 0)
502 		return (error);
503 
504 	switch (fmt) {
505 	case S_IFCHR:
506 		sd->sc_dk.dk_copenmask &= ~(1 << part);
507 		break;
508 	case S_IFBLK:
509 		sd->sc_dk.dk_bopenmask &= ~(1 << part);
510 		break;
511 	}
512 	sd->sc_dk.dk_openmask =
513 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
514 
515 	if (sd->sc_dk.dk_openmask == 0) {
516 		/*
517 		 * If the disk cache needs flushing, and the disk supports
518 		 * it, do it now.
519 		 */
520 		if ((sd->flags & SDF_DIRTY) != 0 &&
521 		    sd->sc_ops->sdo_flush != NULL) {
522 			if ((*sd->sc_ops->sdo_flush)(sd, 0)) {
523 				printf("%s: cache synchronization failed\n",
524 				    sd->sc_dev.dv_xname);
525 				sd->flags &= ~SDF_FLUSHING;
526 			} else
527 				sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
528 		}
529 
530 		scsipi_wait_drain(sd->sc_link);
531 
532 		if (sd->sc_link->flags & SDEV_REMOVABLE) {
533 			scsipi_prevent(sd->sc_link, PR_ALLOW,
534 				       XS_CTL_IGNORE_ILLEGAL_REQUEST
535 				       | XS_CTL_IGNORE_NOT_READY);
536 		}
537 
538 		sd->sc_link->flags &= ~SDEV_OPEN;
539 
540 		if (! (sd->sc_link->flags & SDEV_KEEP_LABEL))
541 			sd->sc_link->flags &= ~SDEV_MEDIA_LOADED;
542 
543 		scsipi_wait_drain(sd->sc_link);
544 
545 		scsipi_adapter_delref(sd->sc_link);
546 	}
547 
548 	sdunlock(sd);
549 	return (0);
550 }
551 
552 /*
553  * Actually translate the requested transfer into one the physical driver
554  * can understand.  The transfer is described by a buf and will include
555  * only one physical transfer.
556  */
557 void
558 sdstrategy(bp)
559 	struct buf *bp;
560 {
561 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
562 	struct disklabel *lp;
563 	daddr_t blkno;
564 	int s;
565 	boolean_t sector_aligned;
566 
567 	SC_DEBUG(sd->sc_link, SDEV_DB2, ("sdstrategy "));
568 	SC_DEBUG(sd->sc_link, SDEV_DB1,
569 	    ("%ld bytes @ blk %d\n", bp->b_bcount, bp->b_blkno));
570 	/*
571 	 * If the device has been made invalid, error out
572 	 */
573 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0 ||
574 	    (sd->sc_dev.dv_flags & DVF_ACTIVE) == 0) {
575 		if (sd->sc_link->flags & SDEV_OPEN)
576 			bp->b_error = EIO;
577 		else
578 			bp->b_error = ENODEV;
579 		goto bad;
580 	}
581 
582 	lp = sd->sc_dk.dk_label;
583 
584 	/*
585 	 * The transfer must be a whole number of blocks, offset must not be
586 	 * negative.
587 	 */
588 	if (lp->d_secsize == DEV_BSIZE) {
589 		sector_aligned = (bp->b_bcount & (DEV_BSIZE - 1)) == 0;
590 	} else {
591 		sector_aligned = (bp->b_bcount % lp->d_secsize) == 0;
592 	}
593 	if (!sector_aligned || bp->b_blkno < 0) {
594 		bp->b_error = EINVAL;
595 		goto bad;
596 	}
597 	/*
598 	 * If it's a null transfer, return immediatly
599 	 */
600 	if (bp->b_bcount == 0)
601 		goto done;
602 
603 	/*
604 	 * Do bounds checking, adjust transfer. if error, process.
605 	 * If end of partition, just return.
606 	 */
607 	if (SDPART(bp->b_dev) != RAW_PART &&
608 	    bounds_check_with_label(bp, lp,
609 	    (sd->flags & (SDF_WLABEL|SDF_LABELLING)) != 0) <= 0)
610 		goto done;
611 
612 	/*
613 	 * Now convert the block number to absolute and put it in
614 	 * terms of the device's logical block size.
615 	 */
616 	if (lp->d_secsize == DEV_BSIZE)
617 		blkno = bp->b_blkno;
618 	else if (lp->d_secsize > DEV_BSIZE)
619 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
620 	else
621 		blkno = bp->b_blkno * (DEV_BSIZE / lp->d_secsize);
622 
623 	if (SDPART(bp->b_dev) != RAW_PART)
624 		blkno += lp->d_partitions[SDPART(bp->b_dev)].p_offset;
625 
626 	bp->b_rawblkno = blkno;
627 
628 	s = splbio();
629 
630 	/*
631 	 * Place it in the queue of disk activities for this disk
632 	 */
633 	disksort_blkno(&sd->buf_queue, bp);
634 
635 	/*
636 	 * Tell the device to get going on the transfer if it's
637 	 * not doing anything, otherwise just wait for completion
638 	 */
639 	sdstart(sd);
640 
641 	splx(s);
642 	return;
643 
644 bad:
645 	bp->b_flags |= B_ERROR;
646 done:
647 	/*
648 	 * Correctly set the buf to indicate a completed xfer
649 	 */
650 	bp->b_resid = bp->b_bcount;
651 	biodone(bp);
652 }
653 
654 /*
655  * sdstart looks to see if there is a buf waiting for the device
656  * and that the device is not already busy. If both are true,
657  * It dequeues the buf and creates a scsi command to perform the
658  * transfer in the buf. The transfer request will call scsipi_done
659  * on completion, which will in turn call this routine again
660  * so that the next queued transfer is performed.
661  * The bufs are queued by the strategy routine (sdstrategy)
662  *
663  * This routine is also called after other non-queued requests
664  * have been made of the scsi driver, to ensure that the queue
665  * continues to be drained.
666  *
667  * must be called at the correct (highish) spl level
668  * sdstart() is called at splbio from sdstrategy and scsipi_done
669  */
670 void
671 sdstart(v)
672 	void *v;
673 {
674 	struct sd_softc *sd = v;
675 	struct scsipi_link *sc_link = sd->sc_link;
676 	struct disklabel *lp = sd->sc_dk.dk_label;
677 	struct buf *bp = 0;
678 	struct scsipi_rw_big cmd_big;
679 #if NSD_SCSIBUS > 0
680 	struct scsi_rw cmd_small;
681 #endif
682 	struct scsipi_generic *cmdp;
683 	int nblks, cmdlen, error;
684 
685 	SC_DEBUG(sc_link, SDEV_DB2, ("sdstart "));
686 	/*
687 	 * Check if the device has room for another command
688 	 */
689 	while (sc_link->active < sc_link->openings) {
690 		/*
691 		 * there is excess capacity, but a special waits
692 		 * It'll need the adapter as soon as we clear out of the
693 		 * way and let it run (user level wait).
694 		 */
695 		if (sc_link->flags & SDEV_WAITING) {
696 			sc_link->flags &= ~SDEV_WAITING;
697 			wakeup((caddr_t)sc_link);
698 			return;
699 		}
700 
701 		/*
702 		 * See if there is a buf with work for us to do..
703 		 */
704 		if ((bp = BUFQ_FIRST(&sd->buf_queue)) == NULL)
705 			return;
706 		BUFQ_REMOVE(&sd->buf_queue, bp);
707 
708 		/*
709 		 * If the device has become invalid, abort all the
710 		 * reads and writes until all files have been closed and
711 		 * re-opened
712 		 */
713 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
714 			bp->b_error = EIO;
715 			bp->b_flags |= B_ERROR;
716 			bp->b_resid = bp->b_bcount;
717 			biodone(bp);
718 			continue;
719 		}
720 
721 		/*
722 		 * We have a buf, now we should make a command.
723 		 */
724 
725 		if (lp->d_secsize == DEV_BSIZE)
726 			nblks = bp->b_bcount >> DEV_BSHIFT;
727 		else
728 			nblks = howmany(bp->b_bcount, lp->d_secsize);
729 
730 #if NSD_SCSIBUS > 0
731 		/*
732 		 *  Fill out the scsi command.  If the transfer will
733 		 *  fit in a "small" cdb, use it.
734 		 */
735 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
736 		    ((nblks & 0xff) == nblks) && sc_link->type == BUS_SCSI &&
737 		    !(sc_link->quirks & SDEV_ONLYBIG)) {
738 			/*
739 			 * We can fit in a small cdb.
740 			 */
741 			bzero(&cmd_small, sizeof(cmd_small));
742 			cmd_small.opcode = (bp->b_flags & B_READ) ?
743 			    SCSI_READ_COMMAND : SCSI_WRITE_COMMAND;
744 			_lto3b(bp->b_rawblkno, cmd_small.addr);
745 			cmd_small.length = nblks & 0xff;
746 			cmdlen = sizeof(cmd_small);
747 			cmdp = (struct scsipi_generic *)&cmd_small;
748 		} else
749 #endif
750 		{
751 			/*
752 			 * Need a large cdb.
753 			 */
754 			bzero(&cmd_big, sizeof(cmd_big));
755 			cmd_big.opcode = (bp->b_flags & B_READ) ?
756 			    READ_BIG : WRITE_BIG;
757 			_lto4b(bp->b_rawblkno, cmd_big.addr);
758 			_lto2b(nblks, cmd_big.length);
759 			cmdlen = sizeof(cmd_big);
760 			cmdp = (struct scsipi_generic *)&cmd_big;
761 		}
762 
763 		/* Instrumentation. */
764 		disk_busy(&sd->sc_dk);
765 
766 		/*
767 		 * Mark the disk dirty so that the cache will be
768 		 * flushed on close.
769 		 */
770 		if ((bp->b_flags & B_READ) == 0)
771 			sd->flags |= SDF_DIRTY;
772 
773 		/*
774 		 * Call the routine that chats with the adapter.
775 		 * Note: we cannot sleep as we may be an interrupt
776 		 * XXX Really need NOSLEEP?
777 		 */
778 		error = scsipi_command(sc_link, cmdp, cmdlen,
779 		    (u_char *)bp->b_data, bp->b_bcount,
780 		    SDRETRIES, 60000, bp, XS_CTL_NOSLEEP | XS_CTL_ASYNC |
781 		    ((bp->b_flags & B_READ) ?
782 		     XS_CTL_DATA_IN : XS_CTL_DATA_OUT));
783 		if (error) {
784 			disk_unbusy(&sd->sc_dk, 0);
785 			printf("%s: not queued, error %d\n",
786 			    sd->sc_dev.dv_xname, error);
787 		}
788 	}
789 }
790 
791 void
792 sddone(xs)
793 	struct scsipi_xfer *xs;
794 {
795 	struct sd_softc *sd = xs->sc_link->device_softc;
796 
797 	if (sd->flags & SDF_FLUSHING) {
798 		/* Flush completed, no longer dirty. */
799 		sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
800 	}
801 	if (sd->flags & SDF_RESTART) {
802 		sd->flags &= ~SDF_RESTART;
803 		return;
804 	}
805 
806 	if (xs->bp != NULL) {
807 		disk_unbusy(&sd->sc_dk, xs->bp->b_bcount - xs->bp->b_resid);
808 #if NRND > 0
809 		rnd_add_uint32(&sd->rnd_source, xs->bp->b_rawblkno);
810 #endif
811 	}
812 }
813 
814 void
815 sdminphys(bp)
816 	struct buf *bp;
817 {
818 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
819 	long max;
820 
821 	/*
822 	 * If the device is ancient, we want to make sure that
823 	 * the transfer fits into a 6-byte cdb.
824 	 *
825 	 * XXX Note that the SCSI-I spec says that 256-block transfers
826 	 * are allowed in a 6-byte read/write, and are specified
827 	 * by settng the "length" to 0.  However, we're conservative
828 	 * here, allowing only 255-block transfers in case an
829 	 * ancient device gets confused by length == 0.  A length of 0
830 	 * in a 10-byte read/write actually means 0 blocks.
831 	 */
832 	if ((sd->flags & SDF_ANCIENT) &&
833 	    ((sd->sc_link->flags & (SDEV_REMOVABLE | SDEV_MEDIA_LOADED)) !=
834 	     SDEV_REMOVABLE)) {
835 		max = sd->sc_dk.dk_label->d_secsize * 0xff;
836 
837 		if (bp->b_bcount > max)
838 			bp->b_bcount = max;
839 	}
840 
841 	(*sd->sc_link->adapter->scsipi_minphys)(bp);
842 }
843 
844 int
845 sdread(dev, uio, ioflag)
846 	dev_t dev;
847 	struct uio *uio;
848 	int ioflag;
849 {
850 
851 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
852 }
853 
854 int
855 sdwrite(dev, uio, ioflag)
856 	dev_t dev;
857 	struct uio *uio;
858 	int ioflag;
859 {
860 
861 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
862 }
863 
864 /*
865  * Perform special action on behalf of the user
866  * Knows about the internals of this device
867  */
868 int
869 sdioctl(dev, cmd, addr, flag, p)
870 	dev_t dev;
871 	u_long cmd;
872 	caddr_t addr;
873 	int flag;
874 	struct proc *p;
875 {
876 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
877 	int part = SDPART(dev);
878 	int error;
879 #ifdef __HAVE_OLD_DISKLABEL
880 	struct disklabel newlabel;
881 #endif
882 
883 	SC_DEBUG(sd->sc_link, SDEV_DB2, ("sdioctl 0x%lx ", cmd));
884 
885 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
886 		return (ENODEV);
887 
888 	/*
889 	 * If the device is not valid, some IOCTLs can still be
890 	 * handled on the raw partition. Check this here.
891 	 */
892 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
893 		switch (cmd) {
894 		case DIOCKLABEL:
895 		case DIOCWLABEL:
896 		case DIOCLOCK:
897 		case DIOCEJECT:
898 		case ODIOCEJECT:
899 		case SCIOCIDENTIFY:
900 		case OSCIOCIDENTIFY:
901 		case SCIOCCOMMAND:
902 		case SCIOCDEBUG:
903 			if (part == RAW_PART)
904 				break;
905 		/* FALLTHROUGH */
906 		default:
907 			if ((sd->sc_link->flags & SDEV_OPEN) == 0)
908 				return (ENODEV);
909 			else
910 				return (EIO);
911 		}
912 	}
913 
914 	switch (cmd) {
915 	case DIOCGDINFO:
916 		*(struct disklabel *)addr = *(sd->sc_dk.dk_label);
917 		return (0);
918 
919 #ifdef __HAVE_OLD_DISKLABEL
920 	case ODIOCGDINFO:
921 		newlabel = *(sd->sc_dk.dk_label);
922 		if (newlabel.d_npartitions > OLDMAXPARTITIONS)
923 			return ENOTTY;
924 		memcpy(addr, &newlabel, sizeof (struct olddisklabel));
925 		return (0);
926 #endif
927 
928 	case DIOCGPART:
929 		((struct partinfo *)addr)->disklab = sd->sc_dk.dk_label;
930 		((struct partinfo *)addr)->part =
931 		    &sd->sc_dk.dk_label->d_partitions[part];
932 		return (0);
933 
934 	case DIOCWDINFO:
935 	case DIOCSDINFO:
936 #ifdef __HAVE_OLD_DISKLABEL
937 	case ODIOCWDINFO:
938 	case ODIOCSDINFO:
939 #endif
940 	{
941 		struct disklabel *lp;
942 
943 #ifdef __HAVE_OLD_DISKLABEL
944  		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
945 			memset(&newlabel, 0, sizeof newlabel);
946 			memcpy(&newlabel, addr, sizeof (struct olddisklabel));
947 			lp = &newlabel;
948 		} else
949 #endif
950 		lp = (struct disklabel *)addr;
951 
952 		if ((flag & FWRITE) == 0)
953 			return (EBADF);
954 
955 		if ((error = sdlock(sd)) != 0)
956 			return (error);
957 		sd->flags |= SDF_LABELLING;
958 
959 		error = setdisklabel(sd->sc_dk.dk_label,
960 		    lp, /*sd->sc_dk.dk_openmask : */0,
961 		    sd->sc_dk.dk_cpulabel);
962 		if (error == 0) {
963 			if (cmd == DIOCWDINFO
964 #ifdef __HAVE_OLD_DISKLABEL
965 			    || cmd == ODIOCWDINFO
966 #endif
967 			   )
968 				error = writedisklabel(SDLABELDEV(dev),
969 				    sdstrategy, sd->sc_dk.dk_label,
970 				    sd->sc_dk.dk_cpulabel);
971 		}
972 
973 		sd->flags &= ~SDF_LABELLING;
974 		sdunlock(sd);
975 		return (error);
976 	}
977 
978 	case DIOCKLABEL:
979 		if (*(int *)addr)
980 			sd->sc_link->flags |= SDEV_KEEP_LABEL;
981 		else
982 			sd->sc_link->flags &= ~SDEV_KEEP_LABEL;
983 		return (0);
984 
985 	case DIOCWLABEL:
986 		if ((flag & FWRITE) == 0)
987 			return (EBADF);
988 		if (*(int *)addr)
989 			sd->flags |= SDF_WLABEL;
990 		else
991 			sd->flags &= ~SDF_WLABEL;
992 		return (0);
993 
994 	case DIOCLOCK:
995 		return (scsipi_prevent(sd->sc_link,
996 		    (*(int *)addr) ? PR_PREVENT : PR_ALLOW, 0));
997 
998 	case DIOCEJECT:
999 		if ((sd->sc_link->flags & SDEV_REMOVABLE) == 0)
1000 			return (ENOTTY);
1001 		if (*(int *)addr == 0) {
1002 			/*
1003 			 * Don't force eject: check that we are the only
1004 			 * partition open. If so, unlock it.
1005 			 */
1006 			if ((sd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
1007 			    sd->sc_dk.dk_bopenmask + sd->sc_dk.dk_copenmask ==
1008 			    sd->sc_dk.dk_openmask) {
1009 				error = scsipi_prevent(sd->sc_link, PR_ALLOW,
1010 				    XS_CTL_IGNORE_NOT_READY);
1011 				if (error)
1012 					return (error);
1013 			} else {
1014 				return (EBUSY);
1015 			}
1016 		}
1017 		/* FALLTHROUGH */
1018 	case ODIOCEJECT:
1019 		return ((sd->sc_link->flags & SDEV_REMOVABLE) == 0 ? ENOTTY :
1020 		    scsipi_start(sd->sc_link, SSS_STOP|SSS_LOEJ, 0));
1021 
1022 	case DIOCGDEFLABEL:
1023 		sdgetdefaultlabel(sd, (struct disklabel *)addr);
1024 		return (0);
1025 
1026 #ifdef __HAVE_OLD_DISKLABEL
1027 	case ODIOCGDEFLABEL:
1028 		sdgetdefaultlabel(sd, &newlabel);
1029 		if (newlabel.d_npartitions > OLDMAXPARTITIONS)
1030 			return ENOTTY;
1031 		memcpy(addr, &newlabel, sizeof (struct olddisklabel));
1032 		return (0);
1033 #endif
1034 
1035 	default:
1036 		if (part != RAW_PART)
1037 			return (ENOTTY);
1038 		return (scsipi_do_ioctl(sd->sc_link, dev, cmd, addr, flag, p));
1039 	}
1040 
1041 #ifdef DIAGNOSTIC
1042 	panic("sdioctl: impossible");
1043 #endif
1044 }
1045 
1046 void
1047 sdgetdefaultlabel(sd, lp)
1048 	struct sd_softc *sd;
1049 	struct disklabel *lp;
1050 {
1051 
1052 	bzero(lp, sizeof(struct disklabel));
1053 
1054 	lp->d_secsize = sd->params.blksize;
1055 	lp->d_ntracks = sd->params.heads;
1056 	lp->d_nsectors = sd->params.sectors;
1057 	lp->d_ncylinders = sd->params.cyls;
1058 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
1059 
1060 	switch (sd->sc_link->type) {
1061 #if NSD_SCSIBUS > 0
1062 	    case BUS_SCSI:
1063 		lp->d_type = DTYPE_SCSI;
1064 		break;
1065 #endif
1066 #if NSD_ATAPIBUS > 0
1067 	    case BUS_ATAPI:
1068 		lp->d_type = DTYPE_ATAPI;
1069 		break;
1070 #endif
1071 	}
1072 	strncpy(lp->d_typename, sd->name, 16);
1073 	strncpy(lp->d_packname, "fictitious", 16);
1074 	lp->d_secperunit = sd->params.disksize;
1075 	lp->d_rpm = sd->params.rot_rate;
1076 	lp->d_interleave = 1;
1077 	lp->d_flags = 0;
1078 
1079 	lp->d_partitions[RAW_PART].p_offset = 0;
1080 	lp->d_partitions[RAW_PART].p_size =
1081 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
1082 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
1083 	lp->d_npartitions = RAW_PART + 1;
1084 
1085 	lp->d_magic = DISKMAGIC;
1086 	lp->d_magic2 = DISKMAGIC;
1087 	lp->d_checksum = dkcksum(lp);
1088 }
1089 
1090 
1091 /*
1092  * Load the label information on the named device
1093  */
1094 void
1095 sdgetdisklabel(sd)
1096 	struct sd_softc *sd;
1097 {
1098 	struct disklabel *lp = sd->sc_dk.dk_label;
1099 	char *errstring;
1100 
1101 	bzero(sd->sc_dk.dk_cpulabel, sizeof(struct cpu_disklabel));
1102 
1103 	sdgetdefaultlabel(sd, lp);
1104 
1105 	if (lp->d_secpercyl == 0) {
1106 		lp->d_secpercyl = 100;
1107 		/* as long as it's not 0 - readdisklabel divides by it (?) */
1108 	}
1109 
1110 	/*
1111 	 * Call the generic disklabel extraction routine
1112 	 */
1113 	errstring = readdisklabel(MAKESDDEV(0, sd->sc_dev.dv_unit, RAW_PART),
1114 	    sdstrategy, lp, sd->sc_dk.dk_cpulabel);
1115 	if (errstring) {
1116 		printf("%s: %s\n", sd->sc_dev.dv_xname, errstring);
1117 		return;
1118 	}
1119 }
1120 
1121 void
1122 sd_shutdown(arg)
1123 	void *arg;
1124 {
1125 	struct sd_softc *sd = arg;
1126 
1127 	/*
1128 	 * If the disk cache needs to be flushed, and the disk supports
1129 	 * it, flush it.  We're cold at this point, so we poll for
1130 	 * completion.
1131 	 */
1132 	if ((sd->flags & SDF_DIRTY) != 0 && sd->sc_ops->sdo_flush != NULL) {
1133 		if ((*sd->sc_ops->sdo_flush)(sd, XS_CTL_NOSLEEP|XS_CTL_POLL)) {
1134 			printf("%s: cache synchronization failed\n",
1135 			    sd->sc_dev.dv_xname);
1136 			sd->flags &= ~SDF_FLUSHING;
1137 		} else
1138 			sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
1139 	}
1140 }
1141 
1142 /*
1143  * Tell the device to map out a defective block
1144  */
1145 int
1146 sd_reassign_blocks(sd, blkno)
1147 	struct sd_softc *sd;
1148 	u_long blkno;
1149 {
1150 	struct scsi_reassign_blocks scsipi_cmd;
1151 	struct scsi_reassign_blocks_data rbdata;
1152 
1153 	bzero(&scsipi_cmd, sizeof(scsipi_cmd));
1154 	bzero(&rbdata, sizeof(rbdata));
1155 	scsipi_cmd.opcode = SCSI_REASSIGN_BLOCKS;
1156 
1157 	_lto2b(sizeof(rbdata.defect_descriptor[0]), rbdata.length);
1158 	_lto4b(blkno, rbdata.defect_descriptor[0].dlbaddr);
1159 
1160 	return (scsipi_command(sd->sc_link,
1161 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
1162 	    (u_char *)&rbdata, sizeof(rbdata), SDRETRIES, 5000, NULL,
1163 	    XS_CTL_DATA_OUT | XS_CTL_DATA_ONSTACK));
1164 }
1165 
1166 /*
1167  * Check Errors
1168  */
1169 int
1170 sd_interpret_sense(xs)
1171 	struct scsipi_xfer *xs;
1172 {
1173 	struct scsipi_link *sc_link = xs->sc_link;
1174 	struct scsipi_sense_data *sense = &xs->sense.scsi_sense;
1175 	struct sd_softc *sd = sc_link->device_softc;
1176 	int retval = SCSIRET_CONTINUE;
1177 
1178 	/*
1179 	 * If the device is not open yet, let the generic code handle it.
1180 	 */
1181 	if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
1182 		return (retval);
1183 	}
1184 
1185 	/*
1186 	 * If it isn't a extended or extended/deferred error, let
1187 	 * the generic code handle it.
1188 	 */
1189 	if ((sense->error_code & SSD_ERRCODE) != 0x70 &&
1190 	    (sense->error_code & SSD_ERRCODE) != 0x71) {	/* DEFFERRED */
1191 		return (retval);
1192 	}
1193 
1194 	if ((sense->flags & SSD_KEY) == SKEY_NOT_READY &&
1195 	    sense->add_sense_code == 0x4) {
1196 		if (sense->add_sense_code_qual == 0x01)	{
1197 			printf("%s: ..is spinning up...waiting\n",
1198 			    sd->sc_dev.dv_xname);
1199 			/*
1200 			 * I really need a sdrestart function I can call here.
1201 			 */
1202 			delay(1000000 * 5);	/* 5 seconds */
1203 			retval = SCSIRET_RETRY;
1204 		} else if ((sense->add_sense_code_qual == 0x2) &&
1205 		    (sd->sc_link->quirks & SDEV_NOSTARTUNIT) == 0) {
1206 			if (sd->sc_link->flags & SDEV_REMOVABLE) {
1207 				printf(
1208 				"%s: removable disk stopped - not restarting\n",
1209 				    sd->sc_dev.dv_xname);
1210 				retval = EIO;
1211 			} else {
1212 				if (sd->flags & SDF_RESTART)
1213 					return SCSIRET_RETRY;
1214 				sd->flags |= SDF_RESTART;
1215 				printf("%s: respinning up disk\n",
1216 				    sd->sc_dev.dv_xname);
1217 				retval = scsipi_start(sd->sc_link, SSS_START,
1218 				    XS_CTL_URGENT | XS_CTL_NOSLEEP |
1219 				    ((xs->xs_control & XS_CTL_ASYNC) ?
1220 				    XS_CTL_ASYNC : 0));
1221 				if ((xs->xs_control & XS_CTL_ASYNC) == 0)
1222 					sd->flags &= ~SDF_RESTART;
1223 				if (retval != 0) {
1224 					printf(
1225 					    "%s: respin of disk failed - %d\n",
1226 					    sd->sc_dev.dv_xname, retval);
1227 					retval = EIO;
1228 				} else {
1229 					retval = SCSIRET_RETRY;
1230 				}
1231 			}
1232 		}
1233 	}
1234 	return (retval);
1235 }
1236 
1237 
1238 int
1239 sdsize(dev)
1240 	dev_t dev;
1241 {
1242 	struct sd_softc *sd;
1243 	int part, unit, omask;
1244 	int size;
1245 
1246 	unit = SDUNIT(dev);
1247 	if (unit >= sd_cd.cd_ndevs)
1248 		return (-1);
1249 	sd = sd_cd.cd_devs[unit];
1250 	if (sd == NULL)
1251 		return (-1);
1252 
1253 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
1254 		return (-1);
1255 
1256 	part = SDPART(dev);
1257 	omask = sd->sc_dk.dk_openmask & (1 << part);
1258 
1259 	if (omask == 0 && sdopen(dev, 0, S_IFBLK, NULL) != 0)
1260 		return (-1);
1261 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0)
1262 		size = -1;
1263 	else if (sd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
1264 		size = -1;
1265 	else
1266 		size = sd->sc_dk.dk_label->d_partitions[part].p_size *
1267 		    (sd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
1268 	if (omask == 0 && sdclose(dev, 0, S_IFBLK, NULL) != 0)
1269 		return (-1);
1270 	return (size);
1271 }
1272 
1273 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
1274 static struct scsipi_xfer sx;
1275 static int sddoingadump;
1276 
1277 /*
1278  * dump all of physical memory into the partition specified, starting
1279  * at offset 'dumplo' into the partition.
1280  */
1281 int
1282 sddump(dev, blkno, va, size)
1283 	dev_t dev;
1284 	daddr_t blkno;
1285 	caddr_t va;
1286 	size_t size;
1287 {
1288 	struct sd_softc *sd;	/* disk unit to do the I/O */
1289 	struct disklabel *lp;	/* disk's disklabel */
1290 	int	unit, part;
1291 	int	sectorsize;	/* size of a disk sector */
1292 	int	nsects;		/* number of sectors in partition */
1293 	int	sectoff;	/* sector offset of partition */
1294 	int	totwrt;		/* total number of sectors left to write */
1295 	int	nwrt;		/* current number of sectors to write */
1296 	struct scsipi_rw_big cmd;	/* write command */
1297 	struct scsipi_xfer *xs;	/* ... convenience */
1298 	int	retval;
1299 
1300 	/* Check if recursive dump; if so, punt. */
1301 	if (sddoingadump)
1302 		return (EFAULT);
1303 
1304 	/* Mark as active early. */
1305 	sddoingadump = 1;
1306 
1307 	unit = SDUNIT(dev);	/* Decompose unit & partition. */
1308 	part = SDPART(dev);
1309 
1310 	/* Check for acceptable drive number. */
1311 	if (unit >= sd_cd.cd_ndevs || (sd = sd_cd.cd_devs[unit]) == NULL)
1312 		return (ENXIO);
1313 
1314 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
1315 		return (ENODEV);
1316 
1317 	/* Make sure it was initialized. */
1318 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) != SDEV_MEDIA_LOADED)
1319 		return (ENXIO);
1320 
1321 	/* Convert to disk sectors.  Request must be a multiple of size. */
1322 	lp = sd->sc_dk.dk_label;
1323 	sectorsize = lp->d_secsize;
1324 	if ((size % sectorsize) != 0)
1325 		return (EFAULT);
1326 	totwrt = size / sectorsize;
1327 	blkno = dbtob(blkno) / sectorsize;	/* blkno in DEV_BSIZE units */
1328 
1329 	nsects = lp->d_partitions[part].p_size;
1330 	sectoff = lp->d_partitions[part].p_offset;
1331 
1332 	/* Check transfer bounds against partition size. */
1333 	if ((blkno < 0) || ((blkno + totwrt) > nsects))
1334 		return (EINVAL);
1335 
1336 	/* Offset block number to start of partition. */
1337 	blkno += sectoff;
1338 
1339 	xs = &sx;
1340 
1341 	while (totwrt > 0) {
1342 		nwrt = totwrt;		/* XXX */
1343 #ifndef	SD_DUMP_NOT_TRUSTED
1344 		/*
1345 		 *  Fill out the scsi command
1346 		 */
1347 		bzero(&cmd, sizeof(cmd));
1348 		cmd.opcode = WRITE_BIG;
1349 		_lto4b(blkno, cmd.addr);
1350 		_lto2b(nwrt, cmd.length);
1351 		/*
1352 		 * Fill out the scsipi_xfer structure
1353 		 *    Note: we cannot sleep as we may be an interrupt
1354 		 * don't use scsipi_command() as it may want to wait
1355 		 * for an xs.
1356 		 */
1357 		bzero(xs, sizeof(sx));
1358 		xs->xs_control |= XS_CTL_NOSLEEP | XS_CTL_POLL |
1359 		    XS_CTL_DATA_OUT;
1360 		xs->xs_status = 0;
1361 		xs->sc_link = sd->sc_link;
1362 		xs->retries = SDRETRIES;
1363 		xs->timeout = 10000;	/* 10000 millisecs for a disk ! */
1364 		xs->cmd = (struct scsipi_generic *)&cmd;
1365 		xs->cmdlen = sizeof(cmd);
1366 		xs->resid = nwrt * sectorsize;
1367 		xs->error = XS_NOERROR;
1368 		xs->bp = 0;
1369 		xs->data = va;
1370 		xs->datalen = nwrt * sectorsize;
1371 
1372 		/*
1373 		 * Pass all this info to the scsi driver.
1374 		 */
1375 		retval = scsipi_command_direct(xs);
1376 		if (retval != COMPLETE)
1377 			return (ENXIO);
1378 #else	/* SD_DUMP_NOT_TRUSTED */
1379 		/* Let's just talk about this first... */
1380 		printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
1381 		delay(500 * 1000);	/* half a second */
1382 #endif	/* SD_DUMP_NOT_TRUSTED */
1383 
1384 		/* update block count */
1385 		totwrt -= nwrt;
1386 		blkno += nwrt;
1387 		va += sectorsize * nwrt;
1388 	}
1389 	sddoingadump = 0;
1390 	return (0);
1391 }
1392