Home | History | Annotate | Line # | Download | only in scsipi
sd.c revision 1.186
      1 /*	$NetBSD: sd.c,v 1.186 2002/08/30 15:43:38 hannken 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 <sys/cdefs.h>
     57 __KERNEL_RCSID(0, "$NetBSD: sd.c,v 1.186 2002/08/30 15:43:38 hannken Exp $");
     58 
     59 #include "opt_scsi.h"
     60 #include "rnd.h"
     61 
     62 #include <sys/param.h>
     63 #include <sys/systm.h>
     64 #include <sys/kernel.h>
     65 #include <sys/file.h>
     66 #include <sys/stat.h>
     67 #include <sys/ioctl.h>
     68 #include <sys/scsiio.h>
     69 #include <sys/buf.h>
     70 #include <sys/uio.h>
     71 #include <sys/malloc.h>
     72 #include <sys/errno.h>
     73 #include <sys/device.h>
     74 #include <sys/disklabel.h>
     75 #include <sys/disk.h>
     76 #include <sys/proc.h>
     77 #include <sys/conf.h>
     78 #include <sys/vnode.h>
     79 #if NRND > 0
     80 #include <sys/rnd.h>
     81 #endif
     82 
     83 #include <dev/scsipi/scsipi_all.h>
     84 #include <dev/scsipi/scsi_all.h>
     85 #include <dev/scsipi/scsipi_disk.h>
     86 #include <dev/scsipi/scsi_disk.h>
     87 #include <dev/scsipi/scsiconf.h>
     88 #include <dev/scsipi/sdvar.h>
     89 
     90 #include "sd.h"		/* NSD_SCSIBUS and NSD_ATAPIBUS come from here */
     91 
     92 #define	SDUNIT(dev)			DISKUNIT(dev)
     93 #define	SDPART(dev)			DISKPART(dev)
     94 #define	SDMINOR(unit, part)		DISKMINOR(unit, part)
     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((struct scsipi_periph *));
    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 const struct scsipi_periphsw 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  * Attach routine common to atapi & scsi.
    123  */
    124 void
    125 sdattach(parent, sd, periph, ops)
    126 	struct device *parent;
    127 	struct sd_softc *sd;
    128 	struct scsipi_periph *periph;
    129 	const struct sd_ops *ops;
    130 {
    131 	int error, result;
    132 	struct disk_parms *dp = &sd->params;
    133 	char pbuf[9];
    134 
    135 	SC_DEBUG(periph, SCSIPI_DB2, ("sdattach: "));
    136 
    137 	bufq_alloc(&sd->buf_queue, BUFQ_DISKSORT|BUFQ_SORT_RAWBLOCK);
    138 
    139 	/*
    140 	 * Store information needed to contact our base driver
    141 	 */
    142 	sd->sc_periph = periph;
    143 	sd->sc_ops = ops;
    144 
    145 	periph->periph_dev = &sd->sc_dev;
    146 	periph->periph_switch = &sd_switch;
    147 
    148         /*
    149          * Increase our openings to the maximum-per-periph
    150          * supported by the adapter.  This will either be
    151          * clamped down or grown by the adapter if necessary.
    152          */
    153 	periph->periph_openings =
    154 	    SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
    155 	periph->periph_flags |= PERIPH_GROW_OPENINGS;
    156 
    157 	/*
    158 	 * Initialize and attach the disk structure.
    159 	 */
    160 	sd->sc_dk.dk_driver = &sddkdriver;
    161 	sd->sc_dk.dk_name = sd->sc_dev.dv_xname;
    162 	disk_attach(&sd->sc_dk);
    163 
    164 #ifdef __BROKEN_DK_ESTABLISH
    165 	dk_establish(&sd->sc_dk, &sd->sc_dev);		/* XXX */
    166 #endif
    167 
    168 	/*
    169 	 * Use the subdriver to request information regarding the drive.
    170 	 */
    171 	printf("\n");
    172 
    173 	error = scsipi_start(periph, SSS_START,
    174 	    XS_CTL_DISCOVERY | XS_CTL_IGNORE_ILLEGAL_REQUEST |
    175 	    XS_CTL_IGNORE_MEDIA_CHANGE | XS_CTL_SILENT);
    176 
    177 	if (error)
    178 		result = SDGP_RESULT_OFFLINE;
    179 	else
    180 		result = (*sd->sc_ops->sdo_get_parms)(sd, &sd->params,
    181 		    XS_CTL_DISCOVERY);
    182 	printf("%s: ", sd->sc_dev.dv_xname);
    183 	switch (result) {
    184 	case SDGP_RESULT_OK:
    185 		format_bytes(pbuf, sizeof(pbuf),
    186 		    (u_int64_t)dp->disksize * dp->blksize);
    187 	        printf(
    188 		"%s, %ld cyl, %ld head, %ld sec, %ld bytes/sect x %lu sectors",
    189 		    pbuf, dp->cyls, dp->heads, dp->sectors, dp->blksize,
    190 		    dp->disksize);
    191 		break;
    192 
    193 	case SDGP_RESULT_OFFLINE:
    194 		printf("drive offline");
    195 		break;
    196 
    197 	case SDGP_RESULT_UNFORMATTED:
    198 		printf("unformatted media");
    199 		break;
    200 
    201 #ifdef DIAGNOSTIC
    202 	default:
    203 		panic("sdattach: unknown result from get_parms");
    204 		break;
    205 #endif
    206 	}
    207 	printf("\n");
    208 
    209 	/*
    210 	 * Establish a shutdown hook so that we can ensure that
    211 	 * our data has actually made it onto the platter at
    212 	 * shutdown time.  Note that this relies on the fact
    213 	 * that the shutdown hook code puts us at the head of
    214 	 * the list (thus guaranteeing that our hook runs before
    215 	 * our ancestors').
    216 	 */
    217 	if ((sd->sc_sdhook =
    218 	    shutdownhook_establish(sd_shutdown, sd)) == NULL)
    219 		printf("%s: WARNING: unable to establish shutdown hook\n",
    220 		    sd->sc_dev.dv_xname);
    221 
    222 #if NRND > 0
    223 	/*
    224 	 * attach the device into the random source list
    225 	 */
    226 	rnd_attach_source(&sd->rnd_source, sd->sc_dev.dv_xname,
    227 			  RND_TYPE_DISK, 0);
    228 #endif
    229 }
    230 
    231 int
    232 sdactivate(self, act)
    233 	struct device *self;
    234 	enum devact act;
    235 {
    236 	int rv = 0;
    237 
    238 	switch (act) {
    239 	case DVACT_ACTIVATE:
    240 		rv = EOPNOTSUPP;
    241 		break;
    242 
    243 	case DVACT_DEACTIVATE:
    244 		/*
    245 		 * Nothing to do; we key off the device's DVF_ACTIVE.
    246 		 */
    247 		break;
    248 	}
    249 	return (rv);
    250 }
    251 
    252 int
    253 sddetach(self, flags)
    254 	struct device *self;
    255 	int flags;
    256 {
    257 	struct sd_softc *sd = (struct sd_softc *) self;
    258 	struct buf *bp;
    259 	int s, bmaj, cmaj, i, mn;
    260 
    261 	/* locate the major number */
    262 	for (bmaj = 0; bmaj <= nblkdev; bmaj++)
    263 		if (bdevsw[bmaj].d_open == sdopen)
    264 			break;
    265 	for (cmaj = 0; cmaj <= nchrdev; cmaj++)
    266 		if (cdevsw[cmaj].d_open == sdopen)
    267 			break;
    268 
    269 	s = splbio();
    270 
    271 	/* Kill off any queued buffers. */
    272 	while ((bp = BUFQ_GET(&sd->buf_queue)) != NULL) {
    273 		bp->b_error = EIO;
    274 		bp->b_flags |= B_ERROR;
    275 		bp->b_resid = bp->b_bcount;
    276 		biodone(bp);
    277 	}
    278 
    279 	bufq_free(&sd->buf_queue);
    280 
    281 	/* Kill off any pending commands. */
    282 	scsipi_kill_pending(sd->sc_periph);
    283 
    284 	splx(s);
    285 
    286 	/* Nuke the vnodes for any open instances */
    287 	for (i = 0; i < MAXPARTITIONS; i++) {
    288 		mn = SDMINOR(self->dv_unit, i);
    289 		vdevgone(bmaj, mn, mn, VBLK);
    290 		vdevgone(cmaj, mn, mn, VCHR);
    291 	}
    292 
    293 	/* Detach from the disk list. */
    294 	disk_detach(&sd->sc_dk);
    295 
    296 	/* Get rid of the shutdown hook. */
    297 	shutdownhook_disestablish(sd->sc_sdhook);
    298 
    299 #if NRND > 0
    300 	/* Unhook the entropy source. */
    301 	rnd_detach_source(&sd->rnd_source);
    302 #endif
    303 
    304 	return (0);
    305 }
    306 
    307 /*
    308  * Wait interruptibly for an exclusive lock.
    309  *
    310  * XXX
    311  * Several drivers do this; it should be abstracted and made MP-safe.
    312  */
    313 int
    314 sdlock(sd)
    315 	struct sd_softc *sd;
    316 {
    317 	int error;
    318 
    319 	while ((sd->flags & SDF_LOCKED) != 0) {
    320 		sd->flags |= SDF_WANTED;
    321 		if ((error = tsleep(sd, PRIBIO | PCATCH, "sdlck", 0)) != 0)
    322 			return (error);
    323 	}
    324 	sd->flags |= SDF_LOCKED;
    325 	return (0);
    326 }
    327 
    328 /*
    329  * Unlock and wake up any waiters.
    330  */
    331 void
    332 sdunlock(sd)
    333 	struct sd_softc *sd;
    334 {
    335 
    336 	sd->flags &= ~SDF_LOCKED;
    337 	if ((sd->flags & SDF_WANTED) != 0) {
    338 		sd->flags &= ~SDF_WANTED;
    339 		wakeup(sd);
    340 	}
    341 }
    342 
    343 /*
    344  * open the device. Make sure the partition info is a up-to-date as can be.
    345  */
    346 int
    347 sdopen(dev, flag, fmt, p)
    348 	dev_t dev;
    349 	int flag, fmt;
    350 	struct proc *p;
    351 {
    352 	struct sd_softc *sd;
    353 	struct scsipi_periph *periph;
    354 	struct scsipi_adapter *adapt;
    355 	int unit, part;
    356 	int error;
    357 
    358 	unit = SDUNIT(dev);
    359 	if (unit >= sd_cd.cd_ndevs)
    360 		return (ENXIO);
    361 	sd = sd_cd.cd_devs[unit];
    362 	if (sd == NULL)
    363 		return (ENXIO);
    364 
    365 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
    366 		return (ENODEV);
    367 
    368 	periph = sd->sc_periph;
    369 	adapt = periph->periph_channel->chan_adapter;
    370 	part = SDPART(dev);
    371 
    372 	SC_DEBUG(periph, SCSIPI_DB1,
    373 	    ("sdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev, unit,
    374 	    sd_cd.cd_ndevs, part));
    375 
    376 	/*
    377 	 * If this is the first open of this device, add a reference
    378 	 * to the adapter.
    379 	 */
    380 	if (sd->sc_dk.dk_openmask == 0 &&
    381 	    (error = scsipi_adapter_addref(adapt)) != 0)
    382 		return (error);
    383 
    384 	if ((error = sdlock(sd)) != 0)
    385 		goto bad4;
    386 
    387 	if ((periph->periph_flags & PERIPH_OPEN) != 0) {
    388 		/*
    389 		 * If any partition is open, but the disk has been invalidated,
    390 		 * disallow further opens of non-raw partition
    391 		 */
    392 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
    393 		    (part != RAW_PART || fmt != S_IFCHR)) {
    394 			error = EIO;
    395 			goto bad3;
    396 		}
    397 	} else {
    398 		/* Check that it is still responding and ok. */
    399 		error = scsipi_test_unit_ready(periph,
    400 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
    401 		    XS_CTL_IGNORE_NOT_READY);
    402 		if (error)
    403 			goto bad3;
    404 
    405 		/*
    406 		 * Start the pack spinning if necessary. Always allow the
    407 		 * raw parition to be opened, for raw IOCTLs. Data transfers
    408 		 * will check for SDEV_MEDIA_LOADED.
    409 		 */
    410 		error = scsipi_start(periph, SSS_START,
    411 		    XS_CTL_IGNORE_ILLEGAL_REQUEST |
    412 		    XS_CTL_IGNORE_MEDIA_CHANGE | XS_CTL_SILENT);
    413 		if (error) {
    414 			if (part != RAW_PART || fmt != S_IFCHR)
    415 				goto bad3;
    416 			else
    417 				goto out;
    418 		}
    419 
    420 		periph->periph_flags |= PERIPH_OPEN;
    421 
    422 		if (periph->periph_flags & PERIPH_REMOVABLE) {
    423 			/* Lock the pack in. */
    424 			error = scsipi_prevent(periph, PR_PREVENT,
    425 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
    426 			    XS_CTL_IGNORE_MEDIA_CHANGE);
    427 			if (error)
    428 				goto bad;
    429 		}
    430 
    431 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
    432 			periph->periph_flags |= PERIPH_MEDIA_LOADED;
    433 
    434 			/*
    435 			 * Load the physical device parameters.
    436 			 *
    437 			 * Note that if media is present but unformatted,
    438 			 * we allow the open (so that it can be formatted!).
    439 			 * The drive should refuse real I/O, if the media is
    440 			 * unformatted.
    441 			 */
    442 			if ((*sd->sc_ops->sdo_get_parms)(sd, &sd->params,
    443 			    0) == SDGP_RESULT_OFFLINE) {
    444 				error = ENXIO;
    445 				goto bad2;
    446 			}
    447 			SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));
    448 
    449 			/* Load the partition info if not already loaded. */
    450 			sdgetdisklabel(sd);
    451 			SC_DEBUG(periph, SCSIPI_DB3, ("Disklabel loaded "));
    452 		}
    453 	}
    454 
    455 	/* Check that the partition exists. */
    456 	if (part != RAW_PART &&
    457 	    (part >= sd->sc_dk.dk_label->d_npartitions ||
    458 	     sd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
    459 		error = ENXIO;
    460 		goto bad;
    461 	}
    462 
    463 out:	/* Insure only one open at a time. */
    464 	switch (fmt) {
    465 	case S_IFCHR:
    466 		sd->sc_dk.dk_copenmask |= (1 << part);
    467 		break;
    468 	case S_IFBLK:
    469 		sd->sc_dk.dk_bopenmask |= (1 << part);
    470 		break;
    471 	}
    472 	sd->sc_dk.dk_openmask =
    473 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
    474 
    475 	SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));
    476 	sdunlock(sd);
    477 	return (0);
    478 
    479 bad2:
    480 	periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
    481 
    482 bad:
    483 	if (sd->sc_dk.dk_openmask == 0) {
    484 		scsipi_prevent(periph, PR_ALLOW,
    485 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE);
    486 		periph->periph_flags &= ~PERIPH_OPEN;
    487 	}
    488 
    489 bad3:
    490 	sdunlock(sd);
    491 bad4:
    492 	if (sd->sc_dk.dk_openmask == 0)
    493 		scsipi_adapter_delref(adapt);
    494 	return (error);
    495 }
    496 
    497 /*
    498  * close the device.. only called if we are the LAST occurence of an open
    499  * device.  Convenient now but usually a pain.
    500  */
    501 int
    502 sdclose(dev, flag, fmt, p)
    503 	dev_t dev;
    504 	int flag, fmt;
    505 	struct proc *p;
    506 {
    507 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
    508 	struct scsipi_periph *periph = sd->sc_periph;
    509 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
    510 	int part = SDPART(dev);
    511 	int error;
    512 
    513 	if ((error = sdlock(sd)) != 0)
    514 		return (error);
    515 
    516 	switch (fmt) {
    517 	case S_IFCHR:
    518 		sd->sc_dk.dk_copenmask &= ~(1 << part);
    519 		break;
    520 	case S_IFBLK:
    521 		sd->sc_dk.dk_bopenmask &= ~(1 << part);
    522 		break;
    523 	}
    524 	sd->sc_dk.dk_openmask =
    525 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
    526 
    527 	if (sd->sc_dk.dk_openmask == 0) {
    528 		/*
    529 		 * If the disk cache needs flushing, and the disk supports
    530 		 * it, do it now.
    531 		 */
    532 		if ((sd->flags & SDF_DIRTY) != 0 &&
    533 		    sd->sc_ops->sdo_flush != NULL) {
    534 			if ((*sd->sc_ops->sdo_flush)(sd, 0)) {
    535 				printf("%s: cache synchronization failed\n",
    536 				    sd->sc_dev.dv_xname);
    537 				sd->flags &= ~SDF_FLUSHING;
    538 			} else
    539 				sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
    540 		}
    541 
    542 		if (! (periph->periph_flags & PERIPH_KEEP_LABEL))
    543 			periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
    544 
    545 		scsipi_wait_drain(periph);
    546 
    547 		if (periph->periph_flags & PERIPH_REMOVABLE) {
    548 			scsipi_prevent(periph, PR_ALLOW,
    549 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
    550 			    XS_CTL_IGNORE_NOT_READY);
    551 		}
    552 		periph->periph_flags &= ~PERIPH_OPEN;
    553 
    554 		scsipi_wait_drain(periph);
    555 
    556 		scsipi_adapter_delref(adapt);
    557 	}
    558 
    559 	sdunlock(sd);
    560 	return (0);
    561 }
    562 
    563 /*
    564  * Actually translate the requested transfer into one the physical driver
    565  * can understand.  The transfer is described by a buf and will include
    566  * only one physical transfer.
    567  */
    568 void
    569 sdstrategy(bp)
    570 	struct buf *bp;
    571 {
    572 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
    573 	struct scsipi_periph *periph = sd->sc_periph;
    574 	struct disklabel *lp;
    575 	daddr_t blkno;
    576 	int s;
    577 	boolean_t sector_aligned;
    578 
    579 	SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdstrategy "));
    580 	SC_DEBUG(sd->sc_periph, SCSIPI_DB1,
    581 	    ("%ld bytes @ blk %d\n", bp->b_bcount, bp->b_blkno));
    582 	/*
    583 	 * If the device has been made invalid, error out
    584 	 */
    585 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 ||
    586 	    (sd->sc_dev.dv_flags & DVF_ACTIVE) == 0) {
    587 		if (periph->periph_flags & PERIPH_OPEN)
    588 			bp->b_error = EIO;
    589 		else
    590 			bp->b_error = ENODEV;
    591 		goto bad;
    592 	}
    593 
    594 	lp = sd->sc_dk.dk_label;
    595 
    596 	/*
    597 	 * The transfer must be a whole number of blocks, offset must not be
    598 	 * negative.
    599 	 */
    600 	if (lp->d_secsize == DEV_BSIZE) {
    601 		sector_aligned = (bp->b_bcount & (DEV_BSIZE - 1)) == 0;
    602 	} else {
    603 		sector_aligned = (bp->b_bcount % lp->d_secsize) == 0;
    604 	}
    605 	if (!sector_aligned || bp->b_blkno < 0) {
    606 		bp->b_error = EINVAL;
    607 		goto bad;
    608 	}
    609 	/*
    610 	 * If it's a null transfer, return immediatly
    611 	 */
    612 	if (bp->b_bcount == 0)
    613 		goto done;
    614 
    615 	/*
    616 	 * Do bounds checking, adjust transfer. if error, process.
    617 	 * If end of partition, just return.
    618 	 */
    619 	if (SDPART(bp->b_dev) != RAW_PART &&
    620 	    bounds_check_with_label(bp, lp,
    621 	    (sd->flags & (SDF_WLABEL|SDF_LABELLING)) != 0) <= 0)
    622 		goto done;
    623 
    624 	/*
    625 	 * Now convert the block number to absolute and put it in
    626 	 * terms of the device's logical block size.
    627 	 */
    628 	if (lp->d_secsize == DEV_BSIZE)
    629 		blkno = bp->b_blkno;
    630 	else if (lp->d_secsize > DEV_BSIZE)
    631 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
    632 	else
    633 		blkno = bp->b_blkno * (DEV_BSIZE / lp->d_secsize);
    634 
    635 	if (SDPART(bp->b_dev) != RAW_PART)
    636 		blkno += lp->d_partitions[SDPART(bp->b_dev)].p_offset;
    637 
    638 	bp->b_rawblkno = blkno;
    639 
    640 	s = splbio();
    641 
    642 	/*
    643 	 * Place it in the queue of disk activities for this disk.
    644 	 *
    645 	 * XXX Only do disksort() if the current operating mode does not
    646 	 * XXX include tagged queueing.
    647 	 */
    648 	BUFQ_PUT(&sd->buf_queue, bp);
    649 
    650 	/*
    651 	 * Tell the device to get going on the transfer if it's
    652 	 * not doing anything, otherwise just wait for completion
    653 	 */
    654 	sdstart(sd->sc_periph);
    655 
    656 	splx(s);
    657 	return;
    658 
    659 bad:
    660 	bp->b_flags |= B_ERROR;
    661 done:
    662 	/*
    663 	 * Correctly set the buf to indicate a completed xfer
    664 	 */
    665 	bp->b_resid = bp->b_bcount;
    666 	biodone(bp);
    667 }
    668 
    669 /*
    670  * sdstart looks to see if there is a buf waiting for the device
    671  * and that the device is not already busy. If both are true,
    672  * It dequeues the buf and creates a scsi command to perform the
    673  * transfer in the buf. The transfer request will call scsipi_done
    674  * on completion, which will in turn call this routine again
    675  * so that the next queued transfer is performed.
    676  * The bufs are queued by the strategy routine (sdstrategy)
    677  *
    678  * This routine is also called after other non-queued requests
    679  * have been made of the scsi driver, to ensure that the queue
    680  * continues to be drained.
    681  *
    682  * must be called at the correct (highish) spl level
    683  * sdstart() is called at splbio from sdstrategy and scsipi_done
    684  */
    685 void
    686 sdstart(periph)
    687 	struct scsipi_periph *periph;
    688 {
    689 	struct sd_softc *sd = (void *)periph->periph_dev;
    690 	struct disklabel *lp = sd->sc_dk.dk_label;
    691 	struct buf *bp = 0;
    692 	struct scsipi_rw_big cmd_big;
    693 #if NSD_SCSIBUS > 0
    694 	struct scsi_rw cmd_small;
    695 #endif
    696 	struct scsipi_generic *cmdp;
    697 	int nblks, cmdlen, error, flags;
    698 
    699 	SC_DEBUG(periph, SCSIPI_DB2, ("sdstart "));
    700 	/*
    701 	 * Check if the device has room for another command
    702 	 */
    703 	while (periph->periph_active < periph->periph_openings) {
    704 		/*
    705 		 * there is excess capacity, but a special waits
    706 		 * It'll need the adapter as soon as we clear out of the
    707 		 * way and let it run (user level wait).
    708 		 */
    709 		if (periph->periph_flags & PERIPH_WAITING) {
    710 			periph->periph_flags &= ~PERIPH_WAITING;
    711 			wakeup((caddr_t)periph);
    712 			return;
    713 		}
    714 
    715 		/*
    716 		 * See if there is a buf with work for us to do..
    717 		 */
    718 		if ((bp = BUFQ_GET(&sd->buf_queue)) == NULL)
    719 			return;
    720 
    721 		/*
    722 		 * If the device has become invalid, abort all the
    723 		 * reads and writes until all files have been closed and
    724 		 * re-opened
    725 		 */
    726 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
    727 			bp->b_error = EIO;
    728 			bp->b_flags |= B_ERROR;
    729 			bp->b_resid = bp->b_bcount;
    730 			biodone(bp);
    731 			continue;
    732 		}
    733 
    734 		/*
    735 		 * We have a buf, now we should make a command.
    736 		 */
    737 
    738 		if (lp->d_secsize == DEV_BSIZE)
    739 			nblks = bp->b_bcount >> DEV_BSHIFT;
    740 		else
    741 			nblks = howmany(bp->b_bcount, lp->d_secsize);
    742 
    743 #if NSD_SCSIBUS > 0
    744 		/*
    745 		 *  Fill out the scsi command.  If the transfer will
    746 		 *  fit in a "small" cdb, use it.
    747 		 */
    748 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
    749 		    ((nblks & 0xff) == nblks) &&
    750 		    !(periph->periph_quirks & PQUIRK_ONLYBIG) &&
    751 		    scsipi_periph_bustype(periph) == SCSIPI_BUSTYPE_SCSI) {
    752 			/*
    753 			 * We can fit in a small cdb.
    754 			 */
    755 			memset(&cmd_small, 0, sizeof(cmd_small));
    756 			cmd_small.opcode = (bp->b_flags & B_READ) ?
    757 			    SCSI_READ_COMMAND : SCSI_WRITE_COMMAND;
    758 			_lto3b(bp->b_rawblkno, cmd_small.addr);
    759 			cmd_small.length = nblks & 0xff;
    760 			cmdlen = sizeof(cmd_small);
    761 			cmdp = (struct scsipi_generic *)&cmd_small;
    762 		} else
    763 #endif /* NSD_SCSIBUS > 0 */
    764 		{
    765 			/*
    766 			 * Need a large cdb.
    767 			 */
    768 			memset(&cmd_big, 0, sizeof(cmd_big));
    769 			cmd_big.opcode = (bp->b_flags & B_READ) ?
    770 			    READ_BIG : WRITE_BIG;
    771 			_lto4b(bp->b_rawblkno, cmd_big.addr);
    772 			_lto2b(nblks, cmd_big.length);
    773 			cmdlen = sizeof(cmd_big);
    774 			cmdp = (struct scsipi_generic *)&cmd_big;
    775 		}
    776 
    777 		/* Instrumentation. */
    778 		disk_busy(&sd->sc_dk);
    779 
    780 		/*
    781 		 * Mark the disk dirty so that the cache will be
    782 		 * flushed on close.
    783 		 */
    784 		if ((bp->b_flags & B_READ) == 0)
    785 			sd->flags |= SDF_DIRTY;
    786 
    787 		/*
    788 		 * Figure out what flags to use.
    789 		 */
    790 		flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
    791 		if (bp->b_flags & B_READ)
    792 			flags |= XS_CTL_DATA_IN;
    793 		else
    794 			flags |= XS_CTL_DATA_OUT;
    795 
    796 		/*
    797 		 * Call the routine that chats with the adapter.
    798 		 * Note: we cannot sleep as we may be an interrupt
    799 		 */
    800 		error = scsipi_command(periph, cmdp, cmdlen,
    801 		    (u_char *)bp->b_data, bp->b_bcount,
    802 		    SDRETRIES, SD_IO_TIMEOUT, bp, flags);
    803 		if (error) {
    804 			disk_unbusy(&sd->sc_dk, 0);
    805 			printf("%s: not queued, error %d\n",
    806 			    sd->sc_dev.dv_xname, error);
    807 		}
    808 	}
    809 }
    810 
    811 void
    812 sddone(xs)
    813 	struct scsipi_xfer *xs;
    814 {
    815 	struct sd_softc *sd = (void *)xs->xs_periph->periph_dev;
    816 
    817 	if (sd->flags & SDF_FLUSHING) {
    818 		/* Flush completed, no longer dirty. */
    819 		sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
    820 	}
    821 
    822 	if (xs->bp != NULL) {
    823 		disk_unbusy(&sd->sc_dk, xs->bp->b_bcount - xs->bp->b_resid);
    824 #if NRND > 0
    825 		rnd_add_uint32(&sd->rnd_source, xs->bp->b_rawblkno);
    826 #endif
    827 	}
    828 }
    829 
    830 void
    831 sdminphys(bp)
    832 	struct buf *bp;
    833 {
    834 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
    835 	long max;
    836 
    837 	/*
    838 	 * If the device is ancient, we want to make sure that
    839 	 * the transfer fits into a 6-byte cdb.
    840 	 *
    841 	 * XXX Note that the SCSI-I spec says that 256-block transfers
    842 	 * are allowed in a 6-byte read/write, and are specified
    843 	 * by settng the "length" to 0.  However, we're conservative
    844 	 * here, allowing only 255-block transfers in case an
    845 	 * ancient device gets confused by length == 0.  A length of 0
    846 	 * in a 10-byte read/write actually means 0 blocks.
    847 	 */
    848 	if ((sd->flags & SDF_ANCIENT) &&
    849 	    ((sd->sc_periph->periph_flags &
    850 	    (PERIPH_REMOVABLE | PERIPH_MEDIA_LOADED)) != PERIPH_REMOVABLE)) {
    851 		max = sd->sc_dk.dk_label->d_secsize * 0xff;
    852 
    853 		if (bp->b_bcount > max)
    854 			bp->b_bcount = max;
    855 	}
    856 
    857 	(*sd->sc_periph->periph_channel->chan_adapter->adapt_minphys)(bp);
    858 }
    859 
    860 int
    861 sdread(dev, uio, ioflag)
    862 	dev_t dev;
    863 	struct uio *uio;
    864 	int ioflag;
    865 {
    866 
    867 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
    868 }
    869 
    870 int
    871 sdwrite(dev, uio, ioflag)
    872 	dev_t dev;
    873 	struct uio *uio;
    874 	int ioflag;
    875 {
    876 
    877 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
    878 }
    879 
    880 /*
    881  * Perform special action on behalf of the user
    882  * Knows about the internals of this device
    883  */
    884 int
    885 sdioctl(dev, cmd, addr, flag, p)
    886 	dev_t dev;
    887 	u_long cmd;
    888 	caddr_t addr;
    889 	int flag;
    890 	struct proc *p;
    891 {
    892 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
    893 	struct scsipi_periph *periph = sd->sc_periph;
    894 	int part = SDPART(dev);
    895 	int error;
    896 #ifdef __HAVE_OLD_DISKLABEL
    897 	struct disklabel newlabel;
    898 #endif
    899 
    900 	SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdioctl 0x%lx ", cmd));
    901 
    902 	/*
    903 	 * If the device is not valid, some IOCTLs can still be
    904 	 * handled on the raw partition. Check this here.
    905 	 */
    906 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
    907 		switch (cmd) {
    908 		case DIOCKLABEL:
    909 		case DIOCWLABEL:
    910 		case DIOCLOCK:
    911 		case DIOCEJECT:
    912 		case ODIOCEJECT:
    913 		case DIOCGCACHE:
    914 		case DIOCSCACHE:
    915 		case SCIOCIDENTIFY:
    916 		case OSCIOCIDENTIFY:
    917 		case SCIOCCOMMAND:
    918 		case SCIOCDEBUG:
    919 			if (part == RAW_PART)
    920 				break;
    921 		/* FALLTHROUGH */
    922 		default:
    923 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
    924 				return (ENODEV);
    925 			else
    926 				return (EIO);
    927 		}
    928 	}
    929 
    930 	switch (cmd) {
    931 	case DIOCGDINFO:
    932 		*(struct disklabel *)addr = *(sd->sc_dk.dk_label);
    933 		return (0);
    934 
    935 #ifdef __HAVE_OLD_DISKLABEL
    936 	case ODIOCGDINFO:
    937 		newlabel = *(sd->sc_dk.dk_label);
    938 		if (newlabel.d_npartitions > OLDMAXPARTITIONS)
    939 			return ENOTTY;
    940 		memcpy(addr, &newlabel, sizeof (struct olddisklabel));
    941 		return (0);
    942 #endif
    943 
    944 	case DIOCGPART:
    945 		((struct partinfo *)addr)->disklab = sd->sc_dk.dk_label;
    946 		((struct partinfo *)addr)->part =
    947 		    &sd->sc_dk.dk_label->d_partitions[part];
    948 		return (0);
    949 
    950 	case DIOCWDINFO:
    951 	case DIOCSDINFO:
    952 #ifdef __HAVE_OLD_DISKLABEL
    953 	case ODIOCWDINFO:
    954 	case ODIOCSDINFO:
    955 #endif
    956 	{
    957 		struct disklabel *lp;
    958 
    959 #ifdef __HAVE_OLD_DISKLABEL
    960  		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
    961 			memset(&newlabel, 0, sizeof newlabel);
    962 			memcpy(&newlabel, addr, sizeof (struct olddisklabel));
    963 			lp = &newlabel;
    964 		} else
    965 #endif
    966 		lp = (struct disklabel *)addr;
    967 
    968 		if ((flag & FWRITE) == 0)
    969 			return (EBADF);
    970 
    971 		if ((error = sdlock(sd)) != 0)
    972 			return (error);
    973 		sd->flags |= SDF_LABELLING;
    974 
    975 		error = setdisklabel(sd->sc_dk.dk_label,
    976 		    lp, /*sd->sc_dk.dk_openmask : */0,
    977 		    sd->sc_dk.dk_cpulabel);
    978 		if (error == 0) {
    979 			if (cmd == DIOCWDINFO
    980 #ifdef __HAVE_OLD_DISKLABEL
    981 			    || cmd == ODIOCWDINFO
    982 #endif
    983 			   )
    984 				error = writedisklabel(SDLABELDEV(dev),
    985 				    sdstrategy, sd->sc_dk.dk_label,
    986 				    sd->sc_dk.dk_cpulabel);
    987 		}
    988 
    989 		sd->flags &= ~SDF_LABELLING;
    990 		sdunlock(sd);
    991 		return (error);
    992 	}
    993 
    994 	case DIOCKLABEL:
    995 		if (*(int *)addr)
    996 			periph->periph_flags |= PERIPH_KEEP_LABEL;
    997 		else
    998 			periph->periph_flags &= ~PERIPH_KEEP_LABEL;
    999 		return (0);
   1000 
   1001 	case DIOCWLABEL:
   1002 		if ((flag & FWRITE) == 0)
   1003 			return (EBADF);
   1004 		if (*(int *)addr)
   1005 			sd->flags |= SDF_WLABEL;
   1006 		else
   1007 			sd->flags &= ~SDF_WLABEL;
   1008 		return (0);
   1009 
   1010 	case DIOCLOCK:
   1011 		return (scsipi_prevent(periph,
   1012 		    (*(int *)addr) ? PR_PREVENT : PR_ALLOW, 0));
   1013 
   1014 	case DIOCEJECT:
   1015 		if ((periph->periph_flags & PERIPH_REMOVABLE) == 0)
   1016 			return (ENOTTY);
   1017 		if (*(int *)addr == 0) {
   1018 			/*
   1019 			 * Don't force eject: check that we are the only
   1020 			 * partition open. If so, unlock it.
   1021 			 */
   1022 			if ((sd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
   1023 			    sd->sc_dk.dk_bopenmask + sd->sc_dk.dk_copenmask ==
   1024 			    sd->sc_dk.dk_openmask) {
   1025 				error = scsipi_prevent(periph, PR_ALLOW,
   1026 				    XS_CTL_IGNORE_NOT_READY);
   1027 				if (error)
   1028 					return (error);
   1029 			} else {
   1030 				return (EBUSY);
   1031 			}
   1032 		}
   1033 		/* FALLTHROUGH */
   1034 	case ODIOCEJECT:
   1035 		return ((periph->periph_flags & PERIPH_REMOVABLE) == 0 ?
   1036 		    ENOTTY : scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
   1037 
   1038 	case DIOCGDEFLABEL:
   1039 		sdgetdefaultlabel(sd, (struct disklabel *)addr);
   1040 		return (0);
   1041 
   1042 #ifdef __HAVE_OLD_DISKLABEL
   1043 	case ODIOCGDEFLABEL:
   1044 		sdgetdefaultlabel(sd, &newlabel);
   1045 		if (newlabel.d_npartitions > OLDMAXPARTITIONS)
   1046 			return ENOTTY;
   1047 		memcpy(addr, &newlabel, sizeof (struct olddisklabel));
   1048 		return (0);
   1049 #endif
   1050 
   1051 	case DIOCGCACHE:
   1052 		if (sd->sc_ops->sdo_getcache != NULL)
   1053 			return ((*sd->sc_ops->sdo_getcache)(sd, (int *) addr));
   1054 
   1055 		/* Not supported on this device. */
   1056 		*(int *) addr = 0;
   1057 		return (0);
   1058 
   1059 	case DIOCSCACHE:
   1060 		if ((flag & FWRITE) == 0)
   1061 			return (EBADF);
   1062 		if (sd->sc_ops->sdo_setcache != NULL)
   1063 			return ((*sd->sc_ops->sdo_setcache)(sd, *(int *) addr));
   1064 
   1065 		/* Not supported on this device. */
   1066 		return (EOPNOTSUPP);
   1067 
   1068 	case DIOCCACHESYNC:
   1069 		/*
   1070 		 * XXX Do we really need to care about having a writeable
   1071 		 * file descriptor here?
   1072 		 */
   1073 		if ((flag & FWRITE) == 0)
   1074 			return (EBADF);
   1075 		if (((sd->flags & SDF_DIRTY) != 0 || *(int *)addr != 0) &&
   1076 		    sd->sc_ops->sdo_flush != NULL) {
   1077 			error = (*sd->sc_ops->sdo_flush)(sd, 0);
   1078 			if (error)
   1079 				sd->flags &= ~SDF_FLUSHING;
   1080 			else
   1081 				sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
   1082 		} else
   1083 			error = 0;
   1084 		return (error);
   1085 
   1086 	default:
   1087 		if (part != RAW_PART)
   1088 			return (ENOTTY);
   1089 		return (scsipi_do_ioctl(periph, dev, cmd, addr, flag, p));
   1090 	}
   1091 
   1092 #ifdef DIAGNOSTIC
   1093 	panic("sdioctl: impossible");
   1094 #endif
   1095 }
   1096 
   1097 void
   1098 sdgetdefaultlabel(sd, lp)
   1099 	struct sd_softc *sd;
   1100 	struct disklabel *lp;
   1101 {
   1102 
   1103 	memset(lp, 0, sizeof(struct disklabel));
   1104 
   1105 	lp->d_secsize = sd->params.blksize;
   1106 	lp->d_ntracks = sd->params.heads;
   1107 	lp->d_nsectors = sd->params.sectors;
   1108 	lp->d_ncylinders = sd->params.cyls;
   1109 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
   1110 
   1111 	switch (scsipi_periph_bustype(sd->sc_periph)) {
   1112 #if NSD_SCSIBUS > 0
   1113 	case SCSIPI_BUSTYPE_SCSI:
   1114 		lp->d_type = DTYPE_SCSI;
   1115 		break;
   1116 #endif
   1117 #if NSD_ATAPIBUS > 0
   1118 	case SCSIPI_BUSTYPE_ATAPI:
   1119 		lp->d_type = DTYPE_ATAPI;
   1120 		break;
   1121 #endif
   1122 	}
   1123 	strncpy(lp->d_typename, sd->name, 16);
   1124 	strncpy(lp->d_packname, "fictitious", 16);
   1125 	lp->d_secperunit = sd->params.disksize;
   1126 	lp->d_rpm = sd->params.rot_rate;
   1127 	lp->d_interleave = 1;
   1128 	lp->d_flags = 0;
   1129 
   1130 	lp->d_partitions[RAW_PART].p_offset = 0;
   1131 	lp->d_partitions[RAW_PART].p_size =
   1132 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
   1133 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
   1134 	lp->d_npartitions = RAW_PART + 1;
   1135 
   1136 	lp->d_magic = DISKMAGIC;
   1137 	lp->d_magic2 = DISKMAGIC;
   1138 	lp->d_checksum = dkcksum(lp);
   1139 }
   1140 
   1141 
   1142 /*
   1143  * Load the label information on the named device
   1144  */
   1145 void
   1146 sdgetdisklabel(sd)
   1147 	struct sd_softc *sd;
   1148 {
   1149 	struct disklabel *lp = sd->sc_dk.dk_label;
   1150 	char *errstring;
   1151 
   1152 	memset(sd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
   1153 
   1154 	sdgetdefaultlabel(sd, lp);
   1155 
   1156 	if (lp->d_secpercyl == 0) {
   1157 		lp->d_secpercyl = 100;
   1158 		/* as long as it's not 0 - readdisklabel divides by it (?) */
   1159 	}
   1160 
   1161 	/*
   1162 	 * Call the generic disklabel extraction routine
   1163 	 */
   1164 	errstring = readdisklabel(MAKESDDEV(0, sd->sc_dev.dv_unit, RAW_PART),
   1165 	    sdstrategy, lp, sd->sc_dk.dk_cpulabel);
   1166 	if (errstring) {
   1167 		printf("%s: %s\n", sd->sc_dev.dv_xname, errstring);
   1168 		return;
   1169 	}
   1170 }
   1171 
   1172 void
   1173 sd_shutdown(arg)
   1174 	void *arg;
   1175 {
   1176 	struct sd_softc *sd = arg;
   1177 
   1178 	/*
   1179 	 * If the disk cache needs to be flushed, and the disk supports
   1180 	 * it, flush it.  We're cold at this point, so we poll for
   1181 	 * completion.
   1182 	 */
   1183 	if ((sd->flags & SDF_DIRTY) != 0 && sd->sc_ops->sdo_flush != NULL) {
   1184 		if ((*sd->sc_ops->sdo_flush)(sd, XS_CTL_NOSLEEP|XS_CTL_POLL)) {
   1185 			printf("%s: cache synchronization failed\n",
   1186 			    sd->sc_dev.dv_xname);
   1187 			sd->flags &= ~SDF_FLUSHING;
   1188 		} else
   1189 			sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
   1190 	}
   1191 }
   1192 
   1193 /*
   1194  * Tell the device to map out a defective block
   1195  */
   1196 int
   1197 sd_reassign_blocks(sd, blkno)
   1198 	struct sd_softc *sd;
   1199 	u_long blkno;
   1200 {
   1201 	struct scsi_reassign_blocks scsipi_cmd;
   1202 	struct scsi_reassign_blocks_data rbdata;
   1203 
   1204 	memset(&scsipi_cmd, 0, sizeof(scsipi_cmd));
   1205 	memset(&rbdata, 0, sizeof(rbdata));
   1206 	scsipi_cmd.opcode = SCSI_REASSIGN_BLOCKS;
   1207 
   1208 	_lto2b(sizeof(rbdata.defect_descriptor[0]), rbdata.length);
   1209 	_lto4b(blkno, rbdata.defect_descriptor[0].dlbaddr);
   1210 
   1211 	return (scsipi_command(sd->sc_periph,
   1212 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
   1213 	    (u_char *)&rbdata, sizeof(rbdata), SDRETRIES, 5000, NULL,
   1214 	    XS_CTL_DATA_OUT | XS_CTL_DATA_ONSTACK));
   1215 }
   1216 
   1217 /*
   1218  * Check Errors
   1219  */
   1220 int
   1221 sd_interpret_sense(xs)
   1222 	struct scsipi_xfer *xs;
   1223 {
   1224 	struct scsipi_periph *periph = xs->xs_periph;
   1225 	struct scsipi_sense_data *sense = &xs->sense.scsi_sense;
   1226 	struct sd_softc *sd = (void *)periph->periph_dev;
   1227 	int s, error, retval = EJUSTRETURN;
   1228 
   1229 	/*
   1230 	 * If the periph is already recovering, just do the normal
   1231 	 * error processing.
   1232 	 */
   1233 	if (periph->periph_flags & PERIPH_RECOVERING)
   1234 		return (retval);
   1235 
   1236 	/*
   1237 	 * If the device is not open yet, let the generic code handle it.
   1238 	 */
   1239 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1240 		return (retval);
   1241 
   1242 	/*
   1243 	 * If it isn't a extended or extended/deferred error, let
   1244 	 * the generic code handle it.
   1245 	 */
   1246 	if ((sense->error_code & SSD_ERRCODE) != 0x70 &&
   1247 	    (sense->error_code & SSD_ERRCODE) != 0x71)
   1248 		return (retval);
   1249 
   1250 	if ((sense->flags & SSD_KEY) == SKEY_NOT_READY &&
   1251 	    sense->add_sense_code == 0x4) {
   1252 		if (sense->add_sense_code_qual == 0x01)	{
   1253 			/*
   1254 			 * Unit In The Process Of Becoming Ready.
   1255 			 */
   1256 			printf("%s: waiting for pack to spin up...\n",
   1257 			    sd->sc_dev.dv_xname);
   1258 			if (!callout_active(&periph->periph_callout))
   1259 				scsipi_periph_freeze(periph, 1);
   1260 			callout_reset(&periph->periph_callout,
   1261 			    5 * hz, scsipi_periph_timed_thaw, periph);
   1262 			retval = ERESTART;
   1263 		} else if ((sense->add_sense_code_qual == 0x2) &&
   1264 		    (periph->periph_quirks & PQUIRK_NOSTARTUNIT) == 0) {
   1265 			printf("%s: pack is stopped, restarting...\n",
   1266 			    sd->sc_dev.dv_xname);
   1267 			s = splbio();
   1268 			periph->periph_flags |= PERIPH_RECOVERING;
   1269 			splx(s);
   1270 			error = scsipi_start(periph, SSS_START,
   1271 			    XS_CTL_URGENT|XS_CTL_HEAD_TAG|
   1272 			    XS_CTL_THAW_PERIPH|XS_CTL_FREEZE_PERIPH);
   1273 			if (error) {
   1274 				printf("%s: unable to restart pack\n",
   1275 				    sd->sc_dev.dv_xname);
   1276 				retval = error;
   1277 			} else
   1278 				retval = ERESTART;
   1279 			s = splbio();
   1280 			periph->periph_flags &= ~PERIPH_RECOVERING;
   1281 			splx(s);
   1282 		}
   1283 	}
   1284 	return (retval);
   1285 }
   1286 
   1287 
   1288 int
   1289 sdsize(dev)
   1290 	dev_t dev;
   1291 {
   1292 	struct sd_softc *sd;
   1293 	int part, unit, omask;
   1294 	int size;
   1295 
   1296 	unit = SDUNIT(dev);
   1297 	if (unit >= sd_cd.cd_ndevs)
   1298 		return (-1);
   1299 	sd = sd_cd.cd_devs[unit];
   1300 	if (sd == NULL)
   1301 		return (-1);
   1302 
   1303 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
   1304 		return (-1);
   1305 
   1306 	part = SDPART(dev);
   1307 	omask = sd->sc_dk.dk_openmask & (1 << part);
   1308 
   1309 	if (omask == 0 && sdopen(dev, 0, S_IFBLK, NULL) != 0)
   1310 		return (-1);
   1311 	if ((sd->sc_periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1312 		size = -1;
   1313 	else if (sd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
   1314 		size = -1;
   1315 	else
   1316 		size = sd->sc_dk.dk_label->d_partitions[part].p_size *
   1317 		    (sd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
   1318 	if (omask == 0 && sdclose(dev, 0, S_IFBLK, NULL) != 0)
   1319 		return (-1);
   1320 	return (size);
   1321 }
   1322 
   1323 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
   1324 static struct scsipi_xfer sx;
   1325 static int sddoingadump;
   1326 
   1327 /*
   1328  * dump all of physical memory into the partition specified, starting
   1329  * at offset 'dumplo' into the partition.
   1330  */
   1331 int
   1332 sddump(dev, blkno, va, size)
   1333 	dev_t dev;
   1334 	daddr_t blkno;
   1335 	caddr_t va;
   1336 	size_t size;
   1337 {
   1338 	struct sd_softc *sd;	/* disk unit to do the I/O */
   1339 	struct disklabel *lp;	/* disk's disklabel */
   1340 	int	unit, part;
   1341 	int	sectorsize;	/* size of a disk sector */
   1342 	int	nsects;		/* number of sectors in partition */
   1343 	int	sectoff;	/* sector offset of partition */
   1344 	int	totwrt;		/* total number of sectors left to write */
   1345 	int	nwrt;		/* current number of sectors to write */
   1346 	struct scsipi_rw_big cmd;	/* write command */
   1347 	struct scsipi_xfer *xs;	/* ... convenience */
   1348 	struct scsipi_periph *periph;
   1349 	struct scsipi_channel *chan;
   1350 
   1351 	/* Check if recursive dump; if so, punt. */
   1352 	if (sddoingadump)
   1353 		return (EFAULT);
   1354 
   1355 	/* Mark as active early. */
   1356 	sddoingadump = 1;
   1357 
   1358 	unit = SDUNIT(dev);	/* Decompose unit & partition. */
   1359 	part = SDPART(dev);
   1360 
   1361 	/* Check for acceptable drive number. */
   1362 	if (unit >= sd_cd.cd_ndevs || (sd = sd_cd.cd_devs[unit]) == NULL)
   1363 		return (ENXIO);
   1364 
   1365 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
   1366 		return (ENODEV);
   1367 
   1368 	periph = sd->sc_periph;
   1369 	chan = periph->periph_channel;
   1370 
   1371 	/* Make sure it was initialized. */
   1372 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1373 		return (ENXIO);
   1374 
   1375 	/* Convert to disk sectors.  Request must be a multiple of size. */
   1376 	lp = sd->sc_dk.dk_label;
   1377 	sectorsize = lp->d_secsize;
   1378 	if ((size % sectorsize) != 0)
   1379 		return (EFAULT);
   1380 	totwrt = size / sectorsize;
   1381 	blkno = dbtob(blkno) / sectorsize;	/* blkno in DEV_BSIZE units */
   1382 
   1383 	nsects = lp->d_partitions[part].p_size;
   1384 	sectoff = lp->d_partitions[part].p_offset;
   1385 
   1386 	/* Check transfer bounds against partition size. */
   1387 	if ((blkno < 0) || ((blkno + totwrt) > nsects))
   1388 		return (EINVAL);
   1389 
   1390 	/* Offset block number to start of partition. */
   1391 	blkno += sectoff;
   1392 
   1393 	xs = &sx;
   1394 
   1395 	while (totwrt > 0) {
   1396 		nwrt = totwrt;		/* XXX */
   1397 #ifndef	SD_DUMP_NOT_TRUSTED
   1398 		/*
   1399 		 *  Fill out the scsi command
   1400 		 */
   1401 		memset(&cmd, 0, sizeof(cmd));
   1402 		cmd.opcode = WRITE_BIG;
   1403 		_lto4b(blkno, cmd.addr);
   1404 		_lto2b(nwrt, cmd.length);
   1405 		/*
   1406 		 * Fill out the scsipi_xfer structure
   1407 		 *    Note: we cannot sleep as we may be an interrupt
   1408 		 * don't use scsipi_command() as it may want to wait
   1409 		 * for an xs.
   1410 		 */
   1411 		memset(xs, 0, sizeof(sx));
   1412 		xs->xs_control |= XS_CTL_NOSLEEP | XS_CTL_POLL |
   1413 		    XS_CTL_DATA_OUT;
   1414 		xs->xs_status = 0;
   1415 		xs->xs_periph = periph;
   1416 		xs->xs_retries = SDRETRIES;
   1417 		xs->timeout = 10000;	/* 10000 millisecs for a disk ! */
   1418 		xs->cmd = (struct scsipi_generic *)&cmd;
   1419 		xs->cmdlen = sizeof(cmd);
   1420 		xs->resid = nwrt * sectorsize;
   1421 		xs->error = XS_NOERROR;
   1422 		xs->bp = 0;
   1423 		xs->data = va;
   1424 		xs->datalen = nwrt * sectorsize;
   1425 
   1426 		/*
   1427 		 * Pass all this info to the scsi driver.
   1428 		 */
   1429 		scsipi_adapter_request(chan, ADAPTER_REQ_RUN_XFER, xs);
   1430 		if ((xs->xs_status & XS_STS_DONE) == 0 ||
   1431 		    xs->error != XS_NOERROR)
   1432 			return (EIO);
   1433 #else	/* SD_DUMP_NOT_TRUSTED */
   1434 		/* Let's just talk about this first... */
   1435 		printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
   1436 		delay(500 * 1000);	/* half a second */
   1437 #endif	/* SD_DUMP_NOT_TRUSTED */
   1438 
   1439 		/* update block count */
   1440 		totwrt -= nwrt;
   1441 		blkno += nwrt;
   1442 		va += sectorsize * nwrt;
   1443 	}
   1444 	sddoingadump = 0;
   1445 	return (0);
   1446 }
   1447