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