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