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