Home | History | Annotate | Line # | Download | only in scsipi
sd.c revision 1.141
      1 /*	$NetBSD: sd.c,v 1.141 1999/01/29 11:17:59 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 || fmt != S_IFCHR)) {
    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 || fmt != S_IFCHR)
    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 		if (sd->sc_link->flags & SDEV_OPEN)
    473 			bp->b_error = EIO;
    474 		else
    475 			bp->b_error = ENODEV;
    476 		goto bad;
    477 	}
    478 	/*
    479 	 * The transfer must be a whole number of blocks.
    480 	 */
    481 	if ((bp->b_bcount % sd->sc_dk.dk_label->d_secsize) != 0) {
    482 		bp->b_error = EINVAL;
    483 		goto bad;
    484 	}
    485 	/*
    486 	 * If it's a null transfer, return immediatly
    487 	 */
    488 	if (bp->b_bcount == 0)
    489 		goto done;
    490 
    491 	/*
    492 	 * Do bounds checking, adjust transfer. if error, process.
    493 	 * If end of partition, just return.
    494 	 */
    495 	if (SDPART(bp->b_dev) != RAW_PART &&
    496 	    bounds_check_with_label(bp, sd->sc_dk.dk_label,
    497 	    (sd->flags & (SDF_WLABEL|SDF_LABELLING)) != 0) <= 0)
    498 		goto done;
    499 
    500 	s = splbio();
    501 
    502 	/*
    503 	 * Place it in the queue of disk activities for this disk
    504 	 */
    505 	disksort(&sd->buf_queue, bp);
    506 
    507 	/*
    508 	 * Tell the device to get going on the transfer if it's
    509 	 * not doing anything, otherwise just wait for completion
    510 	 */
    511 	sdstart(sd);
    512 
    513 	splx(s);
    514 	return;
    515 
    516 bad:
    517 	bp->b_flags |= B_ERROR;
    518 done:
    519 	/*
    520 	 * Correctly set the buf to indicate a completed xfer
    521 	 */
    522 	bp->b_resid = bp->b_bcount;
    523 	biodone(bp);
    524 }
    525 
    526 /*
    527  * sdstart looks to see if there is a buf waiting for the device
    528  * and that the device is not already busy. If both are true,
    529  * It dequeues the buf and creates a scsi command to perform the
    530  * transfer in the buf. The transfer request will call scsipi_done
    531  * on completion, which will in turn call this routine again
    532  * so that the next queued transfer is performed.
    533  * The bufs are queued by the strategy routine (sdstrategy)
    534  *
    535  * This routine is also called after other non-queued requests
    536  * have been made of the scsi driver, to ensure that the queue
    537  * continues to be drained.
    538  *
    539  * must be called at the correct (highish) spl level
    540  * sdstart() is called at splbio from sdstrategy and scsipi_done
    541  */
    542 void
    543 sdstart(v)
    544 	register void *v;
    545 {
    546 	register struct sd_softc *sd = v;
    547 	register struct	scsipi_link *sc_link = sd->sc_link;
    548 	struct disklabel *lp = sd->sc_dk.dk_label;
    549 	struct buf *bp = 0;
    550 	struct buf *dp;
    551 	struct scsipi_rw_big cmd_big;
    552 #if NSD_SCSIBUS > 0
    553 	struct scsi_rw cmd_small;
    554 #endif
    555 	struct scsipi_generic *cmdp;
    556 	int blkno, nblks, cmdlen, error;
    557 	struct partition *p;
    558 
    559 	SC_DEBUG(sc_link, SDEV_DB2, ("sdstart "));
    560 	/*
    561 	 * Check if the device has room for another command
    562 	 */
    563 	while (sc_link->openings > 0) {
    564 		/*
    565 		 * there is excess capacity, but a special waits
    566 		 * It'll need the adapter as soon as we clear out of the
    567 		 * way and let it run (user level wait).
    568 		 */
    569 		if (sc_link->flags & SDEV_WAITING) {
    570 			sc_link->flags &= ~SDEV_WAITING;
    571 			wakeup((caddr_t)sc_link);
    572 			return;
    573 		}
    574 
    575 		/*
    576 		 * See if there is a buf with work for us to do..
    577 		 */
    578 		dp = &sd->buf_queue;
    579 		if ((bp = dp->b_actf) == NULL)	/* yes, an assign */
    580 			return;
    581 		dp->b_actf = bp->b_actf;
    582 
    583 		/*
    584 		 * If the device has become invalid, abort all the
    585 		 * reads and writes until all files have been closed and
    586 		 * re-opened
    587 		 */
    588 		if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
    589 			bp->b_error = EIO;
    590 			bp->b_flags |= B_ERROR;
    591 			bp->b_resid = bp->b_bcount;
    592 			biodone(bp);
    593 			continue;
    594 		}
    595 
    596 		/*
    597 		 * We have a buf, now we should make a command
    598 		 *
    599 		 * First, translate the block to absolute and put it in terms
    600 		 * of the logical blocksize of the device.
    601 		 */
    602 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
    603 		if (SDPART(bp->b_dev) != RAW_PART) {
    604 			p = &lp->d_partitions[SDPART(bp->b_dev)];
    605 			blkno += p->p_offset;
    606 		}
    607 		nblks = howmany(bp->b_bcount, lp->d_secsize);
    608 
    609 #if NSD_SCSIBUS > 0
    610 		/*
    611 		 *  Fill out the scsi command.  If the transfer will
    612 		 *  fit in a "small" cdb, use it.
    613 		 */
    614 		if (((blkno & 0x1fffff) == blkno) &&
    615 		    ((nblks & 0xff) == nblks) && sc_link->type == BUS_SCSI) {
    616 			/*
    617 			 * We can fit in a small cdb.
    618 			 */
    619 			bzero(&cmd_small, sizeof(cmd_small));
    620 			cmd_small.opcode = (bp->b_flags & B_READ) ?
    621 			    SCSI_READ_COMMAND : SCSI_WRITE_COMMAND;
    622 			_lto3b(blkno, cmd_small.addr);
    623 			cmd_small.length = nblks & 0xff;
    624 			cmdlen = sizeof(cmd_small);
    625 			cmdp = (struct scsipi_generic *)&cmd_small;
    626 		} else
    627 #endif
    628 		{
    629 			/*
    630 			 * Need a large cdb.
    631 			 */
    632 			bzero(&cmd_big, sizeof(cmd_big));
    633 			cmd_big.opcode = (bp->b_flags & B_READ) ?
    634 			    READ_BIG : WRITE_BIG;
    635 			_lto4b(blkno, cmd_big.addr);
    636 			_lto2b(nblks, cmd_big.length);
    637 			cmdlen = sizeof(cmd_big);
    638 			cmdp = (struct scsipi_generic *)&cmd_big;
    639 		}
    640 
    641 		/* Instrumentation. */
    642 		disk_busy(&sd->sc_dk);
    643 
    644 		/*
    645 		 * Mark the disk dirty so that the cache will be
    646 		 * flushed on close.
    647 		 */
    648 		if ((bp->b_flags & B_READ) == 0)
    649 			sd->flags |= SDF_DIRTY;
    650 
    651 		/*
    652 		 * Call the routine that chats with the adapter.
    653 		 * Note: we cannot sleep as we may be an interrupt
    654 		 */
    655 		error = scsipi_command(sc_link, cmdp, cmdlen,
    656 		    (u_char *)bp->b_data, bp->b_bcount,
    657 		    SDRETRIES, 60000, bp, SCSI_NOSLEEP |
    658 		    ((bp->b_flags & B_READ) ? SCSI_DATA_IN : SCSI_DATA_OUT));
    659 		if (error) {
    660 			disk_unbusy(&sd->sc_dk, 0);
    661 			printf("%s: not queued, error %d\n",
    662 			    sd->sc_dev.dv_xname, error);
    663 		}
    664 	}
    665 }
    666 
    667 void
    668 sddone(xs)
    669 	struct scsipi_xfer *xs;
    670 {
    671 	struct sd_softc *sd = xs->sc_link->device_softc;
    672 
    673 	if (sd->flags & SDF_FLUSHING) {
    674 		/* Flush completed, no longer dirty. */
    675 		sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
    676 	}
    677 
    678 	if (xs->bp != NULL) {
    679 		disk_unbusy(&sd->sc_dk, xs->bp->b_bcount - xs->bp->b_resid);
    680 #if NRND > 0
    681 		rnd_add_uint32(&sd->rnd_source, xs->bp->b_blkno);
    682 #endif
    683 	}
    684 }
    685 
    686 void
    687 sdminphys(bp)
    688 	struct buf *bp;
    689 {
    690 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
    691 	long max;
    692 
    693 	/*
    694 	 * If the device is ancient, we want to make sure that
    695 	 * the transfer fits into a 6-byte cdb.
    696 	 *
    697 	 * XXX Note that the SCSI-I spec says that 256-block transfers
    698 	 * are allowed in a 6-byte read/write, and are specified
    699 	 * by settng the "length" to 0.  However, we're conservative
    700 	 * here, allowing only 255-block transfers in case an
    701 	 * ancient device gets confused by length == 0.  A length of 0
    702 	 * in a 10-byte read/write actually means 0 blocks.
    703 	 */
    704 	if (sd->flags & SDF_ANCIENT) {
    705 		max = sd->sc_dk.dk_label->d_secsize * 0xff;
    706 
    707 		if (bp->b_bcount > max)
    708 			bp->b_bcount = max;
    709 	}
    710 
    711 	(*sd->sc_link->adapter->scsipi_minphys)(bp);
    712 }
    713 
    714 int
    715 sdread(dev, uio, ioflag)
    716 	dev_t dev;
    717 	struct uio *uio;
    718 	int ioflag;
    719 {
    720 
    721 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
    722 }
    723 
    724 int
    725 sdwrite(dev, uio, ioflag)
    726 	dev_t dev;
    727 	struct uio *uio;
    728 	int ioflag;
    729 {
    730 
    731 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
    732 }
    733 
    734 /*
    735  * Perform special action on behalf of the user
    736  * Knows about the internals of this device
    737  */
    738 int
    739 sdioctl(dev, cmd, addr, flag, p)
    740 	dev_t dev;
    741 	u_long cmd;
    742 	caddr_t addr;
    743 	int flag;
    744 	struct proc *p;
    745 {
    746 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
    747 	int error;
    748 
    749 	SC_DEBUG(sd->sc_link, SDEV_DB2, ("sdioctl 0x%lx ", cmd));
    750 
    751 	/*
    752 	 * If the device is not valid, some IOCTLs can still be
    753 	 * handled on the raw partition. Check this here.
    754 	 */
    755 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
    756 		switch (cmd) {
    757 		case DIOCWLABEL:
    758 		case DIOCLOCK:
    759 		case DIOCEJECT:
    760 		case SCIOCIDENTIFY:
    761 		case OSCIOCIDENTIFY:
    762 		case SCIOCCOMMAND:
    763 		case SCIOCDEBUG:
    764 			if (SDPART(dev) == RAW_PART)
    765 				break;
    766 		/* FALLTHROUGH */
    767 		default:
    768 			if ((sd->sc_link->flags & SDEV_OPEN) == 0)
    769 				return (ENODEV);
    770 			else
    771 				return (EIO);
    772 		}
    773 	}
    774 
    775 	switch (cmd) {
    776 	case DIOCGDINFO:
    777 		*(struct disklabel *)addr = *(sd->sc_dk.dk_label);
    778 		return (0);
    779 
    780 	case DIOCGPART:
    781 		((struct partinfo *)addr)->disklab = sd->sc_dk.dk_label;
    782 		((struct partinfo *)addr)->part =
    783 		    &sd->sc_dk.dk_label->d_partitions[SDPART(dev)];
    784 		return (0);
    785 
    786 	case DIOCWDINFO:
    787 	case DIOCSDINFO:
    788 		if ((flag & FWRITE) == 0)
    789 			return (EBADF);
    790 
    791 		if ((error = sdlock(sd)) != 0)
    792 			return (error);
    793 		sd->flags |= SDF_LABELLING;
    794 
    795 		error = setdisklabel(sd->sc_dk.dk_label,
    796 		    (struct disklabel *)addr, /*sd->sc_dk.dk_openmask : */0,
    797 		    sd->sc_dk.dk_cpulabel);
    798 		if (error == 0) {
    799 			if (cmd == DIOCWDINFO)
    800 				error = writedisklabel(SDLABELDEV(dev),
    801 				    sdstrategy, sd->sc_dk.dk_label,
    802 				    sd->sc_dk.dk_cpulabel);
    803 		}
    804 
    805 		sd->flags &= ~SDF_LABELLING;
    806 		sdunlock(sd);
    807 		return (error);
    808 
    809 	case DIOCWLABEL:
    810 		if ((flag & FWRITE) == 0)
    811 			return (EBADF);
    812 		if (*(int *)addr)
    813 			sd->flags |= SDF_WLABEL;
    814 		else
    815 			sd->flags &= ~SDF_WLABEL;
    816 		return (0);
    817 
    818 	case DIOCLOCK:
    819 		return (scsipi_prevent(sd->sc_link,
    820 		    (*(int *)addr) ? PR_PREVENT : PR_ALLOW, 0));
    821 
    822 	case DIOCEJECT:
    823 		return ((sd->sc_link->flags & SDEV_REMOVABLE) == 0 ? ENOTTY :
    824 		    scsipi_start(sd->sc_link, SSS_STOP|SSS_LOEJ, 0));
    825 
    826 	case DIOCGDEFLABEL:
    827 		sdgetdefaultlabel(sd, (struct disklabel *)addr);
    828 		return (0);
    829 
    830 	default:
    831 		if (SDPART(dev) != RAW_PART)
    832 			return (ENOTTY);
    833 		return (scsipi_do_ioctl(sd->sc_link, dev, cmd, addr, flag, p));
    834 	}
    835 
    836 #ifdef DIAGNOSTIC
    837 	panic("sdioctl: impossible");
    838 #endif
    839 }
    840 
    841 void
    842 sdgetdefaultlabel(sd, lp)
    843 	struct sd_softc *sd;
    844 	struct disklabel *lp;
    845 {
    846 
    847 	bzero(lp, sizeof(struct disklabel));
    848 
    849 	lp->d_secsize = sd->params.blksize;
    850 	lp->d_ntracks = sd->params.heads;
    851 	lp->d_nsectors = sd->params.sectors;
    852 	lp->d_ncylinders = sd->params.cyls;
    853 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
    854 
    855 	switch (sd->sc_link->type) {
    856 #if NSD_SCSIBUS > 0
    857 	    case BUS_SCSI:
    858 		lp->d_type = DTYPE_SCSI;
    859 		break;
    860 #endif
    861 #if NSD_ATAPIBUS > 0
    862 	    case BUS_ATAPI:
    863 		lp->d_type = DTYPE_ATAPI;
    864 		break;
    865 #endif
    866 	}
    867 	strncpy(lp->d_typename, sd->name, 16);
    868 	strncpy(lp->d_packname, "fictitious", 16);
    869 	lp->d_secperunit = sd->params.disksize;
    870 	lp->d_rpm = sd->params.rot_rate;
    871 	lp->d_interleave = 1;
    872 	lp->d_flags = 0;
    873 
    874 	lp->d_partitions[RAW_PART].p_offset = 0;
    875 	lp->d_partitions[RAW_PART].p_size =
    876 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
    877 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
    878 	lp->d_npartitions = RAW_PART + 1;
    879 
    880 	lp->d_magic = DISKMAGIC;
    881 	lp->d_magic2 = DISKMAGIC;
    882 	lp->d_checksum = dkcksum(lp);
    883 }
    884 
    885 
    886 /*
    887  * Load the label information on the named device
    888  */
    889 void
    890 sdgetdisklabel(sd)
    891 	struct sd_softc *sd;
    892 {
    893 	struct disklabel *lp = sd->sc_dk.dk_label;
    894 	char *errstring;
    895 
    896 	bzero(sd->sc_dk.dk_cpulabel, sizeof(struct cpu_disklabel));
    897 
    898 	sdgetdefaultlabel(sd, lp);
    899 
    900 	if (lp->d_secpercyl == 0) {
    901 		lp->d_secpercyl = 100;
    902 		/* as long as it's not 0 - readdisklabel divides by it (?) */
    903 	}
    904 
    905 	/*
    906 	 * Call the generic disklabel extraction routine
    907 	 */
    908 	errstring = readdisklabel(MAKESDDEV(0, sd->sc_dev.dv_unit, RAW_PART),
    909 	    sdstrategy, lp, sd->sc_dk.dk_cpulabel);
    910 	if (errstring) {
    911 		printf("%s: %s\n", sd->sc_dev.dv_xname, errstring);
    912 		return;
    913 	}
    914 }
    915 
    916 void
    917 sd_shutdown(arg)
    918 	void *arg;
    919 {
    920 	struct sd_softc *sd = arg;
    921 
    922 	/*
    923 	 * If the disk cache needs to be flushed, and the disk supports
    924 	 * it, flush it.  We're cold at this point, so we poll for
    925 	 * completion.
    926 	 */
    927 	if ((sd->flags & SDF_DIRTY) != 0 && sd->sc_ops->sdo_flush != NULL)
    928 		(*sd->sc_ops->sdo_flush)(sd, SCSI_AUTOCONF);
    929 }
    930 
    931 /*
    932  * Tell the device to map out a defective block
    933  */
    934 int
    935 sd_reassign_blocks(sd, blkno)
    936 	struct sd_softc *sd;
    937 	u_long blkno;
    938 {
    939 	struct scsi_reassign_blocks scsipi_cmd;
    940 	struct scsi_reassign_blocks_data rbdata;
    941 
    942 	bzero(&scsipi_cmd, sizeof(scsipi_cmd));
    943 	bzero(&rbdata, sizeof(rbdata));
    944 	scsipi_cmd.opcode = SCSI_REASSIGN_BLOCKS;
    945 
    946 	_lto2b(sizeof(rbdata.defect_descriptor[0]), rbdata.length);
    947 	_lto4b(blkno, rbdata.defect_descriptor[0].dlbaddr);
    948 
    949 	return (scsipi_command(sd->sc_link,
    950 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
    951 	    (u_char *)&rbdata, sizeof(rbdata), SDRETRIES, 5000, NULL,
    952 	    SCSI_DATA_OUT));
    953 }
    954 
    955 /*
    956  * Check Errors
    957  */
    958 int
    959 sd_interpret_sense(xs)
    960 	struct scsipi_xfer *xs;
    961 {
    962 	struct scsipi_link *sc_link = xs->sc_link;
    963 	struct scsipi_sense_data *sense = &xs->sense.scsi_sense;
    964 	struct sd_softc *sd = sc_link->device_softc;
    965 	int retval = SCSIRET_CONTINUE;
    966 
    967 	/*
    968 	 * If the device is not open yet, let the generic code handle it.
    969 	 */
    970 	if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0) {
    971 		return (retval);
    972 	}
    973 
    974 	/*
    975 	 * If it isn't a extended or extended/deferred error, let
    976 	 * the generic code handle it.
    977 	 */
    978 	if ((sense->error_code & SSD_ERRCODE) != 0x70 &&
    979 	    (sense->error_code & SSD_ERRCODE) != 0x71) {	/* DEFFERRED */
    980 		return (retval);
    981 	}
    982 
    983 	if ((sense->flags & SSD_KEY) == SKEY_NOT_READY &&
    984 	    sense->add_sense_code == 0x4) {
    985 		if (sense->add_sense_code_qual == 0x01)	{
    986 			printf("%s: ..is spinning up...waiting\n",
    987 			    sd->sc_dev.dv_xname);
    988 			/*
    989 			 * I really need a sdrestart function I can call here.
    990 			 */
    991 			delay(1000000 * 5);	/* 5 seconds */
    992 			retval = SCSIRET_RETRY;
    993 		} else if ((sense->add_sense_code_qual == 0x2) &&
    994 		    (sd->sc_link->quirks & SDEV_NOSTARTUNIT) == 0) {
    995 			if (sd->sc_link->flags & SDEV_REMOVABLE) {
    996 				printf("%s: removable disk stopped- not "
    997 				    "restarting\n", sd->sc_dev.dv_xname);
    998 				retval = EIO;
    999 			} else {
   1000 				printf("%s: respinning up disk\n",
   1001 				    sd->sc_dev.dv_xname);
   1002 				retval = scsipi_start(sd->sc_link, SSS_START,
   1003 				    SCSI_URGENT | SCSI_NOSLEEP);
   1004 				if (retval != 0) {
   1005 					printf("%s: respin of disk failed-%d\n",
   1006 					    sd->sc_dev.dv_xname, retval);
   1007 					retval = EIO;
   1008 				} else {
   1009 					retval = SCSIRET_RETRY;
   1010 				}
   1011 			}
   1012 		}
   1013 	}
   1014 	return (retval);
   1015 }
   1016 
   1017 
   1018 int
   1019 sdsize(dev)
   1020 	dev_t dev;
   1021 {
   1022 	struct sd_softc *sd;
   1023 	int part, unit, omask;
   1024 	int size;
   1025 
   1026 	unit = SDUNIT(dev);
   1027 	if (unit >= sd_cd.cd_ndevs)
   1028 		return (-1);
   1029 	sd = sd_cd.cd_devs[unit];
   1030 	if (sd == NULL)
   1031 		return (-1);
   1032 
   1033 	part = SDPART(dev);
   1034 	omask = sd->sc_dk.dk_openmask & (1 << part);
   1035 
   1036 	if (omask == 0 && sdopen(dev, 0, S_IFBLK, NULL) != 0)
   1037 		return (-1);
   1038 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) == 0)
   1039 		size = -1;
   1040 	else if (sd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
   1041 		size = -1;
   1042 	else
   1043 		size = sd->sc_dk.dk_label->d_partitions[part].p_size *
   1044 		    (sd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
   1045 	if (omask == 0 && sdclose(dev, 0, S_IFBLK, NULL) != 0)
   1046 		return (-1);
   1047 	return (size);
   1048 }
   1049 
   1050 #ifndef __BDEVSW_DUMP_OLD_TYPE
   1051 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
   1052 static struct scsipi_xfer sx;
   1053 static int sddoingadump;
   1054 
   1055 /*
   1056  * dump all of physical memory into the partition specified, starting
   1057  * at offset 'dumplo' into the partition.
   1058  */
   1059 int
   1060 sddump(dev, blkno, va, size)
   1061 	dev_t dev;
   1062 	daddr_t blkno;
   1063 	caddr_t va;
   1064 	size_t size;
   1065 {
   1066 	struct sd_softc *sd;	/* disk unit to do the I/O */
   1067 	struct disklabel *lp;	/* disk's disklabel */
   1068 	int	unit, part;
   1069 	int	sectorsize;	/* size of a disk sector */
   1070 	int	nsects;		/* number of sectors in partition */
   1071 	int	sectoff;	/* sector offset of partition */
   1072 	int	totwrt;		/* total number of sectors left to write */
   1073 	int	nwrt;		/* current number of sectors to write */
   1074 	struct scsipi_rw_big cmd;	/* write command */
   1075 	struct scsipi_xfer *xs;	/* ... convenience */
   1076 	int	retval;
   1077 
   1078 	/* Check if recursive dump; if so, punt. */
   1079 	if (sddoingadump)
   1080 		return (EFAULT);
   1081 
   1082 	/* Mark as active early. */
   1083 	sddoingadump = 1;
   1084 
   1085 	unit = SDUNIT(dev);	/* Decompose unit & partition. */
   1086 	part = SDPART(dev);
   1087 
   1088 	/* Check for acceptable drive number. */
   1089 	if (unit >= sd_cd.cd_ndevs || (sd = sd_cd.cd_devs[unit]) == NULL)
   1090 		return (ENXIO);
   1091 
   1092 	/* Make sure it was initialized. */
   1093 	if ((sd->sc_link->flags & SDEV_MEDIA_LOADED) != SDEV_MEDIA_LOADED)
   1094 		return (ENXIO);
   1095 
   1096 	/* Convert to disk sectors.  Request must be a multiple of size. */
   1097 	lp = sd->sc_dk.dk_label;
   1098 	sectorsize = lp->d_secsize;
   1099 	if ((size % sectorsize) != 0)
   1100 		return (EFAULT);
   1101 	totwrt = size / sectorsize;
   1102 	blkno = dbtob(blkno) / sectorsize;	/* blkno in DEV_BSIZE units */
   1103 
   1104 	nsects = lp->d_partitions[part].p_size;
   1105 	sectoff = lp->d_partitions[part].p_offset;
   1106 
   1107 	/* Check transfer bounds against partition size. */
   1108 	if ((blkno < 0) || ((blkno + totwrt) > nsects))
   1109 		return (EINVAL);
   1110 
   1111 	/* Offset block number to start of partition. */
   1112 	blkno += sectoff;
   1113 
   1114 	xs = &sx;
   1115 
   1116 	while (totwrt > 0) {
   1117 		nwrt = totwrt;		/* XXX */
   1118 #ifndef	SD_DUMP_NOT_TRUSTED
   1119 		/*
   1120 		 *  Fill out the scsi command
   1121 		 */
   1122 		bzero(&cmd, sizeof(cmd));
   1123 		cmd.opcode = WRITE_BIG;
   1124 		_lto4b(blkno, cmd.addr);
   1125 		_lto2b(nwrt, cmd.length);
   1126 		/*
   1127 		 * Fill out the scsipi_xfer structure
   1128 		 *    Note: we cannot sleep as we may be an interrupt
   1129 		 * don't use scsipi_command() as it may want to wait
   1130 		 * for an xs.
   1131 		 */
   1132 		bzero(xs, sizeof(sx));
   1133 		xs->flags |= SCSI_AUTOCONF | INUSE | SCSI_DATA_OUT;
   1134 		xs->sc_link = sd->sc_link;
   1135 		xs->retries = SDRETRIES;
   1136 		xs->timeout = 10000;	/* 10000 millisecs for a disk ! */
   1137 		xs->cmd = (struct scsipi_generic *)&cmd;
   1138 		xs->cmdlen = sizeof(cmd);
   1139 		xs->resid = nwrt * sectorsize;
   1140 		xs->error = XS_NOERROR;
   1141 		xs->bp = 0;
   1142 		xs->data = va;
   1143 		xs->datalen = nwrt * sectorsize;
   1144 
   1145 		/*
   1146 		 * Pass all this info to the scsi driver.
   1147 		 */
   1148 		retval = scsipi_command_direct(xs);
   1149 		if (retval != COMPLETE)
   1150 			return (ENXIO);
   1151 #else	/* SD_DUMP_NOT_TRUSTED */
   1152 		/* Let's just talk about this first... */
   1153 		printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
   1154 		delay(500 * 1000);	/* half a second */
   1155 #endif	/* SD_DUMP_NOT_TRUSTED */
   1156 
   1157 		/* update block count */
   1158 		totwrt -= nwrt;
   1159 		blkno += nwrt;
   1160 		va += sectorsize * nwrt;
   1161 	}
   1162 	sddoingadump = 0;
   1163 	return (0);
   1164 }
   1165 #else	/* __BDEVSW_DUMP_NEW_TYPE */
   1166 int
   1167 sddump(dev, blkno, va, size)
   1168 	dev_t dev;
   1169 	daddr_t blkno;
   1170 	caddr_t va;
   1171 	size_t size;
   1172 {
   1173 
   1174 	/* Not implemented. */
   1175 	return (ENXIO);
   1176 }
   1177 #endif	/* __BDEVSW_DUMP_NEW_TYPE */
   1178