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