xref: /netbsd-src/sys/dev/scsipi/sd.c (revision e1e74f372d4580af0ad34c25f04bfd9fa29bb82c)
1 /*	$NetBSD: sd.c,v 1.271 2008/02/29 06:42:35 dyoung Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 2003, 2004 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Charles M. Hannum.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*
40  * Originally written by Julian Elischer (julian@dialix.oz.au)
41  * for TRW Financial Systems for use under the MACH(2.5) operating system.
42  *
43  * TRW Financial Systems, in accordance with their agreement with Carnegie
44  * Mellon University, makes this software available to CMU to distribute
45  * or use in any manner that they see fit as long as this message is kept with
46  * the software. For this reason TFS also grants any other persons or
47  * organisations permission to use or modify this software.
48  *
49  * TFS supplies this software to be publicly redistributed
50  * on the understanding that TFS is not responsible for the correct
51  * functioning of this software in any circumstances.
52  *
53  * Ported to run under 386BSD by Julian Elischer (julian@dialix.oz.au) Sept 1992
54  */
55 
56 #include <sys/cdefs.h>
57 __KERNEL_RCSID(0, "$NetBSD: sd.c,v 1.271 2008/02/29 06:42:35 dyoung Exp $");
58 
59 #include "opt_scsi.h"
60 #include "rnd.h"
61 
62 #include <sys/param.h>
63 #include <sys/systm.h>
64 #include <sys/kernel.h>
65 #include <sys/file.h>
66 #include <sys/stat.h>
67 #include <sys/ioctl.h>
68 #include <sys/scsiio.h>
69 #include <sys/buf.h>
70 #include <sys/bufq.h>
71 #include <sys/uio.h>
72 #include <sys/malloc.h>
73 #include <sys/errno.h>
74 #include <sys/device.h>
75 #include <sys/disklabel.h>
76 #include <sys/disk.h>
77 #include <sys/proc.h>
78 #include <sys/conf.h>
79 #include <sys/vnode.h>
80 #if NRND > 0
81 #include <sys/rnd.h>
82 #endif
83 
84 #include <dev/scsipi/scsi_spc.h>
85 #include <dev/scsipi/scsipi_all.h>
86 #include <dev/scsipi/scsi_all.h>
87 #include <dev/scsipi/scsipi_disk.h>
88 #include <dev/scsipi/scsi_disk.h>
89 #include <dev/scsipi/scsiconf.h>
90 #include <dev/scsipi/scsipi_base.h>
91 #include <dev/scsipi/sdvar.h>
92 
93 #include <prop/proplib.h>
94 
95 #define	SDUNIT(dev)			DISKUNIT(dev)
96 #define	SDPART(dev)			DISKPART(dev)
97 #define	SDMINOR(unit, part)		DISKMINOR(unit, part)
98 #define	MAKESDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
99 
100 #define	SDLABELDEV(dev)	(MAKESDDEV(major(dev), SDUNIT(dev), RAW_PART))
101 
102 #define	SD_DEFAULT_BLKSIZE	512
103 
104 static void	sdminphys(struct buf *);
105 static void	sdgetdefaultlabel(struct sd_softc *, struct disklabel *);
106 static int	sdgetdisklabel(struct sd_softc *);
107 static void	sdstart(struct scsipi_periph *);
108 static void	sdrestart(void *);
109 static void	sddone(struct scsipi_xfer *, int);
110 static bool	sd_suspend(device_t PMF_FN_PROTO);
111 static void	sd_shutdown(void *);
112 static int	sd_interpret_sense(struct scsipi_xfer *);
113 
114 static int	sd_mode_sense(struct sd_softc *, u_int8_t, void *, size_t, int,
115 		    int, int *);
116 static int	sd_mode_select(struct sd_softc *, u_int8_t, void *, size_t, int,
117 		    int);
118 static int	sd_validate_blksize(struct scsipi_periph *, int);
119 static u_int64_t sd_read_capacity(struct scsipi_periph *, int *, int flags);
120 static int	sd_get_simplifiedparms(struct sd_softc *, struct disk_parms *,
121 		    int);
122 static int	sd_get_capacity(struct sd_softc *, struct disk_parms *, int);
123 static int	sd_get_parms(struct sd_softc *, struct disk_parms *, int);
124 static int	sd_get_parms_page4(struct sd_softc *, struct disk_parms *,
125 		    int);
126 static int	sd_get_parms_page5(struct sd_softc *, struct disk_parms *,
127 		    int);
128 
129 static int	sd_flush(struct sd_softc *, int);
130 static int	sd_getcache(struct sd_softc *, int *);
131 static int	sd_setcache(struct sd_softc *, int);
132 
133 static int	sdmatch(struct device *, struct cfdata *, void *);
134 static void	sdattach(struct device *, struct device *, void *);
135 static int	sdactivate(struct device *, enum devact);
136 static int	sddetach(struct device *, int);
137 static void	sd_set_properties(struct sd_softc *);
138 
139 CFATTACH_DECL(sd, sizeof(struct sd_softc), sdmatch, sdattach, sddetach,
140     sdactivate);
141 
142 extern struct cfdriver sd_cd;
143 
144 static const struct scsipi_inquiry_pattern sd_patterns[] = {
145 	{T_DIRECT, T_FIXED,
146 	 "",         "",                 ""},
147 	{T_DIRECT, T_REMOV,
148 	 "",         "",                 ""},
149 	{T_OPTICAL, T_FIXED,
150 	 "",         "",                 ""},
151 	{T_OPTICAL, T_REMOV,
152 	 "",         "",                 ""},
153 	{T_SIMPLE_DIRECT, T_FIXED,
154 	 "",         "",                 ""},
155 	{T_SIMPLE_DIRECT, T_REMOV,
156 	 "",         "",                 ""},
157 };
158 
159 static dev_type_open(sdopen);
160 static dev_type_close(sdclose);
161 static dev_type_read(sdread);
162 static dev_type_write(sdwrite);
163 static dev_type_ioctl(sdioctl);
164 static dev_type_strategy(sdstrategy);
165 static dev_type_dump(sddump);
166 static dev_type_size(sdsize);
167 
168 const struct bdevsw sd_bdevsw = {
169 	sdopen, sdclose, sdstrategy, sdioctl, sddump, sdsize, D_DISK
170 };
171 
172 const struct cdevsw sd_cdevsw = {
173 	sdopen, sdclose, sdread, sdwrite, sdioctl,
174 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
175 };
176 
177 static struct dkdriver sddkdriver = { sdstrategy, sdminphys };
178 
179 static const struct scsipi_periphsw sd_switch = {
180 	sd_interpret_sense,	/* check our error handler first */
181 	sdstart,		/* have a queue, served by this */
182 	NULL,			/* have no async handler */
183 	sddone,			/* deal with stats at interrupt time */
184 };
185 
186 struct sd_mode_sense_data {
187 	/*
188 	 * XXX
189 	 * We are not going to parse this as-is -- it just has to be large
190 	 * enough.
191 	 */
192 	union {
193 		struct scsi_mode_parameter_header_6 small;
194 		struct scsi_mode_parameter_header_10 big;
195 	} header;
196 	struct scsi_general_block_descriptor blk_desc;
197 	union scsi_disk_pages pages;
198 };
199 
200 /*
201  * The routine called by the low level scsi routine when it discovers
202  * A device suitable for this driver
203  */
204 static int
205 sdmatch(struct device *parent, struct cfdata *match,
206     void *aux)
207 {
208 	struct scsipibus_attach_args *sa = aux;
209 	int priority;
210 
211 	(void)scsipi_inqmatch(&sa->sa_inqbuf,
212 	    sd_patterns, sizeof(sd_patterns) / sizeof(sd_patterns[0]),
213 	    sizeof(sd_patterns[0]), &priority);
214 
215 	return (priority);
216 }
217 
218 /*
219  * Attach routine common to atapi & scsi.
220  */
221 static void
222 sdattach(struct device *parent, struct device *self, void *aux)
223 {
224 	struct sd_softc *sd = device_private(self);
225 	struct scsipibus_attach_args *sa = aux;
226 	struct scsipi_periph *periph = sa->sa_periph;
227 	int error, result;
228 	struct disk_parms *dp = &sd->params;
229 	char pbuf[9];
230 
231 	SC_DEBUG(periph, SCSIPI_DB2, ("sdattach: "));
232 
233 	sd->type = (sa->sa_inqbuf.type & SID_TYPE);
234 	strncpy(sd->name, sa->sa_inqbuf.product, sizeof(sd->name));
235 	if (sd->type == T_SIMPLE_DIRECT)
236 		periph->periph_quirks |= PQUIRK_ONLYBIG | PQUIRK_NOBIGMODESENSE;
237 
238 	if (scsipi_periph_bustype(sa->sa_periph) == SCSIPI_BUSTYPE_SCSI &&
239 	    periph->periph_version == 0)
240 		sd->flags |= SDF_ANCIENT;
241 
242 	bufq_alloc(&sd->buf_queue, BUFQ_DISK_DEFAULT_STRAT, BUFQ_SORT_RAWBLOCK);
243 
244 	callout_init(&sd->sc_callout, 0);
245 
246 	/*
247 	 * Store information needed to contact our base driver
248 	 */
249 	sd->sc_periph = periph;
250 
251 	periph->periph_dev = &sd->sc_dev;
252 	periph->periph_switch = &sd_switch;
253 
254         /*
255          * Increase our openings to the maximum-per-periph
256          * supported by the adapter.  This will either be
257          * clamped down or grown by the adapter if necessary.
258          */
259 	periph->periph_openings =
260 	    SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
261 	periph->periph_flags |= PERIPH_GROW_OPENINGS;
262 
263 	/*
264 	 * Initialize and attach the disk structure.
265 	 */
266 	disk_init(&sd->sc_dk, sd->sc_dev.dv_xname, &sddkdriver);
267 	disk_attach(&sd->sc_dk);
268 
269 	/*
270 	 * Use the subdriver to request information regarding the drive.
271 	 */
272 	aprint_naive("\n");
273 	aprint_normal("\n");
274 
275 	error = scsipi_test_unit_ready(periph,
276 	    XS_CTL_DISCOVERY | XS_CTL_IGNORE_ILLEGAL_REQUEST |
277 	    XS_CTL_IGNORE_MEDIA_CHANGE | XS_CTL_SILENT_NODEV);
278 
279 	if (error)
280 		result = SDGP_RESULT_OFFLINE;
281 	else
282 		result = sd_get_parms(sd, &sd->params, XS_CTL_DISCOVERY);
283 	aprint_normal("%s: ", sd->sc_dev.dv_xname);
284 	switch (result) {
285 	case SDGP_RESULT_OK:
286 		format_bytes(pbuf, sizeof(pbuf),
287 		    (u_int64_t)dp->disksize * dp->blksize);
288 	        aprint_normal(
289 		"%s, %ld cyl, %ld head, %ld sec, %ld bytes/sect x %llu sectors",
290 		    pbuf, dp->cyls, dp->heads, dp->sectors, dp->blksize,
291 		    (unsigned long long)dp->disksize);
292 		break;
293 
294 	case SDGP_RESULT_OFFLINE:
295 		aprint_normal("drive offline");
296 		break;
297 
298 	case SDGP_RESULT_UNFORMATTED:
299 		aprint_normal("unformatted media");
300 		break;
301 
302 #ifdef DIAGNOSTIC
303 	default:
304 		panic("sdattach: unknown result from get_parms");
305 		break;
306 #endif
307 	}
308 	aprint_normal("\n");
309 
310 	/*
311 	 * Establish a shutdown hook so that we can ensure that
312 	 * our data has actually made it onto the platter at
313 	 * shutdown time.  Note that this relies on the fact
314 	 * that the shutdown hook code puts us at the head of
315 	 * the list (thus guaranteeing that our hook runs before
316 	 * our ancestors').
317 	 */
318 	if ((sd->sc_sdhook =
319 	    shutdownhook_establish(sd_shutdown, sd)) == NULL)
320 		aprint_error("%s: WARNING: unable to establish shutdown hook\n",
321 			sd->sc_dev.dv_xname);
322 
323 	if (!pmf_device_register(self, sd_suspend, NULL))
324 		aprint_error_dev(self, "couldn't establish power handler\n");
325 
326 #if NRND > 0
327 	/*
328 	 * attach the device into the random source list
329 	 */
330 	rnd_attach_source(&sd->rnd_source, sd->sc_dev.dv_xname,
331 			  RND_TYPE_DISK, 0);
332 #endif
333 
334 	/* Discover wedges on this disk. */
335 	dkwedge_discover(&sd->sc_dk);
336 
337 	sd_set_properties(sd);
338 }
339 
340 static int
341 sdactivate(struct device *self, enum devact act)
342 {
343 	int rv = 0;
344 
345 	switch (act) {
346 	case DVACT_ACTIVATE:
347 		rv = EOPNOTSUPP;
348 		break;
349 
350 	case DVACT_DEACTIVATE:
351 		/*
352 		 * Nothing to do; we key off the device's DVF_ACTIVE.
353 		 */
354 		break;
355 	}
356 	return (rv);
357 }
358 
359 static int
360 sddetach(struct device *self, int flags)
361 {
362 	struct sd_softc *sd = device_private(self);
363 	int s, bmaj, cmaj, i, mn;
364 
365 	/* locate the major number */
366 	bmaj = bdevsw_lookup_major(&sd_bdevsw);
367 	cmaj = cdevsw_lookup_major(&sd_cdevsw);
368 
369 	/* Nuke the vnodes for any open instances */
370 	for (i = 0; i < MAXPARTITIONS; i++) {
371 		mn = SDMINOR(device_unit(self), i);
372 		vdevgone(bmaj, mn, mn, VBLK);
373 		vdevgone(cmaj, mn, mn, VCHR);
374 	}
375 
376 	/* kill any pending restart */
377 	callout_stop(&sd->sc_callout);
378 
379 	/* Delete all of our wedges. */
380 	dkwedge_delall(&sd->sc_dk);
381 
382 	s = splbio();
383 
384 	/* Kill off any queued buffers. */
385 	bufq_drain(sd->buf_queue);
386 
387 	bufq_free(sd->buf_queue);
388 
389 	/* Kill off any pending commands. */
390 	scsipi_kill_pending(sd->sc_periph);
391 
392 	splx(s);
393 
394 	/* Detach from the disk list. */
395 	disk_detach(&sd->sc_dk);
396 	disk_destroy(&sd->sc_dk);
397 
398 	pmf_device_deregister(self);
399 	shutdownhook_disestablish(sd->sc_sdhook);
400 
401 #if NRND > 0
402 	/* Unhook the entropy source. */
403 	rnd_detach_source(&sd->rnd_source);
404 #endif
405 
406 	return (0);
407 }
408 
409 /*
410  * open the device. Make sure the partition info is a up-to-date as can be.
411  */
412 static int
413 sdopen(dev_t dev, int flag, int fmt, struct lwp *l)
414 {
415 	struct sd_softc *sd;
416 	struct scsipi_periph *periph;
417 	struct scsipi_adapter *adapt;
418 	int unit, part;
419 	int error;
420 
421 	unit = SDUNIT(dev);
422 	if (unit >= sd_cd.cd_ndevs)
423 		return (ENXIO);
424 	sd = sd_cd.cd_devs[unit];
425 	if (sd == NULL)
426 		return (ENXIO);
427 
428 	if (!device_is_active(&sd->sc_dev))
429 		return (ENODEV);
430 
431 	part = SDPART(dev);
432 
433 	mutex_enter(&sd->sc_dk.dk_openlock);
434 
435 	/*
436 	 * If there are wedges, and this is not RAW_PART, then we
437 	 * need to fail.
438 	 */
439 	if (sd->sc_dk.dk_nwedges != 0 && part != RAW_PART) {
440 		error = EBUSY;
441 		goto bad1;
442 	}
443 
444 	periph = sd->sc_periph;
445 	adapt = periph->periph_channel->chan_adapter;
446 
447 	SC_DEBUG(periph, SCSIPI_DB1,
448 	    ("sdopen: dev=0x%x (unit %d (of %d), partition %d)\n", dev, unit,
449 	    sd_cd.cd_ndevs, part));
450 
451 	/*
452 	 * If this is the first open of this device, add a reference
453 	 * to the adapter.
454 	 */
455 	if (sd->sc_dk.dk_openmask == 0 &&
456 	    (error = scsipi_adapter_addref(adapt)) != 0)
457 		goto bad1;
458 
459 	if ((periph->periph_flags & PERIPH_OPEN) != 0) {
460 		/*
461 		 * If any partition is open, but the disk has been invalidated,
462 		 * disallow further opens of non-raw partition
463 		 */
464 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
465 		    (part != RAW_PART || fmt != S_IFCHR)) {
466 			error = EIO;
467 			goto bad2;
468 		}
469 	} else {
470 		int silent;
471 
472 		if (part == RAW_PART && fmt == S_IFCHR)
473 			silent = XS_CTL_SILENT;
474 		else
475 			silent = 0;
476 
477 		/* Check that it is still responding and ok. */
478 		error = scsipi_test_unit_ready(periph,
479 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
480 		    silent);
481 
482 		/*
483 		 * Start the pack spinning if necessary. Always allow the
484 		 * raw parition to be opened, for raw IOCTLs. Data transfers
485 		 * will check for SDEV_MEDIA_LOADED.
486 		 */
487 		if (error == EIO) {
488 			int error2;
489 
490 			error2 = scsipi_start(periph, SSS_START, silent);
491 			switch (error2) {
492 			case 0:
493 				error = 0;
494 				break;
495 			case EIO:
496 			case EINVAL:
497 				break;
498 			default:
499 				error = error2;
500 				break;
501 			}
502 		}
503 		if (error) {
504 			if (silent)
505 				goto out;
506 			goto bad2;
507 		}
508 
509 		periph->periph_flags |= PERIPH_OPEN;
510 
511 		if (periph->periph_flags & PERIPH_REMOVABLE) {
512 			/* Lock the pack in. */
513 			error = scsipi_prevent(periph, SPAMR_PREVENT_DT,
514 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
515 			    XS_CTL_IGNORE_MEDIA_CHANGE |
516 			    XS_CTL_SILENT);
517 			if (error)
518 				goto bad3;
519 		}
520 
521 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
522 			int param_error;
523 			periph->periph_flags |= PERIPH_MEDIA_LOADED;
524 
525 			/*
526 			 * Load the physical device parameters.
527 			 *
528 			 * Note that if media is present but unformatted,
529 			 * we allow the open (so that it can be formatted!).
530 			 * The drive should refuse real I/O, if the media is
531 			 * unformatted.
532 			 */
533 			if ((param_error = sd_get_parms(sd, &sd->params, 0))
534 			     == SDGP_RESULT_OFFLINE) {
535 				error = ENXIO;
536 				periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
537 				goto bad3;
538 			}
539 			SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));
540 
541 			/* Load the partition info if not already loaded. */
542 			if (param_error == 0) {
543 				if ((sdgetdisklabel(sd) != 0) && (part != RAW_PART)) {
544 					error = EIO;
545 					goto bad3;
546 				}
547 				SC_DEBUG(periph, SCSIPI_DB3,
548 				     ("Disklabel loaded "));
549 			}
550 		}
551 	}
552 
553 	/* Check that the partition exists. */
554 	if (part != RAW_PART &&
555 	    (part >= sd->sc_dk.dk_label->d_npartitions ||
556 	     sd->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
557 		error = ENXIO;
558 		goto bad3;
559 	}
560 
561  out:	/* Insure only one open at a time. */
562 	switch (fmt) {
563 	case S_IFCHR:
564 		sd->sc_dk.dk_copenmask |= (1 << part);
565 		break;
566 	case S_IFBLK:
567 		sd->sc_dk.dk_bopenmask |= (1 << part);
568 		break;
569 	}
570 	sd->sc_dk.dk_openmask =
571 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
572 
573 	SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));
574 	mutex_exit(&sd->sc_dk.dk_openlock);
575 	return (0);
576 
577  bad3:
578 	if (sd->sc_dk.dk_openmask == 0) {
579 		if (periph->periph_flags & PERIPH_REMOVABLE)
580 			scsipi_prevent(periph, SPAMR_ALLOW,
581 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
582 			    XS_CTL_IGNORE_MEDIA_CHANGE |
583 			    XS_CTL_SILENT);
584 		periph->periph_flags &= ~PERIPH_OPEN;
585 	}
586 
587  bad2:
588 	if (sd->sc_dk.dk_openmask == 0)
589 		scsipi_adapter_delref(adapt);
590 
591  bad1:
592 	mutex_exit(&sd->sc_dk.dk_openlock);
593 	return (error);
594 }
595 
596 /*
597  * close the device.. only called if we are the LAST occurence of an open
598  * device.  Convenient now but usually a pain.
599  */
600 static int
601 sdclose(dev_t dev, int flag, int fmt, struct lwp *l)
602 {
603 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
604 	struct scsipi_periph *periph = sd->sc_periph;
605 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
606 	int part = SDPART(dev);
607 
608 	mutex_enter(&sd->sc_dk.dk_openlock);
609 	switch (fmt) {
610 	case S_IFCHR:
611 		sd->sc_dk.dk_copenmask &= ~(1 << part);
612 		break;
613 	case S_IFBLK:
614 		sd->sc_dk.dk_bopenmask &= ~(1 << part);
615 		break;
616 	}
617 	sd->sc_dk.dk_openmask =
618 	    sd->sc_dk.dk_copenmask | sd->sc_dk.dk_bopenmask;
619 
620 	if (sd->sc_dk.dk_openmask == 0) {
621 		/*
622 		 * If the disk cache needs flushing, and the disk supports
623 		 * it, do it now.
624 		 */
625 		if ((sd->flags & SDF_DIRTY) != 0) {
626 			if (sd_flush(sd, 0)) {
627 				printf("%s: cache synchronization failed\n",
628 				    sd->sc_dev.dv_xname);
629 				sd->flags &= ~SDF_FLUSHING;
630 			} else
631 				sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
632 		}
633 
634 		scsipi_wait_drain(periph);
635 
636 		if (periph->periph_flags & PERIPH_REMOVABLE)
637 			scsipi_prevent(periph, SPAMR_ALLOW,
638 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
639 			    XS_CTL_IGNORE_NOT_READY |
640 			    XS_CTL_SILENT);
641 		periph->periph_flags &= ~PERIPH_OPEN;
642 
643 		scsipi_wait_drain(periph);
644 
645 		scsipi_adapter_delref(adapt);
646 	}
647 
648 	mutex_exit(&sd->sc_dk.dk_openlock);
649 	return (0);
650 }
651 
652 /*
653  * Actually translate the requested transfer into one the physical driver
654  * can understand.  The transfer is described by a buf and will include
655  * only one physical transfer.
656  */
657 static void
658 sdstrategy(struct buf *bp)
659 {
660 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
661 	struct scsipi_periph *periph = sd->sc_periph;
662 	struct disklabel *lp;
663 	daddr_t blkno;
664 	int s;
665 	bool sector_aligned;
666 
667 	SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdstrategy "));
668 	SC_DEBUG(sd->sc_periph, SCSIPI_DB1,
669 	    ("%d bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));
670 	/*
671 	 * If the device has been made invalid, error out
672 	 */
673 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 ||
674 	    !device_is_active(&sd->sc_dev)) {
675 		if (periph->periph_flags & PERIPH_OPEN)
676 			bp->b_error = EIO;
677 		else
678 			bp->b_error = ENODEV;
679 		goto done;
680 	}
681 
682 	lp = sd->sc_dk.dk_label;
683 
684 	/*
685 	 * The transfer must be a whole number of blocks, offset must not be
686 	 * negative.
687 	 */
688 	if (lp->d_secsize == DEV_BSIZE) {
689 		sector_aligned = (bp->b_bcount & (DEV_BSIZE - 1)) == 0;
690 	} else {
691 		sector_aligned = (bp->b_bcount % lp->d_secsize) == 0;
692 	}
693 	if (!sector_aligned || bp->b_blkno < 0) {
694 		bp->b_error = EINVAL;
695 		goto done;
696 	}
697 	/*
698 	 * If it's a null transfer, return immediatly
699 	 */
700 	if (bp->b_bcount == 0)
701 		goto done;
702 
703 	/*
704 	 * Do bounds checking, adjust transfer. if error, process.
705 	 * If end of partition, just return.
706 	 */
707 	if (SDPART(bp->b_dev) == RAW_PART) {
708 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
709 		    sd->params.disksize512) <= 0)
710 			goto done;
711 	} else {
712 		if (bounds_check_with_label(&sd->sc_dk, bp,
713 		    (sd->flags & (SDF_WLABEL|SDF_LABELLING)) != 0) <= 0)
714 			goto done;
715 	}
716 
717 	/*
718 	 * Now convert the block number to absolute and put it in
719 	 * terms of the device's logical block size.
720 	 */
721 	if (lp->d_secsize == DEV_BSIZE)
722 		blkno = bp->b_blkno;
723 	else if (lp->d_secsize > DEV_BSIZE)
724 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
725 	else
726 		blkno = bp->b_blkno * (DEV_BSIZE / lp->d_secsize);
727 
728 	if (SDPART(bp->b_dev) != RAW_PART)
729 		blkno += lp->d_partitions[SDPART(bp->b_dev)].p_offset;
730 
731 	bp->b_rawblkno = blkno;
732 
733 	s = splbio();
734 
735 	/*
736 	 * Place it in the queue of disk activities for this disk.
737 	 *
738 	 * XXX Only do disksort() if the current operating mode does not
739 	 * XXX include tagged queueing.
740 	 */
741 	BUFQ_PUT(sd->buf_queue, bp);
742 
743 	/*
744 	 * Tell the device to get going on the transfer if it's
745 	 * not doing anything, otherwise just wait for completion
746 	 */
747 	sdstart(sd->sc_periph);
748 
749 	splx(s);
750 	return;
751 
752 done:
753 	/*
754 	 * Correctly set the buf to indicate a completed xfer
755 	 */
756 	bp->b_resid = bp->b_bcount;
757 	biodone(bp);
758 }
759 
760 /*
761  * sdstart looks to see if there is a buf waiting for the device
762  * and that the device is not already busy. If both are true,
763  * It dequeues the buf and creates a scsi command to perform the
764  * transfer in the buf. The transfer request will call scsipi_done
765  * on completion, which will in turn call this routine again
766  * so that the next queued transfer is performed.
767  * The bufs are queued by the strategy routine (sdstrategy)
768  *
769  * This routine is also called after other non-queued requests
770  * have been made of the scsi driver, to ensure that the queue
771  * continues to be drained.
772  *
773  * must be called at the correct (highish) spl level
774  * sdstart() is called at splbio from sdstrategy, sdrestart and scsipi_done
775  */
776 static void
777 sdstart(struct scsipi_periph *periph)
778 {
779 	struct sd_softc *sd = (void *)periph->periph_dev;
780 	struct disklabel *lp = sd->sc_dk.dk_label;
781 	struct buf *bp = 0;
782 	struct scsipi_rw_16 cmd16;
783 	struct scsipi_rw_10 cmd_big;
784 	struct scsi_rw_6 cmd_small;
785 	struct scsipi_generic *cmdp;
786 	struct scsipi_xfer *xs;
787 	int nblks, cmdlen, error, flags;
788 
789 	SC_DEBUG(periph, SCSIPI_DB2, ("sdstart "));
790 	/*
791 	 * Check if the device has room for another command
792 	 */
793 	while (periph->periph_active < periph->periph_openings) {
794 		/*
795 		 * there is excess capacity, but a special waits
796 		 * It'll need the adapter as soon as we clear out of the
797 		 * way and let it run (user level wait).
798 		 */
799 		if (periph->periph_flags & PERIPH_WAITING) {
800 			periph->periph_flags &= ~PERIPH_WAITING;
801 			wakeup((void *)periph);
802 			return;
803 		}
804 
805 		/*
806 		 * If the device has become invalid, abort all the
807 		 * reads and writes until all files have been closed and
808 		 * re-opened
809 		 */
810 		if (__predict_false(
811 		    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
812 			if ((bp = BUFQ_GET(sd->buf_queue)) != NULL) {
813 				bp->b_error = EIO;
814 				bp->b_resid = bp->b_bcount;
815 				biodone(bp);
816 				continue;
817 			} else {
818 				return;
819 			}
820 		}
821 
822 		/*
823 		 * See if there is a buf with work for us to do..
824 		 */
825 		if ((bp = BUFQ_PEEK(sd->buf_queue)) == NULL)
826 			return;
827 
828 		/*
829 		 * We have a buf, now we should make a command.
830 		 */
831 
832 		if (lp->d_secsize == DEV_BSIZE)
833 			nblks = bp->b_bcount >> DEV_BSHIFT;
834 		else
835 			nblks = howmany(bp->b_bcount, lp->d_secsize);
836 
837 		/*
838 		 * Fill out the scsi command.  Use the smallest CDB possible
839 		 * (6-byte, 10-byte, or 16-byte).
840 		 */
841 		if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
842 		    ((nblks & 0xff) == nblks) &&
843 		    !(periph->periph_quirks & PQUIRK_ONLYBIG)) {
844 			/* 6-byte CDB */
845 			memset(&cmd_small, 0, sizeof(cmd_small));
846 			cmd_small.opcode = (bp->b_flags & B_READ) ?
847 			    SCSI_READ_6_COMMAND : SCSI_WRITE_6_COMMAND;
848 			_lto3b(bp->b_rawblkno, cmd_small.addr);
849 			cmd_small.length = nblks & 0xff;
850 			cmdlen = sizeof(cmd_small);
851 			cmdp = (struct scsipi_generic *)&cmd_small;
852 		} else if ((bp->b_rawblkno & 0xffffffff) == bp->b_rawblkno) {
853 			/* 10-byte CDB */
854 			memset(&cmd_big, 0, sizeof(cmd_big));
855 			cmd_big.opcode = (bp->b_flags & B_READ) ?
856 			    READ_10 : WRITE_10;
857 			_lto4b(bp->b_rawblkno, cmd_big.addr);
858 			_lto2b(nblks, cmd_big.length);
859 			cmdlen = sizeof(cmd_big);
860 			cmdp = (struct scsipi_generic *)&cmd_big;
861 		} else {
862 			/* 16-byte CDB */
863 			memset(&cmd16, 0, sizeof(cmd16));
864 			cmd16.opcode = (bp->b_flags & B_READ) ?
865 			    READ_16 : WRITE_16;
866 			_lto8b(bp->b_rawblkno, cmd16.addr);
867 			_lto4b(nblks, cmd16.length);
868 			cmdlen = sizeof(cmd16);
869 			cmdp = (struct scsipi_generic *)&cmd16;
870 		}
871 
872 		/* Instrumentation. */
873 		disk_busy(&sd->sc_dk);
874 
875 		/*
876 		 * Mark the disk dirty so that the cache will be
877 		 * flushed on close.
878 		 */
879 		if ((bp->b_flags & B_READ) == 0)
880 			sd->flags |= SDF_DIRTY;
881 
882 		/*
883 		 * Figure out what flags to use.
884 		 */
885 		flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
886 		if (bp->b_flags & B_READ)
887 			flags |= XS_CTL_DATA_IN;
888 		else
889 			flags |= XS_CTL_DATA_OUT;
890 
891 		/*
892 		 * Call the routine that chats with the adapter.
893 		 * Note: we cannot sleep as we may be an interrupt
894 		 */
895 		xs = scsipi_make_xs(periph, cmdp, cmdlen,
896 		    (u_char *)bp->b_data, bp->b_bcount,
897 		    SDRETRIES, SD_IO_TIMEOUT, bp, flags);
898 		if (__predict_false(xs == NULL)) {
899 			/*
900 			 * out of memory. Keep this buffer in the queue, and
901 			 * retry later.
902 			 */
903 			callout_reset(&sd->sc_callout, hz / 2, sdrestart,
904 			    periph);
905 			return;
906 		}
907 		/*
908 		 * need to dequeue the buffer before queuing the command,
909 		 * because cdstart may be called recursively from the
910 		 * HBA driver
911 		 */
912 #ifdef DIAGNOSTIC
913 		if (BUFQ_GET(sd->buf_queue) != bp)
914 			panic("sdstart(): dequeued wrong buf");
915 #else
916 		BUFQ_GET(sd->buf_queue);
917 #endif
918 		error = scsipi_execute_xs(xs);
919 		/* with a scsipi_xfer preallocated, scsipi_command can't fail */
920 		KASSERT(error == 0);
921 	}
922 }
923 
924 static void
925 sdrestart(void *v)
926 {
927 	int s = splbio();
928 	sdstart((struct scsipi_periph *)v);
929 	splx(s);
930 }
931 
932 static void
933 sddone(struct scsipi_xfer *xs, int error)
934 {
935 	struct sd_softc *sd = (void *)xs->xs_periph->periph_dev;
936 	struct buf *bp = xs->bp;
937 
938 	if (sd->flags & SDF_FLUSHING) {
939 		/* Flush completed, no longer dirty. */
940 		sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
941 	}
942 
943 	if (bp) {
944 		bp->b_error = error;
945 		bp->b_resid = xs->resid;
946 		if (error) {
947 			/* on a read/write error bp->b_resid is zero, so fix */
948 			bp->b_resid = bp->b_bcount;
949 		}
950 
951 		disk_unbusy(&sd->sc_dk, bp->b_bcount - bp->b_resid,
952 		    (bp->b_flags & B_READ));
953 #if NRND > 0
954 		rnd_add_uint32(&sd->rnd_source, bp->b_rawblkno);
955 #endif
956 
957 		biodone(bp);
958 	}
959 }
960 
961 static void
962 sdminphys(struct buf *bp)
963 {
964 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(bp->b_dev)];
965 	long xmax;
966 
967 	/*
968 	 * If the device is ancient, we want to make sure that
969 	 * the transfer fits into a 6-byte cdb.
970 	 *
971 	 * XXX Note that the SCSI-I spec says that 256-block transfers
972 	 * are allowed in a 6-byte read/write, and are specified
973 	 * by settng the "length" to 0.  However, we're conservative
974 	 * here, allowing only 255-block transfers in case an
975 	 * ancient device gets confused by length == 0.  A length of 0
976 	 * in a 10-byte read/write actually means 0 blocks.
977 	 */
978 	if ((sd->flags & SDF_ANCIENT) &&
979 	    ((sd->sc_periph->periph_flags &
980 	    (PERIPH_REMOVABLE | PERIPH_MEDIA_LOADED)) != PERIPH_REMOVABLE)) {
981 		xmax = sd->sc_dk.dk_label->d_secsize * 0xff;
982 
983 		if (bp->b_bcount > xmax)
984 			bp->b_bcount = xmax;
985 	}
986 
987 	scsipi_adapter_minphys(sd->sc_periph->periph_channel, bp);
988 }
989 
990 static int
991 sdread(dev_t dev, struct uio *uio, int ioflag)
992 {
993 
994 	return (physio(sdstrategy, NULL, dev, B_READ, sdminphys, uio));
995 }
996 
997 static int
998 sdwrite(dev_t dev, struct uio *uio, int ioflag)
999 {
1000 
1001 	return (physio(sdstrategy, NULL, dev, B_WRITE, sdminphys, uio));
1002 }
1003 
1004 /*
1005  * Perform special action on behalf of the user
1006  * Knows about the internals of this device
1007  */
1008 static int
1009 sdioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
1010 {
1011 	struct sd_softc *sd = sd_cd.cd_devs[SDUNIT(dev)];
1012 	struct scsipi_periph *periph = sd->sc_periph;
1013 	int part = SDPART(dev);
1014 	int error = 0;
1015 #ifdef __HAVE_OLD_DISKLABEL
1016 	struct disklabel *newlabel = NULL;
1017 #endif
1018 
1019 	SC_DEBUG(sd->sc_periph, SCSIPI_DB2, ("sdioctl 0x%lx ", cmd));
1020 
1021 	/*
1022 	 * If the device is not valid, some IOCTLs can still be
1023 	 * handled on the raw partition. Check this here.
1024 	 */
1025 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
1026 		switch (cmd) {
1027 		case DIOCKLABEL:
1028 		case DIOCWLABEL:
1029 		case DIOCLOCK:
1030 		case DIOCEJECT:
1031 		case ODIOCEJECT:
1032 		case DIOCGCACHE:
1033 		case DIOCSCACHE:
1034 		case SCIOCIDENTIFY:
1035 		case OSCIOCIDENTIFY:
1036 		case SCIOCCOMMAND:
1037 		case SCIOCDEBUG:
1038 			if (part == RAW_PART)
1039 				break;
1040 		/* FALLTHROUGH */
1041 		default:
1042 			if ((periph->periph_flags & PERIPH_OPEN) == 0)
1043 				return (ENODEV);
1044 			else
1045 				return (EIO);
1046 		}
1047 	}
1048 
1049 	switch (cmd) {
1050 	case DIOCGDINFO:
1051 		*(struct disklabel *)addr = *(sd->sc_dk.dk_label);
1052 		return (0);
1053 
1054 #ifdef __HAVE_OLD_DISKLABEL
1055 	case ODIOCGDINFO:
1056 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
1057 		if (newlabel == NULL)
1058 			return EIO;
1059 		memcpy(newlabel, sd->sc_dk.dk_label, sizeof (*newlabel));
1060 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
1061 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1062 		else
1063 			error = ENOTTY;
1064 		free(newlabel, M_TEMP);
1065 		return error;
1066 #endif
1067 
1068 	case DIOCGPART:
1069 		((struct partinfo *)addr)->disklab = sd->sc_dk.dk_label;
1070 		((struct partinfo *)addr)->part =
1071 		    &sd->sc_dk.dk_label->d_partitions[part];
1072 		return (0);
1073 
1074 	case DIOCWDINFO:
1075 	case DIOCSDINFO:
1076 #ifdef __HAVE_OLD_DISKLABEL
1077 	case ODIOCWDINFO:
1078 	case ODIOCSDINFO:
1079 #endif
1080 	{
1081 		struct disklabel *lp;
1082 
1083 		if ((flag & FWRITE) == 0)
1084 			return (EBADF);
1085 
1086 #ifdef __HAVE_OLD_DISKLABEL
1087  		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
1088 			newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
1089 			if (newlabel == NULL)
1090 				return EIO;
1091 			memset(newlabel, 0, sizeof newlabel);
1092 			memcpy(newlabel, addr, sizeof (struct olddisklabel));
1093 			lp = newlabel;
1094 		} else
1095 #endif
1096 		lp = (struct disklabel *)addr;
1097 
1098 		mutex_enter(&sd->sc_dk.dk_openlock);
1099 		sd->flags |= SDF_LABELLING;
1100 
1101 		error = setdisklabel(sd->sc_dk.dk_label,
1102 		    lp, /*sd->sc_dk.dk_openmask : */0,
1103 		    sd->sc_dk.dk_cpulabel);
1104 		if (error == 0) {
1105 			if (cmd == DIOCWDINFO
1106 #ifdef __HAVE_OLD_DISKLABEL
1107 			    || cmd == ODIOCWDINFO
1108 #endif
1109 			   )
1110 				error = writedisklabel(SDLABELDEV(dev),
1111 				    sdstrategy, sd->sc_dk.dk_label,
1112 				    sd->sc_dk.dk_cpulabel);
1113 		}
1114 
1115 		sd->flags &= ~SDF_LABELLING;
1116 		mutex_exit(&sd->sc_dk.dk_openlock);
1117 #ifdef __HAVE_OLD_DISKLABEL
1118 		if (newlabel != NULL)
1119 			free(newlabel, M_TEMP);
1120 #endif
1121 		return (error);
1122 	}
1123 
1124 	case DIOCKLABEL:
1125 		if (*(int *)addr)
1126 			periph->periph_flags |= PERIPH_KEEP_LABEL;
1127 		else
1128 			periph->periph_flags &= ~PERIPH_KEEP_LABEL;
1129 		return (0);
1130 
1131 	case DIOCWLABEL:
1132 		if ((flag & FWRITE) == 0)
1133 			return (EBADF);
1134 		if (*(int *)addr)
1135 			sd->flags |= SDF_WLABEL;
1136 		else
1137 			sd->flags &= ~SDF_WLABEL;
1138 		return (0);
1139 
1140 	case DIOCLOCK:
1141 		if (periph->periph_flags & PERIPH_REMOVABLE)
1142 			return (scsipi_prevent(periph,
1143 			    (*(int *)addr) ?
1144 			    SPAMR_PREVENT_DT : SPAMR_ALLOW, 0));
1145 		else
1146 			return (ENOTTY);
1147 
1148 	case DIOCEJECT:
1149 		if ((periph->periph_flags & PERIPH_REMOVABLE) == 0)
1150 			return (ENOTTY);
1151 		if (*(int *)addr == 0) {
1152 			/*
1153 			 * Don't force eject: check that we are the only
1154 			 * partition open. If so, unlock it.
1155 			 */
1156 			if ((sd->sc_dk.dk_openmask & ~(1 << part)) == 0 &&
1157 			    sd->sc_dk.dk_bopenmask + sd->sc_dk.dk_copenmask ==
1158 			    sd->sc_dk.dk_openmask) {
1159 				error = scsipi_prevent(periph, SPAMR_ALLOW,
1160 				    XS_CTL_IGNORE_NOT_READY);
1161 				if (error)
1162 					return (error);
1163 			} else {
1164 				return (EBUSY);
1165 			}
1166 		}
1167 		/* FALLTHROUGH */
1168 	case ODIOCEJECT:
1169 		return ((periph->periph_flags & PERIPH_REMOVABLE) == 0 ?
1170 		    ENOTTY : scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0));
1171 
1172 	case DIOCGDEFLABEL:
1173 		sdgetdefaultlabel(sd, (struct disklabel *)addr);
1174 		return (0);
1175 
1176 #ifdef __HAVE_OLD_DISKLABEL
1177 	case ODIOCGDEFLABEL:
1178 		newlabel = malloc(sizeof *newlabel, M_TEMP, M_WAITOK);
1179 		if (newlabel == NULL)
1180 			return EIO;
1181 		sdgetdefaultlabel(sd, newlabel);
1182 		if (newlabel->d_npartitions <= OLDMAXPARTITIONS)
1183 			memcpy(addr, newlabel, sizeof (struct olddisklabel));
1184 		else
1185 			error = ENOTTY;
1186 		free(newlabel, M_TEMP);
1187 		return error;
1188 #endif
1189 
1190 	case DIOCGCACHE:
1191 		return (sd_getcache(sd, (int *) addr));
1192 
1193 	case DIOCSCACHE:
1194 		if ((flag & FWRITE) == 0)
1195 			return (EBADF);
1196 		return (sd_setcache(sd, *(int *) addr));
1197 
1198 	case DIOCCACHESYNC:
1199 		/*
1200 		 * XXX Do we really need to care about having a writable
1201 		 * file descriptor here?
1202 		 */
1203 		if ((flag & FWRITE) == 0)
1204 			return (EBADF);
1205 		if (((sd->flags & SDF_DIRTY) != 0 || *(int *)addr != 0)) {
1206 			error = sd_flush(sd, 0);
1207 			if (error)
1208 				sd->flags &= ~SDF_FLUSHING;
1209 			else
1210 				sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
1211 		} else
1212 			error = 0;
1213 		return (error);
1214 
1215 	case DIOCAWEDGE:
1216 	    {
1217 	    	struct dkwedge_info *dkw = (void *) addr;
1218 
1219 		if ((flag & FWRITE) == 0)
1220 			return (EBADF);
1221 
1222 		/* If the ioctl happens here, the parent is us. */
1223 		strcpy(dkw->dkw_parent, sd->sc_dev.dv_xname);
1224 		return (dkwedge_add(dkw));
1225 	    }
1226 
1227 	case DIOCDWEDGE:
1228 	    {
1229 	    	struct dkwedge_info *dkw = (void *) addr;
1230 
1231 		if ((flag & FWRITE) == 0)
1232 			return (EBADF);
1233 
1234 		/* If the ioctl happens here, the parent is us. */
1235 		strcpy(dkw->dkw_parent, sd->sc_dev.dv_xname);
1236 		return (dkwedge_del(dkw));
1237 	    }
1238 
1239 	case DIOCLWEDGES:
1240 	    {
1241 	    	struct dkwedge_list *dkwl = (void *) addr;
1242 
1243 		return (dkwedge_list(&sd->sc_dk, dkwl, l));
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_periph_bustype(sd->sc_periph)) {
1270 	case SCSIPI_BUSTYPE_SCSI:
1271 		lp->d_type = DTYPE_SCSI;
1272 		break;
1273 	case SCSIPI_BUSTYPE_ATAPI:
1274 		lp->d_type = DTYPE_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 	lp->d_secperunit = sd->params.disksize;
1285 	lp->d_rpm = sd->params.rot_rate;
1286 	lp->d_interleave = 1;
1287 	lp->d_flags = sd->sc_periph->periph_flags & PERIPH_REMOVABLE ?
1288 	    D_REMOVABLE : 0;
1289 
1290 	lp->d_partitions[RAW_PART].p_offset = 0;
1291 	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
1292 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
1293 	lp->d_npartitions = RAW_PART + 1;
1294 
1295 	lp->d_magic = DISKMAGIC;
1296 	lp->d_magic2 = DISKMAGIC;
1297 	lp->d_checksum = dkcksum(lp);
1298 }
1299 
1300 
1301 /*
1302  * Load the label information on the named device
1303  */
1304 static int
1305 sdgetdisklabel(struct sd_softc *sd)
1306 {
1307 	struct disklabel *lp = sd->sc_dk.dk_label;
1308 	const char *errstring;
1309 
1310 	memset(sd->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
1311 
1312 	sdgetdefaultlabel(sd, lp);
1313 
1314 	if (lp->d_secpercyl == 0) {
1315 		lp->d_secpercyl = 100;
1316 		/* as long as it's not 0 - readdisklabel divides by it (?) */
1317 	}
1318 
1319 	/*
1320 	 * Call the generic disklabel extraction routine
1321 	 */
1322 	errstring = readdisklabel(MAKESDDEV(0, device_unit(&sd->sc_dev),
1323 	    RAW_PART), sdstrategy, lp, sd->sc_dk.dk_cpulabel);
1324 	if (errstring) {
1325 		printf("%s: %s\n", sd->sc_dev.dv_xname, errstring);
1326 		return EIO;
1327 	}
1328 	return 0;
1329 }
1330 
1331 static void
1332 sd_shutdown(void *arg)
1333 {
1334 	struct sd_softc *sd = arg;
1335 
1336 	/*
1337 	 * If the disk cache needs to be flushed, and the disk supports
1338 	 * it, flush it.  We're cold at this point, so we poll for
1339 	 * completion.
1340 	 */
1341 	if ((sd->flags & SDF_DIRTY) != 0) {
1342 		if (sd_flush(sd, XS_CTL_NOSLEEP|XS_CTL_POLL)) {
1343 			printf("%s: cache synchronization failed\n",
1344 			    sd->sc_dev.dv_xname);
1345 			sd->flags &= ~SDF_FLUSHING;
1346 		} else
1347 			sd->flags &= ~(SDF_FLUSHING|SDF_DIRTY);
1348 	}
1349 }
1350 
1351 static bool
1352 sd_suspend(device_t dv PMF_FN_ARGS)
1353 {
1354 	struct sd_softc *sd = device_private(dv);
1355 
1356 	sd_shutdown(sd); /* XXX no need to poll */
1357 	return true;
1358 }
1359 
1360 /*
1361  * Check Errors
1362  */
1363 static int
1364 sd_interpret_sense(struct scsipi_xfer *xs)
1365 {
1366 	struct scsipi_periph *periph = xs->xs_periph;
1367 	struct scsi_sense_data *sense = &xs->sense.scsi_sense;
1368 	struct sd_softc *sd = (void *)periph->periph_dev;
1369 	int s, error, retval = EJUSTRETURN;
1370 
1371 	/*
1372 	 * If the periph is already recovering, just do the normal
1373 	 * error processing.
1374 	 */
1375 	if (periph->periph_flags & PERIPH_RECOVERING)
1376 		return (retval);
1377 
1378 	/*
1379 	 * Ignore errors from accessing illegal fields (e.g. trying to
1380 	 * lock the door of a digicam, which doesn't have a door that
1381 	 * can be locked) for the SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL command.
1382 	 */
1383 	if (xs->cmd->opcode == SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL &&
1384 	    SSD_SENSE_KEY(sense->flags) == SKEY_ILLEGAL_REQUEST &&
1385 	    sense->asc == 0x24 &&
1386 	    sense->ascq == 0x00) { /* Illegal field in CDB */
1387 		if (!(xs->xs_control & XS_CTL_SILENT)) {
1388 			scsipi_printaddr(periph);
1389 			printf("no door lock\n");
1390 		}
1391 		xs->xs_control |= XS_CTL_IGNORE_ILLEGAL_REQUEST;
1392 		return (retval);
1393 	}
1394 
1395 
1396 
1397 	/*
1398 	 * If the device is not open yet, let the generic code handle it.
1399 	 */
1400 	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
1401 		return (retval);
1402 
1403 	/*
1404 	 * If it isn't a extended or extended/deferred error, let
1405 	 * the generic code handle it.
1406 	 */
1407 	if (SSD_RCODE(sense->response_code) != SSD_RCODE_CURRENT &&
1408 	    SSD_RCODE(sense->response_code) != SSD_RCODE_DEFERRED)
1409 		return (retval);
1410 
1411 	if (SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY &&
1412 	    sense->asc == 0x4) {
1413 		if (sense->ascq == 0x01)	{
1414 			/*
1415 			 * Unit In The Process Of Becoming Ready.
1416 			 */
1417 			printf("%s: waiting for pack to spin up...\n",
1418 			    sd->sc_dev.dv_xname);
1419 			if (!callout_pending(&periph->periph_callout))
1420 				scsipi_periph_freeze(periph, 1);
1421 			callout_reset(&periph->periph_callout,
1422 			    5 * hz, scsipi_periph_timed_thaw, periph);
1423 			retval = ERESTART;
1424 		} else if (sense->ascq == 0x02) {
1425 			printf("%s: pack is stopped, restarting...\n",
1426 			    sd->sc_dev.dv_xname);
1427 			s = splbio();
1428 			periph->periph_flags |= PERIPH_RECOVERING;
1429 			splx(s);
1430 			error = scsipi_start(periph, SSS_START,
1431 			    XS_CTL_URGENT|XS_CTL_HEAD_TAG|
1432 			    XS_CTL_THAW_PERIPH|XS_CTL_FREEZE_PERIPH);
1433 			if (error) {
1434 				printf("%s: unable to restart pack\n",
1435 				    sd->sc_dev.dv_xname);
1436 				retval = error;
1437 			} else
1438 				retval = ERESTART;
1439 			s = splbio();
1440 			periph->periph_flags &= ~PERIPH_RECOVERING;
1441 			splx(s);
1442 		}
1443 	}
1444 	if (SSD_SENSE_KEY(sense->flags) == SKEY_MEDIUM_ERROR &&
1445 	    sense->asc == 0x31 &&
1446 	    sense->ascq == 0x00)	{ /* maybe for any asq ? */
1447 		/* Medium Format Corrupted */
1448 		retval = EFTYPE;
1449 	}
1450 	return (retval);
1451 }
1452 
1453 
1454 static int
1455 sdsize(dev_t dev)
1456 {
1457 	struct sd_softc *sd;
1458 	int part, unit, omask;
1459 	int size;
1460 
1461 	unit = SDUNIT(dev);
1462 	if (unit >= sd_cd.cd_ndevs)
1463 		return (-1);
1464 	sd = sd_cd.cd_devs[unit];
1465 	if (sd == NULL)
1466 		return (-1);
1467 
1468 	if (!device_is_active(&sd->sc_dev))
1469 		return (-1);
1470 
1471 	part = SDPART(dev);
1472 	omask = sd->sc_dk.dk_openmask & (1 << part);
1473 
1474 	if (omask == 0 && sdopen(dev, 0, S_IFBLK, NULL) != 0)
1475 		return (-1);
1476 	if ((sd->sc_periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
1477 		size = -1;
1478 	else if (sd->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
1479 		size = -1;
1480 	else
1481 		size = sd->sc_dk.dk_label->d_partitions[part].p_size *
1482 		    (sd->sc_dk.dk_label->d_secsize / DEV_BSIZE);
1483 	if (omask == 0 && sdclose(dev, 0, S_IFBLK, NULL) != 0)
1484 		return (-1);
1485 	return (size);
1486 }
1487 
1488 /* #define SD_DUMP_NOT_TRUSTED if you just want to watch */
1489 static struct scsipi_xfer sx;
1490 static int sddoingadump;
1491 
1492 /*
1493  * dump all of physical memory into the partition specified, starting
1494  * at offset 'dumplo' into the partition.
1495  */
1496 static int
1497 sddump(dev_t dev, daddr_t blkno, void *va, size_t size)
1498 {
1499 	struct sd_softc *sd;	/* disk unit to do the I/O */
1500 	struct disklabel *lp;	/* disk's disklabel */
1501 	int	unit, part;
1502 	int	sectorsize;	/* size of a disk sector */
1503 	int	nsects;		/* number of sectors in partition */
1504 	int	sectoff;	/* sector offset of partition */
1505 	int	totwrt;		/* total number of sectors left to write */
1506 	int	nwrt;		/* current number of sectors to write */
1507 	struct scsipi_rw_10 cmd;	/* write command */
1508 	struct scsipi_xfer *xs;	/* ... convenience */
1509 	struct scsipi_periph *periph;
1510 	struct scsipi_channel *chan;
1511 
1512 	/* Check if recursive dump; if so, punt. */
1513 	if (sddoingadump)
1514 		return (EFAULT);
1515 
1516 	/* Mark as active early. */
1517 	sddoingadump = 1;
1518 
1519 	unit = SDUNIT(dev);	/* Decompose unit & partition. */
1520 	part = SDPART(dev);
1521 
1522 	/* Check for acceptable drive number. */
1523 	if (unit >= sd_cd.cd_ndevs || (sd = sd_cd.cd_devs[unit]) == 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 | XS_CTL_DATA_ONSTACK, 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 | XS_CTL_DATA_ONSTACK, 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 | XS_CTL_DATA_ONSTACK, 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 | XS_CTL_DATA_ONSTACK, 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 | XS_CTL_DATA_ONSTACK, 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 | XS_CTL_DATA_ONSTACK);
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 			disk_blocksize(&sd->sc_dk, dp->blksize);
2085 		return (error);
2086 	}
2087 
2088 	error = sd_get_capacity(sd, dp, flags);
2089 	if (error)
2090 		return (error);
2091 
2092 	disk_blocksize(&sd->sc_dk, dp->blksize);
2093 
2094 	if (sd->type == T_OPTICAL)
2095 		goto page0;
2096 
2097 	if (sd->sc_periph->periph_flags & PERIPH_REMOVABLE) {
2098 		if (!sd_get_parms_page5(sd, dp, flags) ||
2099 		    !sd_get_parms_page4(sd, dp, flags))
2100 			return (SDGP_RESULT_OK);
2101 	} else {
2102 		if (!sd_get_parms_page4(sd, dp, flags) ||
2103 		    !sd_get_parms_page5(sd, dp, flags))
2104 			return (SDGP_RESULT_OK);
2105 	}
2106 
2107 page0:
2108 	printf("%s: fabricating a geometry\n", sd->sc_dev.dv_xname);
2109 	/* Try calling driver's method for figuring out geometry. */
2110 	if (!sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom ||
2111 	    !(*sd->sc_periph->periph_channel->chan_adapter->adapt_getgeom)
2112 		(sd->sc_periph, dp, dp->disksize)) {
2113 		/*
2114 		 * Use adaptec standard fictitious geometry
2115 		 * this depends on which controller (e.g. 1542C is
2116 		 * different. but we have to put SOMETHING here..)
2117 		 */
2118 		dp->heads = 64;
2119 		dp->sectors = 32;
2120 		dp->cyls = dp->disksize / (64 * 32);
2121 	}
2122 	dp->rot_rate = 3600;
2123 	return (SDGP_RESULT_OK);
2124 }
2125 
2126 static int
2127 sd_flush(struct sd_softc *sd, int flags)
2128 {
2129 	struct scsipi_periph *periph = sd->sc_periph;
2130 	struct scsi_synchronize_cache_10 cmd;
2131 
2132 	/*
2133 	 * If the device is SCSI-2, issue a SYNCHRONIZE CACHE.
2134 	 * We issue with address 0 length 0, which should be
2135 	 * interpreted by the device as "all remaining blocks
2136 	 * starting at address 0".  We ignore ILLEGAL REQUEST
2137 	 * in the event that the command is not supported by
2138 	 * the device, and poll for completion so that we know
2139 	 * that the cache has actually been flushed.
2140 	 *
2141 	 * Unless, that is, the device can't handle the SYNCHRONIZE CACHE
2142 	 * command, as indicated by our quirks flags.
2143 	 *
2144 	 * XXX What about older devices?
2145 	 */
2146 	if (periph->periph_version < 2 ||
2147 	    (periph->periph_quirks & PQUIRK_NOSYNCCACHE))
2148 		return (0);
2149 
2150 	sd->flags |= SDF_FLUSHING;
2151 	memset(&cmd, 0, sizeof(cmd));
2152 	cmd.opcode = SCSI_SYNCHRONIZE_CACHE_10;
2153 
2154 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
2155 	    SDRETRIES, 100000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
2156 }
2157 
2158 static int
2159 sd_getcache(struct sd_softc *sd, int *bitsp)
2160 {
2161 	struct scsipi_periph *periph = sd->sc_periph;
2162 	struct sd_mode_sense_data scsipi_sense;
2163 	int error, bits = 0;
2164 	int big;
2165 	union scsi_disk_pages *pages;
2166 
2167 	if (periph->periph_version < 2)
2168 		return (EOPNOTSUPP);
2169 
2170 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
2171 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
2172 	    sizeof(scsipi_sense.pages.caching_params), 8, 0, &big);
2173 	if (error)
2174 		return (error);
2175 
2176 	if (big)
2177 		pages = (void *)(&scsipi_sense.header.big + 1);
2178 	else
2179 		pages = (void *)(&scsipi_sense.header.small + 1);
2180 
2181 	if ((pages->caching_params.flags & CACHING_RCD) == 0)
2182 		bits |= DKCACHE_READ;
2183 	if (pages->caching_params.flags & CACHING_WCE)
2184 		bits |= DKCACHE_WRITE;
2185 	if (pages->caching_params.pg_code & PGCODE_PS)
2186 		bits |= DKCACHE_SAVE;
2187 
2188 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
2189 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
2190 	    sizeof(scsipi_sense.pages.caching_params),
2191 	    SMS_PCTRL_CHANGEABLE|8, 0, &big);
2192 	if (error == 0) {
2193 		if (big)
2194 			pages = (void *)(&scsipi_sense.header.big + 1);
2195 		else
2196 			pages = (void *)(&scsipi_sense.header.small + 1);
2197 
2198 		if (pages->caching_params.flags & CACHING_RCD)
2199 			bits |= DKCACHE_RCHANGE;
2200 		if (pages->caching_params.flags & CACHING_WCE)
2201 			bits |= DKCACHE_WCHANGE;
2202 	}
2203 
2204 	*bitsp = bits;
2205 
2206 	return (0);
2207 }
2208 
2209 static int
2210 sd_setcache(struct sd_softc *sd, int bits)
2211 {
2212 	struct scsipi_periph *periph = sd->sc_periph;
2213 	struct sd_mode_sense_data scsipi_sense;
2214 	int error;
2215 	uint8_t oflags, byte2 = 0;
2216 	int big;
2217 	union scsi_disk_pages *pages;
2218 
2219 	if (periph->periph_version < 2)
2220 		return (EOPNOTSUPP);
2221 
2222 	memset(&scsipi_sense, 0, sizeof(scsipi_sense));
2223 	error = sd_mode_sense(sd, SMS_DBD, &scsipi_sense,
2224 	    sizeof(scsipi_sense.pages.caching_params), 8, 0, &big);
2225 	if (error)
2226 		return (error);
2227 
2228 	if (big)
2229 		pages = (void *)(&scsipi_sense.header.big + 1);
2230 	else
2231 		pages = (void *)(&scsipi_sense.header.small + 1);
2232 
2233 	oflags = pages->caching_params.flags;
2234 
2235 	if (bits & DKCACHE_READ)
2236 		pages->caching_params.flags &= ~CACHING_RCD;
2237 	else
2238 		pages->caching_params.flags |= CACHING_RCD;
2239 
2240 	if (bits & DKCACHE_WRITE)
2241 		pages->caching_params.flags |= CACHING_WCE;
2242 	else
2243 		pages->caching_params.flags &= ~CACHING_WCE;
2244 
2245 	if (oflags == pages->caching_params.flags)
2246 		return (0);
2247 
2248 	pages->caching_params.pg_code &= PGCODE_MASK;
2249 
2250 	if (bits & DKCACHE_SAVE)
2251 		byte2 |= SMS_SP;
2252 
2253 	return (sd_mode_select(sd, byte2|SMS_PF, &scsipi_sense,
2254 	    sizeof(struct scsi_mode_page_header) +
2255 	    pages->caching_params.pg_length, 0, big));
2256 }
2257 
2258 static void
2259 sd_set_properties(struct sd_softc *sd)
2260 {
2261 	prop_dictionary_t disk_info, odisk_info, geom;
2262 
2263 	disk_info = prop_dictionary_create();
2264 
2265 	geom = prop_dictionary_create();
2266 
2267 	prop_dictionary_set_uint64(geom, "sectors-per-unit",
2268 	    sd->params.disksize);
2269 
2270 	prop_dictionary_set_uint32(geom, "sector-size",
2271 	    sd->params.blksize);
2272 
2273 	prop_dictionary_set_uint16(geom, "sectors-per-track",
2274 	    sd->params.sectors);
2275 
2276 	prop_dictionary_set_uint16(geom, "tracks-per-cylinder",
2277 	    sd->params.heads);
2278 
2279 	prop_dictionary_set_uint64(geom, "cylinders-per-unit",
2280 	    sd->params.cyls);
2281 
2282 	prop_dictionary_set(disk_info, "geometry", geom);
2283 	prop_object_release(geom);
2284 
2285 	prop_dictionary_set(device_properties(&sd->sc_dev),
2286 	    "disk-info", disk_info);
2287 
2288 	/*
2289 	 * Don't release disk_info here; we keep a reference to it.
2290 	 * disk_detach() will release it when we go away.
2291 	 */
2292 
2293 	odisk_info = sd->sc_dk.dk_info;
2294 	sd->sc_dk.dk_info = disk_info;
2295 	if (odisk_info)
2296 		prop_object_release(odisk_info);
2297 }
2298