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