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