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