Home | History | Annotate | Line # | Download | only in scsipi
sd.c revision 1.221
      1 /*	$NetBSD: sd.c,v 1.221 2004/08/27 20:37:28 bouyer Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 2003 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.221 2004/08/27 20:37:28 bouyer 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 #define	SDUNIT(dev)			DISKUNIT(dev)
     91 #define	SDPART(dev)			DISKPART(dev)
     92 #define	SDMINOR(unit, part)		DISKMINOR(unit, part)
     93 #define	MAKESDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
     94 
     95 #define	SDLABELDEV(dev)	(MAKESDDEV(major(dev), SDUNIT(dev), RAW_PART))
     96 
     97 static int	sdlock(struct sd_softc *);
     98 static void	sdunlock(struct sd_softc *);
     99 static void	sdminphys(struct buf *);
    100 static void	sdgetdefaultlabel(struct sd_softc *, struct disklabel *);
    101 static void	sdgetdisklabel(struct sd_softc *);
    102 static void	sdstart(struct scsipi_periph *);
    103 static void	sdrestart(void *);
    104 static void	sddone(struct scsipi_xfer *);
    105 static void	sd_shutdown(void *);
    106 static int	sd_interpret_sense(struct scsipi_xfer *);
    107 
    108 static int	sd_mode_sense(struct sd_softc *, u_int8_t, void *, size_t, int,
    109 		    int, int *);
    110 static int	sd_mode_select(struct sd_softc *, u_int8_t, void *, size_t, int,
    111 		    int);
    112 static int	sd_get_simplifiedparms(struct sd_softc *, struct disk_parms *,
    113 		    int);
    114 static int	sd_get_capacity(struct sd_softc *, struct disk_parms *, int);
    115 static int	sd_get_parms(struct sd_softc *, struct disk_parms *, int);
    116 static int	sd_get_parms_page4(struct sd_softc *, struct disk_parms *,
    117 		    int);
    118 static int	sd_get_parms_page5(struct sd_softc *, struct disk_parms *,
    119 		    int);
    120 
    121 static int	sd_flush(struct sd_softc *, int);
    122 static int	sd_getcache(struct sd_softc *, int *);
    123 static int	sd_setcache(struct sd_softc *, int);
    124 
    125 static int	sdmatch(struct device *, struct cfdata *, void *);
    126 static void	sdattach(struct device *, struct device *, void *);
    127 static int	sdactivate(struct device *, enum devact);
    128 static int	sddetach(struct device *, int);
    129 
    130 CFATTACH_DECL(sd, sizeof(struct sd_softc), sdmatch, sdattach, sddetach,
    131     sdactivate);
    132 
    133 extern struct cfdriver sd_cd;
    134 
    135 static const struct scsipi_inquiry_pattern sd_patterns[] = {
    136 	{T_DIRECT, T_FIXED,
    137 	 "",         "",                 ""},
    138 	{T_DIRECT, T_REMOV,
    139 	 "",         "",                 ""},
    140 	{T_OPTICAL, T_FIXED,
    141 	 "",         "",                 ""},
    142 	{T_OPTICAL, T_REMOV,
    143 	 "",         "",                 ""},
    144 	{T_SIMPLE_DIRECT, T_FIXED,
    145 	 "",         "",                 ""},
    146 	{T_SIMPLE_DIRECT, T_REMOV,
    147 	 "",         "",                 ""},
    148 };
    149 
    150 static dev_type_open(sdopen);
    151 static dev_type_close(sdclose);
    152 static dev_type_read(sdread);
    153 static dev_type_write(sdwrite);
    154 static dev_type_ioctl(sdioctl);
    155 static dev_type_strategy(sdstrategy);
    156 static dev_type_dump(sddump);
    157 static dev_type_size(sdsize);
    158 
    159 const struct bdevsw sd_bdevsw = {
    160 	sdopen, sdclose, sdstrategy, sdioctl, sddump, sdsize, D_DISK
    161 };
    162 
    163 const struct cdevsw sd_cdevsw = {
    164 	sdopen, sdclose, sdread, sdwrite, sdioctl,
    165 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
    166 };
    167 
    168 static struct dkdriver sddkdriver = { sdstrategy };
    169 
    170 static const struct scsipi_periphsw sd_switch = {
    171 	sd_interpret_sense,	/* check our error handler first */
    172 	sdstart,		/* have a queue, served by this */
    173 	NULL,			/* have no async handler */
    174 	sddone,			/* deal with stats at interrupt time */
    175 };
    176 
    177 struct sd_mode_sense_data {
    178 	/*
    179 	 * XXX
    180 	 * We are not going to parse this as-is -- it just has to be large
    181 	 * enough.
    182 	 */
    183 	union {
    184 		struct scsipi_mode_header small;
    185 		struct scsipi_mode_header_big big;
    186 	} header;
    187 	struct scsi_blk_desc blk_desc;
    188 	union scsi_disk_pages pages;
    189 };
    190 
    191 /*
    192  * The routine called by the low level scsi routine when it discovers
    193  * A device suitable for this driver
    194  */
    195 static int
    196 sdmatch(struct device *parent, struct cfdata *match, void *aux)
    197 {
    198 	struct scsipibus_attach_args *sa = aux;
    199 	int priority;
    200 
    201 	(void)scsipi_inqmatch(&sa->sa_inqbuf,
    202 	    (caddr_t)sd_patterns, sizeof(sd_patterns) / sizeof(sd_patterns[0]),
    203 	    sizeof(sd_patterns[0]), &priority);
    204 
    205 	return (priority);
    206 }
    207 
    208 /*
    209  * Attach routine common to atapi & scsi.
    210  */
    211 static void
    212 sdattach(struct device *parent, struct device *self, void *aux)
    213 {
    214 	struct sd_softc *sd = (void *)self;
    215 	struct scsipibus_attach_args *sa = aux;
    216 	struct scsipi_periph *periph = sa->sa_periph;
    217 	int error, result;
    218 	struct disk_parms *dp = &sd->params;
    219 	char pbuf[9];
    220 
    221 	SC_DEBUG(periph, SCSIPI_DB2, ("sdattach: "));
    222 
    223 	sd->type = (sa->sa_inqbuf.type & SID_TYPE);
    224 	if (sd->type == T_SIMPLE_DIRECT)
    225 		periph->periph_quirks |= PQUIRK_ONLYBIG | PQUIRK_NOBIGMODESENSE;
    226 
    227 	if (scsipi_periph_bustype(sa->sa_periph) == SCSIPI_BUSTYPE_SCSI &&
    228 	    periph->periph_version == 0)
    229 		sd->flags |= SDF_ANCIENT;
    230 
    231 	bufq_alloc(&sd->buf_queue,
    232 	    BUFQ_DISK_DEFAULT_STRAT()|BUFQ_SORT_RAWBLOCK);
    233 
    234 	callout_init(&sd->sc_callout);
    235 
    236 	/*
    237 	 * Store information needed to contact our base driver
    238 	 */
    239 	sd->sc_periph = periph;
    240 
    241 	periph->periph_dev = &sd->sc_dev;
    242 	periph->periph_switch = &sd_switch;
    243 
    244         /*
    245          * Increase our openings to the maximum-per-periph
    246          * supported by the adapter.  This will either be
    247          * clamped down or grown by the adapter if necessary.
    248          */
    249 	periph->periph_openings =
    250 	    SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
    251 	periph->periph_flags |= PERIPH_GROW_OPENINGS;
    252 
    253 	/*
    254 	 * Initialize and attach the disk structure.
    255 	 */
    256 	sd->sc_dk.dk_driver = &sddkdriver;
    257 	sd->sc_dk.dk_name = sd->sc_dev.dv_xname;
    258 	disk_attach(&sd->sc_dk);
    259 
    260 	/*
    261 	 * Use the subdriver to request information regarding the drive.
    262 	 */
    263 	aprint_naive("\n");
    264 	aprint_normal("\n");
    265 
    266 	error = scsipi_test_unit_ready(periph,
    267 	    XS_CTL_DISCOVERY | XS_CTL_IGNORE_ILLEGAL_REQUEST |
    268 	    XS_CTL_IGNORE_MEDIA_CHANGE | XS_CTL_SILENT_NODEV);
    269 
    270 	if (error)
    271 		result = SDGP_RESULT_OFFLINE;
    272 	else
    273 		result = sd_get_parms(sd, &sd->params, XS_CTL_DISCOVERY);
    274 	aprint_normal("%s: ", sd->sc_dev.dv_xname);
    275 	switch (result) {
    276 	case SDGP_RESULT_OK:
    277 		format_bytes(pbuf, sizeof(pbuf),
    278 		    (u_int64_t)dp->disksize * dp->blksize);
    279 	        aprint_normal(
    280 		"%s, %ld cyl, %ld head, %ld sec, %ld bytes/sect x %llu sectors",
    281 		    pbuf, dp->cyls, dp->heads, dp->sectors, dp->blksize,
    282 		    (unsigned long long)dp->disksize);
    283 		break;
    284 
    285 	case SDGP_RESULT_OFFLINE:
    286 		aprint_normal("drive offline");
    287 		break;
    288 
    289 	case SDGP_RESULT_UNFORMATTED:
    290 		aprint_normal("unformatted media");
    291 		break;
    292 
    293 #ifdef DIAGNOSTIC
    294 	default:
    295 		panic("sdattach: unknown result from get_parms");
    296 		break;
    297 #endif
    298 	}
    299 	aprint_normal("\n");
    300 
    301 	/*
    302 	 * Establish a shutdown hook so that we can ensure that
    303 	 * our data has actually made it onto the platter at
    304 	 * shutdown time.  Note that this relies on the fact
    305 	 * that the shutdown hook code puts us at the head of
    306 	 * the list (thus guaranteeing that our hook runs before
    307 	 * our ancestors').
    308 	 */
    309 	if ((sd->sc_sdhook =
    310 	    shutdownhook_establish(sd_shutdown, sd)) == NULL)
    311 		aprint_error("%s: WARNING: unable to establish shutdown hook\n",
    312 		    sd->sc_dev.dv_xname);
    313 
    314 #if NRND > 0
    315 	/*
    316 	 * attach the device into the random source list
    317 	 */
    318 	rnd_attach_source(&sd->rnd_source, sd->sc_dev.dv_xname,
    319 			  RND_TYPE_DISK, 0);
    320 #endif
    321 }
    322 
    323 static int
    324 sdactivate(struct device *self, enum devact act)
    325 {
    326 	int rv = 0;
    327 
    328 	switch (act) {
    329 	case DVACT_ACTIVATE:
    330 		rv = EOPNOTSUPP;
    331 		break;
    332 
    333 	case DVACT_DEACTIVATE:
    334 		/*
    335 		 * Nothing to do; we key off the device's DVF_ACTIVE.
    336 		 */
    337 		break;
    338 	}
    339 	return (rv);
    340 }
    341 
    342 static int
    343 sddetach(struct device *self, int flags)
    344 {
    345 	struct sd_softc *sd = (struct sd_softc *) self;
    346 	struct buf *bp;
    347 	int s, bmaj, cmaj, i, mn;
    348 
    349 	/* locate the major number */
    350 	bmaj = bdevsw_lookup_major(&sd_bdevsw);
    351 	cmaj = cdevsw_lookup_major(&sd_cdevsw);
    352 
    353 	/* kill any pending restart */
    354 	callout_stop(&sd->sc_callout);
    355 
    356 	s = splbio();
    357 
    358 	/* Kill off any queued buffers. */
    359 	while ((bp = BUFQ_GET(&sd->buf_queue)) != NULL) {
    360 		bp->b_error = EIO;
    361 		bp->b_flags |= B_ERROR;
    362 		bp->b_resid = bp->b_bcount;
    363 		biodone(bp);
    364 	}
    365 
    366 	bufq_free(&sd->buf_queue);
    367 
    368 	/* Kill off any pending commands. */
    369 	scsipi_kill_pending(sd->sc_periph);
    370 
    371 	splx(s);
    372 
    373 	/* Nuke the vnodes for any open instances */
    374 	for (i = 0; i < MAXPARTITIONS; i++) {
    375 		mn = SDMINOR(self->dv_unit, i);
    376 		vdevgone(bmaj, mn, mn, VBLK);
    377 		vdevgone(cmaj, mn, mn, VCHR);
    378 	}
    379 
    380 	/* Detach from the disk list. */
    381 	disk_detach(&sd->sc_dk);
    382 
    383 	/* Get rid of the shutdown hook. */
    384 	shutdownhook_disestablish(sd->sc_sdhook);
    385 
    386 #if NRND > 0
    387 	/* Unhook the entropy source. */
    388 	rnd_detach_source(&sd->rnd_source);
    389 #endif
    390 
    391 	return (0);
    392 }
    393 
    394 /*
    395  * Wait interruptibly for an exclusive lock.
    396  *
    397  * XXX
    398  * Several drivers do this; it should be abstracted and made MP-safe.
    399  */
    400 static int
    401 sdlock(struct sd_softc *sd)
    402 {
    403 	int error;
    404 
    405 	while ((sd->flags & SDF_LOCKED) != 0) {
    406 		sd->flags |= SDF_WANTED;
    407 		if ((error = tsleep(sd, PRIBIO | PCATCH, "sdlck", 0)) != 0)
    408 			return (error);
    409 	}
    410 	sd->flags |= SDF_LOCKED;
    411 	return (0);
    412 }
    413 
    414 /*
    415  * Unlock and wake up any waiters.
    416  */
    417 static void
    418 sdunlock(struct sd_softc *sd)
    419 {
    420 
    421 	sd->flags &= ~SDF_LOCKED;
    422 	if ((sd->flags & SDF_WANTED) != 0) {
    423 		sd->flags &= ~SDF_WANTED;
    424 		wakeup(sd);
    425 	}
    426 }
    427 
    428 /*
    429  * open the device. Make sure the partition info is a up-to-date as can be.
    430  */
    431 static int
    432 sdopen(dev_t dev, int flag, int fmt, struct proc *p)
    433 {
    434 	struct sd_softc *sd;
    435 	struct scsipi_periph *periph;
    436 	struct scsipi_adapter *adapt;
    437 	int unit, part;
    438 	int error;
    439 
    440 	unit = SDUNIT(dev);
    441 	if (unit >= sd_cd.cd_ndevs)
    442 		return (ENXIO);
    443 	sd = sd_cd.cd_devs[unit];
    444 	if (sd == NULL)
    445 		return (ENXIO);
    446 
    447 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
    448 		return (ENODEV);
    449 
    450 	periph = sd->sc_periph;
    451 	adapt = periph->periph_channel->chan_adapter;
    452 	part = SDPART(dev);
    453 
    454 	SC_DEBUG(periph, SCSIPI_DB1,
    455 	    ("sdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev, unit,
    456 	    sd_cd.cd_ndevs, part));
    457 
    458 	/*
    459 	 * If this is the first open of this device, add a reference
    460 	 * to the adapter.
    461 	 */
    462 	if (sd->sc_dk.dk_openmask == 0 &&
    463 	    (error = scsipi_adapter_addref(adapt)) != 0)
    464 		return (error);
    465 
    466 	if ((error = sdlock(sd)) != 0)
    467 		goto bad4;
    468 
    469 	if ((periph->periph_flags & PERIPH_OPEN) != 0) {
    470 		/*
    471 		 * If any partition is open, but the disk has been invalidated,
    472 		 * disallow further opens of non-raw partition
    473 		 */
    474 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
    475 		    (part != RAW_PART || fmt != S_IFCHR)) {
    476 			error = EIO;
    477 			goto bad3;
    478 		}
    479 	} else {
    480 		int silent;
    481 
    482 		if (part == RAW_PART && fmt == S_IFCHR)
    483 			silent = XS_CTL_SILENT;
    484 		else
    485 			silent = 0;
    486 
    487 		/* Check that it is still responding and ok. */
    488 		error = scsipi_test_unit_ready(periph,
    489 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
    490 		    silent);
    491 
    492 		/*
    493 		 * Start the pack spinning if necessary. Always allow the
    494 		 * raw parition to be opened, for raw IOCTLs. Data transfers
    495 		 * will check for SDEV_MEDIA_LOADED.
    496 		 */
    497 		if (error == EIO) {
    498 			int error2;
    499 
    500 			error2 = scsipi_start(periph, SSS_START, silent);
    501 			switch (error2) {
    502 			case 0:
    503 				error = 0;
    504 				break;
    505 			case EIO:
    506 			case EINVAL:
    507 				break;
    508 			default:
    509 				error = error2;
    510 				break;
    511 			}
    512 		}
    513 		if (error) {
    514 			if (silent)
    515 				goto out;
    516 			goto bad3;
    517 		}
    518 
    519 		periph->periph_flags |= PERIPH_OPEN;
    520 
    521 		if (periph->periph_flags & PERIPH_REMOVABLE) {
    522 			/* Lock the pack in. */
    523 			error = scsipi_prevent(periph, PR_PREVENT,
    524 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
    525 			    XS_CTL_IGNORE_MEDIA_CHANGE);
    526 			if (error)
    527 				goto bad;
    528 		}
    529 
    530 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
    531 			int param_error;
    532 			periph->periph_flags |= PERIPH_MEDIA_LOADED;
    533 
    534 			/*
    535 			 * Load the physical device parameters.
    536 			 *
    537 			 * Note that if media is present but unformatted,
    538 			 * we allow the open (so that it can be formatted!).
    539 			 * The drive should refuse real I/O, if the media is
    540 			 * unformatted.
    541 			 */
    542 			if ((param_error = sd_get_parms(sd, &sd->params, 0))
    543 			     == SDGP_RESULT_OFFLINE) {
    544 				error = ENXIO;
    545 				goto bad2;
    546 			}
    547 			SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));
    548 
    549 			/* Load the partition info if not already loaded. */
    550 			if (param_error == 0) {
    551 				sdgetdisklabel(sd);
    552 				SC_DEBUG(periph, SCSIPI_DB3,
    553 				     ("Disklabel loaded "));
    554 			}
    555 		}
    556 	}
    557 
    558 	/* Check that the partition exists. */
    559 	if (part != RAW_PART &&
    560 	    (part >= sd->sc_dk.dk_label->d_npartitions ||
    561 	     sd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
    562 		error = ENXIO;
    563 		goto bad;
    564 	}
    565 
    566 out:	/* Insure only one open at a time. */
    567 	switch (fmt) {
    568 	case S_IFCHR:
    569 		sd->sc_dk.dk_copenmask |= (1 << part);
    570 		break;
    571 	case S_IFBLK:
    572 		sd->sc_dk.dk_bopenmask |= (1 << part);
    573 		break;
    574 	}
    575 	sd->sc_dk.dk_openmask =
    576 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
    577 
    578 	SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));
    579 	sdunlock(sd);
    580 	return (0);
    581 
    582 bad2:
    583 	periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
    584 
    585 bad:
    586 	if (sd->sc_dk.dk_openmask == 0) {
    587 		if (periph->periph_flags & PERIPH_REMOVABLE)
    588 			scsipi_prevent(periph, PR_ALLOW,
    589 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
    590 			    XS_CTL_IGNORE_MEDIA_CHANGE);
    591 		periph->periph_flags &= ~PERIPH_OPEN;
    592 	}
    593 
    594 bad3:
    595 	sdunlock(sd);
    596 bad4:
    597 	if (sd->sc_dk.dk_openmask == 0)
    598 		scsipi_adapter_delref(adapt);
    599 	return (error);
    600 }
    601 
    602 /*
    603  * close the device.. only called if we are the LAST occurence of an open
    604  * device.  Convenient now but usually a pain.
    605  */
    606 static int
    607 sdclose(dev_t dev, int flag, int fmt, struct proc *p)
    608 {
    609 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
    610 	struct scsipi_periph *periph = sd->sc_periph;
    611 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
    612 	int part = SDPART(dev);
    613 	int error;
    614 
    615 	if ((error = sdlock(sd)) != 0)
    616 		return (error);
    617 
    618 	switch (fmt) {
    619 	case S_IFCHR:
    620 		sd->sc_dk.dk_copenmask &= ~(1 << part);
    621 		break;
    622 	case S_IFBLK:
    623 		sd->sc_dk.dk_bopenmask &= ~(1 << part);
    624 		break;
    625 	}
    626 	sd->sc_dk.dk_openmask =
    627 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
    628 
    629 	if (sd->sc_dk.dk_openmask == 0) {
    630 		/*
    631 		 * If the disk cache needs flushing, and the disk supports
    632 		 * it, do it now.
    633 		 */
    634 		if ((sd->flags & SDF_DIRTY) != 0) {
    635 			if (sd_flush(sd, 0)) {
    636 				printf("%s: cache synchronization failed\n",
    637 				    sd->sc_dev.dv_xname);
    638 				sd->flags &= ~SDF_FLUSHING;
    639 			} else
    640 				sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
    641 		}
    642 
    643 		if (! (periph->periph_flags & PERIPH_KEEP_LABEL))
    644 			periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
    645 
    646 		scsipi_wait_drain(periph);
    647 
    648 		if (periph->periph_flags & PERIPH_REMOVABLE)
    649 			scsipi_prevent(periph, PR_ALLOW,
    650 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
    651 			    XS_CTL_IGNORE_NOT_READY);
    652 		periph->periph_flags &= ~PERIPH_OPEN;
    653 
    654 		scsipi_wait_drain(periph);
    655 
    656 		scsipi_adapter_delref(adapt);
    657 	}
    658 
    659 	sdunlock(sd);
    660 	return (0);
    661 }
    662 
    663 /*
    664  * Actually translate the requested transfer into one the physical driver
    665  * can understand.  The transfer is described by a buf and will include
    666  * only one physical transfer.
    667  */
    668 static void
    669 sdstrategy(struct buf *bp)
    670 {
    671 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
    672 	struct scsipi_periph *periph = sd->sc_periph;
    673 	struct disklabel *lp;
    674 	daddr_t blkno;
    675 	int s;
    676 	boolean_t sector_aligned;
    677 
    678 	SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdstrategy "));
    679 	SC_DEBUG(sd->sc_periph, SCSIPI_DB1,
    680 	    ("%ld bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));
    681 	/*
    682 	 * If the device has been made invalid, error out
    683 	 */
    684 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 ||
    685 	    (sd->sc_dev.dv_flags & DVF_ACTIVE) == 0) {
    686 		if (periph->periph_flags & PERIPH_OPEN)
    687 			bp->b_error = EIO;
    688 		else
    689 			bp->b_error = ENODEV;
    690 		goto bad;
    691 	}
    692 
    693 	lp = sd->sc_dk.dk_label;
    694 
    695 	/*
    696 	 * The transfer must be a whole number of blocks, offset must not be
    697 	 * negative.
    698 	 */
    699 	if (lp->d_secsize == DEV_BSIZE) {
    700 		sector_aligned = (bp->b_bcount & (DEV_BSIZE - 1)) == 0;
    701 	} else {
    702 		sector_aligned = (bp->b_bcount % lp->d_secsize) == 0;
    703 	}
    704 	if (!sector_aligned || bp->b_blkno < 0) {
    705 		bp->b_error = EINVAL;
    706 		goto bad;
    707 	}
    708 	/*
    709 	 * If it's a null transfer, return immediatly
    710 	 */
    711 	if (bp->b_bcount == 0)
    712 		goto done;
    713 
    714 	/*
    715 	 * Do bounds checking, adjust transfer. if error, process.
    716 	 * If end of partition, just return.
    717 	 */
    718 	if (SDPART(bp->b_dev) == RAW_PART) {
    719 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
    720 		    sd->params.disksize512) <= 0)
    721 			goto done;
    722 	} else {
    723 		if (bounds_check_with_label(&sd->sc_dk, bp,
    724 		    (sd->flags & (SDF_WLABEL|SDF_LABELLING)) != 0) <= 0)
    725 			goto done;
    726 	}
    727 
    728 	/*
    729 	 * Now convert the block number to absolute and put it in
    730 	 * terms of the device's logical block size.
    731 	 */
    732 	if (lp->d_secsize == DEV_BSIZE)
    733 		blkno = bp->b_blkno;
    734 	else if (lp->d_secsize > DEV_BSIZE)
    735 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
    736 	else
    737 		blkno = bp->b_blkno * (DEV_BSIZE / lp->d_secsize);
    738 
    739 	if (SDPART(bp->b_dev) != RAW_PART)
    740 		blkno += lp->d_partitions[SDPART(bp->b_dev)].p_offset;
    741 
    742 	bp->b_rawblkno = blkno;
    743 
    744 	s = splbio();
    745 
    746 	/*
    747 	 * Place it in the queue of disk activities for this disk.
    748 	 *
    749 	 * XXX Only do disksort() if the current operating mode does not
    750 	 * XXX include tagged queueing.
    751 	 */
    752 	BUFQ_PUT(&sd->buf_queue, bp);
    753 
    754 	/*
    755 	 * Tell the device to get going on the transfer if it's
    756 	 * not doing anything, otherwise just wait for completion
    757 	 */
    758 	sdstart(sd->sc_periph);
    759 
    760 	splx(s);
    761 	return;
    762 
    763 bad:
    764 	bp->b_flags |= B_ERROR;
    765 done:
    766 	/*
    767 	 * Correctly set the buf to indicate a completed xfer
    768 	 */
    769 	bp->b_resid = bp->b_bcount;
    770 	biodone(bp);
    771 }
    772 
    773 /*
    774  * sdstart looks to see if there is a buf waiting for the device
    775  * and that the device is not already busy. If both are true,
    776  * It dequeues the buf and creates a scsi command to perform the
    777  * transfer in the buf. The transfer request will call scsipi_done
    778  * on completion, which will in turn call this routine again
    779  * so that the next queued transfer is performed.
    780  * The bufs are queued by the strategy routine (sdstrategy)
    781  *
    782  * This routine is also called after other non-queued requests
    783  * have been made of the scsi driver, to ensure that the queue
    784  * continues to be drained.
    785  *
    786  * must be called at the correct (highish) spl level
    787  * sdstart() is called at splbio from sdstrategy and scsipi_done
    788  */
    789 static void
    790 sdstart(struct scsipi_periph *periph)
    791 {
    792 	struct sd_softc *sd = (void *)periph->periph_dev;
    793 	struct disklabel *lp = sd->sc_dk.dk_label;
    794 	struct buf *bp = 0;
    795 	struct scsipi_rw_big cmd_big;
    796 	struct scsi_rw cmd_small;
    797 	struct scsipi_generic *cmdp;
    798 	int nblks, cmdlen, error, flags;
    799 
    800 	SC_DEBUG(periph, SCSIPI_DB2, ("sdstart "));
    801 	/*
    802 	 * Check if the device has room for another command
    803 	 */
    804 	while (periph->periph_active < periph->periph_openings) {
    805 		/*
    806 		 * there is excess capacity, but a special waits
    807 		 * It'll need the adapter as soon as we clear out of the
    808 		 * way and let it run (user level wait).
    809 		 */
    810 		if (periph->periph_flags & PERIPH_WAITING) {
    811 			periph->periph_flags &= ~PERIPH_WAITING;
    812 			wakeup((caddr_t)periph);
    813 			return;
    814 		}
    815 
    816 		/*
    817 		 * If the device has become invalid, abort all the
    818 		 * reads and writes until all files have been closed and
    819 		 * re-opened
    820 		 */
    821 		if (__predict_false(
    822 		    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
    823 			if ((bp = BUFQ_GET(&sd->buf_queue)) != NULL) {
    824 				bp->b_error = EIO;
    825 				bp->b_flags |= B_ERROR;
    826 				bp->b_resid = bp->b_bcount;
    827 				biodone(bp);
    828 				continue;
    829 			} else {
    830 				return;
    831 			}
    832 		}
    833 
    834 		/*
    835 		 * See if there is a buf with work for us to do..
    836 		 */
    837 		if ((bp = BUFQ_PEEK(&sd->buf_queue)) == NULL)
    838 			return;
    839 
    840 		/*
    841 		 * We have a buf, now we should make a command.
    842 		 */
    843 
    844 		if (lp->d_secsize == DEV_BSIZE)
    845 			nblks = bp->b_bcount >> DEV_BSHIFT;
    846 		else
    847 			nblks = howmany(bp->b_bcount, lp->d_secsize);
    848 
    849 		/*
    850 		 *  Fill out the scsi command.  If the transfer will
    851 		 *  fit in a "small" cdb, use it.
    852 		 */
    853 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
    854 		    ((nblks & 0xff) == nblks) &&
    855 		    !(periph->periph_quirks & PQUIRK_ONLYBIG)) {
    856 			/*
    857 			 * We can fit in a small cdb.
    858 			 */
    859 			memset(&cmd_small, 0, sizeof(cmd_small));
    860 			cmd_small.opcode = (bp->b_flags & B_READ) ?
    861 			    SCSI_READ_COMMAND : SCSI_WRITE_COMMAND;
    862 			_lto3b(bp->b_rawblkno, cmd_small.addr);
    863 			cmd_small.length = nblks & 0xff;
    864 			cmdlen = sizeof(cmd_small);
    865 			cmdp = (struct scsipi_generic *)&cmd_small;
    866 		} else {
    867 			/*
    868 			 * Need a large cdb.
    869 			 */
    870 			memset(&cmd_big, 0, sizeof(cmd_big));
    871 			cmd_big.opcode = (bp->b_flags & B_READ) ?
    872 			    READ_BIG : WRITE_BIG;
    873 			_lto4b(bp->b_rawblkno, cmd_big.addr);
    874 			_lto2b(nblks, cmd_big.length);
    875 			cmdlen = sizeof(cmd_big);
    876 			cmdp = (struct scsipi_generic *)&cmd_big;
    877 		}
    878 
    879 		/* Instrumentation. */
    880 		disk_busy(&sd->sc_dk);
    881 
    882 		/*
    883 		 * Mark the disk dirty so that the cache will be
    884 		 * flushed on close.
    885 		 */
    886 		if ((bp->b_flags & B_READ) == 0)
    887 			sd->flags |= SDF_DIRTY;
    888 
    889 		/*
    890 		 * Figure out what flags to use.
    891 		 */
    892 		flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
    893 		if (bp->b_flags & B_READ)
    894 			flags |= XS_CTL_DATA_IN;
    895 		else
    896 			flags |= XS_CTL_DATA_OUT;
    897 
    898 		/*
    899 		 * Call the routine that chats with the adapter.
    900 		 * Note: we cannot sleep as we may be an interrupt
    901 		 */
    902 		error = scsipi_command(periph, cmdp, cmdlen,
    903 		    (u_char *)bp->b_data, bp->b_bcount,
    904 		    SDRETRIES, SD_IO_TIMEOUT, bp, flags);
    905 		if (__predict_false(error)) {
    906 			disk_unbusy(&sd->sc_dk, 0, 0);
    907 			printf("%s: not queued, error %d\n",
    908 			    sd->sc_dev.dv_xname, error);
    909 		}
    910 		if (__predict_false(error == ENOMEM)) {
    911 			/*
    912 			 * out of memory. Keep this buffer in the queue, and
    913 			 * retry later.
    914 			 */
    915 			callout_reset(&sd->sc_callout, hz / 2, sdrestart,
    916 			    periph);
    917 			return;
    918 		}
    919 #ifdef DIAGNOSTIC
    920 		if (BUFQ_GET(&sd->buf_queue) != bp)
    921 			panic("sdstart(): dequeued wrong buf");
    922 #else
    923 		BUFQ_GET(&sd->buf_queue);
    924 #endif
    925 
    926 	}
    927 }
    928 
    929 static void
    930 sdrestart(void *v)
    931 {
    932 	int s = splbio();
    933 	sdstart((struct scsipi_periph *)v);
    934 	splx(s);
    935 }
    936 
    937 static void
    938 sddone(struct scsipi_xfer *xs)
    939 {
    940 	struct sd_softc *sd = (void *)xs->xs_periph->periph_dev;
    941 
    942 	if (sd->flags & SDF_FLUSHING) {
    943 		/* Flush completed, no longer dirty. */
    944 		sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
    945 	}
    946 
    947 	if (xs->bp != NULL) {
    948 		disk_unbusy(&sd->sc_dk, xs->bp->b_bcount - xs->bp->b_resid,
    949 		    (xs->bp->b_flags & B_READ));
    950 #if NRND > 0
    951 		rnd_add_uint32(&sd->rnd_source, xs->bp->b_rawblkno);
    952 #endif
    953 	}
    954 }
    955 
    956 static void
    957 sdminphys(struct buf *bp)
    958 {
    959 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
    960 	long max;
    961 
    962 	/*
    963 	 * If the device is ancient, we want to make sure that
    964 	 * the transfer fits into a 6-byte cdb.
    965 	 *
    966 	 * XXX Note that the SCSI-I spec says that 256-block transfers
    967 	 * are allowed in a 6-byte read/write, and are specified
    968 	 * by settng the "length" to 0.  However, we're conservative
    969 	 * here, allowing only 255-block transfers in case an
    970 	 * ancient device gets confused by length == 0.  A length of 0
    971 	 * in a 10-byte read/write actually means 0 blocks.
    972 	 */
    973 	if ((sd->flags & SDF_ANCIENT) &&
    974 	    ((sd->sc_periph->periph_flags &
    975 	    (PERIPH_REMOVABLE | PERIPH_MEDIA_LOADED)) != PERIPH_REMOVABLE)) {
    976 		max = sd->sc_dk.dk_label->d_secsize * 0xff;
    977 
    978 		if (bp->b_bcount > max)
    979 			bp->b_bcount = max;
    980 	}
    981 
    982 	scsipi_adapter_minphys(sd->sc_periph->periph_channel, bp);
    983 }
    984 
    985 static int
    986 sdread(dev_t dev, struct uio *uio, int ioflag)
    987 {
    988 
    989 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
    990 }
    991 
    992 static int
    993 sdwrite(dev_t dev, struct uio *uio, int ioflag)
    994 {
    995 
    996 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
    997 }
    998 
    999 /*
   1000  * Perform special action on behalf of the user
   1001  * Knows about the internals of this device
   1002  */
   1003 static int
   1004 sdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
   1005 {
   1006 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
   1007 	struct scsipi_periph *periph = sd->sc_periph;
   1008 	int part = SDPART(dev);
   1009 	int error = 0;
   1010 #ifdef __HAVE_OLD_DISKLABEL
   1011 	struct disklabel *newlabel = NULL;
   1012 #endif
   1013 
   1014 	SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdioctl 0x%lx ", cmd));
   1015 
   1016 	/*
   1017 	 * If the device is not valid, some IOCTLs can still be
   1018 	 * handled on the raw partition. Check this here.
   1019 	 */
   1020 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
   1021 		switch (cmd) {
   1022 		case DIOCKLABEL:
   1023 		case DIOCWLABEL:
   1024 		case DIOCLOCK:
   1025 		case DIOCEJECT:
   1026 		case ODIOCEJECT:
   1027 		case DIOCGCACHE:
   1028 		case DIOCSCACHE:
   1029 		case SCIOCIDENTIFY:
   1030 		case OSCIOCIDENTIFY:
   1031 		case SCIOCCOMMAND:
   1032 		case SCIOCDEBUG:
   1033 			if (part == RAW_PART)
   1034 				break;
   1035 		/* FALLTHROUGH */
   1036 		default:
   1037 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
   1038 				return (ENODEV);
   1039 			else
   1040 				return (EIO);
   1041 		}
   1042 	}
   1043 
   1044 	switch (cmd) {
   1045 	case DIOCGDINFO:
   1046 		*(struct disklabel *)addr = *(sd->sc_dk.dk_label);
   1047 		return (0);
   1048 
   1049 #ifdef __HAVE_OLD_DISKLABEL
   1050 	case ODIOCGDINFO:
   1051 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1052 		if (newlabel == NULL)
   1053 			return EIO;
   1054 		memcpy(newlabel, sd->sc_dk.dk_label, sizeof (*newlabel));
   1055 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
   1056 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
   1057 		else
   1058 			error = ENOTTY;
   1059 		free(newlabel, M_TEMP);
   1060 		return error;
   1061 #endif
   1062 
   1063 	case DIOCGPART:
   1064 		((struct partinfo *)addr)->disklab = sd->sc_dk.dk_label;
   1065 		((struct partinfo *)addr)->part =
   1066 		    &sd->sc_dk.dk_label->d_partitions[part];
   1067 		return (0);
   1068 
   1069 	case DIOCWDINFO:
   1070 	case DIOCSDINFO:
   1071 #ifdef __HAVE_OLD_DISKLABEL
   1072 	case ODIOCWDINFO:
   1073 	case ODIOCSDINFO:
   1074 #endif
   1075 	{
   1076 		struct disklabel *lp;
   1077 
   1078 		if ((flag & FWRITE) == 0)
   1079 			return (EBADF);
   1080 
   1081 #ifdef __HAVE_OLD_DISKLABEL
   1082  		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
   1083 			newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1084 			if (newlabel == NULL)
   1085 				return EIO;
   1086 			memset(newlabel, 0, sizeof newlabel);
   1087 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
   1088 			lp = newlabel;
   1089 		} else
   1090 #endif
   1091 		lp = (struct disklabel *)addr;
   1092 
   1093 		if ((error = sdlock(sd)) != 0)
   1094 			goto bad;
   1095 		sd->flags |= SDF_LABELLING;
   1096 
   1097 		error = setdisklabel(sd->sc_dk.dk_label,
   1098 		    lp, /*sd->sc_dk.dk_openmask : */0,
   1099 		    sd->sc_dk.dk_cpulabel);
   1100 		if (error == 0) {
   1101 			if (cmd == DIOCWDINFO
   1102 #ifdef __HAVE_OLD_DISKLABEL
   1103 			    || cmd == ODIOCWDINFO
   1104 #endif
   1105 			   )
   1106 				error = writedisklabel(SDLABELDEV(dev),
   1107 				    sdstrategy, sd->sc_dk.dk_label,
   1108 				    sd->sc_dk.dk_cpulabel);
   1109 		}
   1110 
   1111 		sd->flags &= ~SDF_LABELLING;
   1112 		sdunlock(sd);
   1113 bad:
   1114 #ifdef __HAVE_OLD_DISKLABEL
   1115 		if (newlabel != NULL)
   1116 			free(newlabel, M_TEMP);
   1117 #endif
   1118 		return (error);
   1119 	}
   1120 
   1121 	case DIOCKLABEL:
   1122 		if (*(int *)addr)
   1123 			periph->periph_flags |= PERIPH_KEEP_LABEL;
   1124 		else
   1125 			periph->periph_flags &= ~PERIPH_KEEP_LABEL;
   1126 		return (0);
   1127 
   1128 	case DIOCWLABEL:
   1129 		if ((flag & FWRITE) == 0)
   1130 			return (EBADF);
   1131 		if (*(int *)addr)
   1132 			sd->flags |= SDF_WLABEL;
   1133 		else
   1134 			sd->flags &= ~SDF_WLABEL;
   1135 		return (0);
   1136 
   1137 	case DIOCLOCK:
   1138 		return (scsipi_prevent(periph,
   1139 		    (*(int *)addr) ? PR_PREVENT : PR_ALLOW, 0));
   1140 
   1141 	case DIOCEJECT:
   1142 		if ((periph->periph_flags & PERIPH_REMOVABLE) == 0)
   1143 			return (ENOTTY);
   1144 		if (*(int *)addr == 0) {
   1145 			/*
   1146 			 * Don't force eject: check that we are the only
   1147 			 * partition open. If so, unlock it.
   1148 			 */
   1149 			if ((sd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
   1150 			    sd->sc_dk.dk_bopenmask + sd->sc_dk.dk_copenmask ==
   1151 			    sd->sc_dk.dk_openmask) {
   1152 				error = scsipi_prevent(periph, PR_ALLOW,
   1153 				    XS_CTL_IGNORE_NOT_READY);
   1154 				if (error)
   1155 					return (error);
   1156 			} else {
   1157 				return (EBUSY);
   1158 			}
   1159 		}
   1160 		/* FALLTHROUGH */
   1161 	case ODIOCEJECT:
   1162 		return ((periph->periph_flags & PERIPH_REMOVABLE) == 0 ?
   1163 		    ENOTTY : scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
   1164 
   1165 	case DIOCGDEFLABEL:
   1166 		sdgetdefaultlabel(sd, (struct disklabel *)addr);
   1167 		return (0);
   1168 
   1169 #ifdef __HAVE_OLD_DISKLABEL
   1170 	case ODIOCGDEFLABEL:
   1171 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1172 		if (newlabel == NULL)
   1173 			return EIO;
   1174 		sdgetdefaultlabel(sd, newlabel);
   1175 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
   1176 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
   1177 		else
   1178 			error = ENOTTY;
   1179 		free(newlabel, M_TEMP);
   1180 		return error;
   1181 #endif
   1182 
   1183 	case DIOCGCACHE:
   1184 		return (sd_getcache(sd, (int *) addr));
   1185 
   1186 	case DIOCSCACHE:
   1187 		if ((flag & FWRITE) == 0)
   1188 			return (EBADF);
   1189 		return (sd_setcache(sd, *(int *) addr));
   1190 
   1191 	case DIOCCACHESYNC:
   1192 		/*
   1193 		 * XXX Do we really need to care about having a writable
   1194 		 * file descriptor here?
   1195 		 */
   1196 		if ((flag & FWRITE) == 0)
   1197 			return (EBADF);
   1198 		if (((sd->flags & SDF_DIRTY) != 0 || *(int *)addr != 0)) {
   1199 			error = sd_flush(sd, 0);
   1200 			if (error)
   1201 				sd->flags &= ~SDF_FLUSHING;
   1202 			else
   1203 				sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
   1204 		} else
   1205 			error = 0;
   1206 		return (error);
   1207 
   1208 	default:
   1209 		if (part != RAW_PART)
   1210 			return (ENOTTY);
   1211 		return (scsipi_do_ioctl(periph, dev, cmd, addr, flag, p));
   1212 	}
   1213 
   1214 #ifdef DIAGNOSTIC
   1215 	panic("sdioctl: impossible");
   1216 #endif
   1217 }
   1218 
   1219 static void
   1220 sdgetdefaultlabel(struct sd_softc *sd, struct disklabel *lp)
   1221 {
   1222 
   1223 	memset(lp, 0, sizeof(struct disklabel));
   1224 
   1225 	lp->d_secsize = sd->params.blksize;
   1226 	lp->d_ntracks = sd->params.heads;
   1227 	lp->d_nsectors = sd->params.sectors;
   1228 	lp->d_ncylinders = sd->params.cyls;
   1229 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
   1230 
   1231 	switch (scsipi_periph_bustype(sd->sc_periph)) {
   1232 	case SCSIPI_BUSTYPE_SCSI:
   1233 		lp->d_type = DTYPE_SCSI;
   1234 		break;
   1235 	case SCSIPI_BUSTYPE_ATAPI:
   1236 		lp->d_type = DTYPE_ATAPI;
   1237 		break;
   1238 	}
   1239 	/*
   1240 	 * XXX
   1241 	 * We could probe the mode pages to figure out what kind of disc it is.
   1242 	 * Is this worthwhile?
   1243 	 */
   1244 	strncpy(lp->d_typename, "mydisk", 16);
   1245 	strncpy(lp->d_packname, "fictitious", 16);
   1246 	lp->d_secperunit = sd->params.disksize;
   1247 	lp->d_rpm = sd->params.rot_rate;
   1248 	lp->d_interleave = 1;
   1249 	lp->d_flags = sd->sc_periph->periph_flags & PERIPH_REMOVABLE ?
   1250 	    D_REMOVABLE : 0;
   1251 
   1252 	lp->d_partitions[RAW_PART].p_offset = 0;
   1253 	lp->d_partitions[RAW_PART].p_size =
   1254 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
   1255 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
   1256 	lp->d_npartitions = RAW_PART + 1;
   1257 
   1258 	lp->d_magic = DISKMAGIC;
   1259 	lp->d_magic2 = DISKMAGIC;
   1260 	lp->d_checksum = dkcksum(lp);
   1261 }
   1262 
   1263 
   1264 /*
   1265  * Load the label information on the named device
   1266  */
   1267 static void
   1268 sdgetdisklabel(struct sd_softc *sd)
   1269 {
   1270 	struct disklabel *lp = sd->sc_dk.dk_label;
   1271 	const char *errstring;
   1272 
   1273 	memset(sd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
   1274 
   1275 	sdgetdefaultlabel(sd, lp);
   1276 
   1277 	if (lp->d_secpercyl == 0) {
   1278 		lp->d_secpercyl = 100;
   1279 		/* as long as it's not 0 - readdisklabel divides by it (?) */
   1280 	}
   1281 
   1282 	/*
   1283 	 * Call the generic disklabel extraction routine
   1284 	 */
   1285 	errstring = readdisklabel(MAKESDDEV(0, sd->sc_dev.dv_unit, RAW_PART),
   1286 	    sdstrategy, lp, sd->sc_dk.dk_cpulabel);
   1287 	if (errstring) {
   1288 		printf("%s: %s\n", sd->sc_dev.dv_xname, errstring);
   1289 		return;
   1290 	}
   1291 }
   1292 
   1293 static void
   1294 sd_shutdown(void *arg)
   1295 {
   1296 	struct sd_softc *sd = arg;
   1297 
   1298 	/*
   1299 	 * If the disk cache needs to be flushed, and the disk supports
   1300 	 * it, flush it.  We're cold at this point, so we poll for
   1301 	 * completion.
   1302 	 */
   1303 	if ((sd->flags & SDF_DIRTY) != 0) {
   1304 		if (sd_flush(sd, XS_CTL_NOSLEEP|XS_CTL_POLL)) {
   1305 			printf("%s: cache synchronization failed\n",
   1306 			    sd->sc_dev.dv_xname);
   1307 			sd->flags &= ~SDF_FLUSHING;
   1308 		} else
   1309 			sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
   1310 	}
   1311 }
   1312 
   1313 /*
   1314  * Check Errors
   1315  */
   1316 static int
   1317 sd_interpret_sense(struct scsipi_xfer *xs)
   1318 {
   1319 	struct scsipi_periph *periph = xs->xs_periph;
   1320 	struct scsipi_sense_data *sense = &xs->sense.scsi_sense;
   1321 	struct sd_softc *sd = (void *)periph->periph_dev;
   1322 	int s, error, retval = EJUSTRETURN;
   1323 
   1324 	/*
   1325 	 * If the periph is already recovering, just do the normal
   1326 	 * error processing.
   1327 	 */
   1328 	if (periph->periph_flags & PERIPH_RECOVERING)
   1329 		return (retval);
   1330 
   1331 	/*
   1332 	 * If the device is not open yet, let the generic code handle it.
   1333 	 */
   1334 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1335 		return (retval);
   1336 
   1337 	/*
   1338 	 * If it isn't a extended or extended/deferred error, let
   1339 	 * the generic code handle it.
   1340 	 */
   1341 	if ((sense->error_code & SSD_ERRCODE) != 0x70 &&
   1342 	    (sense->error_code & SSD_ERRCODE) != 0x71)
   1343 		return (retval);
   1344 
   1345 	if ((sense->flags & SSD_KEY) == SKEY_NOT_READY &&
   1346 	    sense->add_sense_code == 0x4) {
   1347 		if (sense->add_sense_code_qual == 0x01)	{
   1348 			/*
   1349 			 * Unit In The Process Of Becoming Ready.
   1350 			 */
   1351 			printf("%s: waiting for pack to spin up...\n",
   1352 			    sd->sc_dev.dv_xname);
   1353 			if (!callout_pending(&periph->periph_callout))
   1354 				scsipi_periph_freeze(periph, 1);
   1355 			callout_reset(&periph->periph_callout,
   1356 			    5 * hz, scsipi_periph_timed_thaw, periph);
   1357 			retval = ERESTART;
   1358 		} else if (sense->add_sense_code_qual == 0x02) {
   1359 			printf("%s: pack is stopped, restarting...\n",
   1360 			    sd->sc_dev.dv_xname);
   1361 			s = splbio();
   1362 			periph->periph_flags |= PERIPH_RECOVERING;
   1363 			splx(s);
   1364 			error = scsipi_start(periph, SSS_START,
   1365 			    XS_CTL_URGENT|XS_CTL_HEAD_TAG|
   1366 			    XS_CTL_THAW_PERIPH|XS_CTL_FREEZE_PERIPH);
   1367 			if (error) {
   1368 				printf("%s: unable to restart pack\n",
   1369 				    sd->sc_dev.dv_xname);
   1370 				retval = error;
   1371 			} else
   1372 				retval = ERESTART;
   1373 			s = splbio();
   1374 			periph->periph_flags &= ~PERIPH_RECOVERING;
   1375 			splx(s);
   1376 		}
   1377 	}
   1378 	if ((sense->flags & SSD_KEY) == SKEY_MEDIUM_ERROR &&
   1379 	    sense->add_sense_code == 0x31 &&
   1380 	    sense->add_sense_code_qual == 0x00)	{ /* maybe for any asq ? */
   1381 		/* Medium Format Corrupted */
   1382 		retval = EFTYPE;
   1383 	}
   1384 	return (retval);
   1385 }
   1386 
   1387 
   1388 static int
   1389 sdsize(dev_t dev)
   1390 {
   1391 	struct sd_softc *sd;
   1392 	int part, unit, omask;
   1393 	int size;
   1394 
   1395 	unit = SDUNIT(dev);
   1396 	if (unit >= sd_cd.cd_ndevs)
   1397 		return (-1);
   1398 	sd = sd_cd.cd_devs[unit];
   1399 	if (sd == NULL)
   1400 		return (-1);
   1401 
   1402 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
   1403 		return (-1);
   1404 
   1405 	part = SDPART(dev);
   1406 	omask = sd->sc_dk.dk_openmask & (1 << part);
   1407 
   1408 	if (omask == 0 && sdopen(dev, 0, S_IFBLK, NULL) != 0)
   1409 		return (-1);
   1410 	if ((sd->sc_periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1411 		size = -1;
   1412 	else if (sd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
   1413 		size = -1;
   1414 	else
   1415 		size = sd->sc_dk.dk_label->d_partitions[part].p_size *
   1416 		    (sd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
   1417 	if (omask == 0 && sdclose(dev, 0, S_IFBLK, NULL) != 0)
   1418 		return (-1);
   1419 	return (size);
   1420 }
   1421 
   1422 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
   1423 static struct scsipi_xfer sx;
   1424 static int sddoingadump;
   1425 
   1426 /*
   1427  * dump all of physical memory into the partition specified, starting
   1428  * at offset 'dumplo' into the partition.
   1429  */
   1430 static int
   1431 sddump(dev_t dev, daddr_t blkno, caddr_t va, size_t size)
   1432 {
   1433 	struct sd_softc *sd;	/* disk unit to do the I/O */
   1434 	struct disklabel *lp;	/* disk's disklabel */
   1435 	int	unit, part;
   1436 	int	sectorsize;	/* size of a disk sector */
   1437 	int	nsects;		/* number of sectors in partition */
   1438 	int	sectoff;	/* sector offset of partition */
   1439 	int	totwrt;		/* total number of sectors left to write */
   1440 	int	nwrt;		/* current number of sectors to write */
   1441 	struct scsipi_rw_big cmd;	/* write command */
   1442 	struct scsipi_xfer *xs;	/* ... convenience */
   1443 	struct scsipi_periph *periph;
   1444 	struct scsipi_channel *chan;
   1445 
   1446 	/* Check if recursive dump; if so, punt. */
   1447 	if (sddoingadump)
   1448 		return (EFAULT);
   1449 
   1450 	/* Mark as active early. */
   1451 	sddoingadump = 1;
   1452 
   1453 	unit = SDUNIT(dev);	/* Decompose unit & partition. */
   1454 	part = SDPART(dev);
   1455 
   1456 	/* Check for acceptable drive number. */
   1457 	if (unit >= sd_cd.cd_ndevs || (sd = sd_cd.cd_devs[unit]) == NULL)
   1458 		return (ENXIO);
   1459 
   1460 	if ((sd->sc_dev.dv_flags & DVF_ACTIVE) == 0)
   1461 		return (ENODEV);
   1462 
   1463 	periph = sd->sc_periph;
   1464 	chan = periph->periph_channel;
   1465 
   1466 	/* Make sure it was initialized. */
   1467 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1468 		return (ENXIO);
   1469 
   1470 	/* Convert to disk sectors.  Request must be a multiple of size. */
   1471 	lp = sd->sc_dk.dk_label;
   1472 	sectorsize = lp->d_secsize;
   1473 	if ((size % sectorsize) != 0)
   1474 		return (EFAULT);
   1475 	totwrt = size / sectorsize;
   1476 	blkno = dbtob(blkno) / sectorsize;	/* blkno in DEV_BSIZE units */
   1477 
   1478 	nsects = lp->d_partitions[part].p_size;
   1479 	sectoff = lp->d_partitions[part].p_offset;
   1480 
   1481 	/* Check transfer bounds against partition size. */
   1482 	if ((blkno < 0) || ((blkno + totwrt) > nsects))
   1483 		return (EINVAL);
   1484 
   1485 	/* Offset block number to start of partition. */
   1486 	blkno += sectoff;
   1487 
   1488 	xs = &sx;
   1489 
   1490 	while (totwrt > 0) {
   1491 		nwrt = totwrt;		/* XXX */
   1492 #ifndef	SD_DUMP_NOT_TRUSTED
   1493 		/*
   1494 		 *  Fill out the scsi command
   1495 		 */
   1496 		memset(&cmd, 0, sizeof(cmd));
   1497 		cmd.opcode = WRITE_BIG;
   1498 		_lto4b(blkno, cmd.addr);
   1499 		_lto2b(nwrt, cmd.length);
   1500 		/*
   1501 		 * Fill out the scsipi_xfer structure
   1502 		 *    Note: we cannot sleep as we may be an interrupt
   1503 		 * don't use scsipi_command() as it may want to wait
   1504 		 * for an xs.
   1505 		 */
   1506 		memset(xs, 0, sizeof(sx));
   1507 		xs->xs_control |= XS_CTL_NOSLEEP | XS_CTL_POLL |
   1508 		    XS_CTL_DATA_OUT;
   1509 		xs->xs_status = 0;
   1510 		xs->xs_periph = periph;
   1511 		xs->xs_retries = SDRETRIES;
   1512 		xs->timeout = 10000;	/* 10000 millisecs for a disk ! */
   1513 		xs->cmd = (struct scsipi_generic *)&cmd;
   1514 		xs->cmdlen = sizeof(cmd);
   1515 		xs->resid = nwrt * sectorsize;
   1516 		xs->error = XS_NOERROR;
   1517 		xs->bp = 0;
   1518 		xs->data = va;
   1519 		xs->datalen = nwrt * sectorsize;
   1520 
   1521 		/*
   1522 		 * Pass all this info to the scsi driver.
   1523 		 */
   1524 		scsipi_adapter_request(chan, ADAPTER_REQ_RUN_XFER, xs);
   1525 		if ((xs->xs_status & XS_STS_DONE) == 0 ||
   1526 		    xs->error != XS_NOERROR)
   1527 			return (EIO);
   1528 #else	/* SD_DUMP_NOT_TRUSTED */
   1529 		/* Let's just talk about this first... */
   1530 		printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
   1531 		delay(500 * 1000);	/* half a second */
   1532 #endif	/* SD_DUMP_NOT_TRUSTED */
   1533 
   1534 		/* update block count */
   1535 		totwrt -= nwrt;
   1536 		blkno += nwrt;
   1537 		va += sectorsize * nwrt;
   1538 	}
   1539 	sddoingadump = 0;
   1540 	return (0);
   1541 }
   1542 
   1543 static int
   1544 sd_mode_sense(struct sd_softc *sd, u_int8_t byte2, void *sense, size_t size,
   1545     int page, int flags, int *big)
   1546 {
   1547 
   1548 	if ((sd->sc_periph->periph_quirks & PQUIRK_ONLYBIG) &&
   1549 	    !(sd->sc_periph->periph_quirks & PQUIRK_NOBIGMODESENSE)) {
   1550 		*big = 1;
   1551 		return scsipi_mode_sense_big(sd->sc_periph, byte2, page, sense,
   1552 		    size + sizeof(struct scsipi_mode_header_big),
   1553 		    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1554 	} else {
   1555 		*big = 0;
   1556 		return scsipi_mode_sense(sd->sc_periph, byte2, page, sense,
   1557 		    size + sizeof(struct scsipi_mode_header),
   1558 		    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1559 	}
   1560 }
   1561 
   1562 static int
   1563 sd_mode_select(struct sd_softc *sd, u_int8_t byte2, void *sense, size_t size,
   1564     int flags, int big)
   1565 {
   1566 
   1567 	if (big) {
   1568 		struct scsipi_mode_header_big *header = sense;
   1569 
   1570 		_lto2b(0, header->data_length);
   1571 		return scsipi_mode_select_big(sd->sc_periph, byte2, sense,
   1572 		    size + sizeof(struct scsipi_mode_header_big),
   1573 		    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1574 	} else {
   1575 		struct scsipi_mode_header *header = sense;
   1576 
   1577 		header->data_length = 0;
   1578 		return scsipi_mode_select(sd->sc_periph, byte2, sense,
   1579 		    size + sizeof(struct scsipi_mode_header),
   1580 		    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1581 	}
   1582 }
   1583 
   1584 static int
   1585 sd_get_simplifiedparms(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1586 {
   1587 	struct {
   1588 		struct scsipi_mode_header header;
   1589 		/* no block descriptor */
   1590 		u_int8_t pg_code; /* page code (should be 6) */
   1591 		u_int8_t pg_length; /* page length (should be 11) */
   1592 		u_int8_t wcd; /* bit0: cache disable */
   1593 		u_int8_t lbs[2]; /* logical block size */
   1594 		u_int8_t size[5]; /* number of log. blocks */
   1595 		u_int8_t pp; /* power/performance */
   1596 		u_int8_t flags;
   1597 		u_int8_t resvd;
   1598 	} scsipi_sense;
   1599 	u_int64_t sectors;
   1600 	int error;
   1601 
   1602 	/*
   1603 	 * scsipi_size (ie "read capacity") and mode sense page 6
   1604 	 * give the same information. Do both for now, and check
   1605 	 * for consistency.
   1606 	 * XXX probably differs for removable media
   1607 	 */
   1608 	dp->blksize = 512;
   1609 	if ((sectors = scsipi_size(sd->sc_periph, flags)) == 0)
   1610 		return (SDGP_RESULT_OFFLINE);		/* XXX? */
   1611 
   1612 	error = scsipi_mode_sense(sd->sc_periph, SMS_DBD, 6,
   1613 	    &scsipi_sense.header, sizeof(scsipi_sense),
   1614 	    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1615 
   1616 	if (error != 0)
   1617 		return (SDGP_RESULT_OFFLINE);		/* XXX? */
   1618 
   1619 	dp->blksize = _2btol(scsipi_sense.lbs);
   1620 	if (dp->blksize == 0)
   1621 		dp->blksize = 512;
   1622 
   1623 	/*
   1624 	 * Create a pseudo-geometry.
   1625 	 */
   1626 	dp->heads = 64;
   1627 	dp->sectors = 32;
   1628 	dp->cyls = sectors / (dp->heads * dp->sectors);
   1629 	dp->disksize = _5btol(scsipi_sense.size);
   1630 	if (dp->disksize <= UINT32_MAX && dp->disksize != sectors) {
   1631 		printf("RBC size: mode sense=%llu, get cap=%llu\n",
   1632 		       (unsigned long long)dp->disksize,
   1633 		       (unsigned long long)sectors);
   1634 		dp->disksize = sectors;
   1635 	}
   1636 	dp->disksize512 = (dp->disksize * dp->blksize) / DEV_BSIZE;
   1637 
   1638 	return (SDGP_RESULT_OK);
   1639 }
   1640 
   1641 /*
   1642  * Get the scsi driver to send a full inquiry to the * device and use the
   1643  * results to fill out the disk parameter structure.
   1644  */
   1645 static int
   1646 sd_get_capacity(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1647 {
   1648 	u_int64_t sectors;
   1649 	int error;
   1650 #if 0
   1651 	int i;
   1652 	u_int8_t *p;
   1653 #endif
   1654 
   1655 	dp->disksize = sectors = scsipi_size(sd->sc_periph, flags);
   1656 	if (sectors == 0) {
   1657 		struct scsipi_read_format_capacities cmd;
   1658 		struct {
   1659 			struct scsipi_capacity_list_header header;
   1660 			struct scsipi_capacity_descriptor desc;
   1661 		} __attribute__((packed)) data;
   1662 
   1663 		memset(&cmd, 0, sizeof(cmd));
   1664 		memset(&data, 0, sizeof(data));
   1665 		cmd.opcode = READ_FORMAT_CAPACITIES;
   1666 		_lto2b(sizeof(data), cmd.length);
   1667 
   1668 		error = scsipi_command(sd->sc_periph, (void *)&cmd, sizeof(cmd),
   1669 		    (void *)&data, sizeof(data), SDRETRIES, 20000, NULL,
   1670 		    flags | XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK);
   1671 		if (error == EFTYPE) {
   1672 			/* Medium Format Corrupted, handle as not formatted */
   1673 			return (SDGP_RESULT_UNFORMATTED);
   1674 		}
   1675 		if (error || data.header.length == 0)
   1676 			return (SDGP_RESULT_OFFLINE);
   1677 
   1678 #if 0
   1679 printf("rfc: length=%d\n", data.header.length);
   1680 printf("rfc result:"); for (i = sizeof(struct scsipi_capacity_list_header) + data.header.length, p = (void *)&data; i; i--, p++) printf(" %02x", *p); printf("\n");
   1681 #endif
   1682 		switch (data.desc.byte5 & SCSIPI_CAP_DESC_CODE_MASK) {
   1683 		case SCSIPI_CAP_DESC_CODE_RESERVED:
   1684 		case SCSIPI_CAP_DESC_CODE_FORMATTED:
   1685 			break;
   1686 
   1687 		case SCSIPI_CAP_DESC_CODE_UNFORMATTED:
   1688 			return (SDGP_RESULT_UNFORMATTED);
   1689 
   1690 		case SCSIPI_CAP_DESC_CODE_NONE:
   1691 			return (SDGP_RESULT_OFFLINE);
   1692 		}
   1693 
   1694 		dp->disksize = sectors = _4btol(data.desc.nblks);
   1695 		if (sectors == 0)
   1696 			return (SDGP_RESULT_OFFLINE);		/* XXX? */
   1697 
   1698 		dp->blksize = _3btol(data.desc.blklen);
   1699 		if (dp->blksize == 0)
   1700 			dp->blksize = 512;
   1701 	} else {
   1702 		struct sd_mode_sense_data scsipi_sense;
   1703 		int big, bsize;
   1704 		struct scsi_blk_desc *bdesc;
   1705 
   1706 		memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1707 		error = sd_mode_sense(sd, 0, &scsipi_sense,
   1708 		    sizeof(scsipi_sense.blk_desc), 0, flags | XS_CTL_SILENT, &big);
   1709 		dp->blksize = 512;
   1710 		if (!error) {
   1711 			if (big) {
   1712 				bdesc = (void *)(&scsipi_sense.header.big + 1);
   1713 				bsize = _2btol(scsipi_sense.header.big.blk_desc_len);
   1714 			} else {
   1715 				bdesc = (void *)(&scsipi_sense.header.small + 1);
   1716 				bsize = scsipi_sense.header.small.blk_desc_len;
   1717 			}
   1718 
   1719 #if 0
   1720 printf("page 0 sense:"); for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i; i--, p++) printf(" %02x", *p); printf("\n");
   1721 printf("page 0 bsize=%d\n", bsize);
   1722 printf("page 0 ok\n");
   1723 #endif
   1724 
   1725 			if (bsize >= 8) {
   1726 				dp->blksize = _3btol(bdesc->blklen);
   1727 				if (dp->blksize == 0)
   1728 					dp->blksize = 512;
   1729 			}
   1730 		}
   1731 	}
   1732 
   1733 	dp->disksize512 = (sectors * dp->blksize) / DEV_BSIZE;
   1734 	return (0);
   1735 }
   1736 
   1737 static int
   1738 sd_get_parms_page4(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1739 {
   1740 	struct sd_mode_sense_data scsipi_sense;
   1741 	int error;
   1742 	int big, poffset, byte2;
   1743 	union scsi_disk_pages *pages;
   1744 #if 0
   1745 	int i;
   1746 	u_int8_t *p;
   1747 #endif
   1748 
   1749 	byte2 = SMS_DBD;
   1750 again:
   1751 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1752 	error = sd_mode_sense(sd, byte2, &scsipi_sense,
   1753 	    (byte2 ? 0 : sizeof(scsipi_sense.blk_desc)) +
   1754 	    sizeof(scsipi_sense.pages.rigid_geometry), 4,
   1755 	    flags | XS_CTL_SILENT, &big);
   1756 	if (error) {
   1757 		if (byte2 == SMS_DBD) {
   1758 			/* No result; try once more with DBD off */
   1759 			byte2 = 0;
   1760 			goto again;
   1761 		}
   1762 		return (error);
   1763 	}
   1764 
   1765 	if (big) {
   1766 		poffset = sizeof scsipi_sense.header.big;
   1767 		poffset += _2btol(scsipi_sense.header.big.blk_desc_len);
   1768 	} else {
   1769 		poffset = sizeof scsipi_sense.header.small;
   1770 		poffset += scsipi_sense.header.small.blk_desc_len;
   1771 	}
   1772 
   1773 	pages = (void *)((u_long)&scsipi_sense + poffset);
   1774 #if 0
   1775 printf("page 4 sense:"); for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i; i--, p++) printf(" %02x", *p); printf("\n");
   1776 printf("page 4 pg_code=%d sense=%p/%p\n", pages->rigid_geometry.pg_code, &scsipi_sense, pages);
   1777 #endif
   1778 
   1779 	if ((pages->rigid_geometry.pg_code & PGCODE_MASK) != 4)
   1780 		return (ERESTART);
   1781 
   1782 	SC_DEBUG(sd->sc_periph, SCSIPI_DB3,
   1783 	    ("%d cyls, %d heads, %d precomp, %d red_write, %d land_zone\n",
   1784 	    _3btol(pages->rigid_geometry.ncyl),
   1785 	    pages->rigid_geometry.nheads,
   1786 	    _2btol(pages->rigid_geometry.st_cyl_wp),
   1787 	    _2btol(pages->rigid_geometry.st_cyl_rwc),
   1788 	    _2btol(pages->rigid_geometry.land_zone)));
   1789 
   1790 	/*
   1791 	 * KLUDGE!! (for zone recorded disks)
   1792 	 * give a number of sectors so that sec * trks * cyls
   1793 	 * is <= disk_size
   1794 	 * can lead to wasted space! THINK ABOUT THIS !
   1795 	 */
   1796 	dp->heads = pages->rigid_geometry.nheads;
   1797 	dp->cyls = _3btol(pages->rigid_geometry.ncyl);
   1798 	if (dp->heads == 0 || dp->cyls == 0)
   1799 		return (ERESTART);
   1800 	dp->sectors = dp->disksize / (dp->heads * dp->cyls);	/* XXX */
   1801 
   1802 	dp->rot_rate = _2btol(pages->rigid_geometry.rpm);
   1803 	if (dp->rot_rate == 0)
   1804 		dp->rot_rate = 3600;
   1805 
   1806 #if 0
   1807 printf("page 4 ok\n");
   1808 #endif
   1809 	return (0);
   1810 }
   1811 
   1812 static int
   1813 sd_get_parms_page5(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1814 {
   1815 	struct sd_mode_sense_data scsipi_sense;
   1816 	int error;
   1817 	int big, poffset, byte2;
   1818 	union scsi_disk_pages *pages;
   1819 #if 0
   1820 	int i;
   1821 	u_int8_t *p;
   1822 #endif
   1823 
   1824 	byte2 = SMS_DBD;
   1825 again:
   1826 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1827 	error = sd_mode_sense(sd, 0, &scsipi_sense,
   1828 	    (byte2 ? 0 : sizeof(scsipi_sense.blk_desc)) +
   1829 	    sizeof(scsipi_sense.pages.flex_geometry), 5,
   1830 	    flags | XS_CTL_SILENT, &big);
   1831 	if (error) {
   1832 		if (byte2 == SMS_DBD) {
   1833 			/* No result; try once more with DBD off */
   1834 			byte2 = 0;
   1835 			goto again;
   1836 		}
   1837 		return (error);
   1838 	}
   1839 
   1840 	if (big) {
   1841 		poffset = sizeof scsipi_sense.header.big;
   1842 		poffset += _2btol(scsipi_sense.header.big.blk_desc_len);
   1843 	} else {
   1844 		poffset = sizeof scsipi_sense.header.small;
   1845 		poffset += scsipi_sense.header.small.blk_desc_len;
   1846 	}
   1847 
   1848 	pages = (void *)((u_long)&scsipi_sense + poffset);
   1849 #if 0
   1850 printf("page 5 sense:"); for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i; i--, p++) printf(" %02x", *p); printf("\n");
   1851 printf("page 5 pg_code=%d sense=%p/%p\n", pages->flex_geometry.pg_code, &scsipi_sense, pages);
   1852 #endif
   1853 
   1854 	if ((pages->flex_geometry.pg_code & PGCODE_MASK) != 5)
   1855 		return (ERESTART);
   1856 
   1857 	SC_DEBUG(sd->sc_periph, SCSIPI_DB3,
   1858 	    ("%d cyls, %d heads, %d sec, %d bytes/sec\n",
   1859 	    _3btol(pages->flex_geometry.ncyl),
   1860 	    pages->flex_geometry.nheads,
   1861 	    pages->flex_geometry.ph_sec_tr,
   1862 	    _2btol(pages->flex_geometry.bytes_s)));
   1863 
   1864 	dp->heads = pages->flex_geometry.nheads;
   1865 	dp->cyls = _2btol(pages->flex_geometry.ncyl);
   1866 	dp->sectors = pages->flex_geometry.ph_sec_tr;
   1867 	if (dp->heads == 0 || dp->cyls == 0 || dp->sectors == 0)
   1868 		return (ERESTART);
   1869 
   1870 	dp->rot_rate = _2btol(pages->rigid_geometry.rpm);
   1871 	if (dp->rot_rate == 0)
   1872 		dp->rot_rate = 3600;
   1873 
   1874 #if 0
   1875 printf("page 5 ok\n");
   1876 #endif
   1877 	return (0);
   1878 }
   1879 
   1880 static int
   1881 sd_get_parms(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1882 {
   1883 	int error;
   1884 
   1885 	/*
   1886 	 * If offline, the SDEV_MEDIA_LOADED flag will be
   1887 	 * cleared by the caller if necessary.
   1888 	 */
   1889 	if (sd->type == T_SIMPLE_DIRECT)
   1890 		return (sd_get_simplifiedparms(sd, dp, flags));
   1891 
   1892 	error = sd_get_capacity(sd, dp, flags);
   1893 	if (error)
   1894 		return (error);
   1895 
   1896 	if (sd->type == T_OPTICAL)
   1897 		goto page0;
   1898 
   1899 	if (sd->sc_periph->periph_flags & PERIPH_REMOVABLE) {
   1900 		if (!sd_get_parms_page5(sd, dp, flags) ||
   1901 		    !sd_get_parms_page4(sd, dp, flags))
   1902 			return (SDGP_RESULT_OK);
   1903 	} else {
   1904 		if (!sd_get_parms_page4(sd, dp, flags) ||
   1905 		    !sd_get_parms_page5(sd, dp, flags))
   1906 			return (SDGP_RESULT_OK);
   1907 	}
   1908 
   1909 page0:
   1910 	printf("%s: fabricating a geometry\n", sd->sc_dev.dv_xname);
   1911 	/* Try calling driver's method for figuring out geometry. */
   1912 	if (!sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom ||
   1913 	    !(*sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom)
   1914 		(sd->sc_periph, dp, dp->disksize)) {
   1915 		/*
   1916 		 * Use adaptec standard fictitious geometry
   1917 		 * this depends on which controller (e.g. 1542C is
   1918 		 * different. but we have to put SOMETHING here..)
   1919 		 */
   1920 		dp->heads = 64;
   1921 		dp->sectors = 32;
   1922 		dp->cyls = dp->disksize / (64 * 32);
   1923 	}
   1924 	dp->rot_rate = 3600;
   1925 	return (SDGP_RESULT_OK);
   1926 }
   1927 
   1928 static int
   1929 sd_flush(struct sd_softc *sd, int flags)
   1930 {
   1931 	struct scsipi_periph *periph = sd->sc_periph;
   1932 	struct scsi_synchronize_cache cmd;
   1933 
   1934 	/*
   1935 	 * If the device is SCSI-2, issue a SYNCHRONIZE CACHE.
   1936 	 * We issue with address 0 length 0, which should be
   1937 	 * interpreted by the device as "all remaining blocks
   1938 	 * starting at address 0".  We ignore ILLEGAL REQUEST
   1939 	 * in the event that the command is not supported by
   1940 	 * the device, and poll for completion so that we know
   1941 	 * that the cache has actually been flushed.
   1942 	 *
   1943 	 * Unless, that is, the device can't handle the SYNCHRONIZE CACHE
   1944 	 * command, as indicated by our quirks flags.
   1945 	 *
   1946 	 * XXX What about older devices?
   1947 	 */
   1948 	if (periph->periph_version < 2 ||
   1949 	    (periph->periph_quirks & PQUIRK_NOSYNCCACHE))
   1950 		return (0);
   1951 
   1952 	sd->flags |= SDF_FLUSHING;
   1953 	memset(&cmd, 0, sizeof(cmd));
   1954 	cmd.opcode = SCSI_SYNCHRONIZE_CACHE;
   1955 
   1956 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
   1957 	    SDRETRIES, 100000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
   1958 }
   1959 
   1960 static int
   1961 sd_getcache(struct sd_softc *sd, int *bitsp)
   1962 {
   1963 	struct scsipi_periph *periph = sd->sc_periph;
   1964 	struct sd_mode_sense_data scsipi_sense;
   1965 	int error, bits = 0;
   1966 	int big;
   1967 	union scsi_disk_pages *pages;
   1968 
   1969 	if (periph->periph_version < 2)
   1970 		return (EOPNOTSUPP);
   1971 
   1972 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1973 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
   1974 	    sizeof(scsipi_sense.pages.caching_params), 8, 0, &big);
   1975 	if (error)
   1976 		return (error);
   1977 
   1978 	if (big)
   1979 		pages = (void *)(&scsipi_sense.header.big + 1);
   1980 	else
   1981 		pages = (void *)(&scsipi_sense.header.small + 1);
   1982 
   1983 	if ((pages->caching_params.flags & CACHING_RCD) == 0)
   1984 		bits |= DKCACHE_READ;
   1985 	if (pages->caching_params.flags & CACHING_WCE)
   1986 		bits |= DKCACHE_WRITE;
   1987 	if (pages->caching_params.pg_code & PGCODE_PS)
   1988 		bits |= DKCACHE_SAVE;
   1989 
   1990 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1991 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
   1992 	    sizeof(scsipi_sense.pages.caching_params),
   1993 	    SMS_PAGE_CTRL_CHANGEABLE|8, 0, &big);
   1994 	if (error == 0) {
   1995 		if (big)
   1996 			pages = (void *)(&scsipi_sense.header.big + 1);
   1997 		else
   1998 			pages = (void *)(&scsipi_sense.header.small + 1);
   1999 
   2000 		if (pages->caching_params.flags & CACHING_RCD)
   2001 			bits |= DKCACHE_RCHANGE;
   2002 		if (pages->caching_params.flags & CACHING_WCE)
   2003 			bits |= DKCACHE_WCHANGE;
   2004 	}
   2005 
   2006 	*bitsp = bits;
   2007 
   2008 	return (0);
   2009 }
   2010 
   2011 static int
   2012 sd_setcache(struct sd_softc *sd, int bits)
   2013 {
   2014 	struct scsipi_periph *periph = sd->sc_periph;
   2015 	struct sd_mode_sense_data scsipi_sense;
   2016 	int error;
   2017 	uint8_t oflags, byte2 = 0;
   2018 	int big;
   2019 	union scsi_disk_pages *pages;
   2020 
   2021 	if (periph->periph_version < 2)
   2022 		return (EOPNOTSUPP);
   2023 
   2024 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   2025 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
   2026 	    sizeof(scsipi_sense.pages.caching_params), 8, 0, &big);
   2027 	if (error)
   2028 		return (error);
   2029 
   2030 	if (big)
   2031 		pages = (void *)(&scsipi_sense.header.big + 1);
   2032 	else
   2033 		pages = (void *)(&scsipi_sense.header.small + 1);
   2034 
   2035 	oflags = pages->caching_params.flags;
   2036 
   2037 	if (bits & DKCACHE_READ)
   2038 		pages->caching_params.flags &= ~CACHING_RCD;
   2039 	else
   2040 		pages->caching_params.flags |= CACHING_RCD;
   2041 
   2042 	if (bits & DKCACHE_WRITE)
   2043 		pages->caching_params.flags |= CACHING_WCE;
   2044 	else
   2045 		pages->caching_params.flags &= ~CACHING_WCE;
   2046 
   2047 	if (oflags == pages->caching_params.flags)
   2048 		return (0);
   2049 
   2050 	pages->caching_params.pg_code &= PGCODE_MASK;
   2051 
   2052 	if (bits & DKCACHE_SAVE)
   2053 		byte2 |= SMS_SP;
   2054 
   2055 	return (sd_mode_select(sd, byte2|SMS_PF, &scsipi_sense,
   2056 	    sizeof(struct scsipi_mode_page_header) +
   2057 	    pages->caching_params.pg_length, 0, big));
   2058 }
   2059