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