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