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