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