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