xref: /netbsd-src/sys/dev/scsipi/sd.c (revision bada23909e740596d0a3785a73bd3583a9807fb8)
1 /*	$NetBSD: sd.c,v 1.144 1999/02/28 17:14:57 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 #if NRND > 0
77 #include <sys/rnd.h>
78 #endif
79 
80 #include <dev/scsipi/scsipi_all.h>
81 #include <dev/scsipi/scsi_all.h>
82 #include <dev/scsipi/scsipi_disk.h>
83 #include <dev/scsipi/scsi_disk.h>
84 #include <dev/scsipi/scsiconf.h>
85 #include <dev/scsipi/sdvar.h>
86 
87 #include "sd.h"		/* NSD_SCSIBUS and NSD_ATAPIBUS come from here */
88 
89 #ifndef	SDOUTSTANDING
90 #define	SDOUTSTANDING	4
91 #endif
92 
93 #define	SDUNIT(dev)			DISKUNIT(dev)
94 #define	SDPART(dev)			DISKPART(dev)
95 #define	MAKESDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
96 
97 #define	SDLABELDEV(dev)	(MAKESDDEV(major(dev), SDUNIT(dev), RAW_PART))
98 
99 int	sdlock __P((struct sd_softc *));
100 void	sdunlock __P((struct sd_softc *));
101 void	sdminphys __P((struct buf *));
102 void	sdgetdefaultlabel __P((struct sd_softc *, struct disklabel *));
103 void	sdgetdisklabel __P((struct sd_softc *));
104 void	sdstart __P((void *));
105 void	sddone __P((struct scsipi_xfer *));
106 void	sd_shutdown __P((void *));
107 int	sd_reassign_blocks __P((struct sd_softc *, u_long));
108 int	sd_interpret_sense __P((struct scsipi_xfer *));
109 
110 extern struct cfdriver sd_cd;
111 
112 struct dkdriver sddkdriver = { sdstrategy };
113 
114 struct scsipi_device sd_switch = {
115 	sd_interpret_sense,	/* check our error handler first */
116 	sdstart,		/* have a queue, served by this */
117 	NULL,			/* have no async handler */
118 	sddone,			/* deal with stats at interrupt time */
119 };
120 
121 /*
122  * The routine called by the low level scsi routine when it discovers
123  * a device suitable for this driver.
124  */
125 void
126 sdattach(parent, sd, sc_link, ops)
127 	struct device *parent;
128 	struct sd_softc *sd;
129 	struct scsipi_link *sc_link;
130 	const struct sd_ops *ops;
131 {
132 	int error, result;
133 	struct disk_parms *dp = &sd->params;
134 
135 	SC_DEBUG(sc_link, SDEV_DB2, ("sdattach: "));
136 
137 	/*
138 	 * Store information needed to contact our base driver
139 	 */
140 	sd->sc_link = sc_link;
141 	sd->sc_ops = ops;
142 	sc_link->device = &sd_switch;
143 	sc_link->device_softc = sd;
144 	if (sc_link->openings > SDOUTSTANDING)
145 		sc_link->openings = SDOUTSTANDING;
146 
147 	/*
148 	 * Initialize and attach the disk structure.
149 	 */
150 	sd->sc_dk.dk_driver = &sddkdriver;
151 	sd->sc_dk.dk_name = sd->sc_dev.dv_xname;
152 	disk_attach(&sd->sc_dk);
153 
154 #if !defined(i386)
155 	dk_establish(&sd->sc_dk, &sd->sc_dev);		/* XXX */
156 #endif
157 
158 	/*
159 	 * Use the subdriver to request information regarding
160 	 * the drive. We cannot use interrupts yet, so the
161 	 * request must specify this.
162 	 */
163 	printf("\n");
164 
165 	error = scsipi_start(sd->sc_link, SSS_START,
166 	    SCSI_AUTOCONF | SCSI_IGNORE_ILLEGAL_REQUEST |
167 	    SCSI_IGNORE_MEDIA_CHANGE | SCSI_SILENT);
168 
169 	if (error)
170 		result = SDGP_RESULT_OFFLINE;
171 	else
172 		result = (*sd->sc_ops->sdo_get_parms)(sd, &sd->params,
173 		    SCSI_AUTOCONF);
174 	printf("%s: ", sd->sc_dev.dv_xname);
175 	switch (result) {
176 	case SDGP_RESULT_OK:
177 	        printf("%ldMB, %ld cyl, %ld head, %ld sec, %ld bytes/sect x %ld sectors",
178 		    dp->disksize / (1048576 / dp->blksize), dp->cyls,
179 		    dp->heads, dp->sectors, dp->blksize, dp->disksize);
180 		break;
181 
182 	case SDGP_RESULT_OFFLINE:
183 		printf("drive offline");
184 		break;
185 
186 	case SDGP_RESULT_UNFORMATTED:
187 		printf("unformatted media");
188 		break;
189 
190 #ifdef DIAGNOSTIC
191 	default:
192 		panic("sdattach: unknown result from get_parms");
193 		break;
194 #endif
195 	}
196 	printf("\n");
197 
198 	/*
199 	 * Establish a shutdown hook so that we can ensure that
200 	 * our data has actually made it onto the platter at
201 	 * shutdown time.  Note that this relies on the fact
202 	 * that the shutdown hook code puts us at the head of
203 	 * the list (thus guaranteeing that our hook runs before
204 	 * our ancestors').
205 	 */
206 	if ((sd->sc_sdhook =
207 	    shutdownhook_establish(sd_shutdown, sd)) == NULL)
208 		printf("%s: WARNING: unable to establish shutdown hook\n",
209 		    sd->sc_dev.dv_xname);
210 
211 #if NRND > 0
212 	/*
213 	 * attach the device into the random source list
214 	 */
215 	rnd_attach_source(&sd->rnd_source, sd->sc_dev.dv_xname,
216 			  RND_TYPE_DISK, 0);
217 #endif
218 }
219 
220 /*
221  * Wait interruptibly for an exclusive lock.
222  *
223  * XXX
224  * Several drivers do this; it should be abstracted and made MP-safe.
225  */
226 int
227 sdlock(sd)
228 	struct sd_softc *sd;
229 {
230 	int error;
231 
232 	while ((sd->flags & SDF_LOCKED) != 0) {
233 		sd->flags |= SDF_WANTED;
234 		if ((error = tsleep(sd, PRIBIO | PCATCH, "sdlck", 0)) != 0)
235 			return (error);
236 	}
237 	sd->flags |= SDF_LOCKED;
238 	return (0);
239 }
240 
241 /*
242  * Unlock and wake up any waiters.
243  */
244 void
245 sdunlock(sd)
246 	struct sd_softc *sd;
247 {
248 
249 	sd->flags &= ~SDF_LOCKED;
250 	if ((sd->flags & SDF_WANTED) != 0) {
251 		sd->flags &= ~SDF_WANTED;
252 		wakeup(sd);
253 	}
254 }
255 
256 /*
257  * open the device. Make sure the partition info is a up-to-date as can be.
258  */
259 int
260 sdopen(dev, flag, fmt, p)
261 	dev_t dev;
262 	int flag, fmt;
263 	struct proc *p;
264 {
265 	struct sd_softc *sd;
266 	struct scsipi_link *sc_link;
267 	int unit, part;
268 	int error;
269 
270 	unit = SDUNIT(dev);
271 	if (unit >= sd_cd.cd_ndevs)
272 		return (ENXIO);
273 	sd = sd_cd.cd_devs[unit];
274 	if (sd == NULL)
275 		return (ENXIO);
276 
277 	sc_link = sd->sc_link;
278 	part = SDPART(dev);
279 
280 	SC_DEBUG(sc_link, SDEV_DB1,
281 	    ("sdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev, unit,
282 	    sd_cd.cd_ndevs, part));
283 
284 	/*
285 	 * If this is the first open of this device, add a reference
286 	 * to the adapter.
287 	 */
288 	if (sd->sc_dk.dk_openmask == 0 &&
289 	    (error = scsipi_adapter_addref(sc_link)) != 0)
290 		return (error);
291 
292 	if ((error = sdlock(sd)) != 0)
293 		goto bad4;
294 
295 	if ((sc_link->flags & SDEV_OPEN) != 0) {
296 		/*
297 		 * If any partition is open, but the disk has been invalidated,
298 		 * disallow further opens of non-raw partition
299 		 */
300 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0 &&
301 		    (part != RAW_PART || fmt != S_IFCHR)) {
302 			error = EIO;
303 			goto bad3;
304 		}
305 	} else {
306 		/* Check that it is still responding and ok. */
307 		error = scsipi_test_unit_ready(sc_link,
308 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE |
309 		    SCSI_IGNORE_NOT_READY);
310 		if (error)
311 			goto bad3;
312 
313 		/*
314 		 * Start the pack spinning if necessary. Always allow the
315 		 * raw parition to be opened, for raw IOCTLs. Data transfers
316 		 * will check for SDEV_MEDIA_LOADED.
317 		 */
318 		error = scsipi_start(sc_link, SSS_START,
319 		    SCSI_IGNORE_ILLEGAL_REQUEST |
320 		    SCSI_IGNORE_MEDIA_CHANGE | SCSI_SILENT);
321 		if (error) {
322 			if (part != RAW_PART || fmt != S_IFCHR)
323 				goto bad3;
324 			else
325 				goto out;
326 		}
327 
328 		sc_link->flags |= SDEV_OPEN;
329 
330 		/* Lock the pack in. */
331 		error = scsipi_prevent(sc_link, PR_PREVENT,
332 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE);
333 		if (error)
334 			goto bad;
335 
336 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
337 			sc_link->flags |= SDEV_MEDIA_LOADED;
338 
339 			/*
340 			 * Load the physical device parameters.
341 			 *
342 			 * Note that if media is present but unformatted,
343 			 * we allow the open (so that it can be formatted!).
344 			 * The drive should refuse real I/O, if the media is
345 			 * unformatted.
346 			 */
347 			if ((*sd->sc_ops->sdo_get_parms)(sd, &sd->params,
348 			    0) == SDGP_RESULT_OFFLINE) {
349 				error = ENXIO;
350 				goto bad2;
351 			}
352 			SC_DEBUG(sc_link, SDEV_DB3, ("Params loaded "));
353 
354 			/* Load the partition info if not already loaded. */
355 			sdgetdisklabel(sd);
356 			SC_DEBUG(sc_link, SDEV_DB3, ("Disklabel loaded "));
357 		}
358 	}
359 
360 	/* Check that the partition exists. */
361 	if (part != RAW_PART &&
362 	    (part >= sd->sc_dk.dk_label->d_npartitions ||
363 	     sd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
364 		error = ENXIO;
365 		goto bad;
366 	}
367 
368 out:	/* Insure only one open at a time. */
369 	switch (fmt) {
370 	case S_IFCHR:
371 		sd->sc_dk.dk_copenmask |= (1 << part);
372 		break;
373 	case S_IFBLK:
374 		sd->sc_dk.dk_bopenmask |= (1 << part);
375 		break;
376 	}
377 	sd->sc_dk.dk_openmask =
378 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
379 
380 	SC_DEBUG(sc_link, SDEV_DB3, ("open complete\n"));
381 	sdunlock(sd);
382 	return (0);
383 
384 bad2:
385 	sc_link->flags &= ~SDEV_MEDIA_LOADED;
386 
387 bad:
388 	if (sd->sc_dk.dk_openmask == 0) {
389 		scsipi_prevent(sc_link, PR_ALLOW,
390 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE);
391 		sc_link->flags &= ~SDEV_OPEN;
392 	}
393 
394 bad3:
395 	sdunlock(sd);
396 bad4:
397 	if (sd->sc_dk.dk_openmask == 0)
398 		scsipi_adapter_delref(sc_link);
399 	return (error);
400 }
401 
402 /*
403  * close the device.. only called if we are the LAST occurence of an open
404  * device.  Convenient now but usually a pain.
405  */
406 int
407 sdclose(dev, flag, fmt, p)
408 	dev_t dev;
409 	int flag, fmt;
410 	struct proc *p;
411 {
412 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
413 	int part = SDPART(dev);
414 	int error;
415 
416 	if ((error = sdlock(sd)) != 0)
417 		return (error);
418 
419 	switch (fmt) {
420 	case S_IFCHR:
421 		sd->sc_dk.dk_copenmask &= ~(1 << part);
422 		break;
423 	case S_IFBLK:
424 		sd->sc_dk.dk_bopenmask &= ~(1 << part);
425 		break;
426 	}
427 	sd->sc_dk.dk_openmask =
428 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
429 
430 	if (sd->sc_dk.dk_openmask == 0) {
431 		/*
432 		 * If the disk cache needs flushing, and the disk supports
433 		 * it, do it now.
434 		 */
435 		if ((sd->flags & SDF_DIRTY) != 0 &&
436 		    sd->sc_ops->sdo_flush != NULL)
437 			(*sd->sc_ops->sdo_flush)(sd, 0);
438 
439 		scsipi_wait_drain(sd->sc_link);
440 
441 		scsipi_prevent(sd->sc_link, PR_ALLOW,
442 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_NOT_READY);
443 		sd->sc_link->flags &= ~SDEV_OPEN;
444 
445 		scsipi_wait_drain(sd->sc_link);
446 
447 		scsipi_adapter_delref(sd->sc_link);
448 	}
449 
450 	sdunlock(sd);
451 	return (0);
452 }
453 
454 /*
455  * Actually translate the requested transfer into one the physical driver
456  * can understand.  The transfer is described by a buf and will include
457  * only one physical transfer.
458  */
459 void
460 sdstrategy(bp)
461 	struct buf *bp;
462 {
463 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
464 	int s;
465 
466 	SC_DEBUG(sd->sc_link, SDEV_DB2, ("sdstrategy "));
467 	SC_DEBUG(sd->sc_link, SDEV_DB1,
468 	    ("%ld bytes @ blk %d\n", bp->b_bcount, bp->b_blkno));
469 	/*
470 	 * If the device has been made invalid, error out
471 	 */
472 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
473 		if (sd->sc_link->flags & SDEV_OPEN)
474 			bp->b_error = EIO;
475 		else
476 			bp->b_error = ENODEV;
477 		goto bad;
478 	}
479 	/*
480 	 * The transfer must be a whole number of blocks, offset must not be
481 	 * negative.
482 	 */
483 	if ((bp->b_bcount % sd->sc_dk.dk_label->d_secsize) != 0 ||
484 	    bp->b_blkno < 0) {
485 		bp->b_error = EINVAL;
486 		goto bad;
487 	}
488 	/*
489 	 * If it's a null transfer, return immediatly
490 	 */
491 	if (bp->b_bcount == 0)
492 		goto done;
493 
494 	/*
495 	 * Do bounds checking, adjust transfer. if error, process.
496 	 * If end of partition, just return.
497 	 */
498 	if (SDPART(bp->b_dev) != RAW_PART &&
499 	    bounds_check_with_label(bp, sd->sc_dk.dk_label,
500 	    (sd->flags & (SDF_WLABEL|SDF_LABELLING)) != 0) <= 0)
501 		goto done;
502 
503 	s = splbio();
504 
505 	/*
506 	 * Place it in the queue of disk activities for this disk
507 	 */
508 	disksort(&sd->buf_queue, bp);
509 
510 	/*
511 	 * Tell the device to get going on the transfer if it's
512 	 * not doing anything, otherwise just wait for completion
513 	 */
514 	sdstart(sd);
515 
516 	splx(s);
517 	return;
518 
519 bad:
520 	bp->b_flags |= B_ERROR;
521 done:
522 	/*
523 	 * Correctly set the buf to indicate a completed xfer
524 	 */
525 	bp->b_resid = bp->b_bcount;
526 	biodone(bp);
527 }
528 
529 /*
530  * sdstart looks to see if there is a buf waiting for the device
531  * and that the device is not already busy. If both are true,
532  * It dequeues the buf and creates a scsi command to perform the
533  * transfer in the buf. The transfer request will call scsipi_done
534  * on completion, which will in turn call this routine again
535  * so that the next queued transfer is performed.
536  * The bufs are queued by the strategy routine (sdstrategy)
537  *
538  * This routine is also called after other non-queued requests
539  * have been made of the scsi driver, to ensure that the queue
540  * continues to be drained.
541  *
542  * must be called at the correct (highish) spl level
543  * sdstart() is called at splbio from sdstrategy and scsipi_done
544  */
545 void
546 sdstart(v)
547 	register void *v;
548 {
549 	register struct sd_softc *sd = v;
550 	register struct	scsipi_link *sc_link = sd->sc_link;
551 	struct disklabel *lp = sd->sc_dk.dk_label;
552 	struct buf *bp = 0;
553 	struct buf *dp;
554 	struct scsipi_rw_big cmd_big;
555 #if NSD_SCSIBUS > 0
556 	struct scsi_rw cmd_small;
557 #endif
558 	struct scsipi_generic *cmdp;
559 	int blkno, nblks, cmdlen, error;
560 	struct partition *p;
561 
562 	SC_DEBUG(sc_link, SDEV_DB2, ("sdstart "));
563 	/*
564 	 * Check if the device has room for another command
565 	 */
566 	while (sc_link->openings > 0) {
567 		/*
568 		 * there is excess capacity, but a special waits
569 		 * It'll need the adapter as soon as we clear out of the
570 		 * way and let it run (user level wait).
571 		 */
572 		if (sc_link->flags & SDEV_WAITING) {
573 			sc_link->flags &= ~SDEV_WAITING;
574 			wakeup((caddr_t)sc_link);
575 			return;
576 		}
577 
578 		/*
579 		 * See if there is a buf with work for us to do..
580 		 */
581 		dp = &sd->buf_queue;
582 		if ((bp = dp->b_actf) == NULL)	/* yes, an assign */
583 			return;
584 		dp->b_actf = bp->b_actf;
585 
586 		/*
587 		 * If the device has become invalid, abort all the
588 		 * reads and writes until all files have been closed and
589 		 * re-opened
590 		 */
591 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
592 			bp->b_error = EIO;
593 			bp->b_flags |= B_ERROR;
594 			bp->b_resid = bp->b_bcount;
595 			biodone(bp);
596 			continue;
597 		}
598 
599 		/*
600 		 * We have a buf, now we should make a command
601 		 *
602 		 * First, translate the block to absolute and put it in terms
603 		 * of the logical blocksize of the device.
604 		 */
605 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
606 		if (SDPART(bp->b_dev) != RAW_PART) {
607 			p = &lp->d_partitions[SDPART(bp->b_dev)];
608 			blkno += p->p_offset;
609 		}
610 		nblks = howmany(bp->b_bcount, lp->d_secsize);
611 
612 #if NSD_SCSIBUS > 0
613 		/*
614 		 *  Fill out the scsi command.  If the transfer will
615 		 *  fit in a "small" cdb, use it.
616 		 */
617 		if (((blkno & 0x1fffff) == blkno) &&
618 		    ((nblks & 0xff) == nblks) && sc_link->type == BUS_SCSI) {
619 			/*
620 			 * We can fit in a small cdb.
621 			 */
622 			bzero(&cmd_small, sizeof(cmd_small));
623 			cmd_small.opcode = (bp->b_flags & B_READ) ?
624 			    SCSI_READ_COMMAND : SCSI_WRITE_COMMAND;
625 			_lto3b(blkno, cmd_small.addr);
626 			cmd_small.length = nblks & 0xff;
627 			cmdlen = sizeof(cmd_small);
628 			cmdp = (struct scsipi_generic *)&cmd_small;
629 		} else
630 #endif
631 		{
632 			/*
633 			 * Need a large cdb.
634 			 */
635 			bzero(&cmd_big, sizeof(cmd_big));
636 			cmd_big.opcode = (bp->b_flags & B_READ) ?
637 			    READ_BIG : WRITE_BIG;
638 			_lto4b(blkno, cmd_big.addr);
639 			_lto2b(nblks, cmd_big.length);
640 			cmdlen = sizeof(cmd_big);
641 			cmdp = (struct scsipi_generic *)&cmd_big;
642 		}
643 
644 		/* Instrumentation. */
645 		disk_busy(&sd->sc_dk);
646 
647 		/*
648 		 * Mark the disk dirty so that the cache will be
649 		 * flushed on close.
650 		 */
651 		if ((bp->b_flags & B_READ) == 0)
652 			sd->flags |= SDF_DIRTY;
653 
654 		/*
655 		 * Call the routine that chats with the adapter.
656 		 * Note: we cannot sleep as we may be an interrupt
657 		 */
658 		error = scsipi_command(sc_link, cmdp, cmdlen,
659 		    (u_char *)bp->b_data, bp->b_bcount,
660 		    SDRETRIES, 60000, bp, SCSI_NOSLEEP |
661 		    ((bp->b_flags & B_READ) ? SCSI_DATA_IN : SCSI_DATA_OUT));
662 		if (error) {
663 			disk_unbusy(&sd->sc_dk, 0);
664 			printf("%s: not queued, error %d\n",
665 			    sd->sc_dev.dv_xname, error);
666 		}
667 	}
668 }
669 
670 void
671 sddone(xs)
672 	struct scsipi_xfer *xs;
673 {
674 	struct sd_softc *sd = xs->sc_link->device_softc;
675 
676 	if (sd->flags & SDF_FLUSHING) {
677 		/* Flush completed, no longer dirty. */
678 		sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
679 	}
680 
681 	if (xs->bp != NULL) {
682 		disk_unbusy(&sd->sc_dk, xs->bp->b_bcount - xs->bp->b_resid);
683 #if NRND > 0
684 		rnd_add_uint32(&sd->rnd_source, xs->bp->b_blkno);
685 #endif
686 	}
687 }
688 
689 void
690 sdminphys(bp)
691 	struct buf *bp;
692 {
693 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
694 	long max;
695 
696 	/*
697 	 * If the device is ancient, we want to make sure that
698 	 * the transfer fits into a 6-byte cdb.
699 	 *
700 	 * XXX Note that the SCSI-I spec says that 256-block transfers
701 	 * are allowed in a 6-byte read/write, and are specified
702 	 * by settng the "length" to 0.  However, we're conservative
703 	 * here, allowing only 255-block transfers in case an
704 	 * ancient device gets confused by length == 0.  A length of 0
705 	 * in a 10-byte read/write actually means 0 blocks.
706 	 */
707 	if (sd->flags & SDF_ANCIENT) {
708 		max = sd->sc_dk.dk_label->d_secsize * 0xff;
709 
710 		if (bp->b_bcount > max)
711 			bp->b_bcount = max;
712 	}
713 
714 	(*sd->sc_link->adapter->scsipi_minphys)(bp);
715 }
716 
717 int
718 sdread(dev, uio, ioflag)
719 	dev_t dev;
720 	struct uio *uio;
721 	int ioflag;
722 {
723 
724 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
725 }
726 
727 int
728 sdwrite(dev, uio, ioflag)
729 	dev_t dev;
730 	struct uio *uio;
731 	int ioflag;
732 {
733 
734 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
735 }
736 
737 /*
738  * Perform special action on behalf of the user
739  * Knows about the internals of this device
740  */
741 int
742 sdioctl(dev, cmd, addr, flag, p)
743 	dev_t dev;
744 	u_long cmd;
745 	caddr_t addr;
746 	int flag;
747 	struct proc *p;
748 {
749 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
750 	int part = SDPART(dev);
751 	int error;
752 
753 	SC_DEBUG(sd->sc_link, SDEV_DB2, ("sdioctl 0x%lx ", cmd));
754 
755 	/*
756 	 * If the device is not valid, some IOCTLs can still be
757 	 * handled on the raw partition. Check this here.
758 	 */
759 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
760 		switch (cmd) {
761 		case DIOCWLABEL:
762 		case DIOCLOCK:
763 		case DIOCEJECT:
764 		case ODIOCEJECT:
765 		case SCIOCIDENTIFY:
766 		case OSCIOCIDENTIFY:
767 		case SCIOCCOMMAND:
768 		case SCIOCDEBUG:
769 			if (part == RAW_PART)
770 				break;
771 		/* FALLTHROUGH */
772 		default:
773 			if ((sd->sc_link->flags & SDEV_OPEN) == 0)
774 				return (ENODEV);
775 			else
776 				return (EIO);
777 		}
778 	}
779 
780 	switch (cmd) {
781 	case DIOCGDINFO:
782 		*(struct disklabel *)addr = *(sd->sc_dk.dk_label);
783 		return (0);
784 
785 	case DIOCGPART:
786 		((struct partinfo *)addr)->disklab = sd->sc_dk.dk_label;
787 		((struct partinfo *)addr)->part =
788 		    &sd->sc_dk.dk_label->d_partitions[part];
789 		return (0);
790 
791 	case DIOCWDINFO:
792 	case DIOCSDINFO:
793 		if ((flag & FWRITE) == 0)
794 			return (EBADF);
795 
796 		if ((error = sdlock(sd)) != 0)
797 			return (error);
798 		sd->flags |= SDF_LABELLING;
799 
800 		error = setdisklabel(sd->sc_dk.dk_label,
801 		    (struct disklabel *)addr, /*sd->sc_dk.dk_openmask : */0,
802 		    sd->sc_dk.dk_cpulabel);
803 		if (error == 0) {
804 			if (cmd == DIOCWDINFO)
805 				error = writedisklabel(SDLABELDEV(dev),
806 				    sdstrategy, sd->sc_dk.dk_label,
807 				    sd->sc_dk.dk_cpulabel);
808 		}
809 
810 		sd->flags &= ~SDF_LABELLING;
811 		sdunlock(sd);
812 		return (error);
813 
814 	case DIOCWLABEL:
815 		if ((flag & FWRITE) == 0)
816 			return (EBADF);
817 		if (*(int *)addr)
818 			sd->flags |= SDF_WLABEL;
819 		else
820 			sd->flags &= ~SDF_WLABEL;
821 		return (0);
822 
823 	case DIOCLOCK:
824 		return (scsipi_prevent(sd->sc_link,
825 		    (*(int *)addr) ? PR_PREVENT : PR_ALLOW, 0));
826 
827 	case DIOCEJECT:
828 		if ((sd->sc_link->flags & SDEV_REMOVABLE) == 0)
829 			return (ENOTTY);
830 		if (*(int *)addr == 0) {
831 			/*
832 			 * Don't force eject: check that we are the only
833 			 * partition open. If so, unlock it.
834 			 */
835 			if ((sd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
836 			    sd->sc_dk.dk_bopenmask + sd->sc_dk.dk_copenmask ==
837 			    sd->sc_dk.dk_openmask) {
838 				error =  scsipi_prevent(sd->sc_link, PR_ALLOW,
839 				    SCSI_IGNORE_NOT_READY);
840 				if (error)
841 					return (error);
842 			} else {
843 				return (EBUSY);
844 			}
845 		}
846 		/* FALLTHROUGH */
847 	case ODIOCEJECT:
848 		return ((sd->sc_link->flags & SDEV_REMOVABLE) == 0 ? ENOTTY :
849 		    scsipi_start(sd->sc_link, SSS_STOP|SSS_LOEJ, 0));
850 
851 	case DIOCGDEFLABEL:
852 		sdgetdefaultlabel(sd, (struct disklabel *)addr);
853 		return (0);
854 
855 	default:
856 		if (part != RAW_PART)
857 			return (ENOTTY);
858 		return (scsipi_do_ioctl(sd->sc_link, dev, cmd, addr, flag, p));
859 	}
860 
861 #ifdef DIAGNOSTIC
862 	panic("sdioctl: impossible");
863 #endif
864 }
865 
866 void
867 sdgetdefaultlabel(sd, lp)
868 	struct sd_softc *sd;
869 	struct disklabel *lp;
870 {
871 
872 	bzero(lp, sizeof(struct disklabel));
873 
874 	lp->d_secsize = sd->params.blksize;
875 	lp->d_ntracks = sd->params.heads;
876 	lp->d_nsectors = sd->params.sectors;
877 	lp->d_ncylinders = sd->params.cyls;
878 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
879 
880 	switch (sd->sc_link->type) {
881 #if NSD_SCSIBUS > 0
882 	    case BUS_SCSI:
883 		lp->d_type = DTYPE_SCSI;
884 		break;
885 #endif
886 #if NSD_ATAPIBUS > 0
887 	    case BUS_ATAPI:
888 		lp->d_type = DTYPE_ATAPI;
889 		break;
890 #endif
891 	}
892 	strncpy(lp->d_typename, sd->name, 16);
893 	strncpy(lp->d_packname, "fictitious", 16);
894 	lp->d_secperunit = sd->params.disksize;
895 	lp->d_rpm = sd->params.rot_rate;
896 	lp->d_interleave = 1;
897 	lp->d_flags = 0;
898 
899 	lp->d_partitions[RAW_PART].p_offset = 0;
900 	lp->d_partitions[RAW_PART].p_size =
901 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
902 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
903 	lp->d_npartitions = RAW_PART + 1;
904 
905 	lp->d_magic = DISKMAGIC;
906 	lp->d_magic2 = DISKMAGIC;
907 	lp->d_checksum = dkcksum(lp);
908 }
909 
910 
911 /*
912  * Load the label information on the named device
913  */
914 void
915 sdgetdisklabel(sd)
916 	struct sd_softc *sd;
917 {
918 	struct disklabel *lp = sd->sc_dk.dk_label;
919 	char *errstring;
920 
921 	bzero(sd->sc_dk.dk_cpulabel, sizeof(struct cpu_disklabel));
922 
923 	sdgetdefaultlabel(sd, lp);
924 
925 	if (lp->d_secpercyl == 0) {
926 		lp->d_secpercyl = 100;
927 		/* as long as it's not 0 - readdisklabel divides by it (?) */
928 	}
929 
930 	/*
931 	 * Call the generic disklabel extraction routine
932 	 */
933 	errstring = readdisklabel(MAKESDDEV(0, sd->sc_dev.dv_unit, RAW_PART),
934 	    sdstrategy, lp, sd->sc_dk.dk_cpulabel);
935 	if (errstring) {
936 		printf("%s: %s\n", sd->sc_dev.dv_xname, errstring);
937 		return;
938 	}
939 }
940 
941 void
942 sd_shutdown(arg)
943 	void *arg;
944 {
945 	struct sd_softc *sd = arg;
946 
947 	/*
948 	 * If the disk cache needs to be flushed, and the disk supports
949 	 * it, flush it.  We're cold at this point, so we poll for
950 	 * completion.
951 	 */
952 	if ((sd->flags & SDF_DIRTY) != 0 && sd->sc_ops->sdo_flush != NULL)
953 		(*sd->sc_ops->sdo_flush)(sd, SCSI_AUTOCONF);
954 }
955 
956 /*
957  * Tell the device to map out a defective block
958  */
959 int
960 sd_reassign_blocks(sd, blkno)
961 	struct sd_softc *sd;
962 	u_long blkno;
963 {
964 	struct scsi_reassign_blocks scsipi_cmd;
965 	struct scsi_reassign_blocks_data rbdata;
966 
967 	bzero(&scsipi_cmd, sizeof(scsipi_cmd));
968 	bzero(&rbdata, sizeof(rbdata));
969 	scsipi_cmd.opcode = SCSI_REASSIGN_BLOCKS;
970 
971 	_lto2b(sizeof(rbdata.defect_descriptor[0]), rbdata.length);
972 	_lto4b(blkno, rbdata.defect_descriptor[0].dlbaddr);
973 
974 	return (scsipi_command(sd->sc_link,
975 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
976 	    (u_char *)&rbdata, sizeof(rbdata), SDRETRIES, 5000, NULL,
977 	    SCSI_DATA_OUT));
978 }
979 
980 /*
981  * Check Errors
982  */
983 int
984 sd_interpret_sense(xs)
985 	struct scsipi_xfer *xs;
986 {
987 	struct scsipi_link *sc_link = xs->sc_link;
988 	struct scsipi_sense_data *sense = &xs->sense.scsi_sense;
989 	struct sd_softc *sd = sc_link->device_softc;
990 	int retval = SCSIRET_CONTINUE;
991 
992 	/*
993 	 * If the device is not open yet, let the generic code handle it.
994 	 */
995 	if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
996 		return (retval);
997 	}
998 
999 	/*
1000 	 * If it isn't a extended or extended/deferred error, let
1001 	 * the generic code handle it.
1002 	 */
1003 	if ((sense->error_code & SSD_ERRCODE) != 0x70 &&
1004 	    (sense->error_code & SSD_ERRCODE) != 0x71) {	/* DEFFERRED */
1005 		return (retval);
1006 	}
1007 
1008 	if ((sense->flags & SSD_KEY) == SKEY_NOT_READY &&
1009 	    sense->add_sense_code == 0x4) {
1010 		if (sense->add_sense_code_qual == 0x01)	{
1011 			printf("%s: ..is spinning up...waiting\n",
1012 			    sd->sc_dev.dv_xname);
1013 			/*
1014 			 * I really need a sdrestart function I can call here.
1015 			 */
1016 			delay(1000000 * 5);	/* 5 seconds */
1017 			retval = SCSIRET_RETRY;
1018 		} else if ((sense->add_sense_code_qual == 0x2) &&
1019 		    (sd->sc_link->quirks & SDEV_NOSTARTUNIT) == 0) {
1020 			if (sd->sc_link->flags & SDEV_REMOVABLE) {
1021 				printf("%s: removable disk stopped- not "
1022 				    "restarting\n", sd->sc_dev.dv_xname);
1023 				retval = EIO;
1024 			} else {
1025 				printf("%s: respinning up disk\n",
1026 				    sd->sc_dev.dv_xname);
1027 				retval = scsipi_start(sd->sc_link, SSS_START,
1028 				    SCSI_URGENT | SCSI_NOSLEEP);
1029 				if (retval != 0) {
1030 					printf("%s: respin of disk failed-%d\n",
1031 					    sd->sc_dev.dv_xname, retval);
1032 					retval = EIO;
1033 				} else {
1034 					retval = SCSIRET_RETRY;
1035 				}
1036 			}
1037 		}
1038 	}
1039 	return (retval);
1040 }
1041 
1042 
1043 int
1044 sdsize(dev)
1045 	dev_t dev;
1046 {
1047 	struct sd_softc *sd;
1048 	int part, unit, omask;
1049 	int size;
1050 
1051 	unit = SDUNIT(dev);
1052 	if (unit >= sd_cd.cd_ndevs)
1053 		return (-1);
1054 	sd = sd_cd.cd_devs[unit];
1055 	if (sd == NULL)
1056 		return (-1);
1057 
1058 	part = SDPART(dev);
1059 	omask = sd->sc_dk.dk_openmask & (1 << part);
1060 
1061 	if (omask == 0 && sdopen(dev, 0, S_IFBLK, NULL) != 0)
1062 		return (-1);
1063 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0)
1064 		size = -1;
1065 	else if (sd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
1066 		size = -1;
1067 	else
1068 		size = sd->sc_dk.dk_label->d_partitions[part].p_size *
1069 		    (sd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
1070 	if (omask == 0 && sdclose(dev, 0, S_IFBLK, NULL) != 0)
1071 		return (-1);
1072 	return (size);
1073 }
1074 
1075 #ifndef __BDEVSW_DUMP_OLD_TYPE
1076 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
1077 static struct scsipi_xfer sx;
1078 static int sddoingadump;
1079 
1080 /*
1081  * dump all of physical memory into the partition specified, starting
1082  * at offset 'dumplo' into the partition.
1083  */
1084 int
1085 sddump(dev, blkno, va, size)
1086 	dev_t dev;
1087 	daddr_t blkno;
1088 	caddr_t va;
1089 	size_t size;
1090 {
1091 	struct sd_softc *sd;	/* disk unit to do the I/O */
1092 	struct disklabel *lp;	/* disk's disklabel */
1093 	int	unit, part;
1094 	int	sectorsize;	/* size of a disk sector */
1095 	int	nsects;		/* number of sectors in partition */
1096 	int	sectoff;	/* sector offset of partition */
1097 	int	totwrt;		/* total number of sectors left to write */
1098 	int	nwrt;		/* current number of sectors to write */
1099 	struct scsipi_rw_big cmd;	/* write command */
1100 	struct scsipi_xfer *xs;	/* ... convenience */
1101 	int	retval;
1102 
1103 	/* Check if recursive dump; if so, punt. */
1104 	if (sddoingadump)
1105 		return (EFAULT);
1106 
1107 	/* Mark as active early. */
1108 	sddoingadump = 1;
1109 
1110 	unit = SDUNIT(dev);	/* Decompose unit & partition. */
1111 	part = SDPART(dev);
1112 
1113 	/* Check for acceptable drive number. */
1114 	if (unit >= sd_cd.cd_ndevs || (sd = sd_cd.cd_devs[unit]) == NULL)
1115 		return (ENXIO);
1116 
1117 	/* Make sure it was initialized. */
1118 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) != SDEV_MEDIA_LOADED)
1119 		return (ENXIO);
1120 
1121 	/* Convert to disk sectors.  Request must be a multiple of size. */
1122 	lp = sd->sc_dk.dk_label;
1123 	sectorsize = lp->d_secsize;
1124 	if ((size % sectorsize) != 0)
1125 		return (EFAULT);
1126 	totwrt = size / sectorsize;
1127 	blkno = dbtob(blkno) / sectorsize;	/* blkno in DEV_BSIZE units */
1128 
1129 	nsects = lp->d_partitions[part].p_size;
1130 	sectoff = lp->d_partitions[part].p_offset;
1131 
1132 	/* Check transfer bounds against partition size. */
1133 	if ((blkno < 0) || ((blkno + totwrt) > nsects))
1134 		return (EINVAL);
1135 
1136 	/* Offset block number to start of partition. */
1137 	blkno += sectoff;
1138 
1139 	xs = &sx;
1140 
1141 	while (totwrt > 0) {
1142 		nwrt = totwrt;		/* XXX */
1143 #ifndef	SD_DUMP_NOT_TRUSTED
1144 		/*
1145 		 *  Fill out the scsi command
1146 		 */
1147 		bzero(&cmd, sizeof(cmd));
1148 		cmd.opcode = WRITE_BIG;
1149 		_lto4b(blkno, cmd.addr);
1150 		_lto2b(nwrt, cmd.length);
1151 		/*
1152 		 * Fill out the scsipi_xfer structure
1153 		 *    Note: we cannot sleep as we may be an interrupt
1154 		 * don't use scsipi_command() as it may want to wait
1155 		 * for an xs.
1156 		 */
1157 		bzero(xs, sizeof(sx));
1158 		xs->flags |= SCSI_AUTOCONF | INUSE | SCSI_DATA_OUT;
1159 		xs->sc_link = sd->sc_link;
1160 		xs->retries = SDRETRIES;
1161 		xs->timeout = 10000;	/* 10000 millisecs for a disk ! */
1162 		xs->cmd = (struct scsipi_generic *)&cmd;
1163 		xs->cmdlen = sizeof(cmd);
1164 		xs->resid = nwrt * sectorsize;
1165 		xs->error = XS_NOERROR;
1166 		xs->bp = 0;
1167 		xs->data = va;
1168 		xs->datalen = nwrt * sectorsize;
1169 
1170 		/*
1171 		 * Pass all this info to the scsi driver.
1172 		 */
1173 		retval = scsipi_command_direct(xs);
1174 		if (retval != COMPLETE)
1175 			return (ENXIO);
1176 #else	/* SD_DUMP_NOT_TRUSTED */
1177 		/* Let's just talk about this first... */
1178 		printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
1179 		delay(500 * 1000);	/* half a second */
1180 #endif	/* SD_DUMP_NOT_TRUSTED */
1181 
1182 		/* update block count */
1183 		totwrt -= nwrt;
1184 		blkno += nwrt;
1185 		va += sectorsize * nwrt;
1186 	}
1187 	sddoingadump = 0;
1188 	return (0);
1189 }
1190 #else	/* __BDEVSW_DUMP_NEW_TYPE */
1191 int
1192 sddump(dev, blkno, va, size)
1193 	dev_t dev;
1194 	daddr_t blkno;
1195 	caddr_t va;
1196 	size_t size;
1197 {
1198 
1199 	/* Not implemented. */
1200 	return (ENXIO);
1201 }
1202 #endif	/* __BDEVSW_DUMP_NEW_TYPE */
1203