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