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