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