xref: /openbsd/sys/scsi/sd.c (revision f2dfb0a4)
1 /*	$OpenBSD: sd.c,v 1.29 1998/05/02 16:48:21 millert Exp $	*/
2 /*	$NetBSD: sd.c,v 1.111 1997/04/02 02:29:41 mycroft Exp $	*/
3 
4 /*
5  * Copyright (c) 1994, 1995, 1997 Charles M. Hannum.  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  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by Charles M. Hannum.
18  * 4. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Originally written by Julian Elischer (julian@dialix.oz.au)
35  * for TRW Financial Systems for use under the MACH(2.5) operating system.
36  *
37  * TRW Financial Systems, in accordance with their agreement with Carnegie
38  * Mellon University, makes this software available to CMU to distribute
39  * or use in any manner that they see fit as long as this message is kept with
40  * the software. For this reason TFS also grants any other persons or
41  * organisations permission to use or modify this software.
42  *
43  * TFS supplies this software to be publicly redistributed
44  * on the understanding that TFS is not responsible for the correct
45  * functioning of this software in any circumstances.
46  *
47  * Ported to run under 386BSD by Julian Elischer (julian@dialix.oz.au) Sept 1992
48  */
49 
50 #include <sys/types.h>
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/kernel.h>
54 #include <sys/file.h>
55 #include <sys/stat.h>
56 #include <sys/ioctl.h>
57 #include <sys/mtio.h>
58 #include <sys/buf.h>
59 #include <sys/uio.h>
60 #include <sys/malloc.h>
61 #include <sys/errno.h>
62 #include <sys/device.h>
63 #include <sys/disklabel.h>
64 #include <sys/disk.h>
65 #include <sys/proc.h>
66 #include <sys/conf.h>
67 #include <sys/scsiio.h>
68 
69 #include <scsi/scsi_all.h>
70 #include <scsi/scsi_disk.h>
71 #include <scsi/scsiconf.h>
72 
73 #include <ufs/ffs/fs.h>			/* for BBSIZE and SBSIZE */
74 
75 #define	SDOUTSTANDING	4
76 #define	SDRETRIES	4
77 
78 #define	SDUNIT(dev)			DISKUNIT(dev)
79 #define	SDPART(dev)			DISKPART(dev)
80 #define	MAKESDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
81 
82 #define	SDLABELDEV(dev)	(MAKESDDEV(major(dev), SDUNIT(dev), RAW_PART))
83 
84 struct sd_softc {
85 	struct device sc_dev;
86 	struct disk sc_dk;
87 
88 	int flags;
89 #define	SDF_LOCKED	0x01
90 #define	SDF_WANTED	0x02
91 #define	SDF_WLABEL	0x04		/* label is writable */
92 #define	SDF_LABELLING	0x08		/* writing label */
93 #define	SDF_ANCIENT	0x10		/* disk is ancient; for minphys */
94 	struct scsi_link *sc_link;	/* contains our targ, lun, etc. */
95 	struct disk_parms {
96 		u_char heads;		/* number of heads */
97 		u_short cyls;		/* number of cylinders */
98 		u_char sectors;		/* number of sectors/track */
99 		int blksize;		/* number of bytes/sector */
100 		u_long disksize;	/* total number sectors */
101 	} params;
102 	struct buf buf_queue;
103 	u_int8_t type;
104 };
105 
106 struct scsi_mode_sense_data {
107 	struct scsi_mode_header header;
108 	struct scsi_blk_desc blk_desc;
109 	union disk_pages pages;
110 };
111 
112 int	sdmatch __P((struct device *, void *, void *));
113 void	sdattach __P((struct device *, struct device *, void *));
114 int	sdlock __P((struct sd_softc *));
115 void	sdunlock __P((struct sd_softc *));
116 void	sdminphys __P((struct buf *));
117 void	sdgetdisklabel __P((dev_t, struct sd_softc *));
118 void	sdstart __P((void *));
119 void	sddone __P((struct scsi_xfer *));
120 int	sd_reassign_blocks __P((struct sd_softc *, u_long));
121 int	sd_get_optparms __P((struct sd_softc *, int, struct disk_parms *));
122 int	sd_get_parms __P((struct sd_softc *, int));
123 static int sd_mode_sense __P((struct sd_softc *, struct scsi_mode_sense_data *,
124 			      int, int));
125 
126 struct cfattach sd_ca = {
127 	sizeof(struct sd_softc), sdmatch, sdattach
128 };
129 
130 struct cfdriver sd_cd = {
131 	NULL, "sd", DV_DISK
132 };
133 
134 struct dkdriver sddkdriver = { sdstrategy };
135 
136 struct scsi_device sd_switch = {
137 	NULL,			/* Use default error handler */
138 	sdstart,		/* have a queue, served by this */
139 	NULL,			/* have no async handler */
140 	sddone,			/* deal with stats at interrupt time */
141 };
142 
143 struct scsi_inquiry_pattern sd_patterns[] = {
144 	{T_DIRECT, T_FIXED,
145 	 "",         "",                 ""},
146 	{T_DIRECT, T_REMOV,
147 	 "",         "",                 ""},
148 	{T_OPTICAL, T_FIXED,
149 	 "",         "",                 ""},
150 	{T_OPTICAL, T_REMOV,
151 	 "",         "",                 ""},
152 };
153 
154 int
155 sdmatch(parent, match, aux)
156 	struct device *parent;
157 	void *match, *aux;
158 {
159 	struct scsibus_attach_args *sa = aux;
160 	int priority;
161 
162 	(void)scsi_inqmatch(sa->sa_inqbuf,
163 	    (caddr_t)sd_patterns, sizeof(sd_patterns)/sizeof(sd_patterns[0]),
164 	    sizeof(sd_patterns[0]), &priority);
165 	return (priority);
166 }
167 
168 /*
169  * The routine called by the low level scsi routine when it discovers
170  * a device suitable for this driver.
171  */
172 void
173 sdattach(parent, self, aux)
174 	struct device *parent, *self;
175 	void *aux;
176 {
177 	int error;
178 	struct sd_softc *sd = (void *)self;
179 	struct disk_parms *dp = &sd->params;
180 	struct scsibus_attach_args *sa = aux;
181 	struct scsi_link *sc_link = sa->sa_sc_link;
182 
183 	SC_DEBUG(sc_link, SDEV_DB2, ("sdattach: "));
184 
185 	/*
186 	 * Store information needed to contact our base driver
187 	 */
188 	sd->sc_link = sc_link;
189 	sd->type = (sa->sa_inqbuf->device & SID_TYPE);
190 	sc_link->device = &sd_switch;
191 	sc_link->device_softc = sd;
192 	if (sc_link->openings > SDOUTSTANDING)
193 		sc_link->openings = SDOUTSTANDING;
194 
195 	/*
196 	 * Initialize and attach the disk structure.
197 	 */
198 	sd->sc_dk.dk_driver = &sddkdriver;
199 	sd->sc_dk.dk_name = sd->sc_dev.dv_xname;
200 	disk_attach(&sd->sc_dk);
201 
202 	dk_establish(&sd->sc_dk, &sd->sc_dev);
203 
204 	/*
205 	 * Note if this device is ancient.  This is used in sdminphys().
206 	 */
207 	if ((sa->sa_inqbuf->version & SID_ANSII) == 0)
208 		sd->flags |= SDF_ANCIENT;
209 
210 	/*
211 	 * Use the subdriver to request information regarding
212 	 * the drive. We cannot use interrupts yet, so the
213 	 * request must specify this.
214 	 */
215 	printf("\n");
216 	printf("%s: ", sd->sc_dev.dv_xname);
217 
218 	if ((sd->sc_link->quirks & SDEV_NOSTARTUNIT) == 0) {
219 		error = scsi_start(sd->sc_link, SSS_START,
220 				   SCSI_AUTOCONF | SCSI_IGNORE_ILLEGAL_REQUEST |
221 				   SCSI_IGNORE_MEDIA_CHANGE | SCSI_SILENT);
222 	} else
223 		error = 0;
224 
225 	if (error || sd_get_parms(sd, SCSI_AUTOCONF) != 0)
226 		printf("drive offline\n");
227 	else
228 	        printf("%ldMB, %d cyl, %d head, %d sec, %d bytes/sec, %ld sec total\n",
229 		    dp->disksize / (1048576 / dp->blksize), dp->cyls,
230 		    dp->heads, dp->sectors, dp->blksize, dp->disksize);
231 }
232 
233 /*
234  * Wait interruptibly for an exclusive lock.
235  *
236  * XXX
237  * Several drivers do this; it should be abstracted and made MP-safe.
238  */
239 int
240 sdlock(sd)
241 	struct sd_softc *sd;
242 {
243 	int error;
244 
245 	while ((sd->flags & SDF_LOCKED) != 0) {
246 		sd->flags |= SDF_WANTED;
247 		if ((error = tsleep(sd, PRIBIO | PCATCH, "sdlck", 0)) != 0)
248 			return error;
249 	}
250 	sd->flags |= SDF_LOCKED;
251 	return 0;
252 }
253 
254 /*
255  * Unlock and wake up any waiters.
256  */
257 void
258 sdunlock(sd)
259 	struct sd_softc *sd;
260 {
261 
262 	sd->flags &= ~SDF_LOCKED;
263 	if ((sd->flags & SDF_WANTED) != 0) {
264 		sd->flags &= ~SDF_WANTED;
265 		wakeup(sd);
266 	}
267 }
268 
269 /*
270  * open the device. Make sure the partition info is a up-to-date as can be.
271  */
272 int
273 sdopen(dev, flag, fmt, p)
274 	dev_t dev;
275 	int flag, fmt;
276 	struct proc *p;
277 {
278 	struct sd_softc *sd;
279 	struct scsi_link *sc_link;
280 	int unit, part;
281 	int error;
282 
283 	unit = SDUNIT(dev);
284 	if (unit >= sd_cd.cd_ndevs)
285 		return ENXIO;
286 	sd = sd_cd.cd_devs[unit];
287 	if (!sd)
288 		return ENXIO;
289 
290 	sc_link = sd->sc_link;
291 
292 	SC_DEBUG(sc_link, SDEV_DB1,
293 	    ("sdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev, unit,
294 	    sd_cd.cd_ndevs, SDPART(dev)));
295 
296 	if ((error = sdlock(sd)) != 0)
297 		return error;
298 
299 	if (sd->sc_dk.dk_openmask != 0) {
300 		/*
301 		 * If any partition is open, but the disk has been invalidated,
302 		 * disallow further opens.
303 		 */
304 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
305 			error = EIO;
306 			goto bad3;
307 		}
308 	} else {
309 		/* Check that it is still responding and ok. */
310 		error = scsi_test_unit_ready(sc_link,
311 					     SCSI_IGNORE_ILLEGAL_REQUEST |
312 					     SCSI_IGNORE_MEDIA_CHANGE |
313 					     SCSI_IGNORE_NOT_READY);
314 		if (error)
315 			goto bad3;
316 
317 		/* Start the pack spinning if necessary. */
318 		if ((sc_link->quirks & SDEV_NOSTARTUNIT) == 0) {
319 			error = scsi_start(sc_link, SSS_START,
320 					   SCSI_IGNORE_ILLEGAL_REQUEST |
321 					   SCSI_IGNORE_MEDIA_CHANGE |
322 					   SCSI_SILENT);
323 			if (error)
324 				goto bad3;
325 		}
326 
327 		sc_link->flags |= SDEV_OPEN;
328 
329 		/* Lock the pack in. */
330 		error = scsi_prevent(sc_link, PR_PREVENT,
331 				     SCSI_IGNORE_ILLEGAL_REQUEST |
332 				     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 			/* Load the physical device parameters. */
340 			if (sd_get_parms(sd, 0) != 0) {
341 				error = ENXIO;
342 				goto bad2;
343 			}
344 			SC_DEBUG(sc_link, SDEV_DB3, ("Params loaded "));
345 
346 			/* Load the partition info if not already loaded. */
347 			sdgetdisklabel(dev, sd);
348 			SC_DEBUG(sc_link, SDEV_DB3, ("Disklabel loaded "));
349 		}
350 	}
351 
352 	part = SDPART(dev);
353 
354 	/* Check that the partition exists. */
355 	if (part != RAW_PART &&
356 	    (part >= sd->sc_dk.dk_label->d_npartitions ||
357 	     sd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
358 		error = ENXIO;
359 		goto bad;
360 	}
361 
362 	/* Insure only one open at a time. */
363 	switch (fmt) {
364 	case S_IFCHR:
365 		sd->sc_dk.dk_copenmask |= (1 << part);
366 		break;
367 	case S_IFBLK:
368 		sd->sc_dk.dk_bopenmask |= (1 << part);
369 		break;
370 	}
371 	sd->sc_dk.dk_openmask = sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
372 
373 	SC_DEBUG(sc_link, SDEV_DB3, ("open complete\n"));
374 	sdunlock(sd);
375 	return 0;
376 
377 bad2:
378 	sc_link->flags &= ~SDEV_MEDIA_LOADED;
379 
380 bad:
381 	if (sd->sc_dk.dk_openmask == 0) {
382 		scsi_prevent(sc_link, PR_ALLOW,
383 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE);
384 		sc_link->flags &= ~SDEV_OPEN;
385 	}
386 
387 bad3:
388 	sdunlock(sd);
389 	return error;
390 }
391 
392 /*
393  * close the device.. only called if we are the LAST occurence of an open
394  * device.  Convenient now but usually a pain.
395  */
396 int
397 sdclose(dev, flag, fmt, p)
398 	dev_t dev;
399 	int flag, fmt;
400 	struct proc *p;
401 {
402 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
403 	int part = SDPART(dev);
404 	int error;
405 
406 	if ((error = sdlock(sd)) != 0)
407 		return error;
408 
409 	switch (fmt) {
410 	case S_IFCHR:
411 		sd->sc_dk.dk_copenmask &= ~(1 << part);
412 		break;
413 	case S_IFBLK:
414 		sd->sc_dk.dk_bopenmask &= ~(1 << part);
415 		break;
416 	}
417 	sd->sc_dk.dk_openmask = sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
418 
419 	if (sd->sc_dk.dk_openmask == 0) {
420 		/* XXX Must wait for I/O to complete! */
421 
422 		scsi_prevent(sd->sc_link, PR_ALLOW,
423 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_NOT_READY);
424 		sd->sc_link->flags &= ~(SDEV_OPEN|SDEV_MEDIA_LOADED);
425 
426 		if (sd->sc_link->flags & SDEV_EJECTING) {
427 		    scsi_start(sd->sc_link, SSS_STOP|SSS_LOEJ, 0);
428 
429 		    sd->sc_link->flags &= ~SDEV_EJECTING;
430 		}
431 	}
432 
433 	sdunlock(sd);
434 	return 0;
435 }
436 
437 /*
438  * Actually translate the requested transfer into one the physical driver
439  * can understand.  The transfer is described by a buf and will include
440  * only one physical transfer.
441  */
442 void
443 sdstrategy(bp)
444 	struct buf *bp;
445 {
446 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
447 	int s;
448 
449 	SC_DEBUG(sd->sc_link, SDEV_DB2, ("sdstrategy "));
450 	SC_DEBUG(sd->sc_link, SDEV_DB1,
451 	    ("%ld bytes @ blk %d\n", bp->b_bcount, bp->b_blkno));
452 	/*
453 	 * The transfer must be a whole number of blocks.
454 	 */
455 	if ((bp->b_bcount % sd->sc_dk.dk_label->d_secsize) != 0) {
456 		bp->b_error = EINVAL;
457 		goto bad;
458 	}
459 	/*
460 	 * If the device has been made invalid, error out
461 	 */
462 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
463 		bp->b_error = EIO;
464 		goto bad;
465 	}
466 	/*
467 	 * If it's a null transfer, return immediatly
468 	 */
469 	if (bp->b_bcount == 0)
470 		goto done;
471 
472 	/*
473 	 * Do bounds checking, adjust transfer. if error, process.
474 	 * If end of partition, just return.
475 	 */
476 	if (SDPART(bp->b_dev) != RAW_PART &&
477 	    bounds_check_with_label(bp, sd->sc_dk.dk_label,
478 	    sd->sc_dk.dk_cpulabel,
479 	    (sd->flags & (SDF_WLABEL|SDF_LABELLING)) != 0) <= 0)
480 		goto done;
481 
482 	s = splbio();
483 
484 	/*
485 	 * Place it in the queue of disk activities for this disk
486 	 */
487 	disksort(&sd->buf_queue, bp);
488 
489 	/*
490 	 * Tell the device to get going on the transfer if it's
491 	 * not doing anything, otherwise just wait for completion
492 	 */
493 	sdstart(sd);
494 
495 	splx(s);
496 	return;
497 
498 bad:
499 	bp->b_flags |= B_ERROR;
500 done:
501 	/*
502 	 * Correctly set the buf to indicate a completed xfer
503 	 */
504 	bp->b_resid = bp->b_bcount;
505 	biodone(bp);
506 }
507 
508 /*
509  * sdstart looks to see if there is a buf waiting for the device
510  * and that the device is not already busy. If both are true,
511  * It dequeues the buf and creates a scsi command to perform the
512  * transfer in the buf. The transfer request will call scsi_done
513  * on completion, which will in turn call this routine again
514  * so that the next queued transfer is performed.
515  * The bufs are queued by the strategy routine (sdstrategy)
516  *
517  * This routine is also called after other non-queued requests
518  * have been made of the scsi driver, to ensure that the queue
519  * continues to be drained.
520  *
521  * must be called at the correct (highish) spl level
522  * sdstart() is called at splbio from sdstrategy and scsi_done
523  */
524 void
525 sdstart(v)
526 	register void *v;
527 {
528 	register struct sd_softc *sd = v;
529 	register struct	scsi_link *sc_link = sd->sc_link;
530 	struct buf *bp = 0;
531 	struct buf *dp;
532 	struct scsi_rw_big cmd_big;
533 	struct scsi_rw cmd_small;
534 	struct scsi_generic *cmdp;
535 	int blkno, nblks, cmdlen, error;
536 	struct partition *p;
537 
538 	SC_DEBUG(sc_link, SDEV_DB2, ("sdstart "));
539 	/*
540 	 * Check if the device has room for another command
541 	 */
542 	while (sc_link->openings > 0) {
543 		/*
544 		 * there is excess capacity, but a special waits
545 		 * It'll need the adapter as soon as we clear out of the
546 		 * way and let it run (user level wait).
547 		 */
548 		if (sc_link->flags & SDEV_WAITING) {
549 			sc_link->flags &= ~SDEV_WAITING;
550 			wakeup((caddr_t)sc_link);
551 			return;
552 		}
553 
554 		/*
555 		 * See if there is a buf with work for us to do..
556 		 */
557 		dp = &sd->buf_queue;
558 		if ((bp = dp->b_actf) == NULL)	/* yes, an assign */
559 			return;
560 		dp->b_actf = bp->b_actf;
561 
562 		/*
563 		 * If the device has become invalid, abort all the
564 		 * reads and writes until all files have been closed and
565 		 * re-opened
566 		 */
567 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
568 			bp->b_error = EIO;
569 			bp->b_flags |= B_ERROR;
570 			bp->b_resid = bp->b_bcount;
571 			biodone(bp);
572 			continue;
573 		}
574 
575 		/*
576 		 * We have a buf, now we should make a command
577 		 *
578 		 * First, translate the block to absolute and put it in terms
579 		 * of the logical blocksize of the device.
580 		 */
581 		blkno =
582 		    bp->b_blkno / (sd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
583 		if (SDPART(bp->b_dev) != RAW_PART) {
584 		     p = &sd->sc_dk.dk_label->d_partitions[SDPART(bp->b_dev)];
585 		     blkno += p->p_offset;
586 		}
587 		nblks = howmany(bp->b_bcount, sd->sc_dk.dk_label->d_secsize);
588 
589 		/*
590 		 *  Fill out the scsi command.  If the transfer will
591 		 *  fit in a "small" cdb, use it.
592 		 */
593 		if (((blkno & 0x1fffff) == blkno) &&
594 		    ((nblks & 0xff) == nblks)) {
595 			/*
596 			 * We can fit in a small cdb.
597 			 */
598 			bzero(&cmd_small, sizeof(cmd_small));
599 			cmd_small.opcode = (bp->b_flags & B_READ) ?
600 			    READ_COMMAND : WRITE_COMMAND;
601 			_lto3b(blkno, cmd_small.addr);
602 			cmd_small.length = nblks & 0xff;
603 			cmdlen = sizeof(cmd_small);
604 			cmdp = (struct scsi_generic *)&cmd_small;
605 		} else {
606 			/*
607 			 * Need a large cdb.
608 			 */
609 			bzero(&cmd_big, sizeof(cmd_big));
610 			cmd_big.opcode = (bp->b_flags & B_READ) ?
611 			    READ_BIG : WRITE_BIG;
612 			_lto4b(blkno, cmd_big.addr);
613 			_lto2b(nblks, cmd_big.length);
614 			cmdlen = sizeof(cmd_big);
615 			cmdp = (struct scsi_generic *)&cmd_big;
616 		}
617 
618 		/* Instrumentation. */
619 		disk_busy(&sd->sc_dk);
620 
621 		/*
622 		 * Call the routine that chats with the adapter.
623 		 * Note: we cannot sleep as we may be an interrupt
624 		 */
625 		error = scsi_scsi_cmd(sc_link, cmdp, cmdlen,
626 		    (u_char *)bp->b_data, bp->b_bcount,
627 		    SDRETRIES, 60000, bp, SCSI_NOSLEEP |
628 		    ((bp->b_flags & B_READ) ? SCSI_DATA_IN : SCSI_DATA_OUT));
629 		if (error) {
630 			disk_unbusy(&sd->sc_dk, 0);
631 			printf("%s: not queued, error %d\n",
632 			    sd->sc_dev.dv_xname, error);
633 		}
634 	}
635 }
636 
637 void
638 sddone(xs)
639 	struct scsi_xfer *xs;
640 {
641 	struct sd_softc *sd = xs->sc_link->device_softc;
642 
643 	if (xs->bp != NULL)
644 		disk_unbusy(&sd->sc_dk, (xs->bp->b_bcount - xs->bp->b_resid));
645 }
646 
647 void
648 sdminphys(bp)
649 	struct buf *bp;
650 {
651 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
652 	long max;
653 
654 	/*
655 	 * If the device is ancient, we want to make sure that
656 	 * the transfer fits into a 6-byte cdb.
657 	 *
658 	 * XXX Note that the SCSI-I spec says that 256-block transfers
659 	 * are allowed in a 6-byte read/write, and are specified
660 	 * by settng the "length" to 0.  However, we're conservative
661 	 * here, allowing only 255-block transfers in case an
662 	 * ancient device gets confused by length == 0.  A length of 0
663 	 * in a 10-byte read/write actually means 0 blocks.
664 	 */
665 	if (sd->flags & SDF_ANCIENT) {
666 		max = sd->sc_dk.dk_label->d_secsize * 0xff;
667 
668 		if (bp->b_bcount > max)
669 			bp->b_bcount = max;
670 	}
671 
672 	(*sd->sc_link->adapter->scsi_minphys)(bp);
673 }
674 
675 int
676 sdread(dev, uio, ioflag)
677 	dev_t dev;
678 	struct uio *uio;
679 	int ioflag;
680 {
681 
682 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
683 }
684 
685 int
686 sdwrite(dev, uio, ioflag)
687 	dev_t dev;
688 	struct uio *uio;
689 	int ioflag;
690 {
691 
692 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
693 }
694 
695 /*
696  * Perform special action on behalf of the user
697  * Knows about the internals of this device
698  */
699 int
700 sdioctl(dev, cmd, addr, flag, p)
701 	dev_t dev;
702 	u_long cmd;
703 	caddr_t addr;
704 	int flag;
705 	struct proc *p;
706 {
707 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
708 	int error;
709 
710 	SC_DEBUG(sd->sc_link, SDEV_DB2, ("sdioctl 0x%lx ", cmd));
711 
712 	/*
713 	 * If the device is not valid.. abandon ship
714 	 */
715 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0)
716 		return EIO;
717 
718 	switch (cmd) {
719 	case DIOCGDINFO:
720 		*(struct disklabel *)addr = *(sd->sc_dk.dk_label);
721 		return 0;
722 
723 	case DIOCGPART:
724 		((struct partinfo *)addr)->disklab = sd->sc_dk.dk_label;
725 		((struct partinfo *)addr)->part =
726 		    &sd->sc_dk.dk_label->d_partitions[SDPART(dev)];
727 		return 0;
728 
729 	case DIOCWDINFO:
730 	case DIOCSDINFO:
731 		if ((flag & FWRITE) == 0)
732 			return EBADF;
733 
734 		if ((error = sdlock(sd)) != 0)
735 			return error;
736 		sd->flags |= SDF_LABELLING;
737 
738 		error = setdisklabel(sd->sc_dk.dk_label,
739 		    (struct disklabel *)addr, /*sd->sc_dk.dk_openmask : */0,
740 		    sd->sc_dk.dk_cpulabel);
741 		if (error == 0) {
742 			if (cmd == DIOCWDINFO)
743 				error = writedisklabel(SDLABELDEV(dev),
744 				    sdstrategy, sd->sc_dk.dk_label,
745 				    sd->sc_dk.dk_cpulabel);
746 		}
747 
748 		sd->flags &= ~SDF_LABELLING;
749 		sdunlock(sd);
750 		return error;
751 
752 	case DIOCWLABEL:
753 		if ((flag & FWRITE) == 0)
754 			return EBADF;
755 		if (*(int *)addr)
756 			sd->flags |= SDF_WLABEL;
757 		else
758 			sd->flags &= ~SDF_WLABEL;
759 		return 0;
760 
761 	case DIOCLOCK:
762 		return scsi_prevent(sd->sc_link,
763 		    (*(int *)addr) ? PR_PREVENT : PR_ALLOW, 0);
764 
765 	case MTIOCTOP:
766 		if (((struct mtop *)addr)->mt_op != MTOFFL)
767 			return EIO;
768 		/* FALLTHROUGH */
769 	case DIOCEJECT:
770 		if ((sd->sc_link->flags & SDEV_REMOVABLE) == 0)
771 			return ENOTTY;
772 		sd->sc_link->flags |= SDEV_EJECTING;
773 		return 0;
774 
775 	case SCIOCREASSIGN:
776 		if ((flag & FWRITE) == 0)
777 			return EBADF;
778 		error = sd_reassign_blocks(sd, (*(int *)addr));
779 		return error;
780 
781 	default:
782 		if (SDPART(dev) != RAW_PART)
783 			return ENOTTY;
784 		return scsi_do_ioctl(sd->sc_link, dev, cmd, addr, flag, p);
785 	}
786 
787 #ifdef DIAGNOSTIC
788 	panic("sdioctl: impossible");
789 #endif
790 }
791 
792 /*
793  * Load the label information on the named device
794  */
795 void
796 sdgetdisklabel(dev, sd)
797 	dev_t dev;
798 	struct sd_softc *sd;
799 {
800 	struct disklabel *lp = sd->sc_dk.dk_label;
801 	char *errstring;
802 
803 	bzero(lp, sizeof(struct disklabel));
804 	bzero(sd->sc_dk.dk_cpulabel, sizeof(struct cpu_disklabel));
805 
806 	lp->d_secsize = sd->params.blksize;
807 	lp->d_ntracks = sd->params.heads;
808 	lp->d_nsectors = sd->params.sectors;
809 	lp->d_ncylinders = sd->params.cyls;
810 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
811 	if (lp->d_secpercyl == 0) {
812 		lp->d_secpercyl = 100;
813 		/* as long as it's not 0 - readdisklabel divides by it (?) */
814 	}
815 
816 	lp->d_type = DTYPE_SCSI;
817 	if (sd->type == T_OPTICAL)
818 		strncpy(lp->d_typename, "SCSI optical",
819 		    sizeof(lp->d_typename) - 1);
820 	else
821 		strncpy(lp->d_typename, "SCSI disk",
822 		    sizeof(lp->d_typename) - 1);
823 	strncpy(lp->d_packname, "fictitious", sizeof(lp->d_packname) - 1);
824 	lp->d_secperunit = sd->params.disksize;
825 	lp->d_rpm = 3600;
826 	lp->d_interleave = 1;
827 	lp->d_flags = 0;
828 
829 	/* XXX - these values for BBSIZE and SBSIZE assume ffs */
830 	lp->d_bbsize = BBSIZE;
831 	lp->d_sbsize = SBSIZE;
832 
833 	lp->d_partitions[RAW_PART].p_offset = 0;
834 	lp->d_partitions[RAW_PART].p_size =
835 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
836 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
837 	lp->d_npartitions = RAW_PART + 1;
838 
839 	lp->d_magic = DISKMAGIC;
840 	lp->d_magic2 = DISKMAGIC;
841 	lp->d_checksum = dkcksum(lp);
842 
843 	/*
844 	 * Call the generic disklabel extraction routine
845 	 */
846 	errstring = readdisklabel(SDLABELDEV(dev), sdstrategy, lp,
847 	    sd->sc_dk.dk_cpulabel);
848 	if (errstring) {
849 		/*printf("%s: %s\n", sd->sc_dev.dv_xname, errstring);*/
850 		return;
851 	}
852 }
853 
854 /*
855  * Tell the device to map out a defective block
856  */
857 int
858 sd_reassign_blocks(sd, blkno)
859 	struct sd_softc *sd;
860 	u_long blkno;
861 {
862 	struct scsi_reassign_blocks scsi_cmd;
863 	struct scsi_reassign_blocks_data rbdata;
864 
865 	bzero(&scsi_cmd, sizeof(scsi_cmd));
866 	bzero(&rbdata, sizeof(rbdata));
867 	scsi_cmd.opcode = REASSIGN_BLOCKS;
868 
869 	_lto2b(sizeof(rbdata.defect_descriptor[0]), rbdata.length);
870 	_lto4b(blkno, rbdata.defect_descriptor[0].dlbaddr);
871 
872 	return scsi_scsi_cmd(sd->sc_link, (struct scsi_generic *)&scsi_cmd,
873 	    sizeof(scsi_cmd), (u_char *)&rbdata, sizeof(rbdata), SDRETRIES,
874 	    5000, NULL, SCSI_DATA_OUT);
875 }
876 
877 
878 static int
879 sd_mode_sense(sd, scsi_sense, page, flags)
880 	struct sd_softc *sd;
881 	struct scsi_mode_sense_data *scsi_sense;
882 	int page, flags;
883 {
884 	struct scsi_mode_sense scsi_cmd;
885 
886 	/*
887 	 * Make sure the sense buffer is clean before we do
888 	 * the mode sense, so that checks for bogus values of
889 	 * 0 will work in case the mode sense fails.
890 	 */
891 	bzero(scsi_sense, sizeof(*scsi_sense));
892 
893 	bzero(&scsi_cmd, sizeof(scsi_cmd));
894 	scsi_cmd.opcode = MODE_SENSE;
895 	scsi_cmd.page = page;
896 	scsi_cmd.length = 0x20;
897 	/*
898 	 * If the command worked, use the results to fill out
899 	 * the parameter structure
900 	 */
901 	return scsi_scsi_cmd(sd->sc_link, (struct scsi_generic *)&scsi_cmd,
902 	    sizeof(scsi_cmd), (u_char *)scsi_sense, sizeof(*scsi_sense),
903 	    SDRETRIES, 6000, NULL, flags | SCSI_DATA_IN | SCSI_SILENT);
904 }
905 
906 int
907 sd_get_optparms(sd, flags, dp)
908 	struct sd_softc *sd;
909 	int flags;
910 	struct disk_parms *dp;
911 {
912 	struct scsi_mode_sense scsi_cmd;
913 	struct scsi_mode_sense_data {
914 		struct scsi_mode_header header;
915 		struct scsi_blk_desc blk_desc;
916 		union disk_pages pages;
917 	} scsi_sense;
918 	u_long sectors;
919 	int error;
920 
921 	dp->blksize = DEV_BSIZE;
922 	if ((sectors = scsi_size(sd->sc_link, flags)) == 0)
923 		return 1;
924 
925 	/* XXX
926 	 * It is better to get the following params from the
927 	 * mode sense page 6 only (optical device parameter page).
928 	 * However, there are stupid optical devices which does NOT
929 	 * support the page 6. Ghaa....
930 	 */
931 	bzero(&scsi_cmd, sizeof(scsi_cmd));
932 	scsi_cmd.opcode = MODE_SENSE;
933 	scsi_cmd.page = 0x3f;	/* all pages */
934 	scsi_cmd.length = sizeof(struct scsi_mode_header) +
935 	    sizeof(struct scsi_blk_desc);
936 
937 	if ((error = scsi_scsi_cmd(sd->sc_link,
938 	    (struct scsi_generic *)&scsi_cmd, sizeof(scsi_cmd),
939 	    (u_char *)&scsi_sense, sizeof(scsi_sense), SDRETRIES,
940 	    6000, NULL, flags | SCSI_DATA_IN)) != 0)
941 		return error;
942 
943 	dp->blksize = _3btol(scsi_sense.blk_desc.blklen);
944 	if (dp->blksize == 0)
945 		dp->blksize = DEV_BSIZE;
946 
947 	/*
948 	 * Create a pseudo-geometry.
949 	 */
950 	dp->heads = 64;
951 	dp->sectors = 32;
952 	dp->cyls = sectors / (dp->heads * dp->sectors);
953 	dp->disksize = sectors;
954 
955 	return 0;
956 }
957 
958 /*
959  * Get the scsi driver to send a full inquiry to the * device and use the
960  * results to fill out the disk parameter structure.
961  */
962 int
963 sd_get_parms(sd, flags)
964 	struct sd_softc *sd;
965 	int flags;
966 {
967 	struct disk_parms *dp = &sd->params;
968 	struct scsi_mode_sense_data scsi_sense;
969 	u_long sectors;
970 	int page;
971 	int error;
972 
973 	if (sd->type == T_OPTICAL) {
974 		if ((error = sd_get_optparms(sd, flags, dp)) != 0)
975 			sd->sc_link->flags &= ~SDEV_MEDIA_LOADED;
976 		return error;
977 	}
978 
979 	if ((error = sd_mode_sense(sd, &scsi_sense, page = 4, flags)) == 0) {
980 		SC_DEBUG(sd->sc_link, SDEV_DB3,
981 		    ("%d cyls, %d heads, %d precomp, %d red_write, %d land_zone\n",
982 		    _3btol(scsi_sense.pages.rigid_geometry.ncyl),
983 		    scsi_sense.pages.rigid_geometry.nheads,
984 		    _2btol(scsi_sense.pages.rigid_geometry.st_cyl_wp),
985 		    _2btol(scsi_sense.pages.rigid_geometry.st_cyl_rwc),
986 		    _2btol(scsi_sense.pages.rigid_geometry.land_zone)));
987 
988 		/*
989 		 * KLUDGE!! (for zone recorded disks)
990 		 * give a number of sectors so that sec * trks * cyls
991 		 * is <= disk_size
992 		 * can lead to wasted space! THINK ABOUT THIS !
993 		 */
994 		dp->heads = scsi_sense.pages.rigid_geometry.nheads;
995 		dp->cyls = _3btol(scsi_sense.pages.rigid_geometry.ncyl);
996 		dp->blksize = _3btol(scsi_sense.blk_desc.blklen);
997 
998 		if (dp->heads == 0 || dp->cyls == 0)
999 			goto fake_it;
1000 
1001 		if (dp->blksize == 0)
1002 			dp->blksize = DEV_BSIZE;
1003 
1004 		sectors = scsi_size(sd->sc_link, flags);
1005 		dp->disksize = sectors;
1006 		sectors /= (dp->heads * dp->cyls);
1007 		dp->sectors = sectors;	/* XXX dubious on SCSI */
1008 
1009 		return 0;
1010 	}
1011 
1012 	if ((error = sd_mode_sense(sd, &scsi_sense, page = 5, flags)) == 0) {
1013 		dp->heads = scsi_sense.pages.flex_geometry.nheads;
1014 		dp->cyls = _2btol(scsi_sense.pages.flex_geometry.ncyl);
1015 		dp->blksize = _3btol(scsi_sense.blk_desc.blklen);
1016 		dp->sectors = scsi_sense.pages.flex_geometry.ph_sec_tr;
1017 		dp->disksize = dp->heads * dp->cyls * dp->sectors;
1018 		if (dp->disksize == 0)
1019 			goto fake_it;
1020 
1021 		if (dp->blksize == 0)
1022 			dp->blksize = DEV_BSIZE;
1023 
1024 		return 0;
1025 	}
1026 
1027 fake_it:
1028 	if ((sd->sc_link->quirks & SDEV_NOMODESENSE) == 0) {
1029 		if (error == 0)
1030 			printf("%s: mode sense (%d) returned nonsense",
1031 			    sd->sc_dev.dv_xname, page);
1032 		else
1033 			printf("%s: could not mode sense (4/5)",
1034 			    sd->sc_dev.dv_xname);
1035 		printf("; using fictitious geometry\n");
1036 	}
1037 	/*
1038 	 * use adaptec standard fictitious geometry
1039 	 * this depends on which controller (e.g. 1542C is
1040 	 * different. but we have to put SOMETHING here..)
1041 	 */
1042 	sectors = scsi_size(sd->sc_link, flags);
1043 	dp->heads = 64;
1044 	dp->sectors = 32;
1045 	dp->cyls = sectors / (64 * 32);
1046 	dp->blksize = DEV_BSIZE;
1047 	dp->disksize = sectors;
1048 	return 0;
1049 }
1050 
1051 int
1052 sdsize(dev)
1053 	dev_t dev;
1054 {
1055 	struct sd_softc *sd;
1056 	int part;
1057 	int size;
1058 
1059 	if (sdopen(dev, 0, S_IFBLK, NULL) != 0)
1060 		return -1;
1061 	sd = sd_cd.cd_devs[SDUNIT(dev)];
1062 	part = SDPART(dev);
1063 	if (sd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
1064 		size = -1;
1065 	else
1066 		size = sd->sc_dk.dk_label->d_partitions[part].p_size;
1067 	if (sdclose(dev, 0, S_IFBLK, NULL) != 0)
1068 		return -1;
1069 	return size;
1070 }
1071 
1072 #ifndef __BDEVSW_DUMP_OLD_TYPE
1073 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
1074 static struct scsi_xfer sx;
1075 static int sddoingadump;
1076 
1077 /*
1078  * dump all of physical memory into the partition specified, starting
1079  * at offset 'dumplo' into the partition.
1080  */
1081 int
1082 sddump(dev, blkno, va, size)
1083 	dev_t dev;
1084 	daddr_t blkno;
1085 	caddr_t va;
1086 	size_t size;
1087 {
1088 	struct sd_softc *sd;	/* disk unit to do the I/O */
1089 	struct disklabel *lp;	/* disk's disklabel */
1090 	int	unit, part;
1091 	int	sectorsize;	/* size of a disk sector */
1092 	int	nsects;		/* number of sectors in partition */
1093 	int	sectoff;	/* sector offset of partition */
1094 	int	totwrt;		/* total number of sectors left to write */
1095 	int	nwrt;		/* current number of sectors to write */
1096 	struct scsi_rw_big cmd;	/* write command */
1097 	struct scsi_xfer *xs;	/* ... convenience */
1098 	int	retval;
1099 
1100 	/* Check if recursive dump; if so, punt. */
1101 	if (sddoingadump)
1102 		return EFAULT;
1103 
1104 	/* Mark as active early. */
1105 	sddoingadump = 1;
1106 
1107 	unit = SDUNIT(dev);	/* Decompose unit & partition. */
1108 	part = SDPART(dev);
1109 
1110 	/* Check for acceptable drive number. */
1111 	if (unit >= sd_cd.cd_ndevs || (sd = sd_cd.cd_devs[unit]) == NULL)
1112 		return ENXIO;
1113 
1114 	/*
1115 	 * XXX Can't do this check, since the media might have been
1116 	 * XXX marked `invalid' by successful unmounting of all
1117 	 * XXX filesystems.
1118 	 */
1119 #if 0
1120 	/* Make sure it was initialized. */
1121 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) != SDEV_MEDIA_LOADED)
1122 		return ENXIO;
1123 #endif
1124 
1125 	/* Convert to disk sectors.  Request must be a multiple of size. */
1126 	lp = sd->sc_dk.dk_label;
1127 	sectorsize = lp->d_secsize;
1128 	if ((size % sectorsize) != 0)
1129 		return EFAULT;
1130 	totwrt = size / sectorsize;
1131 	blkno = dbtob(blkno) / sectorsize;	/* blkno in DEV_BSIZE units */
1132 
1133 	nsects = lp->d_partitions[part].p_size;
1134 	sectoff = lp->d_partitions[part].p_offset;
1135 
1136 	/* Check transfer bounds against partition size. */
1137 	if ((blkno < 0) || ((blkno + totwrt) > nsects))
1138 		return EINVAL;
1139 
1140 	/* Offset block number to start of partition. */
1141 	blkno += sectoff;
1142 
1143 	xs = &sx;
1144 
1145 	while (totwrt > 0) {
1146 		nwrt = totwrt;		/* XXX */
1147 #ifndef	SD_DUMP_NOT_TRUSTED
1148 		/*
1149 		 *  Fill out the scsi command
1150 		 */
1151 		bzero(&cmd, sizeof(cmd));
1152 		cmd.opcode = WRITE_BIG;
1153 		_lto4b(blkno, cmd.addr);
1154 		_lto2b(nwrt, cmd.length);
1155 		/*
1156 		 * Fill out the scsi_xfer structure
1157 		 *    Note: we cannot sleep as we may be an interrupt
1158 		 * don't use scsi_scsi_cmd() as it may want
1159 		 * to wait for an xs.
1160 		 */
1161 		bzero(xs, sizeof(sx));
1162 		xs->flags |= SCSI_AUTOCONF | INUSE | SCSI_DATA_OUT;
1163 		xs->sc_link = sd->sc_link;
1164 		xs->retries = SDRETRIES;
1165 		xs->timeout = 10000;	/* 10000 millisecs for a disk ! */
1166 		xs->cmd = (struct scsi_generic *)&cmd;
1167 		xs->cmdlen = sizeof(cmd);
1168 		xs->resid = nwrt * sectorsize;
1169 		xs->error = XS_NOERROR;
1170 		xs->bp = 0;
1171 		xs->data = va;
1172 		xs->datalen = nwrt * sectorsize;
1173 
1174 		/*
1175 		 * Pass all this info to the scsi driver.
1176 		 */
1177 		retval = (*(sd->sc_link->adapter->scsi_cmd)) (xs);
1178 		if (retval != COMPLETE)
1179 			return ENXIO;
1180 #else	/* SD_DUMP_NOT_TRUSTED */
1181 		/* Let's just talk about this first... */
1182 		printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
1183 		delay(500 * 1000);	/* half a second */
1184 #endif	/* SD_DUMP_NOT_TRUSTED */
1185 
1186 		/* update block count */
1187 		totwrt -= nwrt;
1188 		blkno += nwrt;
1189 		va += sectorsize * nwrt;
1190 	}
1191 	sddoingadump = 0;
1192 	return 0;
1193 }
1194 #else	/* __BDEVSW_DUMP_OLD_TYPE */
1195 int
1196 sddump(dev, blkno, va, size)
1197 	dev_t dev;
1198 	daddr_t blkno;
1199 	caddr_t va;
1200 	size_t size;
1201 {
1202 
1203 	/* Not implemented. */
1204 	return ENXIO;
1205 }
1206 #endif	/* __BDEVSW_DUMP_OLD_TYPE */
1207