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