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