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