xref: /netbsd-src/sys/dev/scsipi/sd.c (revision 9573504567626934c7ee01c7dce0c4bb1dfe7403)
1 /*	$NetBSD: sd.c,v 1.83 1995/12/07 21:54:24 thorpej Exp $	*/
2 
3 /*
4  * Copyright (c) 1994, 1995 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 <sys/types.h>
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/conf.h>
54 #include <sys/file.h>
55 #include <sys/stat.h>
56 #include <sys/ioctl.h>
57 #include <sys/buf.h>
58 #include <sys/uio.h>
59 #include <sys/malloc.h>
60 #include <sys/errno.h>
61 #include <sys/device.h>
62 #include <sys/disklabel.h>
63 #include <sys/disk.h>
64 
65 #include <scsi/scsi_all.h>
66 #include <scsi/scsi_disk.h>
67 #include <scsi/scsiconf.h>
68 
69 #define	SDOUTSTANDING	2
70 #define	SDRETRIES	4
71 
72 #define	SDUNIT(dev)			DISKUNIT(dev)
73 #define	SDPART(dev)			DISKPART(dev)
74 #define	MAKESDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
75 
76 #define	SDLABELDEV(dev)	(MAKESDDEV(major(dev), SDUNIT(dev), RAW_PART))
77 
78 struct sd_softc {
79 	struct device sc_dev;
80 	struct dkdevice sc_dk;
81 
82 	int flags;
83 #define	SDF_LOCKED	0x01
84 #define	SDF_WANTED	0x02
85 #define	SDF_WLABEL	0x04		/* label is writable */
86 #define	SDF_LABELLING	0x08		/* writing label */
87 #define	SDF_ANCIENT	0x10		/* disk is ancient; for minphys */
88 	struct scsi_link *sc_link;	/* contains our targ, lun, etc. */
89 	struct disk_parms {
90 		u_char heads;		/* number of heads */
91 		u_short cyls;		/* number of cylinders */
92 		u_char sectors;		/* number of sectors/track */
93 		int blksize;		/* number of bytes/sector */
94 		u_long disksize;	/* total number sectors */
95 	} params;
96 	struct buf buf_queue;
97 };
98 
99 int sdmatch __P((struct device *, void *, void *));
100 void sdattach __P((struct device *, struct device *, void *));
101 
102 struct cfdriver sdcd = {
103 	NULL, "sd", sdmatch, sdattach, DV_DISK, sizeof(struct sd_softc)
104 };
105 
106 void sdgetdisklabel __P((struct sd_softc *));
107 int sd_get_parms __P((struct sd_softc *, int));
108 void sdstrategy __P((struct buf *));
109 void sdstart __P((struct sd_softc *));
110 void sdminphys __P((struct buf *));
111 
112 struct dkdriver sddkdriver = { sdstrategy };
113 
114 struct scsi_device sd_switch = {
115 	NULL,			/* Use default error handler */
116 	sdstart,		/* have a queue, served by this */
117 	NULL,			/* have no async handler */
118 	NULL,			/* Use default 'done' routine */
119 };
120 
121 struct scsi_inquiry_pattern sd_patterns[] = {
122 	{T_DIRECT, T_FIXED,
123 	 "",         "",                 ""},
124 	{T_DIRECT, T_REMOV,
125 	 "",         "",                 ""},
126 	{T_OPTICAL, T_FIXED,
127 	 "",         "",                 ""},
128 	{T_OPTICAL, T_REMOV,
129 	 "",         "",                 ""},
130 };
131 
132 int
133 sdmatch(parent, match, aux)
134 	struct device *parent;
135 	void *match, *aux;
136 {
137 	struct cfdata *cf = match;
138 	struct scsibus_attach_args *sa = aux;
139 	int priority;
140 
141 	(void)scsi_inqmatch(sa->sa_inqbuf,
142 	    (caddr_t)sd_patterns, sizeof(sd_patterns)/sizeof(sd_patterns[0]),
143 	    sizeof(sd_patterns[0]), &priority);
144 	return (priority);
145 }
146 
147 /*
148  * The routine called by the low level scsi routine when it discovers
149  * a device suitable for this driver.
150  */
151 void
152 sdattach(parent, self, aux)
153 	struct device *parent, *self;
154 	void *aux;
155 {
156 	struct sd_softc *sd = (void *)self;
157 	struct disk_parms *dp = &sd->params;
158 	struct scsibus_attach_args *sa = aux;
159 	struct scsi_link *sc_link = sa->sa_sc_link;
160 
161 	SC_DEBUG(sc_link, SDEV_DB2, ("sdattach: "));
162 
163 	/*
164 	 * Store information needed to contact our base driver
165 	 */
166 	sd->sc_link = sc_link;
167 	sc_link->device = &sd_switch;
168 	sc_link->device_softc = sd;
169 	if (sc_link->openings > SDOUTSTANDING)
170 		sc_link->openings = SDOUTSTANDING;
171 
172 	/*
173 	 * Note if this device is ancient.  This is used in sdminphys().
174 	 */
175 	if ((sa->sa_inqbuf->version & SID_ANSII) == 0)
176 		sd->flags |= SDF_ANCIENT;
177 
178 	sd->sc_dk.dk_driver = &sddkdriver;
179 #if !defined(i386) || defined(NEWCONFIG)
180 	dk_establish(&sd->sc_dk, &sd->sc_dev);
181 #endif
182 
183 	/*
184 	 * Use the subdriver to request information regarding
185 	 * the drive. We cannot use interrupts yet, so the
186 	 * request must specify this.
187 	 */
188 	if (scsi_start(sd->sc_link, SSS_START,
189 	    SCSI_AUTOCONF | SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE | SCSI_SILENT) ||
190 	    sd_get_parms(sd, SCSI_AUTOCONF) != 0)
191 		printf(": drive offline\n");
192 	else
193 	        printf(": %dMB, %d cyl, %d head, %d sec, %d bytes/sec\n",
194 		    dp->disksize / (1048576 / dp->blksize), dp->cyls,
195 		    dp->heads, dp->sectors, dp->blksize);
196 }
197 
198 /*
199  * Wait interruptibly for an exclusive lock.
200  *
201  * XXX
202  * Several drivers do this; it should be abstracted and made MP-safe.
203  */
204 int
205 sdlock(sd)
206 	struct sd_softc *sd;
207 {
208 	int error;
209 
210 	while ((sd->flags & SDF_LOCKED) != 0) {
211 		sd->flags |= SDF_WANTED;
212 		if ((error = tsleep(sd, PRIBIO | PCATCH, "sdlck", 0)) != 0)
213 			return error;
214 	}
215 	sd->flags |= SDF_LOCKED;
216 	return 0;
217 }
218 
219 /*
220  * Unlock and wake up any waiters.
221  */
222 void
223 sdunlock(sd)
224 	struct sd_softc *sd;
225 {
226 
227 	sd->flags &= ~SDF_LOCKED;
228 	if ((sd->flags & SDF_WANTED) != 0) {
229 		sd->flags &= ~SDF_WANTED;
230 		wakeup(sd);
231 	}
232 }
233 
234 /*
235  * open the device. Make sure the partition info is a up-to-date as can be.
236  */
237 int
238 sdopen(dev, flag, fmt)
239 	dev_t dev;
240 	int flag, fmt;
241 {
242 	struct sd_softc *sd;
243 	struct scsi_link *sc_link;
244 	int unit, part;
245 	int error;
246 
247 	unit = SDUNIT(dev);
248 	if (unit >= sdcd.cd_ndevs)
249 		return ENXIO;
250 	sd = sdcd.cd_devs[unit];
251 	if (!sd)
252 		return ENXIO;
253 
254 	sc_link = sd->sc_link;
255 
256 	SC_DEBUG(sc_link, SDEV_DB1,
257 	    ("sdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev, unit,
258 	    sdcd.cd_ndevs, part));
259 
260 	if (error = sdlock(sd))
261 		return error;
262 
263 	if (sd->sc_dk.dk_openmask != 0) {
264 		/*
265 		 * If any partition is open, but the disk has been invalidated,
266 		 * disallow further opens.
267 		 */
268 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
269 			error = EIO;
270 			goto bad3;
271 		}
272 	} else {
273 		/* Check that it is still responding and ok. */
274 		if (error = scsi_test_unit_ready(sc_link,
275 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE | SCSI_IGNORE_NOT_READY))
276 			goto bad3;
277 
278 		/* Start the pack spinning if necessary. */
279 		if (error = scsi_start(sc_link, SSS_START,
280 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE | SCSI_SILENT))
281 			goto bad3;
282 
283 		sc_link->flags |= SDEV_OPEN;
284 
285 		/* Lock the pack in. */
286 		if (error = scsi_prevent(sc_link, PR_PREVENT,
287 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE))
288 			goto bad;
289 
290 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
291 			sc_link->flags |= SDEV_MEDIA_LOADED;
292 
293 			/* Load the physical device parameters. */
294 			if (sd_get_parms(sd, 0) != 0) {
295 				error = ENXIO;
296 				goto bad2;
297 			}
298 			SC_DEBUG(sc_link, SDEV_DB3, ("Params loaded "));
299 
300 			/* Load the partition info if not already loaded. */
301 			sdgetdisklabel(sd);
302 			SC_DEBUG(sc_link, SDEV_DB3, ("Disklabel loaded "));
303 		}
304 	}
305 
306 	part = SDPART(dev);
307 
308 	/* Check that the partition exists. */
309 	if (part != RAW_PART &&
310 	    (part >= sd->sc_dk.dk_label.d_npartitions ||
311 	     sd->sc_dk.dk_label.d_partitions[part].p_fstype == FS_UNUSED)) {
312 		error = ENXIO;
313 		goto bad;
314 	}
315 
316 	/* Insure only one open at a time. */
317 	switch (fmt) {
318 	case S_IFCHR:
319 		sd->sc_dk.dk_copenmask |= (1 << part);
320 		break;
321 	case S_IFBLK:
322 		sd->sc_dk.dk_bopenmask |= (1 << part);
323 		break;
324 	}
325 	sd->sc_dk.dk_openmask = sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
326 
327 	SC_DEBUG(sc_link, SDEV_DB3, ("open complete\n"));
328 	sdunlock(sd);
329 	return 0;
330 
331 bad2:
332 	sc_link->flags &= ~SDEV_MEDIA_LOADED;
333 
334 bad:
335 	if (sd->sc_dk.dk_openmask == 0) {
336 		scsi_prevent(sc_link, PR_ALLOW,
337 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE);
338 		sc_link->flags &= ~SDEV_OPEN;
339 	}
340 
341 bad3:
342 	sdunlock(sd);
343 	return error;
344 }
345 
346 /*
347  * close the device.. only called if we are the LAST occurence of an open
348  * device.  Convenient now but usually a pain.
349  */
350 int
351 sdclose(dev, flag, fmt)
352 	dev_t dev;
353 	int flag, fmt;
354 {
355 	struct sd_softc *sd = sdcd.cd_devs[SDUNIT(dev)];
356 	int part = SDPART(dev);
357 	int error;
358 
359 	if (error = sdlock(sd))
360 		return error;
361 
362 	switch (fmt) {
363 	case S_IFCHR:
364 		sd->sc_dk.dk_copenmask &= ~(1 << part);
365 		break;
366 	case S_IFBLK:
367 		sd->sc_dk.dk_bopenmask &= ~(1 << part);
368 		break;
369 	}
370 	sd->sc_dk.dk_openmask = sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
371 
372 	if (sd->sc_dk.dk_openmask == 0) {
373 		/* XXXX Must wait for I/O to complete! */
374 
375 		scsi_prevent(sd->sc_link, PR_ALLOW,
376 		    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_NOT_READY);
377 		sd->sc_link->flags &= ~SDEV_OPEN;
378 	}
379 
380 	sdunlock(sd);
381 	return 0;
382 }
383 
384 /*
385  * Actually translate the requested transfer into one the physical driver
386  * can understand.  The transfer is described by a buf and will include
387  * only one physical transfer.
388  */
389 void
390 sdstrategy(bp)
391 	struct buf *bp;
392 {
393 	struct sd_softc *sd = sdcd.cd_devs[SDUNIT(bp->b_dev)];
394 	int s;
395 
396 	SC_DEBUG(sd->sc_link, SDEV_DB2, ("sdstrategy "));
397 	SC_DEBUG(sd->sc_link, SDEV_DB1,
398 	    ("%d bytes @ blk %d\n", bp->b_bcount, bp->b_blkno));
399 	/*
400 	 * The transfer must be a whole number of blocks.
401 	 */
402 	if ((bp->b_bcount % sd->sc_dk.dk_label.d_secsize) != 0) {
403 		bp->b_error = EINVAL;
404 		goto bad;
405 	}
406 	/*
407 	 * If the device has been made invalid, error out
408 	 */
409 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
410 		bp->b_error = EIO;
411 		goto bad;
412 	}
413 	/*
414 	 * If it's a null transfer, return immediatly
415 	 */
416 	if (bp->b_bcount == 0)
417 		goto done;
418 
419 	/*
420 	 * Do bounds checking, adjust transfer. if error, process.
421 	 * If end of partition, just return.
422 	 */
423 	if (SDPART(bp->b_dev) != RAW_PART &&
424 	    bounds_check_with_label(bp, &sd->sc_dk.dk_label,
425 	    (sd->flags & (SDF_WLABEL|SDF_LABELLING)) != 0) <= 0)
426 		goto done;
427 
428 	s = splbio();
429 
430 	/*
431 	 * Place it in the queue of disk activities for this disk
432 	 */
433 	disksort(&sd->buf_queue, bp);
434 
435 	/*
436 	 * Tell the device to get going on the transfer if it's
437 	 * not doing anything, otherwise just wait for completion
438 	 */
439 	sdstart(sd);
440 
441 	splx(s);
442 	return;
443 
444 bad:
445 	bp->b_flags |= B_ERROR;
446 done:
447 	/*
448 	 * Correctly set the buf to indicate a completed xfer
449 	 */
450 	bp->b_resid = bp->b_bcount;
451 	biodone(bp);
452 }
453 
454 /*
455  * sdstart looks to see if there is a buf waiting for the device
456  * and that the device is not already busy. If both are true,
457  * It dequeues the buf and creates a scsi command to perform the
458  * transfer in the buf. The transfer request will call scsi_done
459  * on completion, which will in turn call this routine again
460  * so that the next queued transfer is performed.
461  * The bufs are queued by the strategy routine (sdstrategy)
462  *
463  * This routine is also called after other non-queued requests
464  * have been made of the scsi driver, to ensure that the queue
465  * continues to be drained.
466  *
467  * must be called at the correct (highish) spl level
468  * sdstart() is called at splbio from sdstrategy and scsi_done
469  */
470 void
471 sdstart(sd)
472 	register struct sd_softc *sd;
473 {
474 	register struct	scsi_link *sc_link = sd->sc_link;
475 	struct buf *bp = 0;
476 	struct buf *dp;
477 	struct scsi_rw_big cmd_big;
478 	struct scsi_rw cmd_small;
479 	struct scsi_generic *cmdp;
480 	int blkno, nblks, cmdlen;
481 	struct partition *p;
482 
483 	SC_DEBUG(sc_link, SDEV_DB2, ("sdstart "));
484 	/*
485 	 * Check if the device has room for another command
486 	 */
487 	while (sc_link->openings > 0) {
488 		/*
489 		 * there is excess capacity, but a special waits
490 		 * It'll need the adapter as soon as we clear out of the
491 		 * way and let it run (user level wait).
492 		 */
493 		if (sc_link->flags & SDEV_WAITING) {
494 			sc_link->flags &= ~SDEV_WAITING;
495 			wakeup((caddr_t)sc_link);
496 			return;
497 		}
498 
499 		/*
500 		 * See if there is a buf with work for us to do..
501 		 */
502 		dp = &sd->buf_queue;
503 		if ((bp = dp->b_actf) == NULL)	/* yes, an assign */
504 			return;
505 		dp->b_actf = bp->b_actf;
506 
507 		/*
508 		 * If the device has become invalid, abort all the
509 		 * reads and writes until all files have been closed and
510 		 * re-opened
511 		 */
512 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
513 			bp->b_error = EIO;
514 			bp->b_flags |= B_ERROR;
515 			biodone(bp);
516 			continue;
517 		}
518 
519 		/*
520 		 * We have a buf, now we should make a command
521 		 *
522 		 * First, translate the block to absolute and put it in terms
523 		 * of the logical blocksize of the device.
524 		 */
525 		blkno =
526 		    bp->b_blkno / (sd->sc_dk.dk_label.d_secsize / DEV_BSIZE);
527 		if (SDPART(bp->b_dev) != RAW_PART) {
528 			p = &sd->sc_dk.dk_label.d_partitions[SDPART(bp->b_dev)];
529 			blkno += p->p_offset;
530 		}
531 		nblks = howmany(bp->b_bcount, sd->sc_dk.dk_label.d_secsize);
532 
533 		/*
534 		 *  Fill out the scsi command.  If the transfer will
535 		 *  fit in a "small" cdb, use it.
536 		 */
537 		if (((blkno & 0x1fffff) == blkno) &&
538 		    ((nblks & 0xff) == nblks)) {
539 			/*
540 			 * We can fit in a small cdb.
541 			 */
542 			bzero(&cmd_small, sizeof(cmd_small));
543 			cmd_small.opcode = (bp->b_flags & B_READ) ?
544 			    READ_COMMAND : WRITE_COMMAND;
545 			cmd_small.addr_2 = (blkno >> 16) & 0x1f;
546 			cmd_small.addr_1 = (blkno >> 8) & 0xff;
547 			cmd_small.addr_0 = blkno & 0xff;
548 			cmd_small.length = nblks & 0xff;
549 			cmdlen = sizeof(cmd_small);
550 			cmdp = (struct scsi_generic *)&cmd_small;
551 		} else {
552 			/*
553 			 * Need a large cdb.
554 			 */
555 			bzero(&cmd_big, sizeof(cmd_big));
556 			cmd_big.opcode = (bp->b_flags & B_READ) ?
557 			    READ_BIG : WRITE_BIG;
558 			cmd_big.addr_3 = (blkno >> 24) & 0xff;
559 			cmd_big.addr_2 = (blkno >> 16) & 0xff;
560 			cmd_big.addr_1 = (blkno >> 8) & 0xff;
561 			cmd_big.addr_0 = blkno & 0xff;
562 			cmd_big.length2 = (nblks >> 8) & 0xff;
563 			cmd_big.length1 = nblks & 0xff;
564 			cmdlen = sizeof(cmd_big);
565 			cmdp = (struct scsi_generic *)&cmd_big;
566 		}
567 
568 		/*
569 		 * Call the routine that chats with the adapter.
570 		 * Note: we cannot sleep as we may be an interrupt
571 		 */
572 		if (scsi_scsi_cmd(sc_link, cmdp, cmdlen,
573 		    (u_char *)bp->b_data, bp->b_bcount,
574 		    SDRETRIES, 10000, bp, SCSI_NOSLEEP |
575 		    ((bp->b_flags & B_READ) ? SCSI_DATA_IN : SCSI_DATA_OUT)))
576 			printf("%s: not queued", sd->sc_dev.dv_xname);
577 	}
578 }
579 
580 void
581 sdminphys(bp)
582 	struct buf *bp;
583 {
584 	struct sd_softc *sd = sdcd.cd_devs[SDUNIT(bp->b_dev)];
585 	long max;
586 
587 	/*
588 	 * If the device is ancient, we want to make sure that
589 	 * the transfer fits into a 6-byte cdb.
590 	 *
591 	 * XXX Note that the SCSI-I spec says that 256-block transfers
592 	 * are allowed in a 6-byte read/write, and are specified
593 	 * by settng the "length" to 0.  However, we're conservative
594 	 * here, allowing only 255-block transfers in case an
595 	 * ancient device gets confused by length == 0.  A length of 0
596 	 * in a 10-byte read/write actually means 0 blocks.
597 	 */
598 	if (sd->flags & SDF_ANCIENT) {
599 		max = sd->sc_dk.dk_label.d_secsize * 0xff;
600 
601 		if (bp->b_bcount > max)
602 			bp->b_bcount = max;
603 	}
604 
605 	(*sd->sc_link->adapter->scsi_minphys)(bp);
606 }
607 
608 int
609 sdread(dev, uio)
610 	dev_t dev;
611 	struct uio *uio;
612 {
613 
614 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
615 }
616 
617 int
618 sdwrite(dev, uio)
619 	dev_t dev;
620 	struct uio *uio;
621 {
622 
623 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
624 }
625 
626 /*
627  * Perform special action on behalf of the user
628  * Knows about the internals of this device
629  */
630 int
631 sdioctl(dev, cmd, addr, flag, p)
632 	dev_t dev;
633 	u_long cmd;
634 	caddr_t addr;
635 	int flag;
636 	struct proc *p;
637 {
638 	struct sd_softc *sd = sdcd.cd_devs[SDUNIT(dev)];
639 	int error;
640 
641 	SC_DEBUG(sd->sc_link, SDEV_DB2, ("sdioctl 0x%lx ", cmd));
642 
643 	/*
644 	 * If the device is not valid.. abandon ship
645 	 */
646 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0)
647 		return EIO;
648 
649 	switch (cmd) {
650 	case DIOCGDINFO:
651 		*(struct disklabel *)addr = sd->sc_dk.dk_label;
652 		return 0;
653 
654 	case DIOCGPART:
655 		((struct partinfo *)addr)->disklab = &sd->sc_dk.dk_label;
656 		((struct partinfo *)addr)->part =
657 		    &sd->sc_dk.dk_label.d_partitions[SDPART(dev)];
658 		return 0;
659 
660 	case DIOCWDINFO:
661 	case DIOCSDINFO:
662 		if ((flag & FWRITE) == 0)
663 			return EBADF;
664 
665 		if (error = sdlock(sd))
666 			return error;
667 		sd->flags |= SDF_LABELLING;
668 
669 		error = setdisklabel(&sd->sc_dk.dk_label,
670 		    (struct disklabel *)addr, /*sd->sc_dk.dk_openmask : */0,
671 		    &sd->sc_dk.dk_cpulabel);
672 		if (error == 0) {
673 			if (cmd == DIOCWDINFO)
674 				error = writedisklabel(SDLABELDEV(dev),
675 				    sdstrategy, &sd->sc_dk.dk_label,
676 				    &sd->sc_dk.dk_cpulabel);
677 		}
678 
679 		sd->flags &= ~SDF_LABELLING;
680 		sdunlock(sd);
681 		return error;
682 
683 	case DIOCWLABEL:
684 		if ((flag & FWRITE) == 0)
685 			return EBADF;
686 		if (*(int *)addr)
687 			sd->flags |= SDF_WLABEL;
688 		else
689 			sd->flags &= ~SDF_WLABEL;
690 		return 0;
691 
692 	default:
693 		if (SDPART(dev) != RAW_PART)
694 			return ENOTTY;
695 		return scsi_do_ioctl(sd->sc_link, dev, cmd, addr, flag, p);
696 	}
697 
698 #ifdef DIAGNOSTIC
699 	panic("sdioctl: impossible");
700 #endif
701 }
702 
703 /*
704  * Load the label information on the named device
705  */
706 void
707 sdgetdisklabel(sd)
708 	struct sd_softc *sd;
709 {
710 	struct disklabel *lp = &sd->sc_dk.dk_label;
711 	char *errstring;
712 
713 	bzero(lp, sizeof(struct disklabel));
714 	bzero(&sd->sc_dk.dk_cpulabel, sizeof(struct cpu_disklabel));
715 
716 	lp->d_secsize = sd->params.blksize;
717 	lp->d_ntracks = sd->params.heads;
718 	lp->d_nsectors = sd->params.sectors;
719 	lp->d_ncylinders = sd->params.cyls;
720 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
721 	if (lp->d_secpercyl == 0) {
722 		lp->d_secpercyl = 100;
723 		/* as long as it's not 0 - readdisklabel divides by it (?) */
724 	}
725 
726 	strncpy(lp->d_typename, "SCSI disk", 16);
727 	lp->d_type = DTYPE_SCSI;
728 	strncpy(lp->d_packname, "fictitious", 16);
729 	lp->d_secperunit = sd->params.disksize;
730 	lp->d_rpm = 3600;
731 	lp->d_interleave = 1;
732 	lp->d_flags = 0;
733 
734 	lp->d_partitions[RAW_PART].p_offset = 0;
735 	lp->d_partitions[RAW_PART].p_size =
736 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
737 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
738 	lp->d_npartitions = RAW_PART + 1;
739 
740 	lp->d_magic = DISKMAGIC;
741 	lp->d_magic2 = DISKMAGIC;
742 	lp->d_checksum = dkcksum(lp);
743 
744 	/*
745 	 * Call the generic disklabel extraction routine
746 	 */
747 	if (errstring = readdisklabel(MAKESDDEV(0, sd->sc_dev.dv_unit,
748 	    RAW_PART), sdstrategy, lp, &sd->sc_dk.dk_cpulabel)) {
749 		printf("%s: %s\n", sd->sc_dev.dv_xname, errstring);
750 		return;
751 	}
752 }
753 
754 /*
755  * Find out from the device what it's capacity is
756  */
757 u_long
758 sd_size(sd, flags)
759 	struct sd_softc *sd;
760 	int flags;
761 {
762 	struct scsi_read_cap_data rdcap;
763 	struct scsi_read_capacity scsi_cmd;
764 	u_long size;
765 
766 	/*
767 	 * make up a scsi command and ask the scsi driver to do
768 	 * it for you.
769 	 */
770 	bzero(&scsi_cmd, sizeof(scsi_cmd));
771 	scsi_cmd.opcode = READ_CAPACITY;
772 
773 	/*
774 	 * If the command works, interpret the result as a 4 byte
775 	 * number of blocks
776 	 */
777 	if (scsi_scsi_cmd(sd->sc_link, (struct scsi_generic *)&scsi_cmd,
778 	    sizeof(scsi_cmd), (u_char *)&rdcap, sizeof(rdcap), SDRETRIES,
779 	    2000, NULL, flags | SCSI_DATA_IN) != 0)
780 		return 0;
781 
782 	size = (rdcap.addr_3 << 24) + (rdcap.addr_2 << 16) +
783 	    (rdcap.addr_1 << 8) + rdcap.addr_0 + 1;
784 
785 	return size;
786 }
787 
788 /*
789  * Tell the device to map out a defective block
790  */
791 int
792 sd_reassign_blocks(sd, block)
793 	struct sd_softc *sd;
794 	u_long block;
795 {
796 	struct scsi_reassign_blocks scsi_cmd;
797 	struct scsi_reassign_blocks_data rbdata;
798 
799 	bzero(&scsi_cmd, sizeof(scsi_cmd));
800 	bzero(&rbdata, sizeof(rbdata));
801 	scsi_cmd.opcode = REASSIGN_BLOCKS;
802 
803 	rbdata.length_msb = 0;
804 	rbdata.length_lsb = sizeof(rbdata.defect_descriptor[0]);
805 	rbdata.defect_descriptor[0].dlbaddr_3 = (block >> 24) & 0xff;
806 	rbdata.defect_descriptor[0].dlbaddr_2 = (block >> 16) & 0xff;
807 	rbdata.defect_descriptor[0].dlbaddr_1 = (block >> 8) & 0xff;
808 	rbdata.defect_descriptor[0].dlbaddr_0 = block & 0xff;
809 
810 	return scsi_scsi_cmd(sd->sc_link, (struct scsi_generic *)&scsi_cmd,
811 	    sizeof(scsi_cmd), (u_char *)&rbdata, sizeof(rbdata), SDRETRIES,
812 	    5000, NULL, SCSI_DATA_OUT);
813 }
814 
815 #define b2tol(a)	(((unsigned)(a##_1) << 8) + (unsigned)a##_0 )
816 
817 /*
818  * Get the scsi driver to send a full inquiry to the * device and use the
819  * results to fill out the disk parameter structure.
820  */
821 int
822 sd_get_parms(sd, flags)
823 	struct sd_softc *sd;
824 	int flags;
825 {
826 	struct disk_parms *dp = &sd->params;
827 	struct scsi_mode_sense scsi_cmd;
828 	struct scsi_mode_sense_data {
829 		struct scsi_mode_header header;
830 		struct scsi_blk_desc blk_desc;
831 		union disk_pages pages;
832 	} scsi_sense;
833 	u_long sectors;
834 
835 	/*
836 	 * do a "mode sense page 4"
837 	 */
838 	bzero(&scsi_cmd, sizeof(scsi_cmd));
839 	scsi_cmd.opcode = MODE_SENSE;
840 	scsi_cmd.page = 4;
841 	scsi_cmd.length = 0x20;
842 	/*
843 	 * If the command worked, use the results to fill out
844 	 * the parameter structure
845 	 */
846 	if (scsi_scsi_cmd(sd->sc_link, (struct scsi_generic *)&scsi_cmd,
847 	    sizeof(scsi_cmd), (u_char *)&scsi_sense, sizeof(scsi_sense),
848 	    SDRETRIES, 6000, NULL, flags | SCSI_DATA_IN) != 0) {
849 		printf("%s: could not mode sense (4)", sd->sc_dev.dv_xname);
850 	fake_it:
851 		printf("; using fictitious geometry\n");
852 		/*
853 		 * use adaptec standard fictitious geometry
854 		 * this depends on which controller (e.g. 1542C is
855 		 * different. but we have to put SOMETHING here..)
856 		 */
857 		sectors = sd_size(sd, flags);
858 		dp->heads = 64;
859 		dp->sectors = 32;
860 		dp->cyls = sectors / (64 * 32);
861 		dp->blksize = 512;
862 		dp->disksize = sectors;
863 	} else {
864 		SC_DEBUG(sd->sc_link, SDEV_DB3,
865 		    ("%d cyls, %d heads, %d precomp, %d red_write, %d land_zone\n",
866 		    _3btol(&scsi_sense.pages.rigid_geometry.ncyl_2),
867 		    scsi_sense.pages.rigid_geometry.nheads,
868 		    b2tol(scsi_sense.pages.rigid_geometry.st_cyl_wp),
869 		    b2tol(scsi_sense.pages.rigid_geometry.st_cyl_rwc),
870 		    b2tol(scsi_sense.pages.rigid_geometry.land_zone)));
871 
872 		/*
873 		 * KLUDGE!! (for zone recorded disks)
874 		 * give a number of sectors so that sec * trks * cyls
875 		 * is <= disk_size
876 		 * can lead to wasted space! THINK ABOUT THIS !
877 		 */
878 		dp->heads = scsi_sense.pages.rigid_geometry.nheads;
879 		dp->cyls =
880 		    _3btol(&scsi_sense.pages.rigid_geometry.ncyl_2);
881 		dp->blksize = _3btol(scsi_sense.blk_desc.blklen);
882 
883 		if (dp->heads == 0 || dp->cyls == 0) {
884 			printf("%s: mode sense (4) returned nonsense",
885 			    sd->sc_dev.dv_xname);
886 			goto fake_it;
887 		}
888 
889 		if (dp->blksize == 0)
890 			dp->blksize = 512;
891 
892 		sectors = sd_size(sd, flags);
893 		dp->disksize = sectors;
894 		sectors /= (dp->heads * dp->cyls);
895 		dp->sectors = sectors;	/* XXX dubious on SCSI */
896 	}
897 
898 	return 0;
899 }
900 
901 int
902 sdsize(dev)
903 	dev_t dev;
904 {
905 	struct sd_softc *sd;
906 	int part;
907 	int size;
908 
909 	if (sdopen(dev, 0, S_IFBLK) != 0)
910 		return -1;
911 	sd = sdcd.cd_devs[SDUNIT(dev)];
912 	part = SDPART(dev);
913 	if (sd->sc_dk.dk_label.d_partitions[part].p_fstype != FS_SWAP)
914 		size = -1;
915 	else
916 		size = sd->sc_dk.dk_label.d_partitions[part].p_size;
917 	if (sdclose(dev, 0, S_IFBLK) != 0)
918 		return -1;
919 	return size;
920 }
921 
922 #ifndef __BDEVSW_DUMP_OLD_TYPE
923 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
924 static struct scsi_xfer sx;
925 static int sddoingadump;
926 
927 /*
928  * dump all of physical memory into the partition specified, starting
929  * at offset 'dumplo' into the partition.
930  */
931 int
932 sddump(dev, blkno, va, size)
933 	dev_t dev;
934 	daddr_t blkno;
935 	caddr_t va;
936 	size_t size;
937 {
938 	struct sd_softc *sd;	/* disk unit to do the I/O */
939 	struct disklabel *lp;	/* disk's disklabel */
940 	int	unit, part;
941 	int	sectorsize;	/* size of a disk sector */
942 	int	nsects;		/* number of sectors in partition */
943 	int	sectoff;	/* sector offset of partition */
944 	int	totwrt;		/* total number of sectors left to write */
945 	int	nwrt;		/* current number of sectors to write */
946 	struct scsi_rw_big cmd;	/* write command */
947 	struct scsi_xfer *xs;	/* ... convenience */
948 	int	retval;
949 
950 	/* Check if recursive dump; if so, punt. */
951 	if (sddoingadump)
952 		return EFAULT;
953 
954 	/* Mark as active early. */
955 	sddoingadump = 1;
956 
957 	unit = SDUNIT(dev);	/* Decompose unit & partition. */
958 	part = SDPART(dev);
959 
960 	/* Check for acceptable drive number. */
961 	if (unit >= sdcd.cd_ndevs || (sd = sdcd.cd_devs[unit]) == NULL)
962 		return ENXIO;
963 
964 	/* Make sure it was initialized. */
965 	if (sd->sc_link->flags & SDEV_MEDIA_LOADED != SDEV_MEDIA_LOADED)
966 		return ENXIO;
967 
968 	/* Convert to disk sectors.  Request must be a multiple of size. */
969 	lp = &sd->sc_dk.dk_label;
970 	sectorsize = lp->d_secsize;
971 	if ((size % sectorsize) != 0)
972 		return EFAULT;
973 	totwrt = size / sectorsize;
974 	blkno = dbtob(blkno) / sectorsize;	/* blkno in DEV_BSIZE units */
975 
976 	nsects = lp->d_partitions[part].p_size;
977 	sectoff = lp->d_partitions[part].p_offset;
978 
979 	/* Check transfer bounds against partition size. */
980 	if ((blkno < 0) || ((blkno + totwrt) > nsects))
981 		return EINVAL;
982 
983 	/* Offset block number to start of partition. */
984 	blkno += sectoff;
985 
986 	xs = &sx;
987 
988 	while (totwrt > 0) {
989 		nwrt = totwrt;		/* XXX */
990 #ifndef	SD_DUMP_NOT_TRUSTED
991 		/*
992 		 *  Fill out the scsi command
993 		 */
994 		bzero(&cmd, sizeof(cmd));
995 		cmd.opcode = WRITE_BIG;
996 		cmd.addr_3 = (blkno >> 24) & 0xff;
997 		cmd.addr_2 = (blkno >> 16) & 0xff;
998 		cmd.addr_1 = (blkno >> 8) & 0xff;
999 		cmd.addr_0 = blkno & 0xff;
1000 		cmd.length2 = (nwrt >> 8) & 0xff;
1001 		cmd.length1 = nwrt & 0xff;
1002 		/*
1003 		 * Fill out the scsi_xfer structure
1004 		 *    Note: we cannot sleep as we may be an interrupt
1005 		 * don't use scsi_scsi_cmd() as it may want
1006 		 * to wait for an xs.
1007 		 */
1008 		bzero(xs, sizeof(sx));
1009 		xs->flags |= SCSI_AUTOCONF | INUSE | SCSI_DATA_OUT;
1010 		xs->sc_link = sd->sc_link;
1011 		xs->retries = SDRETRIES;
1012 		xs->timeout = 10000;	/* 10000 millisecs for a disk ! */
1013 		xs->cmd = (struct scsi_generic *)&cmd;
1014 		xs->cmdlen = sizeof(cmd);
1015 		xs->resid = nwrt * sectorsize;
1016 		xs->error = XS_NOERROR;
1017 		xs->bp = 0;
1018 		xs->data = va;
1019 		xs->datalen = nwrt * sectorsize;
1020 
1021 		/*
1022 		 * Pass all this info to the scsi driver.
1023 		 */
1024 		retval = (*(sd->sc_link->adapter->scsi_cmd)) (xs);
1025 		if (retval != COMPLETE)
1026 			return ENXIO;
1027 #else	/* SD_DUMP_NOT_TRUSTED */
1028 		/* Let's just talk about this first... */
1029 		printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
1030 		delay(500 * 1000);	/* half a second */
1031 #endif	/* SD_DUMP_NOT_TRUSTED */
1032 
1033 		/* update block count */
1034 		totwrt -= nwrt;
1035 		blkno += nwrt;
1036 		va += sectorsize * nwrt;
1037 	}
1038 	sddoingadump = 0;
1039 	return 0;
1040 }
1041 #else	/* __BDEVSW_DUMP_NEW_TYPE */
1042 int
1043 sddump(dev, blkno, va, size)
1044 	dev_t dev;
1045 	daddr_t blkno;
1046 	caddr_t va;
1047 	size_t size;
1048 {
1049 
1050 	/* Not implemented. */
1051 	return ENXIO;
1052 }
1053 #endif	/* __BDEVSW_DUMP_NEW_TYPE */
1054