Home | History | Annotate | Line # | Download | only in scsipi
sd.c revision 1.339
      1 /*	$NetBSD: sd.c,v 1.339 2025/02/27 15:23:44 jakllsch 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.339 2025/02/27 15:23:44 jakllsch Exp $");
     51 
     52 #ifdef _KERNEL_OPT
     53 #include "opt_scsi.h"
     54 #endif
     55 
     56 #include <sys/param.h>
     57 #include <sys/systm.h>
     58 #include <sys/kernel.h>
     59 #include <sys/file.h>
     60 #include <sys/stat.h>
     61 #include <sys/ioctl.h>
     62 #include <sys/scsiio.h>
     63 #include <sys/buf.h>
     64 #include <sys/bufq.h>
     65 #include <sys/uio.h>
     66 #include <sys/malloc.h>
     67 #include <sys/errno.h>
     68 #include <sys/device.h>
     69 #include <sys/disklabel.h>
     70 #include <sys/disk.h>
     71 #include <sys/proc.h>
     72 #include <sys/conf.h>
     73 #include <sys/vnode.h>
     74 
     75 #include <dev/scsipi/scsi_spc.h>
     76 #include <dev/scsipi/scsipi_all.h>
     77 #include <dev/scsipi/scsi_all.h>
     78 #include <dev/scsipi/scsipi_disk.h>
     79 #include <dev/scsipi/scsi_disk.h>
     80 #include <dev/scsipi/scsiconf.h>
     81 #include <dev/scsipi/scsipi_base.h>
     82 #include <dev/scsipi/sdvar.h>
     83 
     84 #include <prop/proplib.h>
     85 
     86 #define	SDUNIT(dev)			DISKUNIT(dev)
     87 #define	SDPART(dev)			DISKPART(dev)
     88 #define	SDMINOR(unit, part)		DISKMINOR(unit, part)
     89 #define	MAKESDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
     90 
     91 #define	SDLABELDEV(dev)	(MAKESDDEV(major(dev), SDUNIT(dev), RAW_PART))
     92 
     93 #define	SD_DEFAULT_BLKSIZE	512
     94 
     95 static void	sdminphys(struct buf *);
     96 static void	sdstart(struct scsipi_periph *);
     97 static void	sdrestart(void *);
     98 static void	sddone(struct scsipi_xfer *, int);
     99 static bool	sd_suspend(device_t, const pmf_qual_t *);
    100 static bool	sd_shutdown(device_t, int);
    101 static int	sd_interpret_sense(struct scsipi_xfer *);
    102 static int	sd_diskstart(device_t, struct buf *);
    103 static int	sd_dumpblocks(device_t, void *, daddr_t, int);
    104 static void	sd_iosize(device_t, int *);
    105 static int	sd_lastclose(device_t);
    106 static int	sd_firstopen(device_t, dev_t, int, int);
    107 static void	sd_label(device_t, struct disklabel *);
    108 
    109 static int	sd_mode_sense(struct sd_softc *, u_int8_t, void *, size_t, int,
    110 		    int, int *);
    111 static int	sd_mode_select(struct sd_softc *, u_int8_t, void *, size_t, int,
    112 		    int);
    113 static int	sd_validate_blksize(struct scsipi_periph *, int);
    114 static u_int64_t sd_read_capacity(struct scsipi_periph *, int *, int flags);
    115 static int	sd_get_simplifiedparms(struct sd_softc *, struct disk_parms *,
    116 		    int);
    117 static int	sd_get_capacity(struct sd_softc *, struct disk_parms *, int);
    118 static int	sd_get_parms(struct sd_softc *, struct disk_parms *, int);
    119 static int	sd_get_parms_page4(struct sd_softc *, struct disk_parms *,
    120 		    int);
    121 static int	sd_get_parms_page5(struct sd_softc *, struct disk_parms *,
    122 		    int);
    123 
    124 static int	sd_flush(struct sd_softc *, int);
    125 static int	sd_getcache(struct sd_softc *, int *);
    126 static int	sd_setcache(struct sd_softc *, int);
    127 
    128 static int	sdmatch(device_t, cfdata_t, void *);
    129 static void	sdattach(device_t, device_t, void *);
    130 static int	sddetach(device_t, int);
    131 static void	sd_set_geometry(struct sd_softc *);
    132 
    133 CFATTACH_DECL3_NEW(sd, sizeof(struct sd_softc), sdmatch, sdattach, sddetach,
    134     NULL, NULL, NULL, DVF_DETACH_SHUTDOWN);
    135 
    136 extern struct cfdriver sd_cd;
    137 
    138 static const struct scsipi_inquiry_pattern sd_patterns[] = {
    139 	{T_DIRECT, T_FIXED,
    140 	 "",         "",                 ""},
    141 	{T_DIRECT, T_REMOV,
    142 	 "",         "",                 ""},
    143 	{T_OPTICAL, T_FIXED,
    144 	 "",         "",                 ""},
    145 	{T_OPTICAL, T_REMOV,
    146 	 "",         "",                 ""},
    147 	{T_SIMPLE_DIRECT, T_FIXED,
    148 	 "",         "",                 ""},
    149 	{T_SIMPLE_DIRECT, T_REMOV,
    150 	 "",         "",                 ""},
    151 };
    152 
    153 static dev_type_open(sdopen);
    154 static dev_type_close(sdclose);
    155 static dev_type_read(sdread);
    156 static dev_type_write(sdwrite);
    157 static dev_type_ioctl(sdioctl);
    158 static dev_type_strategy(sdstrategy);
    159 static dev_type_dump(sddump);
    160 static dev_type_size(sdsize);
    161 
    162 const struct bdevsw sd_bdevsw = {
    163 	.d_open = sdopen,
    164 	.d_close = sdclose,
    165 	.d_strategy = sdstrategy,
    166 	.d_ioctl = sdioctl,
    167 	.d_dump = sddump,
    168 	.d_psize = sdsize,
    169 	.d_discard = nodiscard,
    170 	.d_cfdriver = &sd_cd,
    171 	.d_devtounit = disklabel_dev_unit,
    172 	.d_flag = D_DISK | D_MPSAFE
    173 };
    174 
    175 const struct cdevsw sd_cdevsw = {
    176 	.d_open = sdopen,
    177 	.d_close = sdclose,
    178 	.d_read = sdread,
    179 	.d_write = sdwrite,
    180 	.d_ioctl = sdioctl,
    181 	.d_stop = nostop,
    182 	.d_tty = notty,
    183 	.d_poll = nopoll,
    184 	.d_mmap = nommap,
    185 	.d_kqfilter = nokqfilter,
    186 	.d_discard = nodiscard,
    187 	.d_cfdriver = &sd_cd,
    188 	.d_devtounit = disklabel_dev_unit,
    189 	.d_flag = D_DISK | D_MPSAFE
    190 };
    191 
    192 static const struct dkdriver sddkdriver = {
    193 	.d_open = sdopen,
    194 	.d_close = sdclose,
    195 	.d_strategy = sdstrategy,
    196 	.d_minphys = sdminphys,
    197 	.d_diskstart = sd_diskstart,
    198 	.d_dumpblocks = sd_dumpblocks,
    199 	.d_iosize = sd_iosize,
    200 	.d_firstopen = sd_firstopen,
    201 	.d_lastclose = sd_lastclose,
    202 	.d_label = sd_label,
    203 };
    204 
    205 static const struct scsipi_periphsw sd_switch = {
    206 	sd_interpret_sense,	/* check our error handler first */
    207 	sdstart,		/* have a queue, served by this */
    208 	NULL,			/* have no async handler */
    209 	sddone,			/* deal with stats at interrupt time */
    210 };
    211 
    212 struct sd_mode_sense_data {
    213 	/*
    214 	 * XXX
    215 	 * We are not going to parse this as-is -- it just has to be large
    216 	 * enough.
    217 	 */
    218 	union {
    219 		struct scsi_mode_parameter_header_6 small;
    220 		struct scsi_mode_parameter_header_10 big;
    221 	} header;
    222 	struct scsi_general_block_descriptor blk_desc;
    223 	union scsi_disk_pages pages;
    224 };
    225 
    226 /*
    227  * The routine called by the low level scsi routine when it discovers
    228  * A device suitable for this driver
    229  */
    230 static int
    231 sdmatch(device_t parent, cfdata_t match,
    232     void *aux)
    233 {
    234 	struct scsipibus_attach_args *sa = aux;
    235 	int priority;
    236 
    237 	(void)scsipi_inqmatch(&sa->sa_inqbuf,
    238 	    sd_patterns, sizeof(sd_patterns) / sizeof(sd_patterns[0]),
    239 	    sizeof(sd_patterns[0]), &priority);
    240 
    241 	return (priority);
    242 }
    243 
    244 /*
    245  * Attach routine common to atapi & scsi.
    246  */
    247 static void
    248 sdattach(device_t parent, device_t self, void *aux)
    249 {
    250 	struct sd_softc *sd = device_private(self);
    251 	struct dk_softc *dksc = &sd->sc_dksc;
    252 	struct scsipibus_attach_args *sa = aux;
    253 	struct scsipi_periph *periph = sa->sa_periph;
    254 	int error, result, dtype;
    255 	struct disk_parms *dp = &sd->params;
    256 	char pbuf[9];
    257 
    258 	SC_DEBUG(periph, SCSIPI_DB2, ("sdattach: "));
    259 
    260 	sd->type = (sa->sa_inqbuf.type & SID_TYPE);
    261 	memcpy(sd->name, sa->sa_inqbuf.product, uimin(16, sizeof(sd->name)));
    262 	memcpy(sd->typename, sa->sa_inqbuf.product, uimin(16, sizeof(sd->typename)));
    263 
    264 	if (sd->type == T_SIMPLE_DIRECT)
    265 		periph->periph_quirks |= PQUIRK_ONLYBIG | PQUIRK_NOBIGMODESENSE;
    266 
    267 	switch (SCSIPI_BUSTYPE_TYPE(scsipi_periph_bustype(sa->sa_periph))) {
    268 	case SCSIPI_BUSTYPE_SCSI:
    269 		dtype = DKTYPE_SCSI;
    270 		if (periph->periph_version == 0)
    271 			sd->flags |= SDF_ANCIENT;
    272 		break;
    273 	case SCSIPI_BUSTYPE_ATAPI:
    274 		dtype = DKTYPE_ATAPI;
    275 		break;
    276 	default:
    277 		dtype = DKTYPE_UNKNOWN;
    278 		break;
    279 	}
    280 
    281 	/* Initialize dk and disk structure. */
    282 	dk_init(dksc, self, dtype);
    283 	disk_init(&dksc->sc_dkdev, dksc->sc_xname, &sddkdriver);
    284 
    285 	/* Attach dk and disk subsystems */
    286 	dk_attach(dksc);
    287 	disk_attach(&dksc->sc_dkdev);
    288 
    289 	bufq_alloc(&dksc->sc_bufq, BUFQ_DISK_DEFAULT_STRAT, BUFQ_SORT_RAWBLOCK);
    290 
    291 	callout_init(&sd->sc_callout, 0);
    292 
    293 	/*
    294 	 * Store information needed to contact our base driver
    295 	 */
    296 	sd->sc_periph = periph;
    297 
    298 	periph->periph_dev = dksc->sc_dev;
    299 	periph->periph_switch = &sd_switch;
    300 
    301 	/*
    302 	 * Increase our openings to the maximum-per-periph
    303 	 * supported by the adapter.  This will either be
    304 	 * clamped down or grown by the adapter if necessary.
    305 	 */
    306 	periph->periph_openings =
    307 	    SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
    308 	periph->periph_flags |= PERIPH_GROW_OPENINGS;
    309 
    310 	/*
    311 	 * Use the subdriver to request information regarding the drive.
    312 	 */
    313 	aprint_naive("\n");
    314 	aprint_normal("\n");
    315 
    316 	if (periph->periph_quirks & PQUIRK_START)
    317 		(void)scsipi_start(periph, SSS_START, XS_CTL_SILENT);
    318 
    319 	error = scsipi_test_unit_ready(periph,
    320 	    XS_CTL_DISCOVERY | XS_CTL_IGNORE_ILLEGAL_REQUEST |
    321 	    XS_CTL_IGNORE_MEDIA_CHANGE | XS_CTL_SILENT_NODEV);
    322 	if (error)
    323 		result = SDGP_RESULT_OFFLINE;
    324 	else
    325 		result = sd_get_parms(sd, &sd->params, XS_CTL_DISCOVERY);
    326 
    327 	aprint_normal_dev(dksc->sc_dev, "");
    328 	switch (result) {
    329 	case SDGP_RESULT_OK:
    330 		format_bytes(pbuf, sizeof(pbuf),
    331 		    (u_int64_t)dp->disksize * dp->blksize);
    332 		aprint_normal(
    333 		"%s, %ld cyl, %ld head, %ld sec, %ld bytes/sect x %llu sectors",
    334 		    pbuf, dp->cyls, dp->heads, dp->sectors, dp->blksize,
    335 		    (unsigned long long)dp->disksize);
    336 		break;
    337 
    338 	case SDGP_RESULT_OFFLINE:
    339 		aprint_normal("drive offline");
    340 		break;
    341 
    342 	case SDGP_RESULT_UNFORMATTED:
    343 		aprint_normal("unformatted media");
    344 		break;
    345 
    346 #ifdef DIAGNOSTIC
    347 	default:
    348 		panic("sdattach: unknown result from get_parms");
    349 		break;
    350 #endif
    351 	}
    352 	aprint_normal("\n");
    353 
    354 	/* Discover wedges on this disk if it is online */
    355 	if (result == SDGP_RESULT_OK)
    356 		dkwedge_discover(&dksc->sc_dkdev);
    357 
    358 	/*
    359 	 * Establish a shutdown hook so that we can ensure that
    360 	 * our data has actually made it onto the platter at
    361 	 * shutdown time.  Note that this relies on the fact
    362 	 * that the shutdown hooks at the "leaves" of the device tree
    363 	 * are run, first (thus guaranteeing that our hook runs before
    364 	 * our ancestors').
    365 	 */
    366 	if (!pmf_device_register1(self, sd_suspend, NULL, sd_shutdown))
    367 		aprint_error_dev(self, "couldn't establish power handler\n");
    368 }
    369 
    370 static int
    371 sddetach(device_t self, int flags)
    372 {
    373 	struct sd_softc *sd = device_private(self);
    374 	struct dk_softc *dksc = &sd->sc_dksc;
    375 	struct scsipi_periph *periph = sd->sc_periph;
    376 	struct scsipi_channel *chan = periph->periph_channel;
    377 	int bmaj, cmaj, i, mn, rc;
    378 
    379 	if ((rc = disk_begindetach(&dksc->sc_dkdev, sd_lastclose, self, flags)) != 0)
    380 		return rc;
    381 
    382 	/* locate the major number */
    383 	bmaj = bdevsw_lookup_major(&sd_bdevsw);
    384 	cmaj = cdevsw_lookup_major(&sd_cdevsw);
    385 
    386 	/* Nuke the vnodes for any open instances */
    387 	for (i = 0; i < MAXPARTITIONS; i++) {
    388 		mn = SDMINOR(device_unit(self), i);
    389 		vdevgone(bmaj, mn, mn, VBLK);
    390 		vdevgone(cmaj, mn, mn, VCHR);
    391 	}
    392 
    393 	/* kill any pending restart */
    394 	callout_halt(&sd->sc_callout, NULL);
    395 
    396 	dk_drain(dksc);
    397 
    398 	/* Kill off any pending commands. */
    399 	mutex_enter(chan_mtx(chan));
    400 	scsipi_kill_pending(periph);
    401 	mutex_exit(chan_mtx(chan));
    402 
    403 	bufq_free(dksc->sc_bufq);
    404 
    405 	/* Delete all of our wedges. */
    406 	dkwedge_delall(&dksc->sc_dkdev);
    407 
    408 	/* Detach from the disk list. */
    409 	disk_detach(&dksc->sc_dkdev);
    410 	disk_destroy(&dksc->sc_dkdev);
    411 
    412 	dk_detach(dksc);
    413 
    414 	callout_destroy(&sd->sc_callout);
    415 
    416 	pmf_device_deregister(self);
    417 
    418 	return (0);
    419 }
    420 
    421 /*
    422  * Serialized by caller
    423  */
    424 static int
    425 sd_firstopen(device_t self, dev_t dev, int flag, int fmt)
    426 {
    427 	struct sd_softc *sd = device_private(self);
    428 	struct scsipi_periph *periph = sd->sc_periph;
    429 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
    430 	int error, silent;
    431 	int part, removable;
    432 
    433 	part = SDPART(dev);
    434 
    435 	error = scsipi_adapter_addref(adapt);
    436 	if (error)
    437 		return error;
    438 
    439 	if ((part == RAW_PART && fmt == S_IFCHR) || (flag & FSILENT))
    440 		silent = XS_CTL_SILENT;
    441 	else
    442 		silent = 0;
    443 
    444 	/* Check that it is still responding and ok. */
    445 	error = scsipi_test_unit_ready(periph,
    446 	    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
    447 	    silent);
    448 
    449 	/*
    450 	 * Start the pack spinning if necessary. Always allow the
    451 	 * raw partition to be opened, for raw IOCTLs. Data transfers
    452 	 * will check for SDEV_MEDIA_LOADED.
    453 	 */
    454 	if (error == EIO) {
    455 		error = scsipi_start(periph, SSS_START, silent);
    456 		if (error == EINVAL)
    457 			error = EIO;
    458 	}
    459 	if (error)
    460 		goto bad;
    461 
    462 	removable = (periph->periph_flags & PERIPH_REMOVABLE) != 0;
    463 	if (removable) {
    464 		/* Lock the pack in. */
    465 		error = scsipi_prevent(periph, SPAMR_PREVENT_DT,
    466 		    XS_CTL_IGNORE_ILLEGAL_REQUEST |
    467 		    XS_CTL_IGNORE_MEDIA_CHANGE |
    468 		    XS_CTL_SILENT);
    469 		if (error)
    470 			goto bad;
    471 	}
    472 
    473 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
    474 		int param_error;
    475 
    476 		/*
    477 		 * Load the physical device parameters.
    478 		 *
    479 		 * Note that if media is present but unformatted,
    480 		 * we allow the open (so that it can be formatted!).
    481 		 * The drive should refuse real I/O, if the media is
    482 		 * unformatted.
    483 		 */
    484 		param_error = sd_get_parms(sd, &sd->params, 0);
    485 		if (param_error == SDGP_RESULT_OFFLINE) {
    486 			error = ENXIO;
    487 			goto bad2;
    488 		}
    489 		periph->periph_flags |= PERIPH_MEDIA_LOADED;
    490 
    491 		SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));
    492 	}
    493 
    494 	periph->periph_flags |= PERIPH_OPEN;
    495 	return 0;
    496 
    497 bad2:
    498 	if (removable)
    499 		scsipi_prevent(periph, SPAMR_ALLOW,
    500 		    XS_CTL_IGNORE_ILLEGAL_REQUEST |
    501 		    XS_CTL_IGNORE_MEDIA_CHANGE |
    502 		    XS_CTL_SILENT);
    503 
    504 bad:
    505 	scsipi_adapter_delref(adapt);
    506 	return error;
    507 }
    508 
    509 /*
    510  * open the device. Make sure the partition info is a up-to-date as can be.
    511  */
    512 static int
    513 sdopen(dev_t dev, int flag, int fmt, struct lwp *l)
    514 {
    515 	struct sd_softc *sd;
    516 	struct dk_softc *dksc;
    517 	struct scsipi_periph *periph;
    518 	int unit, part;
    519 	int error;
    520 
    521 	unit = SDUNIT(dev);
    522 	sd = device_lookup_private(&sd_cd, unit);
    523 	if (sd == NULL)
    524 		return (ENXIO);
    525 	dksc = &sd->sc_dksc;
    526 
    527 	if (!device_is_active(dksc->sc_dev))
    528 		return (ENODEV);
    529 
    530 	periph = sd->sc_periph;
    531 	part = SDPART(dev);
    532 
    533 	SC_DEBUG(periph, SCSIPI_DB1,
    534 	    ("sdopen: dev=0x%"PRIx64" (unit %d (of %d), partition %d)\n",
    535 	    dev, unit, sd_cd.cd_ndevs, SDPART(dev)));
    536 
    537 	/*
    538 	 * If any partition is open, but the disk has been invalidated,
    539 	 * disallow further opens of non-raw partition
    540 	 */
    541 	if ((periph->periph_flags & (PERIPH_OPEN | PERIPH_MEDIA_LOADED)) ==
    542 	    PERIPH_OPEN) {
    543 		if (part != RAW_PART || fmt != S_IFCHR)
    544 			return EIO;
    545 	}
    546 
    547 	error = dk_open(dksc, dev, flag, fmt, l);
    548 
    549 	SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));
    550 
    551 	return error;
    552 }
    553 
    554 /*
    555  * Serialized by caller
    556  */
    557 static int
    558 sd_lastclose(device_t self)
    559 {
    560 	struct sd_softc *sd = device_private(self);
    561 	struct dk_softc *dksc = &sd->sc_dksc;
    562 	struct scsipi_periph *periph = sd->sc_periph;
    563 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
    564 
    565 	/*
    566 	 * If the disk cache needs flushing, and the disk supports
    567 	 * it, do it now.
    568 	 */
    569 	if ((sd->flags & SDF_DIRTY) != 0) {
    570 		if (sd_flush(sd, 0)) {
    571 			aprint_error_dev(dksc->sc_dev,
    572 				"cache synchronization failed\n");
    573 			sd->flags &= ~SDF_FLUSHING;
    574 		} else
    575 			sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
    576 	}
    577 
    578 	scsipi_wait_drain(periph);
    579 
    580 	if (periph->periph_flags & PERIPH_REMOVABLE)
    581 		scsipi_prevent(periph, SPAMR_ALLOW,
    582 		    XS_CTL_IGNORE_ILLEGAL_REQUEST |
    583 		    XS_CTL_IGNORE_NOT_READY |
    584 		    XS_CTL_SILENT);
    585 	periph->periph_flags &= ~PERIPH_OPEN;
    586 
    587 	scsipi_wait_drain(periph);
    588 
    589 	scsipi_adapter_delref(adapt);
    590 
    591 	return 0;
    592 }
    593 
    594 /*
    595  * close the device.. only called if we are the LAST occurrence of an open
    596  * device.  Convenient now but usually a pain.
    597  */
    598 static int
    599 sdclose(dev_t dev, int flag, int fmt, struct lwp *l)
    600 {
    601 	struct sd_softc *sd;
    602 	struct dk_softc *dksc;
    603 	int unit;
    604 
    605 	unit = SDUNIT(dev);
    606 	sd = device_lookup_private(&sd_cd, unit);
    607 	dksc = &sd->sc_dksc;
    608 
    609 	return dk_close(dksc, dev, flag, fmt, l);
    610 }
    611 
    612 /*
    613  * Actually translate the requested transfer into one the physical driver
    614  * can understand.  The transfer is described by a buf and will include
    615  * only one physical transfer.
    616  */
    617 static void
    618 sdstrategy(struct buf *bp)
    619 {
    620 	struct sd_softc *sd = device_lookup_private(&sd_cd, SDUNIT(bp->b_dev));
    621 	struct dk_softc *dksc = &sd->sc_dksc;
    622 	struct scsipi_periph *periph = sd->sc_periph;
    623 
    624 	SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdstrategy "));
    625 	SC_DEBUG(sd->sc_periph, SCSIPI_DB1,
    626 	    ("%d bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));
    627 
    628 	/*
    629 	 * If the device has been made invalid, error out
    630 	 */
    631 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 ||
    632 	    !device_is_active(dksc->sc_dev)) {
    633 		if (periph->periph_flags & PERIPH_OPEN)
    634 			bp->b_error = EIO;
    635 		else
    636 			bp->b_error = ENODEV;
    637 
    638 		bp->b_resid = bp->b_bcount;
    639 		biodone(bp);
    640 		return;
    641 	}
    642 
    643 	dk_strategy(dksc, bp);
    644 }
    645 
    646 /*
    647  * Issue single I/O command
    648  *
    649  * Called from dk_start and implicitly from dk_strategy
    650  */
    651 static int
    652 sd_diskstart(device_t dev, struct buf *bp)
    653 {
    654 	struct sd_softc *sd = device_private(dev);
    655 	struct scsipi_periph *periph = sd->sc_periph;
    656 	struct scsipi_channel *chan = periph->periph_channel;
    657 	struct scsipi_rw_16 cmd16;
    658 	struct scsipi_rw_10 cmd_big;
    659 	struct scsi_rw_6 cmd_small;
    660 	struct scsipi_generic *cmdp;
    661 	struct scsipi_xfer *xs;
    662 	int error, flags, nblks, cmdlen;
    663 	int cdb_flags;
    664 	bool havefua = !(periph->periph_quirks & PQUIRK_NOFUA);
    665 
    666 	mutex_enter(chan_mtx(chan));
    667 
    668 	if (periph->periph_active >= periph->periph_openings) {
    669 		error = EAGAIN;
    670 		goto out;
    671 	}
    672 
    673 	/*
    674 	 * there is excess capacity, but a special waits
    675 	 * It'll need the adapter as soon as we clear out of the
    676 	 * way and let it run (user level wait).
    677 	 */
    678 	if (periph->periph_flags & PERIPH_WAITING) {
    679 		periph->periph_flags &= ~PERIPH_WAITING;
    680 		cv_broadcast(periph_cv_periph(periph));
    681 		error = EAGAIN;
    682 		goto out;
    683 	}
    684 
    685 	/*
    686 	 * If the device has become invalid, abort all the
    687 	 * reads and writes until all files have been closed and
    688 	 * re-opened.
    689 	 */
    690 	if (__predict_false(
    691 	    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
    692 		error = EIO;
    693 		goto out;
    694 	}
    695 
    696 	/*
    697 	 * Mark the disk dirty so that the cache will be
    698 	 * flushed on close.
    699 	 */
    700 	if ((bp->b_flags & B_READ) == 0)
    701 		sd->flags |= SDF_DIRTY;
    702 
    703 	if (sd->params.blksize == DEV_BSIZE)
    704 		nblks = bp->b_bcount >> DEV_BSHIFT;
    705 	else
    706 		nblks = howmany(bp->b_bcount, sd->params.blksize);
    707 
    708 	/*
    709 	 * Pass FUA and/or DPO if requested. Must be done before CDB
    710 	 * selection, as 6-byte CDB doesn't support the flags.
    711 	 */
    712 	cdb_flags = 0;
    713 	if (havefua) {
    714 		if (bp->b_flags & B_MEDIA_FUA)
    715 			cdb_flags |= SRWB_FUA;
    716 
    717 		if (bp->b_flags & B_MEDIA_DPO)
    718 			cdb_flags |= SRWB_DPO;
    719 	}
    720 
    721 	/*
    722 	 * Fill out the scsi command.  Use the smallest CDB possible
    723 	 * (6-byte, 10-byte, or 16-byte). If we need FUA or DPO,
    724 	 * need to use 10-byte or bigger, as the 6-byte doesn't support
    725 	 * the flags.
    726 	 */
    727 	if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
    728 	    ((nblks & 0xff) == nblks) &&
    729 	    !(periph->periph_quirks & PQUIRK_ONLYBIG) &&
    730 	    !cdb_flags) {
    731 		/* 6-byte CDB */
    732 		memset(&cmd_small, 0, sizeof(cmd_small));
    733 		cmd_small.opcode = (bp->b_flags & B_READ) ?
    734 		    SCSI_READ_6_COMMAND : SCSI_WRITE_6_COMMAND;
    735 		_lto3b(bp->b_rawblkno, cmd_small.addr);
    736 		cmd_small.length = nblks & 0xff;
    737 		cmdlen = sizeof(cmd_small);
    738 		cmdp = (struct scsipi_generic *)&cmd_small;
    739 	} else if ((bp->b_rawblkno & 0xffffffff) == bp->b_rawblkno) {
    740 		/* 10-byte CDB */
    741 		memset(&cmd_big, 0, sizeof(cmd_big));
    742 		cmd_big.opcode = (bp->b_flags & B_READ) ?
    743 		    READ_10 : WRITE_10;
    744 		_lto4b(bp->b_rawblkno, cmd_big.addr);
    745 		_lto2b(nblks, cmd_big.length);
    746 		cmdlen = sizeof(cmd_big);
    747 		cmdp = (struct scsipi_generic *)&cmd_big;
    748 	} else {
    749 		/* 16-byte CDB */
    750 		memset(&cmd16, 0, sizeof(cmd16));
    751 		cmd16.opcode = (bp->b_flags & B_READ) ?
    752 		    READ_16 : WRITE_16;
    753 		_lto8b(bp->b_rawblkno, cmd16.addr);
    754 		_lto4b(nblks, cmd16.length);
    755 		cmdlen = sizeof(cmd16);
    756 		cmdp = (struct scsipi_generic *)&cmd16;
    757 	}
    758 
    759 	if (cdb_flags)
    760 		cmdp->bytes[0] = cdb_flags;
    761 
    762 	/*
    763 	 * Figure out what flags to use.
    764 	 */
    765 	flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
    766 	if (bp->b_flags & B_READ)
    767 		flags |= XS_CTL_DATA_IN;
    768 	else
    769 		flags |= XS_CTL_DATA_OUT;
    770 
    771 	/*
    772 	 * Call the routine that chats with the adapter.
    773 	 * Note: we cannot sleep as we may be an interrupt
    774 	 */
    775 	xs = scsipi_make_xs_locked(periph, cmdp, cmdlen,
    776 	    (u_char *)bp->b_data, bp->b_bcount,
    777 	    SDRETRIES, SD_IO_TIMEOUT, bp, flags);
    778 	if (__predict_false(xs == NULL)) {
    779 		/*
    780 		 * out of memory. Keep this buffer in the queue, and
    781 		 * retry later.
    782 		 */
    783 		callout_reset(&sd->sc_callout, hz / 2, sdrestart, sd);
    784 		error = EAGAIN;
    785 		goto out;
    786 	}
    787 
    788 	error = scsipi_execute_xs(xs);
    789 	/* with a scsipi_xfer preallocated, scsipi_command can't fail */
    790 	KASSERT(error == 0);
    791 
    792 out:
    793 	mutex_exit(chan_mtx(chan));
    794 
    795 	return error;
    796 }
    797 
    798 /*
    799  * Recover I/O request after memory shortage
    800  *
    801  * Called from callout
    802  */
    803 static void
    804 sdrestart(void *v)
    805 {
    806 	struct sd_softc *sd = v;
    807 	struct dk_softc *dksc = &sd->sc_dksc;
    808 
    809 	dk_start(dksc, NULL);
    810 }
    811 
    812 /*
    813  * Recover I/O request after memory shortage
    814  *
    815  * Called from scsipi midlayer when resources have been freed
    816  * with channel lock held
    817  */
    818 static void
    819 sdstart(struct scsipi_periph *periph)
    820 {
    821 	struct sd_softc *sd = device_private(periph->periph_dev);
    822 	struct dk_softc *dksc = &sd->sc_dksc;
    823 	struct scsipi_channel *chan = periph->periph_channel;
    824 
    825 	/*
    826 	 * release channel lock as dk_start may need to acquire
    827 	 * other locks
    828 	 *
    829 	 * sdstart is called from scsipi_put_xs and all its callers
    830 	 * release the lock afterwards. So releasing it here
    831 	 * doesn't matter.
    832 	 */
    833 	mutex_exit(chan_mtx(chan));
    834 
    835 	dk_start(dksc, NULL);
    836 
    837 	mutex_enter(chan_mtx(chan));
    838 }
    839 
    840 static void
    841 sddone(struct scsipi_xfer *xs, int error)
    842 {
    843 	struct sd_softc *sd = device_private(xs->xs_periph->periph_dev);
    844 	struct dk_softc *dksc = &sd->sc_dksc;
    845 	struct buf *bp = xs->bp;
    846 
    847 	if (sd->flags & SDF_FLUSHING) {
    848 		/* Flush completed, no longer dirty. */
    849 		sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
    850 	}
    851 
    852 	if (bp) {
    853 		bp->b_error = error;
    854 		bp->b_resid = xs->resid;
    855 		if (error) {
    856 			/* on a read/write error bp->b_resid is zero, so fix */
    857 			bp->b_resid = bp->b_bcount;
    858 		}
    859 
    860 		dk_done(dksc, bp);
    861 		/* dk_start is called from scsipi_complete */
    862 	}
    863 }
    864 
    865 static void
    866 sdminphys(struct buf *bp)
    867 {
    868 	struct sd_softc *sd = device_lookup_private(&sd_cd, SDUNIT(bp->b_dev));
    869 	struct dk_softc *dksc = &sd->sc_dksc;
    870 	long xmax;
    871 
    872 	/*
    873 	 * If the device is ancient, we want to make sure that
    874 	 * the transfer fits into a 6-byte cdb.
    875 	 *
    876 	 * XXX Note that the SCSI-I spec says that 256-block transfers
    877 	 * are allowed in a 6-byte read/write, and are specified
    878 	 * by setting the "length" to 0.  However, we're conservative
    879 	 * here, allowing only 255-block transfers in case an
    880 	 * ancient device gets confused by length == 0.  A length of 0
    881 	 * in a 10-byte read/write actually means 0 blocks.
    882 	 */
    883 	if ((sd->flags & SDF_ANCIENT) &&
    884 	    ((sd->sc_periph->periph_flags &
    885 	    (PERIPH_REMOVABLE | PERIPH_MEDIA_LOADED)) != PERIPH_REMOVABLE)) {
    886 		xmax = dksc->sc_dkdev.dk_geom.dg_secsize * 0xff;
    887 
    888 		if (bp->b_bcount > xmax)
    889 			bp->b_bcount = xmax;
    890 	}
    891 
    892 	scsipi_adapter_minphys(sd->sc_periph->periph_channel, bp);
    893 }
    894 
    895 static void
    896 sd_iosize(device_t dev, int *count)
    897 {
    898 	struct buf B;
    899 	int bmaj;
    900 
    901 	bmaj       = bdevsw_lookup_major(&sd_bdevsw);
    902 	B.b_dev    = MAKESDDEV(bmaj,device_unit(dev),RAW_PART);
    903 	B.b_bcount = *count;
    904 
    905 	sdminphys(&B);
    906 
    907 	*count = B.b_bcount;
    908 }
    909 
    910 static int
    911 sdread(dev_t dev, struct uio *uio, int ioflag)
    912 {
    913 
    914 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
    915 }
    916 
    917 static int
    918 sdwrite(dev_t dev, struct uio *uio, int ioflag)
    919 {
    920 
    921 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
    922 }
    923 
    924 /*
    925  * Perform special action on behalf of the user
    926  * Knows about the internals of this device
    927  */
    928 static int
    929 sdioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
    930 {
    931 	struct sd_softc *sd = device_lookup_private(&sd_cd, SDUNIT(dev));
    932 	struct dk_softc *dksc = &sd->sc_dksc;
    933 	struct scsipi_periph *periph = sd->sc_periph;
    934 
    935 	int part = SDPART(dev);
    936 	int error;
    937 
    938 	SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdioctl 0x%lx ", cmd));
    939 
    940 	/*
    941 	 * If the device is not valid, some IOCTLs can still be
    942 	 * handled on the raw partition. Check this here.
    943 	 */
    944 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
    945 	    part != RAW_PART)
    946 		return (EIO);
    947 
    948 	switch (cmd) {
    949 	case DIOCLOCK:
    950 		if (periph->periph_flags & PERIPH_REMOVABLE)
    951 			return (scsipi_prevent(periph,
    952 			    (*(int *)addr) ?
    953 			    SPAMR_PREVENT_DT : SPAMR_ALLOW, 0));
    954 		else
    955 			return (ENOTTY);
    956 
    957 	case DIOCEJECT:
    958 		if ((periph->periph_flags & PERIPH_REMOVABLE) == 0)
    959 			return (ENOTTY);
    960 		if (*(int *)addr == 0) {
    961 			int pmask = __BIT(part);
    962 			/*
    963 			 * Don't force eject: check that we are the only
    964 			 * partition open. If so, unlock it.
    965 			 */
    966 			if (DK_BUSY(dksc, pmask) == 0) {
    967 				error = scsipi_prevent(periph, SPAMR_ALLOW,
    968 				    XS_CTL_IGNORE_NOT_READY);
    969 				if (error)
    970 					return (error);
    971 			} else {
    972 				return (EBUSY);
    973 			}
    974 		}
    975 		/* FALLTHROUGH */
    976 	case ODIOCEJECT:
    977 		return ((periph->periph_flags & PERIPH_REMOVABLE) == 0 ?
    978 		    ENOTTY : scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
    979 
    980 	case DIOCGCACHE:
    981 		return (sd_getcache(sd, (int *) addr));
    982 
    983 	case DIOCSCACHE:
    984 		if ((flag & FWRITE) == 0)
    985 			return (EBADF);
    986 		return (sd_setcache(sd, *(int *) addr));
    987 
    988 	case DIOCCACHESYNC:
    989 		/*
    990 		 * XXX Do we really need to care about having a writable
    991 		 * file descriptor here?
    992 		 */
    993 		if ((flag & FWRITE) == 0)
    994 			return (EBADF);
    995 		if (((sd->flags & SDF_DIRTY) != 0 || *(int *)addr != 0)) {
    996 			error = sd_flush(sd, 0);
    997 			if (error) {
    998 				sd->flags &= ~SDF_FLUSHING;
    999 				return (error);
   1000 			}
   1001 			sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
   1002 		}
   1003 		return (0);
   1004 
   1005 	default:
   1006 		error = dk_ioctl(dksc, dev, cmd, addr, flag, l);
   1007 		if (error == ENOTTY)
   1008 			error = scsipi_do_ioctl(periph, dev, cmd, addr, flag, l);
   1009 		return (error);
   1010 	}
   1011 
   1012 #ifdef DIAGNOSTIC
   1013 	panic("sdioctl: impossible");
   1014 #endif
   1015 }
   1016 
   1017 static void
   1018 sd_label(device_t self, struct disklabel *lp)
   1019 {
   1020 	struct sd_softc *sd = device_private(self);
   1021 
   1022 	strncpy(lp->d_typename, sd->name, 16);
   1023 	lp->d_rpm = sd->params.rot_rate;
   1024 	if (sd->sc_periph->periph_flags & PERIPH_REMOVABLE)
   1025 		lp->d_flags |= D_REMOVABLE;
   1026 }
   1027 
   1028 static bool
   1029 sd_shutdown(device_t self, int how)
   1030 {
   1031 	struct sd_softc *sd = device_private(self);
   1032 	struct dk_softc *dksc = &sd->sc_dksc;
   1033 
   1034 	/*
   1035 	 * If the disk cache needs to be flushed, and the disk supports
   1036 	 * it, flush it.  We're cold at this point, so we poll for
   1037 	 * completion.
   1038 	 */
   1039 	if ((sd->flags & SDF_DIRTY) != 0) {
   1040 		if (sd_flush(sd, XS_CTL_NOSLEEP|XS_CTL_POLL)) {
   1041 			aprint_error_dev(dksc->sc_dev,
   1042 				"cache synchronization failed\n");
   1043 			sd->flags &= ~SDF_FLUSHING;
   1044 		} else
   1045 			sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
   1046 	}
   1047 	return true;
   1048 }
   1049 
   1050 static bool
   1051 sd_suspend(device_t dv, const pmf_qual_t *qual)
   1052 {
   1053 	return sd_shutdown(dv, boothowto); /* XXX no need to poll */
   1054 }
   1055 
   1056 /*
   1057  * Check Errors
   1058  */
   1059 static int
   1060 sd_interpret_sense(struct scsipi_xfer *xs)
   1061 {
   1062 	struct scsipi_periph *periph = xs->xs_periph;
   1063 	struct scsipi_channel *chan = periph->periph_channel;
   1064 	struct scsi_sense_data *sense = &xs->sense.scsi_sense;
   1065 	struct sd_softc *sd = device_private(periph->periph_dev);
   1066 	struct dk_softc *dksc = &sd->sc_dksc;
   1067 	int error, retval = EJUSTRETURN;
   1068 
   1069 	/*
   1070 	 * If the periph is already recovering, just do the normal
   1071 	 * error processing.
   1072 	 */
   1073 	if (periph->periph_flags & PERIPH_RECOVERING)
   1074 		return (retval);
   1075 
   1076 	/*
   1077 	 * Ignore errors from accessing illegal fields (e.g. trying to
   1078 	 * lock the door of a digicam, which doesn't have a door that
   1079 	 * can be locked) for the SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL command.
   1080 	 */
   1081 	if (xs->cmd->opcode == SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL &&
   1082 	    SSD_SENSE_KEY(sense->flags) == SKEY_ILLEGAL_REQUEST &&
   1083 	    sense->asc == 0x24 &&
   1084 	    sense->ascq == 0x00) { /* Illegal field in CDB */
   1085 		if (!(xs->xs_control & XS_CTL_SILENT)) {
   1086 			scsipi_printaddr(periph);
   1087 			printf("no door lock\n");
   1088 		}
   1089 		xs->xs_control |= XS_CTL_IGNORE_ILLEGAL_REQUEST;
   1090 		return (retval);
   1091 	}
   1092 
   1093 	/*
   1094 	 * If it isn't a extended or extended/deferred error, let
   1095 	 * the generic code handle it.
   1096 	 */
   1097 	if (SSD_RCODE(sense->response_code) != SSD_RCODE_CURRENT &&
   1098 	    SSD_RCODE(sense->response_code) != SSD_RCODE_DEFERRED)
   1099 		return (retval);
   1100 
   1101 	if (SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY &&
   1102 	    sense->asc == 0x4) {
   1103 		if (sense->ascq == 0x01)	{
   1104 			/*
   1105 			 * Unit In The Process Of Becoming Ready.
   1106 			 */
   1107 			printf("%s: waiting for pack to spin up...\n",
   1108 			    dksc->sc_xname);
   1109 			if (!callout_pending(&periph->periph_callout))
   1110 				scsipi_periph_freeze(periph, 1);
   1111 			callout_reset(&periph->periph_callout,
   1112 			    5 * hz, scsipi_periph_timed_thaw, periph);
   1113 			retval = ERESTART;
   1114 		} else if (sense->ascq == 0x02) {
   1115 			printf("%s: pack is stopped, restarting...\n",
   1116 			    dksc->sc_xname);
   1117 			mutex_enter(chan_mtx(chan));
   1118 			periph->periph_flags |= PERIPH_RECOVERING;
   1119 			mutex_exit(chan_mtx(chan));
   1120 			error = scsipi_start(periph, SSS_START,
   1121 			    XS_CTL_URGENT|XS_CTL_HEAD_TAG|
   1122 			    XS_CTL_THAW_PERIPH|XS_CTL_FREEZE_PERIPH);
   1123 			if (error) {
   1124 				aprint_error_dev(dksc->sc_dev,
   1125 					"unable to restart pack\n");
   1126 				retval = error;
   1127 			} else
   1128 				retval = ERESTART;
   1129 			mutex_enter(chan_mtx(chan));
   1130 			periph->periph_flags &= ~PERIPH_RECOVERING;
   1131 			mutex_exit(chan_mtx(chan));
   1132 		}
   1133 	}
   1134 	if (SSD_SENSE_KEY(sense->flags) == SKEY_MEDIUM_ERROR &&
   1135 	    sense->asc == 0x31 &&
   1136 	    sense->ascq == 0x00)	{ /* maybe for any asq ? */
   1137 		/* Medium Format Corrupted */
   1138 		retval = EFTYPE;
   1139 	}
   1140 	return (retval);
   1141 }
   1142 
   1143 
   1144 static int
   1145 sdsize(dev_t dev)
   1146 {
   1147 	struct sd_softc *sd;
   1148 	struct dk_softc *dksc;
   1149 	int unit;
   1150 
   1151 	unit = SDUNIT(dev);
   1152 	sd = device_lookup_private(&sd_cd, unit);
   1153 	if (sd == NULL)
   1154 		return (-1);
   1155 	dksc = &sd->sc_dksc;
   1156 
   1157 	if (!device_is_active(dksc->sc_dev))
   1158 		return (-1);
   1159 
   1160 	return dk_size(dksc, dev);
   1161 }
   1162 
   1163 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
   1164 static struct scsipi_xfer sx;
   1165 
   1166 /*
   1167  * dump all of physical memory into the partition specified, starting
   1168  * at offset 'dumplo' into the partition.
   1169  */
   1170 static int
   1171 sddump(dev_t dev, daddr_t blkno, void *va, size_t size)
   1172 {
   1173 	struct sd_softc *sd;
   1174 	struct dk_softc *dksc;
   1175 	struct scsipi_periph *periph;
   1176 	int unit;
   1177 
   1178 	unit = SDUNIT(dev);
   1179 	if ((sd = device_lookup_private(&sd_cd, unit)) == NULL)
   1180 		return (ENXIO);
   1181 	dksc = &sd->sc_dksc;
   1182 
   1183 	if (!device_is_active(dksc->sc_dev))
   1184 		return (ENODEV);
   1185 
   1186 	periph = sd->sc_periph;
   1187 
   1188 	/* Make sure it was initialized. */
   1189 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
   1190 		return (ENXIO);
   1191 
   1192 	return dk_dump(dksc, dev, blkno, va, size, 0);
   1193 }
   1194 
   1195 static int
   1196 sd_dumpblocks(device_t dev, void *va, daddr_t blkno, int nblk)
   1197 {
   1198 	struct sd_softc *sd = device_private(dev);
   1199 	struct dk_softc *dksc = &sd->sc_dksc;
   1200 	struct disk_geom *dg = &dksc->sc_dkdev.dk_geom;
   1201 	struct scsipi_rw_10 cmd;	/* write command */
   1202 	struct scsipi_xfer *xs;		/* ... convenience */
   1203 	struct scsipi_periph *periph;
   1204 	struct scsipi_channel *chan;
   1205 	size_t sectorsize;
   1206 
   1207 	periph = sd->sc_periph;
   1208 	chan = periph->periph_channel;
   1209 
   1210 	sectorsize = dg->dg_secsize;
   1211 
   1212 	xs = &sx;
   1213 
   1214 #ifndef	SD_DUMP_NOT_TRUSTED
   1215 	/*
   1216 	 *  Fill out the scsi command
   1217 	 */
   1218 	memset(&cmd, 0, sizeof(cmd));
   1219 	cmd.opcode = WRITE_10;
   1220 	_lto4b(blkno, cmd.addr);
   1221 	_lto2b(nblk, cmd.length);
   1222 	/*
   1223 	 * Fill out the scsipi_xfer structure
   1224 	 *    Note: we cannot sleep as we may be an interrupt
   1225 	 * don't use scsipi_command() as it may want to wait
   1226 	 * for an xs.
   1227 	 */
   1228 	memset(xs, 0, sizeof(sx));
   1229 	xs->xs_control |= XS_CTL_NOSLEEP | XS_CTL_POLL |
   1230 	    XS_CTL_DATA_OUT;
   1231 	xs->xs_status = 0;
   1232 	xs->xs_periph = periph;
   1233 	xs->xs_retries = SDRETRIES;
   1234 	xs->timeout = 10000;	/* 10000 millisecs for a disk ! */
   1235 	xs->cmd = (struct scsipi_generic *)&cmd;
   1236 	xs->cmdlen = sizeof(cmd);
   1237 	xs->resid = nblk * sectorsize;
   1238 	xs->error = XS_NOERROR;
   1239 	xs->bp = 0;
   1240 	xs->data = va;
   1241 	xs->datalen = nblk * sectorsize;
   1242 	callout_init(&xs->xs_callout, 0);
   1243 
   1244 	/*
   1245 	 * Pass all this info to the scsi driver.
   1246 	 */
   1247 	scsipi_adapter_request(chan, ADAPTER_REQ_RUN_XFER, xs);
   1248 	if ((xs->xs_status & XS_STS_DONE) == 0 ||
   1249 	    xs->error != XS_NOERROR)
   1250 		return (EIO);
   1251 #else	/* SD_DUMP_NOT_TRUSTED */
   1252 	/* Let's just talk about this first... */
   1253 	printf("sd%d: dump addr 0x%x, blk %d\n", unit, va, blkno);
   1254 	delay(500 * 1000);	/* half a second */
   1255 #endif	/* SD_DUMP_NOT_TRUSTED */
   1256 
   1257 	return (0);
   1258 }
   1259 
   1260 static int
   1261 sd_mode_sense(struct sd_softc *sd, u_int8_t byte2, void *sense, size_t size,
   1262     int page, int flags, int *big)
   1263 {
   1264 
   1265 	if ((sd->sc_periph->periph_quirks & PQUIRK_ONLYBIG) &&
   1266 	    !(sd->sc_periph->periph_quirks & PQUIRK_NOBIGMODESENSE)) {
   1267 		*big = 1;
   1268 		return scsipi_mode_sense_big(sd->sc_periph, byte2, page, sense,
   1269 		    size + sizeof(struct scsi_mode_parameter_header_10),
   1270 		    flags, SDRETRIES, 6000);
   1271 	} else {
   1272 		*big = 0;
   1273 		return scsipi_mode_sense(sd->sc_periph, byte2, page, sense,
   1274 		    size + sizeof(struct scsi_mode_parameter_header_6),
   1275 		    flags, SDRETRIES, 6000);
   1276 	}
   1277 }
   1278 
   1279 static int
   1280 sd_mode_select(struct sd_softc *sd, u_int8_t byte2, void *sense, size_t size,
   1281     int flags, int big)
   1282 {
   1283 
   1284 	if (big) {
   1285 		struct scsi_mode_parameter_header_10 *header = sense;
   1286 
   1287 		_lto2b(0, header->data_length);
   1288 		return scsipi_mode_select_big(sd->sc_periph, byte2, sense,
   1289 		    size + sizeof(struct scsi_mode_parameter_header_10),
   1290 		    flags, SDRETRIES, 6000);
   1291 	} else {
   1292 		struct scsi_mode_parameter_header_6 *header = sense;
   1293 
   1294 		header->data_length = 0;
   1295 		return scsipi_mode_select(sd->sc_periph, byte2, sense,
   1296 		    size + sizeof(struct scsi_mode_parameter_header_6),
   1297 		    flags, SDRETRIES, 6000);
   1298 	}
   1299 }
   1300 
   1301 /*
   1302  * sd_validate_blksize:
   1303  *
   1304  *	Validate the block size.  Print error if periph is specified,
   1305  */
   1306 static int
   1307 sd_validate_blksize(struct scsipi_periph *periph, int len)
   1308 {
   1309 
   1310 	if (len >= 256 && powerof2(len) && len <= MAXPHYS) {
   1311 		return 1;
   1312 	}
   1313 
   1314 	if (periph) {
   1315 		scsipi_printaddr(periph);
   1316 		printf("%s sector size: 0x%x.  Defaulting to %d bytes.\n",
   1317 		    !powerof2(len) ?
   1318 		    "preposterous" : "unsupported",
   1319 		    len, SD_DEFAULT_BLKSIZE);
   1320 	}
   1321 
   1322 	return 0;
   1323 }
   1324 
   1325 /*
   1326  * sd_read_capacity:
   1327  *
   1328  *	Find out from the device what its capacity is.
   1329  */
   1330 static u_int64_t
   1331 sd_read_capacity(struct scsipi_periph *periph, int *blksize, int flags)
   1332 {
   1333 	union {
   1334 		struct scsipi_read_capacity_10 cmd;
   1335 		struct scsipi_read_capacity_16 cmd16;
   1336 	} cmd;
   1337 	union {
   1338 		struct scsipi_read_capacity_10_data data;
   1339 		struct scsipi_read_capacity_16_data data16;
   1340 	} *datap;
   1341 	uint64_t rv;
   1342 
   1343 	memset(&cmd, 0, sizeof(cmd));
   1344 	cmd.cmd.opcode = READ_CAPACITY_10;
   1345 
   1346 	/*
   1347 	 * Don't allocate data buffer on stack;
   1348 	 * The lower driver layer might use the same stack and
   1349 	 * if it uses region which is in the same cacheline,
   1350 	 * cache flush ops against the data buffer won't work properly.
   1351 	 */
   1352 	datap = malloc(sizeof(*datap), M_TEMP, M_WAITOK);
   1353 	if (datap == NULL)
   1354 		return 0;
   1355 
   1356 	/*
   1357 	 * If the command works, interpret the result as a 4 byte
   1358 	 * number of blocks
   1359 	 */
   1360 	rv = 0;
   1361 	memset(datap, 0, sizeof(datap->data));
   1362 	if (scsipi_command(periph, (void *)&cmd.cmd, sizeof(cmd.cmd),
   1363 	    (void *)datap, sizeof(datap->data), SCSIPIRETRIES, 20000, NULL,
   1364 	    flags | XS_CTL_DATA_IN | XS_CTL_SILENT) != 0)
   1365 		goto out;
   1366 
   1367 	if (_4btol(datap->data.addr) != 0xffffffff) {
   1368 		*blksize = _4btol(datap->data.length);
   1369 		rv = _4btol(datap->data.addr) + 1;
   1370 		goto out;
   1371 	}
   1372 
   1373 	/*
   1374 	 * Device is larger than can be reflected by READ CAPACITY (10).
   1375 	 * Try READ CAPACITY (16).
   1376 	 */
   1377 
   1378 	memset(&cmd, 0, sizeof(cmd));
   1379 	cmd.cmd16.opcode = READ_CAPACITY_16;
   1380 	cmd.cmd16.byte2 = SRC16_SERVICE_ACTION;
   1381 	_lto4b(sizeof(datap->data16), cmd.cmd16.len);
   1382 
   1383 	memset(datap, 0, sizeof(datap->data16));
   1384 	if (scsipi_command(periph, (void *)&cmd.cmd16, sizeof(cmd.cmd16),
   1385 	    (void *)datap, sizeof(datap->data16), SCSIPIRETRIES, 20000, NULL,
   1386 	    flags | XS_CTL_DATA_IN | XS_CTL_SILENT) != 0)
   1387 		goto out;
   1388 
   1389 	*blksize = _4btol(datap->data16.length);
   1390 	rv = _8btol(datap->data16.addr) + 1;
   1391 
   1392  out:
   1393 	free(datap, M_TEMP);
   1394 	return rv;
   1395 }
   1396 
   1397 static int
   1398 sd_get_simplifiedparms(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1399 {
   1400 	struct {
   1401 		struct scsi_mode_parameter_header_6 header;
   1402 		/* no block descriptor */
   1403 		u_int8_t pg_code; /* page code (should be 6) */
   1404 		u_int8_t pg_length; /* page length (should be 11) */
   1405 		u_int8_t wcd; /* bit0: cache disable */
   1406 		u_int8_t lbs[2]; /* logical block size */
   1407 		u_int8_t size[5]; /* number of log. blocks */
   1408 		u_int8_t pp; /* power/performance */
   1409 		u_int8_t flags;
   1410 		u_int8_t resvd;
   1411 	} scsipi_sense;
   1412 	u_int64_t blocks;
   1413 	int error, blksize;
   1414 
   1415 	/*
   1416 	 * sd_read_capacity (ie "read capacity") and mode sense page 6
   1417 	 * give the same information. Do both for now, and check
   1418 	 * for consistency.
   1419 	 * XXX probably differs for removable media
   1420 	 */
   1421 	dp->blksize = SD_DEFAULT_BLKSIZE;
   1422 	if ((blocks = sd_read_capacity(sd->sc_periph, &blksize, flags)) == 0)
   1423 		return (SDGP_RESULT_OFFLINE);		/* XXX? */
   1424 
   1425 	error = scsipi_mode_sense(sd->sc_periph, SMS_DBD, 6,
   1426 	    &scsipi_sense.header, sizeof(scsipi_sense),
   1427 	    flags, SDRETRIES, 6000);
   1428 
   1429 	if (error != 0)
   1430 		return (SDGP_RESULT_OFFLINE);		/* XXX? */
   1431 
   1432 	dp->blksize = blksize;
   1433 	if (!sd_validate_blksize(NULL, dp->blksize))
   1434 		dp->blksize = _2btol(scsipi_sense.lbs);
   1435 	if (!sd_validate_blksize(sd->sc_periph, dp->blksize))
   1436 		dp->blksize = SD_DEFAULT_BLKSIZE;
   1437 
   1438 	/*
   1439 	 * Create a pseudo-geometry.
   1440 	 */
   1441 	dp->heads = 64;
   1442 	dp->sectors = 32;
   1443 	dp->cyls = blocks / (dp->heads * dp->sectors);
   1444 	dp->disksize = _5btol(scsipi_sense.size);
   1445 	if (dp->disksize <= UINT32_MAX && dp->disksize != blocks) {
   1446 		printf("RBC size: mode sense=%llu, get cap=%llu\n",
   1447 		       (unsigned long long)dp->disksize,
   1448 		       (unsigned long long)blocks);
   1449 		dp->disksize = blocks;
   1450 	}
   1451 	dp->disksize512 = (dp->disksize * dp->blksize) / DEV_BSIZE;
   1452 
   1453 	return (SDGP_RESULT_OK);
   1454 }
   1455 
   1456 /*
   1457  * Get the scsi driver to send a full inquiry to the * device and use the
   1458  * results to fill out the disk parameter structure.
   1459  */
   1460 static int
   1461 sd_get_capacity(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1462 {
   1463 	u_int64_t blocks;
   1464 	int error, blksize;
   1465 #if 0
   1466 	int i;
   1467 	u_int8_t *p;
   1468 #endif
   1469 
   1470 	dp->disksize = blocks = sd_read_capacity(sd->sc_periph, &blksize,
   1471 	    flags);
   1472 	if (blocks == 0) {
   1473 		struct scsipi_read_format_capacities cmd;
   1474 		struct {
   1475 			struct scsipi_capacity_list_header header;
   1476 			struct scsipi_capacity_descriptor desc;
   1477 		} __packed data;
   1478 
   1479 		memset(&cmd, 0, sizeof(cmd));
   1480 		memset(&data, 0, sizeof(data));
   1481 		cmd.opcode = READ_FORMAT_CAPACITIES;
   1482 		_lto2b(sizeof(data), cmd.length);
   1483 
   1484 		error = scsipi_command(sd->sc_periph,
   1485 		    (void *)&cmd, sizeof(cmd), (void *)&data, sizeof(data),
   1486 		    SDRETRIES, 20000, NULL,
   1487 		    flags | XS_CTL_DATA_IN);
   1488 		if (error == EFTYPE) {
   1489 			/* Medium Format Corrupted, handle as not formatted */
   1490 			return (SDGP_RESULT_UNFORMATTED);
   1491 		}
   1492 		if (error || data.header.length == 0)
   1493 			return (SDGP_RESULT_OFFLINE);
   1494 
   1495 #if 0
   1496 printf("rfc: length=%d\n", data.header.length);
   1497 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");
   1498 #endif
   1499 		switch (data.desc.byte5 & SCSIPI_CAP_DESC_CODE_MASK) {
   1500 		case SCSIPI_CAP_DESC_CODE_RESERVED:
   1501 		case SCSIPI_CAP_DESC_CODE_FORMATTED:
   1502 			break;
   1503 
   1504 		case SCSIPI_CAP_DESC_CODE_UNFORMATTED:
   1505 			return (SDGP_RESULT_UNFORMATTED);
   1506 
   1507 		case SCSIPI_CAP_DESC_CODE_NONE:
   1508 			return (SDGP_RESULT_OFFLINE);
   1509 		}
   1510 
   1511 		dp->disksize = blocks = _4btol(data.desc.nblks);
   1512 		if (blocks == 0)
   1513 			return (SDGP_RESULT_OFFLINE);		/* XXX? */
   1514 
   1515 		blksize = _3btol(data.desc.blklen);
   1516 
   1517 	} else if (!sd_validate_blksize(NULL, blksize)) {
   1518 		struct sd_mode_sense_data scsipi_sense;
   1519 		int big, bsize;
   1520 		struct scsi_general_block_descriptor *bdesc;
   1521 
   1522 		memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1523 		error = sd_mode_sense(sd, 0, &scsipi_sense,
   1524 		    sizeof(scsipi_sense.blk_desc), 0, flags | XS_CTL_SILENT, &big);
   1525 		if (!error) {
   1526 			if (big) {
   1527 				bdesc = (void *)(&scsipi_sense.header.big + 1);
   1528 				bsize = _2btol(scsipi_sense.header.big.blk_desc_len);
   1529 			} else {
   1530 				bdesc = (void *)(&scsipi_sense.header.small + 1);
   1531 				bsize = scsipi_sense.header.small.blk_desc_len;
   1532 			}
   1533 
   1534 #if 0
   1535 printf("page 0 sense:"); for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i; i--, p++) printf(" %02x", *p); printf("\n");
   1536 printf("page 0 bsize=%d\n", bsize);
   1537 printf("page 0 ok\n");
   1538 #endif
   1539 
   1540 			if (bsize >= 8) {
   1541 				blksize = _3btol(bdesc->blklen);
   1542 			}
   1543 		}
   1544 	}
   1545 
   1546 	if (!sd_validate_blksize(sd->sc_periph, blksize))
   1547 		blksize = SD_DEFAULT_BLKSIZE;
   1548 
   1549 	dp->blksize = blksize;
   1550 	dp->disksize512 = (blocks * dp->blksize) / DEV_BSIZE;
   1551 	return (0);
   1552 }
   1553 
   1554 static int
   1555 sd_get_parms_page4(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1556 {
   1557 	struct sd_mode_sense_data scsipi_sense;
   1558 	int error;
   1559 	int big, byte2;
   1560 	size_t poffset;
   1561 	union scsi_disk_pages *pages;
   1562 
   1563 	byte2 = SMS_DBD;
   1564 again:
   1565 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1566 	error = sd_mode_sense(sd, byte2, &scsipi_sense,
   1567 	    (byte2 ? 0 : sizeof(scsipi_sense.blk_desc)) +
   1568 	    sizeof(scsipi_sense.pages.rigid_geometry), 4,
   1569 	    flags | XS_CTL_SILENT, &big);
   1570 	if (error) {
   1571 		if (byte2 == SMS_DBD) {
   1572 			/* No result; try once more with DBD off */
   1573 			byte2 = 0;
   1574 			goto again;
   1575 		}
   1576 		return (error);
   1577 	}
   1578 
   1579 	if (big) {
   1580 		poffset = sizeof scsipi_sense.header.big;
   1581 		poffset += _2btol(scsipi_sense.header.big.blk_desc_len);
   1582 	} else {
   1583 		poffset = sizeof scsipi_sense.header.small;
   1584 		poffset += scsipi_sense.header.small.blk_desc_len;
   1585 	}
   1586 
   1587 	if (poffset > sizeof(scsipi_sense) - sizeof(pages->rigid_geometry))
   1588 		return ERESTART;
   1589 
   1590 	pages = (void *)((u_long)&scsipi_sense + poffset);
   1591 #if 0
   1592 	{
   1593 		size_t i;
   1594 		u_int8_t *p;
   1595 
   1596 		printf("page 4 sense:");
   1597 		for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i;
   1598 		    i--, p++)
   1599 			printf(" %02x", *p);
   1600 		printf("\n");
   1601 		printf("page 4 pg_code=%d sense=%p/%p\n",
   1602 		    pages->rigid_geometry.pg_code, &scsipi_sense, pages);
   1603 	}
   1604 #endif
   1605 
   1606 	if ((pages->rigid_geometry.pg_code & PGCODE_MASK) != 4)
   1607 		return (ERESTART);
   1608 
   1609 	SC_DEBUG(sd->sc_periph, SCSIPI_DB3,
   1610 	    ("%d cyls, %d heads, %d precomp, %d red_write, %d land_zone\n",
   1611 	    _3btol(pages->rigid_geometry.ncyl),
   1612 	    pages->rigid_geometry.nheads,
   1613 	    _2btol(pages->rigid_geometry.st_cyl_wp),
   1614 	    _2btol(pages->rigid_geometry.st_cyl_rwc),
   1615 	    _2btol(pages->rigid_geometry.land_zone)));
   1616 
   1617 	/*
   1618 	 * KLUDGE!! (for zone recorded disks)
   1619 	 * give a number of sectors so that sec * trks * cyls
   1620 	 * is <= disk_size
   1621 	 * can lead to wasted space! THINK ABOUT THIS !
   1622 	 */
   1623 	dp->heads = pages->rigid_geometry.nheads;
   1624 	dp->cyls = _3btol(pages->rigid_geometry.ncyl);
   1625 	if (dp->heads == 0 || dp->cyls == 0)
   1626 		return (ERESTART);
   1627 	dp->sectors = dp->disksize / (dp->heads * dp->cyls);	/* XXX */
   1628 
   1629 	dp->rot_rate = _2btol(pages->rigid_geometry.rpm);
   1630 	if (dp->rot_rate == 0)
   1631 		dp->rot_rate = 3600;
   1632 
   1633 #if 0
   1634 printf("page 4 ok\n");
   1635 #endif
   1636 	return (0);
   1637 }
   1638 
   1639 static int
   1640 sd_get_parms_page5(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1641 {
   1642 	struct sd_mode_sense_data scsipi_sense;
   1643 	int error;
   1644 	int big, byte2;
   1645 	size_t poffset;
   1646 	union scsi_disk_pages *pages;
   1647 
   1648 	byte2 = SMS_DBD;
   1649 again:
   1650 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1651 	error = sd_mode_sense(sd, 0, &scsipi_sense,
   1652 	    (byte2 ? 0 : sizeof(scsipi_sense.blk_desc)) +
   1653 	    sizeof(scsipi_sense.pages.flex_geometry), 5,
   1654 	    flags | XS_CTL_SILENT, &big);
   1655 	if (error) {
   1656 		if (byte2 == SMS_DBD) {
   1657 			/* No result; try once more with DBD off */
   1658 			byte2 = 0;
   1659 			goto again;
   1660 		}
   1661 		return (error);
   1662 	}
   1663 
   1664 	if (big) {
   1665 		poffset = sizeof scsipi_sense.header.big;
   1666 		poffset += _2btol(scsipi_sense.header.big.blk_desc_len);
   1667 	} else {
   1668 		poffset = sizeof scsipi_sense.header.small;
   1669 		poffset += scsipi_sense.header.small.blk_desc_len;
   1670 	}
   1671 
   1672 	if (poffset > sizeof(scsipi_sense) - sizeof(pages->flex_geometry))
   1673 		return ERESTART;
   1674 
   1675 	pages = (void *)((u_long)&scsipi_sense + poffset);
   1676 #if 0
   1677 	{
   1678 		size_t i;
   1679 		u_int8_t *p;
   1680 
   1681 		printf("page 5 sense:");
   1682 		for (i = sizeof(scsipi_sense), p = (void *)&scsipi_sense; i;
   1683 		    i--, p++)
   1684 			printf(" %02x", *p);
   1685 		printf("\n");
   1686 		printf("page 5 pg_code=%d sense=%p/%p\n",
   1687 		    pages->flex_geometry.pg_code, &scsipi_sense, pages);
   1688 	}
   1689 #endif
   1690 
   1691 	if ((pages->flex_geometry.pg_code & PGCODE_MASK) != 5)
   1692 		return (ERESTART);
   1693 
   1694 	SC_DEBUG(sd->sc_periph, SCSIPI_DB3,
   1695 	    ("%d cyls, %d heads, %d sec, %d bytes/sec\n",
   1696 	    _3btol(pages->flex_geometry.ncyl),
   1697 	    pages->flex_geometry.nheads,
   1698 	    pages->flex_geometry.ph_sec_tr,
   1699 	    _2btol(pages->flex_geometry.bytes_s)));
   1700 
   1701 	dp->heads = pages->flex_geometry.nheads;
   1702 	dp->cyls = _2btol(pages->flex_geometry.ncyl);
   1703 	dp->sectors = pages->flex_geometry.ph_sec_tr;
   1704 	if (dp->heads == 0 || dp->cyls == 0 || dp->sectors == 0)
   1705 		return (ERESTART);
   1706 
   1707 	dp->rot_rate = _2btol(pages->rigid_geometry.rpm);
   1708 	if (dp->rot_rate == 0)
   1709 		dp->rot_rate = 3600;
   1710 
   1711 #if 0
   1712 printf("page 5 ok\n");
   1713 #endif
   1714 	return (0);
   1715 }
   1716 
   1717 static int
   1718 sd_get_parms(struct sd_softc *sd, struct disk_parms *dp, int flags)
   1719 {
   1720 	struct dk_softc *dksc = &sd->sc_dksc;
   1721 	int error;
   1722 
   1723 	/*
   1724 	 * If offline, the SDEV_MEDIA_LOADED flag will be
   1725 	 * cleared by the caller if necessary.
   1726 	 */
   1727 	if (sd->type == T_SIMPLE_DIRECT) {
   1728 		error = sd_get_simplifiedparms(sd, dp, flags);
   1729 		if (!error)
   1730 			goto setprops;
   1731 		return (error);
   1732 	}
   1733 
   1734 	error = sd_get_capacity(sd, dp, flags);
   1735 	if (error)
   1736 		return (error);
   1737 
   1738 	if (sd->type == T_OPTICAL)
   1739 		goto page0;
   1740 
   1741 	if (sd->sc_periph->periph_flags & PERIPH_REMOVABLE) {
   1742 		if (!sd_get_parms_page5(sd, dp, flags) ||
   1743 		    !sd_get_parms_page4(sd, dp, flags))
   1744 			goto setprops;
   1745 	} else {
   1746 		if (!sd_get_parms_page4(sd, dp, flags) ||
   1747 		    !sd_get_parms_page5(sd, dp, flags))
   1748 			goto setprops;
   1749 	}
   1750 
   1751 page0:
   1752 	printf("%s: fabricating a geometry\n", dksc->sc_xname);
   1753 	/* Try calling driver's method for figuring out geometry. */
   1754 	if (!sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom ||
   1755 	    !(*sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom)
   1756 		(sd->sc_periph, dp, dp->disksize)) {
   1757 		/*
   1758 		 * Use adaptec standard fictitious geometry
   1759 		 * this depends on which controller (e.g. 1542C is
   1760 		 * different. but we have to put SOMETHING here..)
   1761 		 */
   1762 		dp->heads = 64;
   1763 		dp->sectors = 32;
   1764 		dp->cyls = dp->disksize / (64 * 32);
   1765 	}
   1766 	dp->rot_rate = 3600;
   1767 
   1768 setprops:
   1769 	sd_set_geometry(sd);
   1770 
   1771 	return (SDGP_RESULT_OK);
   1772 }
   1773 
   1774 static int
   1775 sd_flush(struct sd_softc *sd, int flags)
   1776 {
   1777 	struct scsipi_periph *periph = sd->sc_periph;
   1778 	struct scsi_synchronize_cache_10 cmd;
   1779 
   1780 	/*
   1781 	 * If the device is SCSI-2, issue a SYNCHRONIZE CACHE.
   1782 	 * We issue with address 0 length 0, which should be
   1783 	 * interpreted by the device as "all remaining blocks
   1784 	 * starting at address 0".  We ignore ILLEGAL REQUEST
   1785 	 * in the event that the command is not supported by
   1786 	 * the device, and poll for completion so that we know
   1787 	 * that the cache has actually been flushed.
   1788 	 *
   1789 	 * Unless, that is, the device can't handle the SYNCHRONIZE CACHE
   1790 	 * command, as indicated by our quirks flags.
   1791 	 *
   1792 	 * XXX What about older devices?
   1793 	 */
   1794 	if (periph->periph_version < 2 ||
   1795 	    (periph->periph_quirks & PQUIRK_NOSYNCCACHE))
   1796 		return (0);
   1797 
   1798 	sd->flags |= SDF_FLUSHING;
   1799 	memset(&cmd, 0, sizeof(cmd));
   1800 	cmd.opcode = SCSI_SYNCHRONIZE_CACHE_10;
   1801 
   1802 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
   1803 	    SDRETRIES, 100000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
   1804 }
   1805 
   1806 static int
   1807 sd_getcache(struct sd_softc *sd, int *bitsp)
   1808 {
   1809 	struct scsipi_periph *periph = sd->sc_periph;
   1810 	struct sd_mode_sense_data scsipi_sense;
   1811 	int error, bits = 0;
   1812 	int big;
   1813 	union scsi_disk_pages *pages;
   1814 	uint8_t dev_spec;
   1815 
   1816 	/* only SCSI-2 and later supported */
   1817 	if (periph->periph_version < 2)
   1818 		return (EOPNOTSUPP);
   1819 
   1820 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1821 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
   1822 	    sizeof(scsipi_sense.pages.caching_params), 8, XS_CTL_SILENT, &big);
   1823 	if (error)
   1824 		return (error);
   1825 
   1826 	if (big) {
   1827 		pages = (void *)(&scsipi_sense.header.big + 1);
   1828 		dev_spec = scsipi_sense.header.big.dev_spec;
   1829 	} else {
   1830 		pages = (void *)(&scsipi_sense.header.small + 1);
   1831 		dev_spec = scsipi_sense.header.small.dev_spec;
   1832 	}
   1833 
   1834 	if ((pages->caching_params.flags & CACHING_RCD) == 0)
   1835 		bits |= DKCACHE_READ;
   1836 	if (pages->caching_params.flags & CACHING_WCE)
   1837 		bits |= DKCACHE_WRITE;
   1838 	if (pages->caching_params.pg_code & PGCODE_PS)
   1839 		bits |= DKCACHE_SAVE;
   1840 
   1841 	/*
   1842 	 * Support for FUA/DPO, defined starting with SCSI-2. Use only
   1843 	 * if device claims to support it, according to the MODE SENSE.
   1844 	 */
   1845 	if (!(periph->periph_quirks & PQUIRK_NOFUA) &&
   1846 	    ISSET(dev_spec, SMH_DSP_DPOFUA))
   1847 		bits |= DKCACHE_FUA | DKCACHE_DPO;
   1848 
   1849 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1850 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
   1851 	    sizeof(scsipi_sense.pages.caching_params),
   1852 	    SMS_PCTRL_CHANGEABLE|8, XS_CTL_SILENT, &big);
   1853 	if (error == 0) {
   1854 		if (big)
   1855 			pages = (void *)(&scsipi_sense.header.big + 1);
   1856 		else
   1857 			pages = (void *)(&scsipi_sense.header.small + 1);
   1858 
   1859 		if (pages->caching_params.flags & CACHING_RCD)
   1860 			bits |= DKCACHE_RCHANGE;
   1861 		if (pages->caching_params.flags & CACHING_WCE)
   1862 			bits |= DKCACHE_WCHANGE;
   1863 	}
   1864 
   1865 	*bitsp = bits;
   1866 
   1867 	return (0);
   1868 }
   1869 
   1870 static int
   1871 sd_setcache(struct sd_softc *sd, int bits)
   1872 {
   1873 	struct scsipi_periph *periph = sd->sc_periph;
   1874 	struct sd_mode_sense_data scsipi_sense;
   1875 	int error;
   1876 	uint8_t oflags, byte2 = 0;
   1877 	int big;
   1878 	union scsi_disk_pages *pages;
   1879 
   1880 	if (periph->periph_version < 2)
   1881 		return (EOPNOTSUPP);
   1882 
   1883 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
   1884 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
   1885 	    sizeof(scsipi_sense.pages.caching_params), 8, 0, &big);
   1886 	if (error)
   1887 		return (error);
   1888 
   1889 	if (big)
   1890 		pages = (void *)(&scsipi_sense.header.big + 1);
   1891 	else
   1892 		pages = (void *)(&scsipi_sense.header.small + 1);
   1893 
   1894 	oflags = pages->caching_params.flags;
   1895 
   1896 	if (bits & DKCACHE_READ)
   1897 		pages->caching_params.flags &= ~CACHING_RCD;
   1898 	else
   1899 		pages->caching_params.flags |= CACHING_RCD;
   1900 
   1901 	if (bits & DKCACHE_WRITE)
   1902 		pages->caching_params.flags |= CACHING_WCE;
   1903 	else
   1904 		pages->caching_params.flags &= ~CACHING_WCE;
   1905 
   1906 	if (oflags == pages->caching_params.flags)
   1907 		return (0);
   1908 
   1909 	pages->caching_params.pg_code &= PGCODE_MASK;
   1910 
   1911 	if (bits & DKCACHE_SAVE)
   1912 		byte2 |= SMS_SP;
   1913 
   1914 	return (sd_mode_select(sd, byte2|SMS_PF, &scsipi_sense,
   1915 	    sizeof(struct scsi_mode_page_header) +
   1916 	    pages->caching_params.pg_length, 0, big));
   1917 }
   1918 
   1919 static void
   1920 sd_set_geometry(struct sd_softc *sd)
   1921 {
   1922 	struct dk_softc *dksc = &sd->sc_dksc;
   1923 	struct disk_geom *dg = &dksc->sc_dkdev.dk_geom;
   1924 
   1925 	memset(dg, 0, sizeof(*dg));
   1926 
   1927 	dg->dg_secperunit = sd->params.disksize;
   1928 	dg->dg_secsize = sd->params.blksize;
   1929 	dg->dg_nsectors = sd->params.sectors;
   1930 	dg->dg_ntracks = sd->params.heads;
   1931 	dg->dg_ncylinders = sd->params.cyls;
   1932 
   1933 	disk_set_info(dksc->sc_dev, &dksc->sc_dkdev, sd->typename);
   1934 }
   1935