Home | History | Annotate | Line # | Download | only in scsipi
sd.c revision 1.264
      1 /*	$NetBSD: sd.c,v 1.264 2007/07/29 12:50:23 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.264 2007/07/29 12:50:23 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 done;
    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 done;
    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 done:
    749 	/*
    750 	 * Correctly set the buf to indicate a completed xfer
    751 	 */
    752 	bp->b_resid = bp->b_bcount;
    753 	biodone(bp);
    754 }
    755 
    756 /*
    757  * sdstart looks to see if there is a buf waiting for the device
    758  * and that the device is not already busy. If both are true,
    759  * It dequeues the buf and creates a scsi command to perform the
    760  * transfer in the buf. The transfer request will call scsipi_done
    761  * on completion, which will in turn call this routine again
    762  * so that the next queued transfer is performed.
    763  * The bufs are queued by the strategy routine (sdstrategy)
    764  *
    765  * This routine is also called after other non-queued requests
    766  * have been made of the scsi driver, to ensure that the queue
    767  * continues to be drained.
    768  *
    769  * must be called at the correct (highish) spl level
    770  * sdstart() is called at splbio from sdstrategy, sdrestart and scsipi_done
    771  */
    772 static void
    773 sdstart(struct scsipi_periph *periph)
    774 {
    775 	struct sd_softc *sd = (void *)periph->periph_dev;
    776 	struct disklabel *lp = sd->sc_dk.dk_label;
    777 	struct buf *bp = 0;
    778 	struct scsipi_rw_16 cmd16;
    779 	struct scsipi_rw_10 cmd_big;
    780 	struct scsi_rw_6 cmd_small;
    781 	struct scsipi_generic *cmdp;
    782 	struct scsipi_xfer *xs;
    783 	int nblks, cmdlen, error, flags;
    784 
    785 	SC_DEBUG(periph, SCSIPI_DB2, ("sdstart "));
    786 	/*
    787 	 * Check if the device has room for another command
    788 	 */
    789 	while (periph->periph_active < periph->periph_openings) {
    790 		/*
    791 		 * there is excess capacity, but a special waits
    792 		 * It'll need the adapter as soon as we clear out of the
    793 		 * way and let it run (user level wait).
    794 		 */
    795 		if (periph->periph_flags & PERIPH_WAITING) {
    796 			periph->periph_flags &= ~PERIPH_WAITING;
    797 			wakeup((void *)periph);
    798 			return;
    799 		}
    800 
    801 		/*
    802 		 * If the device has become invalid, abort all the
    803 		 * reads and writes until all files have been closed and
    804 		 * re-opened
    805 		 */
    806 		if (__predict_false(
    807 		    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
    808 			if ((bp = BUFQ_GET(sd->buf_queue)) != NULL) {
    809 				bp->b_error = EIO;
    810 				bp->b_resid = bp->b_bcount;
    811 				biodone(bp);
    812 				continue;
    813 			} else {
    814 				return;
    815 			}
    816 		}
    817 
    818 		/*
    819 		 * See if there is a buf with work for us to do..
    820 		 */
    821 		if ((bp = BUFQ_PEEK(sd->buf_queue)) == NULL)
    822 			return;
    823 
    824 		/*
    825 		 * We have a buf, now we should make a command.
    826 		 */
    827 
    828 		if (lp->d_secsize == DEV_BSIZE)
    829 			nblks = bp->b_bcount >> DEV_BSHIFT;
    830 		else
    831 			nblks = howmany(bp->b_bcount, lp->d_secsize);
    832 
    833 		/*
    834 		 * Fill out the scsi command.  Use the smallest CDB possible
    835 		 * (6-byte, 10-byte, or 16-byte).
    836 		 */
    837 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
    838 		    ((nblks & 0xff) == nblks) &&
    839 		    !(periph->periph_quirks & PQUIRK_ONLYBIG)) {
    840 			/* 6-byte CDB */
    841 			memset(&cmd_small, 0, sizeof(cmd_small));
    842 			cmd_small.opcode = (bp->b_flags & B_READ) ?
    843 			    SCSI_READ_6_COMMAND : SCSI_WRITE_6_COMMAND;
    844 			_lto3b(bp->b_rawblkno, cmd_small.addr);
    845 			cmd_small.length = nblks & 0xff;
    846 			cmdlen = sizeof(cmd_small);
    847 			cmdp = (struct scsipi_generic *)&cmd_small;
    848 		} else if ((bp->b_rawblkno & 0xffffffff) == bp->b_rawblkno) {
    849 			/* 10-byte CDB */
    850 			memset(&cmd_big, 0, sizeof(cmd_big));
    851 			cmd_big.opcode = (bp->b_flags & B_READ) ?
    852 			    READ_10 : WRITE_10;
    853 			_lto4b(bp->b_rawblkno, cmd_big.addr);
    854 			_lto2b(nblks, cmd_big.length);
    855 			cmdlen = sizeof(cmd_big);
    856 			cmdp = (struct scsipi_generic *)&cmd_big;
    857 		} else {
    858 			/* 16-byte CDB */
    859 			memset(&cmd16, 0, sizeof(cmd16));
    860 			cmd16.opcode = (bp->b_flags & B_READ) ?
    861 			    READ_16 : WRITE_16;
    862 			_lto8b(bp->b_rawblkno, cmd16.addr);
    863 			_lto4b(nblks, cmd16.length);
    864 			cmdlen = sizeof(cmd16);
    865 			cmdp = (struct scsipi_generic *)&cmd16;
    866 		}
    867 
    868 		/* Instrumentation. */
    869 		disk_busy(&sd->sc_dk);
    870 
    871 		/*
    872 		 * Mark the disk dirty so that the cache will be
    873 		 * flushed on close.
    874 		 */
    875 		if ((bp->b_flags & B_READ) == 0)
    876 			sd->flags |= SDF_DIRTY;
    877 
    878 		/*
    879 		 * Figure out what flags to use.
    880 		 */
    881 		flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
    882 		if (bp->b_flags & B_READ)
    883 			flags |= XS_CTL_DATA_IN;
    884 		else
    885 			flags |= XS_CTL_DATA_OUT;
    886 
    887 		/*
    888 		 * Call the routine that chats with the adapter.
    889 		 * Note: we cannot sleep as we may be an interrupt
    890 		 */
    891 		xs = scsipi_make_xs(periph, cmdp, cmdlen,
    892 		    (u_char *)bp->b_data, bp->b_bcount,
    893 		    SDRETRIES, SD_IO_TIMEOUT, bp, flags);
    894 		if (__predict_false(xs == NULL)) {
    895 			/*
    896 			 * out of memory. Keep this buffer in the queue, and
    897 			 * retry later.
    898 			 */
    899 			callout_reset(&sd->sc_callout, hz / 2, sdrestart,
    900 			    periph);
    901 			return;
    902 		}
    903 		/*
    904 		 * need to dequeue the buffer before queuing the command,
    905 		 * because cdstart may be called recursively from the
    906 		 * HBA driver
    907 		 */
    908 #ifdef DIAGNOSTIC
    909 		if (BUFQ_GET(sd->buf_queue) != bp)
    910 			panic("sdstart(): dequeued wrong buf");
    911 #else
    912 		BUFQ_GET(sd->buf_queue);
    913 #endif
    914 		error = scsipi_execute_xs(xs);
    915 		/* with a scsipi_xfer preallocated, scsipi_command can't fail */
    916 		KASSERT(error == 0);
    917 	}
    918 }
    919 
    920 static void
    921 sdrestart(void *v)
    922 {
    923 	int s = splbio();
    924 	sdstart((struct scsipi_periph *)v);
    925 	splx(s);
    926 }
    927 
    928 static void
    929 sddone(struct scsipi_xfer *xs, int error)
    930 {
    931 	struct sd_softc *sd = (void *)xs->xs_periph->periph_dev;
    932 	struct buf *bp = xs->bp;
    933 
    934 	if (sd->flags & SDF_FLUSHING) {
    935 		/* Flush completed, no longer dirty. */
    936 		sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
    937 	}
    938 
    939 	if (bp) {
    940 		bp->b_error = error;
    941 		bp->b_resid = xs->resid;
    942 		if (error) {
    943 			/* on a read/write error bp->b_resid is zero, so fix */
    944 			bp->b_resid = bp->b_bcount;
    945 		}
    946 
    947 		disk_unbusy(&sd->sc_dk, bp->b_bcount - bp->b_resid,
    948 		    (bp->b_flags & B_READ));
    949 #if NRND > 0
    950 		rnd_add_uint32(&sd->rnd_source, bp->b_rawblkno);
    951 #endif
    952 
    953 		biodone(bp);
    954 	}
    955 }
    956 
    957 static void
    958 sdminphys(struct buf *bp)
    959 {
    960 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
    961 	long xmax;
    962 
    963 	/*
    964 	 * If the device is ancient, we want to make sure that
    965 	 * the transfer fits into a 6-byte cdb.
    966 	 *
    967 	 * XXX Note that the SCSI-I spec says that 256-block transfers
    968 	 * are allowed in a 6-byte read/write, and are specified
    969 	 * by settng the "length" to 0.  However, we're conservative
    970 	 * here, allowing only 255-block transfers in case an
    971 	 * ancient device gets confused by length == 0.  A length of 0
    972 	 * in a 10-byte read/write actually means 0 blocks.
    973 	 */
    974 	if ((sd->flags & SDF_ANCIENT) &&
    975 	    ((sd->sc_periph->periph_flags &
    976 	    (PERIPH_REMOVABLE | PERIPH_MEDIA_LOADED)) != PERIPH_REMOVABLE)) {
    977 		xmax = sd->sc_dk.dk_label->d_secsize * 0xff;
    978 
    979 		if (bp->b_bcount > xmax)
    980 			bp->b_bcount = xmax;
    981 	}
    982 
    983 	scsipi_adapter_minphys(sd->sc_periph->periph_channel, bp);
    984 }
    985 
    986 static int
    987 sdread(dev_t dev, struct uio *uio, int ioflag)
    988 {
    989 
    990 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
    991 }
    992 
    993 static int
    994 sdwrite(dev_t dev, struct uio *uio, int ioflag)
    995 {
    996 
    997 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
    998 }
    999 
   1000 /*
   1001  * Perform special action on behalf of the user
   1002  * Knows about the internals of this device
   1003  */
   1004 static int
   1005 sdioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
   1006 {
   1007 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
   1008 	struct scsipi_periph *periph = sd->sc_periph;
   1009 	int part = SDPART(dev);
   1010 	int error = 0;
   1011 #ifdef __HAVE_OLD_DISKLABEL
   1012 	struct disklabel *newlabel = NULL;
   1013 #endif
   1014 
   1015 	SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdioctl 0x%lx ", cmd));
   1016 
   1017 	/*
   1018 	 * If the device is not valid, some IOCTLs can still be
   1019 	 * handled on the raw partition. Check this here.
   1020 	 */
   1021 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
   1022 		switch (cmd) {
   1023 		case DIOCKLABEL:
   1024 		case DIOCWLABEL:
   1025 		case DIOCLOCK:
   1026 		case DIOCEJECT:
   1027 		case ODIOCEJECT:
   1028 		case DIOCGCACHE:
   1029 		case DIOCSCACHE:
   1030 		case SCIOCIDENTIFY:
   1031 		case OSCIOCIDENTIFY:
   1032 		case SCIOCCOMMAND:
   1033 		case SCIOCDEBUG:
   1034 			if (part == RAW_PART)
   1035 				break;
   1036 		/* FALLTHROUGH */
   1037 		default:
   1038 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
   1039 				return (ENODEV);
   1040 			else
   1041 				return (EIO);
   1042 		}
   1043 	}
   1044 
   1045 	switch (cmd) {
   1046 	case DIOCGDINFO:
   1047 		*(struct disklabel *)addr = *(sd->sc_dk.dk_label);
   1048 		return (0);
   1049 
   1050 #ifdef __HAVE_OLD_DISKLABEL
   1051 	case ODIOCGDINFO:
   1052 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1053 		if (newlabel == NULL)
   1054 			return EIO;
   1055 		memcpy(newlabel, sd->sc_dk.dk_label, sizeof (*newlabel));
   1056 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
   1057 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
   1058 		else
   1059 			error = ENOTTY;
   1060 		free(newlabel, M_TEMP);
   1061 		return error;
   1062 #endif
   1063 
   1064 	case DIOCGPART:
   1065 		((struct partinfo *)addr)->disklab = sd->sc_dk.dk_label;
   1066 		((struct partinfo *)addr)->part =
   1067 		    &sd->sc_dk.dk_label->d_partitions[part];
   1068 		return (0);
   1069 
   1070 	case DIOCWDINFO:
   1071 	case DIOCSDINFO:
   1072 #ifdef __HAVE_OLD_DISKLABEL
   1073 	case ODIOCWDINFO:
   1074 	case ODIOCSDINFO:
   1075 #endif
   1076 	{
   1077 		struct disklabel *lp;
   1078 
   1079 		if ((flag & FWRITE) == 0)
   1080 			return (EBADF);
   1081 
   1082 #ifdef __HAVE_OLD_DISKLABEL
   1083  		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
   1084 			newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1085 			if (newlabel == NULL)
   1086 				return EIO;
   1087 			memset(newlabel, 0, sizeof newlabel);
   1088 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
   1089 			lp = newlabel;
   1090 		} else
   1091 #endif
   1092 		lp = (struct disklabel *)addr;
   1093 
   1094 		mutex_enter(&sd->sc_dk.dk_openlock);
   1095 		sd->flags |= SDF_LABELLING;
   1096 
   1097 		error = setdisklabel(sd->sc_dk.dk_label,
   1098 		    lp, /*sd->sc_dk.dk_openmask : */0,
   1099 		    sd->sc_dk.dk_cpulabel);
   1100 		if (error == 0) {
   1101 			if (cmd == DIOCWDINFO
   1102 #ifdef __HAVE_OLD_DISKLABEL
   1103 			    || cmd == ODIOCWDINFO
   1104 #endif
   1105 			   )
   1106 				error = writedisklabel(SDLABELDEV(dev),
   1107 				    sdstrategy, sd->sc_dk.dk_label,
   1108 				    sd->sc_dk.dk_cpulabel);
   1109 		}
   1110 
   1111 		sd->flags &= ~SDF_LABELLING;
   1112 		mutex_exit(&sd->sc_dk.dk_openlock);
   1113 #ifdef __HAVE_OLD_DISKLABEL
   1114 		if (newlabel != NULL)
   1115 			free(newlabel, M_TEMP);
   1116 #endif
   1117 		return (error);
   1118 	}
   1119 
   1120 	case DIOCKLABEL:
   1121 		if (*(int *)addr)
   1122 			periph->periph_flags |= PERIPH_KEEP_LABEL;
   1123 		else
   1124 			periph->periph_flags &= ~PERIPH_KEEP_LABEL;
   1125 		return (0);
   1126 
   1127 	case DIOCWLABEL:
   1128 		if ((flag & FWRITE) == 0)
   1129 			return (EBADF);
   1130 		if (*(int *)addr)
   1131 			sd->flags |= SDF_WLABEL;
   1132 		else
   1133 			sd->flags &= ~SDF_WLABEL;
   1134 		return (0);
   1135 
   1136 	case DIOCLOCK:
   1137 		if (periph->periph_flags & PERIPH_REMOVABLE)
   1138 			return (scsipi_prevent(periph,
   1139 			    (*(int *)addr) ?
   1140 			    SPAMR_PREVENT_DT : SPAMR_ALLOW, 0));
   1141 		else
   1142 			return (ENOTTY);
   1143 
   1144 	case DIOCEJECT:
   1145 		if ((periph->periph_flags & PERIPH_REMOVABLE) == 0)
   1146 			return (ENOTTY);
   1147 		if (*(int *)addr == 0) {
   1148 			/*
   1149 			 * Don't force eject: check that we are the only
   1150 			 * partition open. If so, unlock it.
   1151 			 */
   1152 			if ((sd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
   1153 			    sd->sc_dk.dk_bopenmask + sd->sc_dk.dk_copenmask ==
   1154 			    sd->sc_dk.dk_openmask) {
   1155 				error = scsipi_prevent(periph, SPAMR_ALLOW,
   1156 				    XS_CTL_IGNORE_NOT_READY);
   1157 				if (error)
   1158 					return (error);
   1159 			} else {
   1160 				return (EBUSY);
   1161 			}
   1162 		}
   1163 		/* FALLTHROUGH */
   1164 	case ODIOCEJECT:
   1165 		return ((periph->periph_flags & PERIPH_REMOVABLE) == 0 ?
   1166 		    ENOTTY : scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
   1167 
   1168 	case DIOCGDEFLABEL:
   1169 		sdgetdefaultlabel(sd, (struct disklabel *)addr);
   1170 		return (0);
   1171 
   1172 #ifdef __HAVE_OLD_DISKLABEL
   1173 	case ODIOCGDEFLABEL:
   1174 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
   1175 		if (newlabel == NULL)
   1176 			return EIO;
   1177 		sdgetdefaultlabel(sd, newlabel);
   1178 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
   1179 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
   1180 		else
   1181 			error = ENOTTY;
   1182 		free(newlabel, M_TEMP);
   1183 		return error;
   1184 #endif
   1185 
   1186 	case DIOCGCACHE:
   1187 		return (sd_getcache(sd, (int *) addr));
   1188 
   1189 	case DIOCSCACHE:
   1190 		if ((flag & FWRITE) == 0)
   1191 			return (EBADF);
   1192 		return (sd_setcache(sd, *(int *) addr));
   1193 
   1194 	case DIOCCACHESYNC:
   1195 		/*
   1196 		 * XXX Do we really need to care about having a writable
   1197 		 * file descriptor here?
   1198 		 */
   1199 		if ((flag & FWRITE) == 0)
   1200 			return (EBADF);
   1201 		if (((sd->flags & SDF_DIRTY) != 0 || *(int *)addr != 0)) {
   1202 			error = sd_flush(sd, 0);
   1203 			if (error)
   1204 				sd->flags &= ~SDF_FLUSHING;
   1205 			else
   1206 				sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
   1207 		} else
   1208 			error = 0;
   1209 		return (error);
   1210 
   1211 	case DIOCAWEDGE:
   1212 	    {
   1213 	    	struct dkwedge_info *dkw = (void *) addr;
   1214 
   1215 		if ((flag & FWRITE) == 0)
   1216 			return (EBADF);
   1217 
   1218 		/* If the ioctl happens here, the parent is us. */
   1219 		strcpy(dkw->dkw_parent, sd->sc_dev.dv_xname);
   1220 		return (dkwedge_add(dkw));
   1221 	    }
   1222 
   1223 	case DIOCDWEDGE:
   1224 	    {
   1225 	    	struct dkwedge_info *dkw = (void *) addr;
   1226 
   1227 		if ((flag & FWRITE) == 0)
   1228 			return (EBADF);
   1229 
   1230 		/* If the ioctl happens here, the parent is us. */
   1231 		strcpy(dkw->dkw_parent, sd->sc_dev.dv_xname);
   1232 		return (dkwedge_del(dkw));
   1233 	    }
   1234 
   1235 	case DIOCLWEDGES:
   1236 	    {
   1237 	    	struct dkwedge_list *dkwl = (void *) addr;
   1238 
   1239 		return (dkwedge_list(&sd->sc_dk, dkwl, l));
   1240 	    }
   1241 
   1242 	default:
   1243 		if (part != RAW_PART)
   1244 			return (ENOTTY);
   1245 		return (scsipi_do_ioctl(periph, dev, cmd, addr, flag, l));
   1246 	}
   1247 
   1248 #ifdef DIAGNOSTIC
   1249 	panic("sdioctl: impossible");
   1250 #endif
   1251 }
   1252 
   1253 static void
   1254 sdgetdefaultlabel(struct sd_softc *sd, struct disklabel *lp)
   1255 {
   1256 
   1257 	memset(lp, 0, sizeof(struct disklabel));
   1258 
   1259 	lp->d_secsize = sd->params.blksize;
   1260 	lp->d_ntracks = sd->params.heads;
   1261 	lp->d_nsectors = sd->params.sectors;
   1262 	lp->d_ncylinders = sd->params.cyls;
   1263 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
   1264 
   1265 	switch (scsipi_periph_bustype(sd->sc_periph)) {
   1266 	case SCSIPI_BUSTYPE_SCSI:
   1267 		lp->d_type = DTYPE_SCSI;
   1268 		break;
   1269 	case SCSIPI_BUSTYPE_ATAPI:
   1270 		lp->d_type = DTYPE_ATAPI;
   1271 		break;
   1272 	}
   1273 	/*
   1274 	 * XXX
   1275 	 * We could probe the mode pages to figure out what kind of disc it is.
   1276 	 * Is this worthwhile?
   1277 	 */
   1278 	strncpy(lp->d_typename, sd->name, 16);
   1279 	strncpy(lp->d_packname, "fictitious", 16);
   1280 	lp->d_secperunit = sd->params.disksize;
   1281 	lp->d_rpm = sd->params.rot_rate;
   1282 	lp->d_interleave = 1;
   1283 	lp->d_flags = sd->sc_periph->periph_flags & PERIPH_REMOVABLE ?
   1284 	    D_REMOVABLE : 0;
   1285 
   1286 	lp->d_partitions[RAW_PART].p_offset = 0;
   1287 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
   1288 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
   1289 	lp->d_npartitions = RAW_PART + 1;
   1290 
   1291 	lp->d_magic = DISKMAGIC;
   1292 	lp->d_magic2 = DISKMAGIC;
   1293 	lp->d_checksum = dkcksum(lp);
   1294 }
   1295 
   1296 
   1297 /*
   1298  * Load the label information on the named device
   1299  */
   1300 static int
   1301 sdgetdisklabel(struct sd_softc *sd)
   1302 {
   1303 	struct disklabel *lp = sd->sc_dk.dk_label;
   1304 	const char *errstring;
   1305 
   1306 	memset(sd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
   1307 
   1308 	sdgetdefaultlabel(sd, lp);
   1309 
   1310 	if (lp->d_secpercyl == 0) {
   1311 		lp->d_secpercyl = 100;
   1312 		/* as long as it's not 0 - readdisklabel divides by it (?) */
   1313 	}
   1314 
   1315 	/*
   1316 	 * Call the generic disklabel extraction routine
   1317 	 */
   1318 	errstring = readdisklabel(MAKESDDEV(0, device_unit(&sd->sc_dev),
   1319 	    RAW_PART), sdstrategy, lp, sd->sc_dk.dk_cpulabel);
   1320 	if (errstring) {
   1321 		printf("%s: %s\n", sd->sc_dev.dv_xname, errstring);
   1322 		return EIO;
   1323 	}
   1324 	return 0;
   1325 }
   1326 
   1327 static void
   1328 sd_shutdown(void *arg)
   1329 {
   1330 	struct sd_softc *sd = arg;
   1331 
   1332 	/*
   1333 	 * If the disk cache needs to be flushed, and the disk supports
   1334 	 * it, flush it.  We're cold at this point, so we poll for
   1335 	 * completion.
   1336 	 */
   1337 	if ((sd->flags & SDF_DIRTY) != 0) {
   1338 		if (sd_flush(sd, XS_CTL_NOSLEEP|XS_CTL_POLL)) {
   1339 			printf("%s: cache synchronization failed\n",
   1340 			    sd->sc_dev.dv_xname);
   1341 			sd->flags &= ~SDF_FLUSHING;
   1342 		} else
   1343 			sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
   1344 	}
   1345 }
   1346 
   1347 /*
   1348  * Check Errors
   1349  */
   1350 static int
   1351 sd_interpret_sense(struct scsipi_xfer *xs)
   1352 {
   1353 	struct scsipi_periph *periph = xs->xs_periph;
   1354 	struct scsi_sense_data *sense = &xs->sense.scsi_sense;
   1355 	struct sd_softc *sd = (void *)periph->periph_dev;
   1356 	int s, error, retval = EJUSTRETURN;
   1357 
   1358 	/*
   1359 	 * If the periph is already recovering, just do the normal
   1360 	 * error processing.
   1361 	 */
   1362 	if (periph->periph_flags & PERIPH_RECOVERING)
   1363 		return (retval);
   1364 
   1365 	/*
   1366 	 * Ignore errors from accessing illegal fields (e.g. trying to
   1367 	 * lock the door of a digicam, which doesn't have a door that
   1368 	 * can be locked) for the SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL command.
   1369 	 */
   1370 	if (xs->cmd->opcode == SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL &&
   1371 	    SSD_SENSE_KEY(sense->flags) == SKEY_ILLEGAL_REQUEST &&
   1372 	    sense->asc == 0x24 &&
   1373 	    sense->ascq == 0x00) { /* Illegal field in CDB */
   1374 		if (!(xs->xs_control & XS_CTL_SILENT)) {
   1375 			scsipi_printaddr(periph);
   1376 			printf("no door lock\n");
   1377 		}
   1378 		xs->xs_control |= XS_CTL_IGNORE_ILLEGAL_REQUEST;
   1379 		return (retval);
   1380 	}
   1381 
   1382 
   1383 
   1384 	/*
   1385 	 * If the device is not open yet, let the generic code handle it.
   1386 	 */
   1387 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1388 		return (retval);
   1389 
   1390 	/*
   1391 	 * If it isn't a extended or extended/deferred error, let
   1392 	 * the generic code handle it.
   1393 	 */
   1394 	if (SSD_RCODE(sense->response_code) != SSD_RCODE_CURRENT &&
   1395 	    SSD_RCODE(sense->response_code) != SSD_RCODE_DEFERRED)
   1396 		return (retval);
   1397 
   1398 	if (SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY &&
   1399 	    sense->asc == 0x4) {
   1400 		if (sense->ascq == 0x01)	{
   1401 			/*
   1402 			 * Unit In The Process Of Becoming Ready.
   1403 			 */
   1404 			printf("%s: waiting for pack to spin up...\n",
   1405 			    sd->sc_dev.dv_xname);
   1406 			if (!callout_pending(&periph->periph_callout))
   1407 				scsipi_periph_freeze(periph, 1);
   1408 			callout_reset(&periph->periph_callout,
   1409 			    5 * hz, scsipi_periph_timed_thaw, periph);
   1410 			retval = ERESTART;
   1411 		} else if (sense->ascq == 0x02) {
   1412 			printf("%s: pack is stopped, restarting...\n",
   1413 			    sd->sc_dev.dv_xname);
   1414 			s = splbio();
   1415 			periph->periph_flags |= PERIPH_RECOVERING;
   1416 			splx(s);
   1417 			error = scsipi_start(periph, SSS_START,
   1418 			    XS_CTL_URGENT|XS_CTL_HEAD_TAG|
   1419 			    XS_CTL_THAW_PERIPH|XS_CTL_FREEZE_PERIPH);
   1420 			if (error) {
   1421 				printf("%s: unable to restart pack\n",
   1422 				    sd->sc_dev.dv_xname);
   1423 				retval = error;
   1424 			} else
   1425 				retval = ERESTART;
   1426 			s = splbio();
   1427 			periph->periph_flags &= ~PERIPH_RECOVERING;
   1428 			splx(s);
   1429 		}
   1430 	}
   1431 	if (SSD_SENSE_KEY(sense->flags) == SKEY_MEDIUM_ERROR &&
   1432 	    sense->asc == 0x31 &&
   1433 	    sense->ascq == 0x00)	{ /* maybe for any asq ? */
   1434 		/* Medium Format Corrupted */
   1435 		retval = EFTYPE;
   1436 	}
   1437 	return (retval);
   1438 }
   1439 
   1440 
   1441 static int
   1442 sdsize(dev_t dev)
   1443 {
   1444 	struct sd_softc *sd;
   1445 	int part, unit, omask;
   1446 	int size;
   1447 
   1448 	unit = SDUNIT(dev);
   1449 	if (unit >= sd_cd.cd_ndevs)
   1450 		return (-1);
   1451 	sd = sd_cd.cd_devs[unit];
   1452 	if (sd == NULL)
   1453 		return (-1);
   1454 
   1455 	if (!device_is_active(&sd->sc_dev))
   1456 		return (-1);
   1457 
   1458 	part = SDPART(dev);
   1459 	omask = sd->sc_dk.dk_openmask & (1 << part);
   1460 
   1461 	if (omask == 0 && sdopen(dev, 0, S_IFBLK, NULL) != 0)
   1462 		return (-1);
   1463 	if ((sd->sc_periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1464 		size = -1;
   1465 	else if (sd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
   1466 		size = -1;
   1467 	else
   1468 		size = sd->sc_dk.dk_label->d_partitions[part].p_size *
   1469 		    (sd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
   1470 	if (omask == 0 && sdclose(dev, 0, S_IFBLK, NULL) != 0)
   1471 		return (-1);
   1472 	return (size);
   1473 }
   1474 
   1475 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
   1476 static struct scsipi_xfer sx;
   1477 static int sddoingadump;
   1478 
   1479 /*
   1480  * dump all of physical memory into the partition specified, starting
   1481  * at offset 'dumplo' into the partition.
   1482  */
   1483 static int
   1484 sddump(dev_t dev, daddr_t blkno, void *va, size_t size)
   1485 {
   1486 	struct sd_softc *sd;	/* disk unit to do the I/O */
   1487 	struct disklabel *lp;	/* disk's disklabel */
   1488 	int	unit, part;
   1489 	int	sectorsize;	/* size of a disk sector */
   1490 	int	nsects;		/* number of sectors in partition */
   1491 	int	sectoff;	/* sector offset of partition */
   1492 	int	totwrt;		/* total number of sectors left to write */
   1493 	int	nwrt;		/* current number of sectors to write */
   1494 	struct scsipi_rw_10 cmd;	/* write command */
   1495 	struct scsipi_xfer *xs;	/* ... convenience */
   1496 	struct scsipi_periph *periph;
   1497 	struct scsipi_channel *chan;
   1498 
   1499 	/* Check if recursive dump; if so, punt. */
   1500 	if (sddoingadump)
   1501 		return (EFAULT);
   1502 
   1503 	/* Mark as active early. */
   1504 	sddoingadump = 1;
   1505 
   1506 	unit = SDUNIT(dev);	/* Decompose unit & partition. */
   1507 	part = SDPART(dev);
   1508 
   1509 	/* Check for acceptable drive number. */
   1510 	if (unit >= sd_cd.cd_ndevs || (sd = sd_cd.cd_devs[unit]) == NULL)
   1511 		return (ENXIO);
   1512 
   1513 	if (!device_is_active(&sd->sc_dev))
   1514 		return (ENODEV);
   1515 
   1516 	periph = sd->sc_periph;
   1517 	chan = periph->periph_channel;
   1518 
   1519 	/* Make sure it was initialized. */
   1520 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1521 		return (ENXIO);
   1522 
   1523 	/* Convert to disk sectors.  Request must be a multiple of size. */
   1524 	lp = sd->sc_dk.dk_label;
   1525 	sectorsize = lp->d_secsize;
   1526 	if ((size % sectorsize) != 0)
   1527 		return (EFAULT);
   1528 	totwrt = size / sectorsize;
   1529 	blkno = dbtob(blkno) / sectorsize;	/* blkno in DEV_BSIZE units */
   1530 
   1531 	nsects = lp->d_partitions[part].p_size;
   1532 	sectoff = lp->d_partitions[part].p_offset;
   1533 
   1534 	/* Check transfer bounds against partition size. */
   1535 	if ((blkno < 0) || ((blkno + totwrt) > nsects))
   1536 		return (EINVAL);
   1537 
   1538 	/* Offset block number to start of partition. */
   1539 	blkno += sectoff;
   1540 
   1541 	xs = &sx;
   1542 
   1543 	while (totwrt > 0) {
   1544 		nwrt = totwrt;		/* XXX */
   1545 #ifndef	SD_DUMP_NOT_TRUSTED
   1546 		/*
   1547 		 *  Fill out the scsi command
   1548 		 */
   1549 		memset(&cmd, 0, sizeof(cmd));
   1550 		cmd.opcode = WRITE_10;
   1551 		_lto4b(blkno, cmd.addr);
   1552 		_lto2b(nwrt, cmd.length);
   1553 		/*
   1554 		 * Fill out the scsipi_xfer structure
   1555 		 *    Note: we cannot sleep as we may be an interrupt
   1556 		 * don't use scsipi_command() as it may want to wait
   1557 		 * for an xs.
   1558 		 */
   1559 		memset(xs, 0, sizeof(sx));
   1560 		xs->xs_control |= XS_CTL_NOSLEEP | XS_CTL_POLL |
   1561 		    XS_CTL_DATA_OUT;
   1562 		xs->xs_status = 0;
   1563 		xs->xs_periph = periph;
   1564 		xs->xs_retries = SDRETRIES;
   1565 		xs->timeout = 10000;	/* 10000 millisecs for a disk ! */
   1566 		xs->cmd = (struct scsipi_generic *)&cmd;
   1567 		xs->cmdlen = sizeof(cmd);
   1568 		xs->resid = nwrt * sectorsize;
   1569 		xs->error = XS_NOERROR;
   1570 		xs->bp = 0;
   1571 		xs->data = va;
   1572 		xs->datalen = nwrt * sectorsize;
   1573 
   1574 		/*
   1575 		 * Pass all this info to the scsi driver.
   1576 		 */
   1577 		scsipi_adapter_request(chan, ADAPTER_REQ_RUN_XFER, xs);
   1578 		if ((xs->xs_status & XS_STS_DONE) == 0 ||
   1579 		    xs->error != XS_NOERROR)
   1580 			return (EIO);
   1581 #else	/* SD_DUMP_NOT_TRUSTED */
   1582 		/* Let's just talk about this first... */
   1583 		printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
   1584 		delay(500 * 1000);	/* half a second */
   1585 #endif	/* SD_DUMP_NOT_TRUSTED */
   1586 
   1587 		/* update block count */
   1588 		totwrt -= nwrt;
   1589 		blkno += nwrt;
   1590 		va = (char *)va + sectorsize * nwrt;
   1591 	}
   1592 	sddoingadump = 0;
   1593 	return (0);
   1594 }
   1595 
   1596 static int
   1597 sd_mode_sense(struct sd_softc *sd, u_int8_t byte2, void *sense, size_t size,
   1598     int page, int flags, int *big)
   1599 {
   1600 
   1601 	if ((sd->sc_periph->periph_quirks & PQUIRK_ONLYBIG) &&
   1602 	    !(sd->sc_periph->periph_quirks & PQUIRK_NOBIGMODESENSE)) {
   1603 		*big = 1;
   1604 		return scsipi_mode_sense_big(sd->sc_periph, byte2, page, sense,
   1605 		    size + sizeof(struct scsi_mode_parameter_header_10),
   1606 		    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1607 	} else {
   1608 		*big = 0;
   1609 		return scsipi_mode_sense(sd->sc_periph, byte2, page, sense,
   1610 		    size + sizeof(struct scsi_mode_parameter_header_6),
   1611 		    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1612 	}
   1613 }
   1614 
   1615 static int
   1616 sd_mode_select(struct sd_softc *sd, u_int8_t byte2, void *sense, size_t size,
   1617     int flags, int big)
   1618 {
   1619 
   1620 	if (big) {
   1621 		struct scsi_mode_parameter_header_10 *header = sense;
   1622 
   1623 		_lto2b(0, header->data_length);
   1624 		return scsipi_mode_select_big(sd->sc_periph, byte2, sense,
   1625 		    size + sizeof(struct scsi_mode_parameter_header_10),
   1626 		    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1627 	} else {
   1628 		struct scsi_mode_parameter_header_6 *header = sense;
   1629 
   1630 		header->data_length = 0;
   1631 		return scsipi_mode_select(sd->sc_periph, byte2, sense,
   1632 		    size + sizeof(struct scsi_mode_parameter_header_6),
   1633 		    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1634 	}
   1635 }
   1636 
   1637 /*
   1638  * sd_validate_blksize:
   1639  *
   1640  *	Validate the block size.  Print error if periph is specified,
   1641  */
   1642 static int
   1643 sd_validate_blksize(struct scsipi_periph *periph, int len)
   1644 {
   1645 
   1646 	switch (len) {
   1647 	case 256:
   1648 	case 512:
   1649 	case 1024:
   1650 	case 2048:
   1651 	case 4096:
   1652 		return 1;
   1653 	}
   1654 
   1655 	if (periph) {
   1656 		scsipi_printaddr(periph);
   1657 		printf("%s sector size: 0x%x.  Defaulting to %d bytes.\n",
   1658 		    (len ^ (1 << (ffs(len) - 1))) ?
   1659 		    "preposterous" : "unsupported",
   1660 		    len, SD_DEFAULT_BLKSIZE);
   1661 	}
   1662 
   1663 	return 0;
   1664 }
   1665 
   1666 /*
   1667  * sd_read_capacity:
   1668  *
   1669  *	Find out from the device what its capacity is.
   1670  */
   1671 static u_int64_t
   1672 sd_read_capacity(struct scsipi_periph *periph, int *blksize, int flags)
   1673 {
   1674 	union {
   1675 		struct scsipi_read_capacity_10 cmd;
   1676 		struct scsipi_read_capacity_16 cmd16;
   1677 	} cmd;
   1678 	union {
   1679 		struct scsipi_read_capacity_10_data data;
   1680 		struct scsipi_read_capacity_16_data data16;
   1681 	} data;
   1682 
   1683 	memset(&cmd, 0, sizeof(cmd));
   1684 	cmd.cmd.opcode = READ_CAPACITY_10;
   1685 
   1686 	/*
   1687 	 * If the command works, interpret the result as a 4 byte
   1688 	 * number of blocks
   1689 	 */
   1690 	memset(&data.data, 0, sizeof(data.data));
   1691 	if (scsipi_command(periph, (void *)&cmd.cmd, sizeof(cmd.cmd),
   1692 	    (void *)&data.data, sizeof(data.data), SCSIPIRETRIES, 20000, NULL,
   1693 	    flags | XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT) != 0)
   1694 		return (0);
   1695 
   1696 	if (_4btol(data.data.addr) != 0xffffffff) {
   1697 		*blksize = _4btol(data.data.length);
   1698 		return (_4btol(data.data.addr) + 1);
   1699 	}
   1700 
   1701 	/*
   1702 	 * Device is larger than can be reflected by READ CAPACITY (10).
   1703 	 * Try READ CAPACITY (16).
   1704 	 */
   1705 
   1706 	memset(&cmd, 0, sizeof(cmd));
   1707 	cmd.cmd16.opcode = READ_CAPACITY_16;
   1708 	cmd.cmd16.byte2 = SRC16_SERVICE_ACTION;
   1709 	_lto4b(sizeof(data.data16), cmd.cmd16.len);
   1710 
   1711 	memset(&data.data16, 0, sizeof(data.data16));
   1712 	if (scsipi_command(periph, (void *)&cmd.cmd16, sizeof(cmd.cmd16),
   1713 	    (void *)&data.data16, sizeof(data.data16), SCSIPIRETRIES, 20000,
   1714 	    NULL,
   1715 	    flags | XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT) != 0)
   1716 		return (0);
   1717 
   1718 	*blksize = _4btol(data.data16.length);
   1719 	return (_8btol(data.data16.addr) + 1);
   1720 }
   1721 
   1722 static int
   1723 sd_get_simplifiedparms(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1724 {
   1725 	struct {
   1726 		struct scsi_mode_parameter_header_6 header;
   1727 		/* no block descriptor */
   1728 		u_int8_t pg_code; /* page code (should be 6) */
   1729 		u_int8_t pg_length; /* page length (should be 11) */
   1730 		u_int8_t wcd; /* bit0: cache disable */
   1731 		u_int8_t lbs[2]; /* logical block size */
   1732 		u_int8_t size[5]; /* number of log. blocks */
   1733 		u_int8_t pp; /* power/performance */
   1734 		u_int8_t flags;
   1735 		u_int8_t resvd;
   1736 	} scsipi_sense;
   1737 	u_int64_t blocks;
   1738 	int error, blksize;
   1739 
   1740 	/*
   1741 	 * sd_read_capacity (ie "read capacity") and mode sense page 6
   1742 	 * give the same information. Do both for now, and check
   1743 	 * for consistency.
   1744 	 * XXX probably differs for removable media
   1745 	 */
   1746 	dp->blksize = SD_DEFAULT_BLKSIZE;
   1747 	if ((blocks = sd_read_capacity(sd->sc_periph, &blksize, flags)) == 0)
   1748 		return (SDGP_RESULT_OFFLINE);		/* XXX? */
   1749 
   1750 	error = scsipi_mode_sense(sd->sc_periph, SMS_DBD, 6,
   1751 	    &scsipi_sense.header, sizeof(scsipi_sense),
   1752 	    flags | XS_CTL_DATA_ONSTACK, SDRETRIES, 6000);
   1753 
   1754 	if (error != 0)
   1755 		return (SDGP_RESULT_OFFLINE);		/* XXX? */
   1756 
   1757 	dp->blksize = blksize;
   1758 	if (!sd_validate_blksize(NULL, dp->blksize))
   1759 		dp->blksize = _2btol(scsipi_sense.lbs);
   1760 	if (!sd_validate_blksize(sd->sc_periph, dp->blksize))
   1761 		dp->blksize = SD_DEFAULT_BLKSIZE;
   1762 
   1763 	/*
   1764 	 * Create a pseudo-geometry.
   1765 	 */
   1766 	dp->heads = 64;
   1767 	dp->sectors = 32;
   1768 	dp->cyls = blocks / (dp->heads * dp->sectors);
   1769 	dp->disksize = _5btol(scsipi_sense.size);
   1770 	if (dp->disksize <= UINT32_MAX && dp->disksize != blocks) {
   1771 		printf("RBC size: mode sense=%llu, get cap=%llu\n",
   1772 		       (unsigned long long)dp->disksize,
   1773 		       (unsigned long long)blocks);
   1774 		dp->disksize = blocks;
   1775 	}
   1776 	dp->disksize512 = (dp->disksize * dp->blksize) / DEV_BSIZE;
   1777 
   1778 	return (SDGP_RESULT_OK);
   1779 }
   1780 
   1781 /*
   1782  * Get the scsi driver to send a full inquiry to the * device and use the
   1783  * results to fill out the disk parameter structure.
   1784  */
   1785 static int
   1786 sd_get_capacity(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1787 {
   1788 	u_int64_t blocks;
   1789 	int error, blksize;
   1790 #if 0
   1791 	int i;
   1792 	u_int8_t *p;
   1793 #endif
   1794 
   1795 	dp->disksize = blocks = sd_read_capacity(sd->sc_periph, &blksize,
   1796 	    flags);
   1797 	if (blocks == 0) {
   1798 		struct scsipi_read_format_capacities cmd;
   1799 		struct {
   1800 			struct scsipi_capacity_list_header header;
   1801 			struct scsipi_capacity_descriptor desc;
   1802 		} __attribute__((packed)) data;
   1803 
   1804 		memset(&cmd, 0, sizeof(cmd));
   1805 		memset(&data, 0, sizeof(data));
   1806 		cmd.opcode = READ_FORMAT_CAPACITIES;
   1807 		_lto2b(sizeof(data), cmd.length);
   1808 
   1809 		error = scsipi_command(sd->sc_periph,
   1810 		    (void *)&cmd, sizeof(cmd), (void *)&data, sizeof(data),
   1811 		    SDRETRIES, 20000, NULL,
   1812 		    flags | XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK);
   1813 		if (error == EFTYPE) {
   1814 			/* Medium Format Corrupted, handle as not formatted */
   1815 			return (SDGP_RESULT_UNFORMATTED);
   1816 		}
   1817 		if (error || data.header.length == 0)
   1818 			return (SDGP_RESULT_OFFLINE);
   1819 
   1820 #if 0
   1821 printf("rfc: length=%d\n", data.header.length);
   1822 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");
   1823 #endif
   1824 		switch (data.desc.byte5 & SCSIPI_CAP_DESC_CODE_MASK) {
   1825 		case SCSIPI_CAP_DESC_CODE_RESERVED:
   1826 		case SCSIPI_CAP_DESC_CODE_FORMATTED:
   1827 			break;
   1828 
   1829 		case SCSIPI_CAP_DESC_CODE_UNFORMATTED:
   1830 			return (SDGP_RESULT_UNFORMATTED);
   1831 
   1832 		case SCSIPI_CAP_DESC_CODE_NONE:
   1833 			return (SDGP_RESULT_OFFLINE);
   1834 		}
   1835 
   1836 		dp->disksize = blocks = _4btol(data.desc.nblks);
   1837 		if (blocks == 0)
   1838 			return (SDGP_RESULT_OFFLINE);		/* XXX? */
   1839 
   1840 		blksize = _3btol(data.desc.blklen);
   1841 
   1842 	} else if (!sd_validate_blksize(NULL, blksize)) {
   1843 		struct sd_mode_sense_data scsipi_sense;
   1844 		int big, bsize;
   1845 		struct scsi_general_block_descriptor *bdesc;
   1846 
   1847 		memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1848 		error = sd_mode_sense(sd, 0, &scsipi_sense,
   1849 		    sizeof(scsipi_sense.blk_desc), 0, flags | XS_CTL_SILENT, &big);
   1850 		if (!error) {
   1851 			if (big) {
   1852 				bdesc = (void *)(&scsipi_sense.header.big + 1);
   1853 				bsize = _2btol(scsipi_sense.header.big.blk_desc_len);
   1854 			} else {
   1855 				bdesc = (void *)(&scsipi_sense.header.small + 1);
   1856 				bsize = scsipi_sense.header.small.blk_desc_len;
   1857 			}
   1858 
   1859 #if 0
   1860 printf("page 0 sense:"); for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i; i--, p++) printf(" %02x", *p); printf("\n");
   1861 printf("page 0 bsize=%d\n", bsize);
   1862 printf("page 0 ok\n");
   1863 #endif
   1864 
   1865 			if (bsize >= 8) {
   1866 				blksize = _3btol(bdesc->blklen);
   1867 			}
   1868 		}
   1869 	}
   1870 
   1871 	if (!sd_validate_blksize(sd->sc_periph, blksize))
   1872 		blksize = SD_DEFAULT_BLKSIZE;
   1873 
   1874 	dp->blksize = blksize;
   1875 	dp->disksize512 = (blocks * dp->blksize) / DEV_BSIZE;
   1876 	return (0);
   1877 }
   1878 
   1879 static int
   1880 sd_get_parms_page4(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1881 {
   1882 	struct sd_mode_sense_data scsipi_sense;
   1883 	int error;
   1884 	int big, byte2;
   1885 	size_t poffset;
   1886 	union scsi_disk_pages *pages;
   1887 
   1888 	byte2 = SMS_DBD;
   1889 again:
   1890 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1891 	error = sd_mode_sense(sd, byte2, &scsipi_sense,
   1892 	    (byte2 ? 0 : sizeof(scsipi_sense.blk_desc)) +
   1893 	    sizeof(scsipi_sense.pages.rigid_geometry), 4,
   1894 	    flags | XS_CTL_SILENT, &big);
   1895 	if (error) {
   1896 		if (byte2 == SMS_DBD) {
   1897 			/* No result; try once more with DBD off */
   1898 			byte2 = 0;
   1899 			goto again;
   1900 		}
   1901 		return (error);
   1902 	}
   1903 
   1904 	if (big) {
   1905 		poffset = sizeof scsipi_sense.header.big;
   1906 		poffset += _2btol(scsipi_sense.header.big.blk_desc_len);
   1907 	} else {
   1908 		poffset = sizeof scsipi_sense.header.small;
   1909 		poffset += scsipi_sense.header.small.blk_desc_len;
   1910 	}
   1911 
   1912 	if (poffset > sizeof(scsipi_sense) - sizeof(pages->rigid_geometry))
   1913 		return ERESTART;
   1914 
   1915 	pages = (void *)((u_long)&scsipi_sense + poffset);
   1916 #if 0
   1917 	{
   1918 		size_t i;
   1919 		u_int8_t *p;
   1920 
   1921 		printf("page 4 sense:");
   1922 		for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i;
   1923 		    i--, p++)
   1924 			printf(" %02x", *p);
   1925 		printf("\n");
   1926 		printf("page 4 pg_code=%d sense=%p/%p\n",
   1927 		    pages->rigid_geometry.pg_code, &scsipi_sense, pages);
   1928 	}
   1929 #endif
   1930 
   1931 	if ((pages->rigid_geometry.pg_code & PGCODE_MASK) != 4)
   1932 		return (ERESTART);
   1933 
   1934 	SC_DEBUG(sd->sc_periph, SCSIPI_DB3,
   1935 	    ("%d cyls, %d heads, %d precomp, %d red_write, %d land_zone\n",
   1936 	    _3btol(pages->rigid_geometry.ncyl),
   1937 	    pages->rigid_geometry.nheads,
   1938 	    _2btol(pages->rigid_geometry.st_cyl_wp),
   1939 	    _2btol(pages->rigid_geometry.st_cyl_rwc),
   1940 	    _2btol(pages->rigid_geometry.land_zone)));
   1941 
   1942 	/*
   1943 	 * KLUDGE!! (for zone recorded disks)
   1944 	 * give a number of sectors so that sec * trks * cyls
   1945 	 * is <= disk_size
   1946 	 * can lead to wasted space! THINK ABOUT THIS !
   1947 	 */
   1948 	dp->heads = pages->rigid_geometry.nheads;
   1949 	dp->cyls = _3btol(pages->rigid_geometry.ncyl);
   1950 	if (dp->heads == 0 || dp->cyls == 0)
   1951 		return (ERESTART);
   1952 	dp->sectors = dp->disksize / (dp->heads * dp->cyls);	/* XXX */
   1953 
   1954 	dp->rot_rate = _2btol(pages->rigid_geometry.rpm);
   1955 	if (dp->rot_rate == 0)
   1956 		dp->rot_rate = 3600;
   1957 
   1958 #if 0
   1959 printf("page 4 ok\n");
   1960 #endif
   1961 	return (0);
   1962 }
   1963 
   1964 static int
   1965 sd_get_parms_page5(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1966 {
   1967 	struct sd_mode_sense_data scsipi_sense;
   1968 	int error;
   1969 	int big, byte2;
   1970 	size_t poffset;
   1971 	union scsi_disk_pages *pages;
   1972 
   1973 	byte2 = SMS_DBD;
   1974 again:
   1975 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1976 	error = sd_mode_sense(sd, 0, &scsipi_sense,
   1977 	    (byte2 ? 0 : sizeof(scsipi_sense.blk_desc)) +
   1978 	    sizeof(scsipi_sense.pages.flex_geometry), 5,
   1979 	    flags | XS_CTL_SILENT, &big);
   1980 	if (error) {
   1981 		if (byte2 == SMS_DBD) {
   1982 			/* No result; try once more with DBD off */
   1983 			byte2 = 0;
   1984 			goto again;
   1985 		}
   1986 		return (error);
   1987 	}
   1988 
   1989 	if (big) {
   1990 		poffset = sizeof scsipi_sense.header.big;
   1991 		poffset += _2btol(scsipi_sense.header.big.blk_desc_len);
   1992 	} else {
   1993 		poffset = sizeof scsipi_sense.header.small;
   1994 		poffset += scsipi_sense.header.small.blk_desc_len;
   1995 	}
   1996 
   1997 	if (poffset > sizeof(scsipi_sense) - sizeof(pages->flex_geometry))
   1998 		return ERESTART;
   1999 
   2000 	pages = (void *)((u_long)&scsipi_sense + poffset);
   2001 #if 0
   2002 	{
   2003 		size_t i;
   2004 		u_int8_t *p;
   2005 
   2006 		printf("page 5 sense:");
   2007 		for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i;
   2008 		    i--, p++)
   2009 			printf(" %02x", *p);
   2010 		printf("\n");
   2011 		printf("page 5 pg_code=%d sense=%p/%p\n",
   2012 		    pages->flex_geometry.pg_code, &scsipi_sense, pages);
   2013 	}
   2014 #endif
   2015 
   2016 	if ((pages->flex_geometry.pg_code & PGCODE_MASK) != 5)
   2017 		return (ERESTART);
   2018 
   2019 	SC_DEBUG(sd->sc_periph, SCSIPI_DB3,
   2020 	    ("%d cyls, %d heads, %d sec, %d bytes/sec\n",
   2021 	    _3btol(pages->flex_geometry.ncyl),
   2022 	    pages->flex_geometry.nheads,
   2023 	    pages->flex_geometry.ph_sec_tr,
   2024 	    _2btol(pages->flex_geometry.bytes_s)));
   2025 
   2026 	dp->heads = pages->flex_geometry.nheads;
   2027 	dp->cyls = _2btol(pages->flex_geometry.ncyl);
   2028 	dp->sectors = pages->flex_geometry.ph_sec_tr;
   2029 	if (dp->heads == 0 || dp->cyls == 0 || dp->sectors == 0)
   2030 		return (ERESTART);
   2031 
   2032 	dp->rot_rate = _2btol(pages->rigid_geometry.rpm);
   2033 	if (dp->rot_rate == 0)
   2034 		dp->rot_rate = 3600;
   2035 
   2036 #if 0
   2037 printf("page 5 ok\n");
   2038 #endif
   2039 	return (0);
   2040 }
   2041 
   2042 static int
   2043 sd_get_parms(struct sd_softc *sd, struct disk_parms *dp, int flags)
   2044 {
   2045 	int error;
   2046 
   2047 	/*
   2048 	 * If offline, the SDEV_MEDIA_LOADED flag will be
   2049 	 * cleared by the caller if necessary.
   2050 	 */
   2051 	if (sd->type == T_SIMPLE_DIRECT) {
   2052 		error = sd_get_simplifiedparms(sd, dp, flags);
   2053 		if (!error)
   2054 			disk_blocksize(&sd->sc_dk, dp->blksize);
   2055 		return (error);
   2056 	}
   2057 
   2058 	error = sd_get_capacity(sd, dp, flags);
   2059 	if (error)
   2060 		return (error);
   2061 
   2062 	disk_blocksize(&sd->sc_dk, dp->blksize);
   2063 
   2064 	if (sd->type == T_OPTICAL)
   2065 		goto page0;
   2066 
   2067 	if (sd->sc_periph->periph_flags & PERIPH_REMOVABLE) {
   2068 		if (!sd_get_parms_page5(sd, dp, flags) ||
   2069 		    !sd_get_parms_page4(sd, dp, flags))
   2070 			return (SDGP_RESULT_OK);
   2071 	} else {
   2072 		if (!sd_get_parms_page4(sd, dp, flags) ||
   2073 		    !sd_get_parms_page5(sd, dp, flags))
   2074 			return (SDGP_RESULT_OK);
   2075 	}
   2076 
   2077 page0:
   2078 	printf("%s: fabricating a geometry\n", sd->sc_dev.dv_xname);
   2079 	/* Try calling driver's method for figuring out geometry. */
   2080 	if (!sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom ||
   2081 	    !(*sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom)
   2082 		(sd->sc_periph, dp, dp->disksize)) {
   2083 		/*
   2084 		 * Use adaptec standard fictitious geometry
   2085 		 * this depends on which controller (e.g. 1542C is
   2086 		 * different. but we have to put SOMETHING here..)
   2087 		 */
   2088 		dp->heads = 64;
   2089 		dp->sectors = 32;
   2090 		dp->cyls = dp->disksize / (64 * 32);
   2091 	}
   2092 	dp->rot_rate = 3600;
   2093 	return (SDGP_RESULT_OK);
   2094 }
   2095 
   2096 static int
   2097 sd_flush(struct sd_softc *sd, int flags)
   2098 {
   2099 	struct scsipi_periph *periph = sd->sc_periph;
   2100 	struct scsi_synchronize_cache_10 cmd;
   2101 
   2102 	/*
   2103 	 * If the device is SCSI-2, issue a SYNCHRONIZE CACHE.
   2104 	 * We issue with address 0 length 0, which should be
   2105 	 * interpreted by the device as "all remaining blocks
   2106 	 * starting at address 0".  We ignore ILLEGAL REQUEST
   2107 	 * in the event that the command is not supported by
   2108 	 * the device, and poll for completion so that we know
   2109 	 * that the cache has actually been flushed.
   2110 	 *
   2111 	 * Unless, that is, the device can't handle the SYNCHRONIZE CACHE
   2112 	 * command, as indicated by our quirks flags.
   2113 	 *
   2114 	 * XXX What about older devices?
   2115 	 */
   2116 	if (periph->periph_version < 2 ||
   2117 	    (periph->periph_quirks & PQUIRK_NOSYNCCACHE))
   2118 		return (0);
   2119 
   2120 	sd->flags |= SDF_FLUSHING;
   2121 	memset(&cmd, 0, sizeof(cmd));
   2122 	cmd.opcode = SCSI_SYNCHRONIZE_CACHE_10;
   2123 
   2124 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
   2125 	    SDRETRIES, 100000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
   2126 }
   2127 
   2128 static int
   2129 sd_getcache(struct sd_softc *sd, int *bitsp)
   2130 {
   2131 	struct scsipi_periph *periph = sd->sc_periph;
   2132 	struct sd_mode_sense_data scsipi_sense;
   2133 	int error, bits = 0;
   2134 	int big;
   2135 	union scsi_disk_pages *pages;
   2136 
   2137 	if (periph->periph_version < 2)
   2138 		return (EOPNOTSUPP);
   2139 
   2140 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   2141 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
   2142 	    sizeof(scsipi_sense.pages.caching_params), 8, 0, &big);
   2143 	if (error)
   2144 		return (error);
   2145 
   2146 	if (big)
   2147 		pages = (void *)(&scsipi_sense.header.big + 1);
   2148 	else
   2149 		pages = (void *)(&scsipi_sense.header.small + 1);
   2150 
   2151 	if ((pages->caching_params.flags & CACHING_RCD) == 0)
   2152 		bits |= DKCACHE_READ;
   2153 	if (pages->caching_params.flags & CACHING_WCE)
   2154 		bits |= DKCACHE_WRITE;
   2155 	if (pages->caching_params.pg_code & PGCODE_PS)
   2156 		bits |= DKCACHE_SAVE;
   2157 
   2158 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   2159 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
   2160 	    sizeof(scsipi_sense.pages.caching_params),
   2161 	    SMS_PCTRL_CHANGEABLE|8, 0, &big);
   2162 	if (error == 0) {
   2163 		if (big)
   2164 			pages = (void *)(&scsipi_sense.header.big + 1);
   2165 		else
   2166 			pages = (void *)(&scsipi_sense.header.small + 1);
   2167 
   2168 		if (pages->caching_params.flags & CACHING_RCD)
   2169 			bits |= DKCACHE_RCHANGE;
   2170 		if (pages->caching_params.flags & CACHING_WCE)
   2171 			bits |= DKCACHE_WCHANGE;
   2172 	}
   2173 
   2174 	*bitsp = bits;
   2175 
   2176 	return (0);
   2177 }
   2178 
   2179 static int
   2180 sd_setcache(struct sd_softc *sd, int bits)
   2181 {
   2182 	struct scsipi_periph *periph = sd->sc_periph;
   2183 	struct sd_mode_sense_data scsipi_sense;
   2184 	int error;
   2185 	uint8_t oflags, byte2 = 0;
   2186 	int big;
   2187 	union scsi_disk_pages *pages;
   2188 
   2189 	if (periph->periph_version < 2)
   2190 		return (EOPNOTSUPP);
   2191 
   2192 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   2193 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
   2194 	    sizeof(scsipi_sense.pages.caching_params), 8, 0, &big);
   2195 	if (error)
   2196 		return (error);
   2197 
   2198 	if (big)
   2199 		pages = (void *)(&scsipi_sense.header.big + 1);
   2200 	else
   2201 		pages = (void *)(&scsipi_sense.header.small + 1);
   2202 
   2203 	oflags = pages->caching_params.flags;
   2204 
   2205 	if (bits & DKCACHE_READ)
   2206 		pages->caching_params.flags &= ~CACHING_RCD;
   2207 	else
   2208 		pages->caching_params.flags |= CACHING_RCD;
   2209 
   2210 	if (bits & DKCACHE_WRITE)
   2211 		pages->caching_params.flags |= CACHING_WCE;
   2212 	else
   2213 		pages->caching_params.flags &= ~CACHING_WCE;
   2214 
   2215 	if (oflags == pages->caching_params.flags)
   2216 		return (0);
   2217 
   2218 	pages->caching_params.pg_code &= PGCODE_MASK;
   2219 
   2220 	if (bits & DKCACHE_SAVE)
   2221 		byte2 |= SMS_SP;
   2222 
   2223 	return (sd_mode_select(sd, byte2|SMS_PF, &scsipi_sense,
   2224 	    sizeof(struct scsi_mode_page_header) +
   2225 	    pages->caching_params.pg_length, 0, big));
   2226 }
   2227 
   2228 static void
   2229 sd_set_properties(struct sd_softc *sd)
   2230 {
   2231 	prop_dictionary_t disk_info, odisk_info, geom;
   2232 
   2233 	disk_info = prop_dictionary_create();
   2234 
   2235 	geom = prop_dictionary_create();
   2236 
   2237 	prop_dictionary_set_uint64(geom, "sectors-per-unit",
   2238 	    sd->params.disksize);
   2239 
   2240 	prop_dictionary_set_uint32(geom, "sector-size",
   2241 	    sd->params.blksize);
   2242 
   2243 	prop_dictionary_set_uint16(geom, "sectors-per-track",
   2244 	    sd->params.sectors);
   2245 
   2246 	prop_dictionary_set_uint16(geom, "tracks-per-cylinder",
   2247 	    sd->params.heads);
   2248 
   2249 	prop_dictionary_set_uint64(geom, "cylinders-per-unit",
   2250 	    sd->params.cyls);
   2251 
   2252 	prop_dictionary_set(disk_info, "geometry", geom);
   2253 	prop_object_release(geom);
   2254 
   2255 	prop_dictionary_set(device_properties(&sd->sc_dev),
   2256 	    "disk-info", disk_info);
   2257 
   2258 	/*
   2259 	 * Don't release disk_info here; we keep a reference to it.
   2260 	 * disk_detach() will release it when we go away.
   2261 	 */
   2262 
   2263 	odisk_info = sd->sc_dk.dk_info;
   2264 	sd->sc_dk.dk_info = disk_info;
   2265 	if (odisk_info)
   2266 		prop_object_release(odisk_info);
   2267 }
   2268