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