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