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