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