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