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