xref: /freebsd/sys/cam/scsi/scsi_da.c (revision 5773cccf19ef7b97e56c1101aa481c43149224da)
1 /*
2  * Implementation of SCSI Direct Access Peripheral driver for CAM.
3  *
4  * Copyright (c) 1997 Justin T. Gibbs.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification, immediately at the beginning of the file.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #ifdef _KERNEL
32 #include "opt_hw_wdog.h"
33 #endif /* _KERNEL */
34 
35 #include <sys/param.h>
36 
37 #ifdef _KERNEL
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/bio.h>
41 #include <sys/sysctl.h>
42 #endif /* _KERNEL */
43 
44 #include <sys/devicestat.h>
45 #include <sys/conf.h>
46 #include <sys/disk.h>
47 #include <sys/eventhandler.h>
48 #include <sys/malloc.h>
49 #include <sys/cons.h>
50 
51 #include <machine/md_var.h>
52 
53 #include <vm/vm.h>
54 #include <vm/pmap.h>
55 
56 #ifndef _KERNEL
57 #include <stdio.h>
58 #include <string.h>
59 #endif /* _KERNEL */
60 
61 #include <cam/cam.h>
62 #include <cam/cam_ccb.h>
63 #include <cam/cam_periph.h>
64 #include <cam/cam_xpt_periph.h>
65 
66 #include <cam/scsi/scsi_message.h>
67 
68 #ifndef _KERNEL
69 #include <cam/scsi/scsi_da.h>
70 #endif /* !_KERNEL */
71 
72 #ifdef _KERNEL
73 typedef enum {
74 	DA_STATE_PROBE,
75 	DA_STATE_NORMAL
76 } da_state;
77 
78 typedef enum {
79 	DA_FLAG_PACK_INVALID	= 0x001,
80 	DA_FLAG_NEW_PACK	= 0x002,
81 	DA_FLAG_PACK_LOCKED	= 0x004,
82 	DA_FLAG_PACK_REMOVABLE	= 0x008,
83 	DA_FLAG_TAGGED_QUEUING	= 0x010,
84 	DA_FLAG_NEED_OTAG	= 0x020,
85 	DA_FLAG_WENT_IDLE	= 0x040,
86 	DA_FLAG_RETRY_UA	= 0x080,
87 	DA_FLAG_OPEN		= 0x100
88 } da_flags;
89 
90 typedef enum {
91 	DA_Q_NONE		= 0x00,
92 	DA_Q_NO_SYNC_CACHE	= 0x01,
93 	DA_Q_NO_6_BYTE		= 0x02
94 } da_quirks;
95 
96 typedef enum {
97 	DA_CCB_PROBE		= 0x01,
98 	DA_CCB_BUFFER_IO	= 0x02,
99 	DA_CCB_WAITING		= 0x03,
100 	DA_CCB_DUMP		= 0x04,
101 	DA_CCB_TYPE_MASK	= 0x0F,
102 	DA_CCB_RETRY_UA		= 0x10
103 } da_ccb_state;
104 
105 /* Offsets into our private area for storing information */
106 #define ccb_state	ppriv_field0
107 #define ccb_bp		ppriv_ptr1
108 
109 struct disk_params {
110 	u_int8_t  heads;
111 	u_int16_t cylinders;
112 	u_int8_t  secs_per_track;
113 	u_int32_t secsize;	/* Number of bytes/sector */
114 	u_int32_t sectors;	/* total number sectors */
115 };
116 
117 struct da_softc {
118 	struct	 bio_queue_head bio_queue;
119 	struct	 devstat device_stats;
120 	SLIST_ENTRY(da_softc) links;
121 	LIST_HEAD(, ccb_hdr) pending_ccbs;
122 	da_state state;
123 	da_flags flags;
124 	da_quirks quirks;
125 	int	 minimum_cmd_size;
126 	int	 ordered_tag_count;
127 	struct	 disk_params params;
128 	struct	 disk disk;
129 	union	 ccb saved_ccb;
130 	dev_t    dev;
131 };
132 
133 struct da_quirk_entry {
134 	struct scsi_inquiry_pattern inq_pat;
135 	da_quirks quirks;
136 };
137 
138 static const char quantum[] = "QUANTUM";
139 static const char microp[] = "MICROP";
140 
141 static struct da_quirk_entry da_quirk_table[] =
142 {
143 	/*
144 	 * Logitec USB/Firewire LHD-P30FU
145 	 */
146 	{
147 		/* USB part */
148 		{T_DIRECT, SIP_MEDIA_FIXED, "HITACHI_", "DK23DA*", "*"},
149 		/*quirks*/ DA_Q_NO_6_BYTE
150 	},
151 	{
152 		/* Firewire part */
153 		{T_DIRECT, SIP_MEDIA_FIXED, "LSILogic", "SYM13FW*", "*"},
154 		/*quirks*/ DA_Q_NO_6_BYTE
155 	},
156 	{
157 		/*
158 		 * Fujitsu M2513A MO drives.
159 		 * Tested devices: M2513A2 firmware versions 1200 & 1300.
160 		 * (dip switch selects whether T_DIRECT or T_OPTICAL device)
161 		 * Reported by: W.Scholten <whs@xs4all.nl>
162 		 */
163 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
164 		/*quirks*/ DA_Q_NO_SYNC_CACHE
165 	},
166 	{
167 		/* See above. */
168 		{T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
169 		/*quirks*/ DA_Q_NO_SYNC_CACHE
170 	},
171 	{
172 		/*
173 		 * This particular Fujitsu drive doesn't like the
174 		 * synchronize cache command.
175 		 * Reported by: Tom Jackson <toj@gorilla.net>
176 		 */
177 		{T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
178 		/*quirks*/ DA_Q_NO_SYNC_CACHE
179 
180 	},
181 	{
182 		/*
183 		 * This drive doesn't like the synchronize cache command
184 		 * either.  Reported by: Matthew Jacob <mjacob@feral.com>
185 		 * in NetBSD PR kern/6027, August 24, 1998.
186 		 */
187 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
188 		/*quirks*/ DA_Q_NO_SYNC_CACHE
189 	},
190 	{
191 		/*
192 		 * This drive doesn't like the synchronize cache command
193 		 * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
194 		 * (PR 8882).
195 		 */
196 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
197 		/*quirks*/ DA_Q_NO_SYNC_CACHE
198 	},
199 	{
200 		/*
201 		 * Doesn't like the synchronize cache command.
202 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
203 		 */
204 		{T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
205 		/*quirks*/ DA_Q_NO_SYNC_CACHE
206 	},
207 	{
208 		/*
209 		 * Doesn't like the synchronize cache command.
210 		 */
211 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
212 		/*quirks*/ DA_Q_NO_SYNC_CACHE
213 	},
214 	{
215 		/*
216 		 * Doesn't like the synchronize cache command.
217 		 */
218 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
219 		/*quirks*/ DA_Q_NO_SYNC_CACHE
220 	},
221 	{
222 		/*
223 		 * Doesn't work correctly with 6 byte reads/writes.
224 		 * Returns illegal request, and points to byte 9 of the
225 		 * 6-byte CDB.
226 		 * Reported by:  Adam McDougall <bsdx@spawnet.com>
227 		 */
228 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
229 		/*quirks*/ DA_Q_NO_6_BYTE
230 	},
231 	{
232 		/*
233 		 * See above.
234 		 */
235 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
236 		/*quirks*/ DA_Q_NO_6_BYTE
237 	},
238 
239 	/* Below a list of quirks for USB devices supported by umass. */
240 	{
241 		/*
242 		 * This USB floppy drive uses the UFI command set. This
243 		 * command set is a derivative of the ATAPI command set and
244 		 * does not support READ_6 commands only READ_10. It also does
245 		 * not support sync cache (0x35).
246 		 */
247 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Y-E DATA", "USB-FDU", "*"},
248 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
249 	},
250 	{
251 		/* Another USB floppy */
252 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "MATSHITA", "FDD CF-VFDU*","*"},
253 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
254 	},
255 	{
256 		/*
257 		 * Sony Memory Stick adapter MSAC-US1 and
258 		 * Sony PCG-C1VJ Internal Memory Stick Slot (MSC-U01).
259 		 * Make all sony MS* products use this quirk.
260 		 */
261 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "MS*", "*"},
262 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
263 	},
264 	{
265 		/*
266 		 * Sony Memory Stick adapter for the CLIE series
267 		 * of PalmOS PDA's
268 		 */
269 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "CLIE*", "*"},
270 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
271 	},
272 	{
273 		/*
274 		 * Sony DSC cameras (DSC-S30, DSC-S50, DSC-S70)
275 		 */
276 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
277 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
278 	},
279 	{
280 		/*
281 		 * Maxtor 3000LE USB Drive
282 		 */
283 		{T_DIRECT, SIP_MEDIA_FIXED, "MAXTOR*", "K040H2*", "*"},
284 		/*quirks*/ DA_Q_NO_6_BYTE
285 	},
286 	{
287 		/*
288 		 * LaCie USB drive, among others
289 		 */
290 		{T_DIRECT, SIP_MEDIA_FIXED, "Maxtor*", "D080H4*", "*"},
291 		/*quirks*/ DA_Q_NO_6_BYTE
292 	},
293 	{
294 		{T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "MCF3064AP", "*"},
295 		/*quirks*/ DA_Q_NO_6_BYTE
296 	},
297 	{
298 		/*
299 		 * Microtech USB CameraMate
300 		 */
301 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "eUSB    Compact*",
302 		 "Compact Flash*", "*"},
303 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
304 	},
305 	{
306 		/*
307 		 * The vendor, product and version strings coming from the
308 		 * controller are null terminated instead of being padded with
309 		 * spaces. The trailing wildcard character '*' is required.
310 		 */
311 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SMSC*", "USB FDC*","*"},
312 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
313 	},
314 	{
315 		/*
316 		 * Olympus digital cameras (C-3040ZOOM, C-2040ZOOM, C-1)
317 		 */
318 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "C-*", "*"},
319 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
320 	},
321 	{
322 		/*
323 		 * Olympus digital cameras (D-370)
324 		 */
325 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "D-*", "*"},
326 		/*quirks*/ DA_Q_NO_6_BYTE
327 	},
328 	{
329 		/*
330 		 * Olympus digital cameras (E-100RS, E-10).
331 		 */
332 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "E-*", "*"},
333 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
334 	},
335 	{
336 		/*
337 		 * KingByte Pen Drives
338 		 */
339 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "NO BRAND", "PEN DRIVE", "*"},
340 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
341  	},
342  	{
343 		/*
344 		 * FujiFilm Camera
345 		 */
346  		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJIFILMUSB-DRIVEUNIT",
347 		 "USB-DRIVEUNIT", "*"},
348  		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
349  	},
350 	{
351 		/*
352 		 * Nikon Coolpix E775/E995 Cameras
353 		 */
354 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "NIKON", "NIKON DSC E*", "*"},
355 		/*quirks*/ DA_Q_NO_6_BYTE
356 	},
357 	{
358 		/*
359 		 * Nikon Coolpix E885 Camera
360 		 */
361 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Nikon", "Digital Camera", "*"},
362 		/*quirks*/ DA_Q_NO_6_BYTE
363 	},
364 	{
365 		/*
366 		 * SimpleTech FlashLink UCF-100
367 		 */
368 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "OEI-USB", "CompactFlash", "*"},
369 		/*quirks*/ DA_Q_NO_6_BYTE
370 	},
371 	{
372 		/*
373 		 * Minolta Dimage 2330
374 		 */
375 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "MINOLTA", "DIMAGE 2330*", "*"},
376 		/*quirks*/ DA_Q_NO_6_BYTE
377 	},
378 	{
379 		/*
380 		 * Minolta Dimage E203
381 		 */
382 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "MINOLTA", "DiMAGE E203", "*"},
383 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
384 	},
385 	{
386 		/*
387 		 * DIVA USB Mp3 Player.
388 		 * PR: kern/33638
389 		 */
390 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "DIVA USB", "Media Reader","*"},
391 		/*quirks*/ DA_Q_NO_6_BYTE
392 	},
393 	{
394 		/*
395 		 * Daisy Technology PhotoClip USB Camera
396 		 */
397 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Digital", "World   DMC","*"},
398 		/*quirks*/ DA_Q_NO_6_BYTE
399 	},
400 	{
401 		/*
402 		 * Apacer HandyDrive
403 		 * PR: kern/43627
404 		 */
405 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Apacer", "HandyDrive", "*"},
406 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
407 	},
408 	{
409 		/*
410 		 * Daisy Technology PhotoClip on Zoran chip
411 		 * PR: kern/43580
412 		 */
413 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ZORAN", "COACH", "*"},
414 		/*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
415 	},
416 	{
417 		/*
418 		 * HP 315 Digital Camera
419 		 * PR: kern/41010
420 		 */
421 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "HP", "USB CAMERA", "*"},
422 		/*quirks*/ DA_Q_NO_6_BYTE
423 	}
424 };
425 
426 static	d_open_t	daopen;
427 static	d_close_t	daclose;
428 static	d_strategy_t	dastrategy;
429 static	d_ioctl_t	daioctl;
430 static	d_dump_t	dadump;
431 static	periph_init_t	dainit;
432 static	void		daasync(void *callback_arg, u_int32_t code,
433 				struct cam_path *path, void *arg);
434 static	periph_ctor_t	daregister;
435 static	periph_dtor_t	dacleanup;
436 static	periph_start_t	dastart;
437 static	periph_oninv_t	daoninvalidate;
438 static	void		dadone(struct cam_periph *periph,
439 			       union ccb *done_ccb);
440 static  int		daerror(union ccb *ccb, u_int32_t cam_flags,
441 				u_int32_t sense_flags);
442 static void		daprevent(struct cam_periph *periph, int action);
443 static void		dasetgeom(struct cam_periph *periph,
444 				  struct scsi_read_capacity_data * rdcap);
445 static timeout_t	dasendorderedtag;
446 static void		dashutdown(void *arg, int howto);
447 
448 #ifndef DA_DEFAULT_TIMEOUT
449 #define DA_DEFAULT_TIMEOUT 60	/* Timeout in seconds */
450 #endif
451 
452 #ifndef	DA_DEFAULT_RETRY
453 #define	DA_DEFAULT_RETRY	4
454 #endif
455 
456 static int da_retry_count = DA_DEFAULT_RETRY;
457 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
458 static int da_no_6_byte = 0;
459 
460 SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
461             "CAM Direct Access Disk driver");
462 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
463            &da_retry_count, 0, "Normal I/O retry count");
464 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
465            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
466 SYSCTL_INT(_kern_cam_da, OID_AUTO, no_6_byte, CTLFLAG_RW,
467            &da_no_6_byte, 0, "No 6 bytes commands");
468 
469 /*
470  * DA_ORDEREDTAG_INTERVAL determines how often, relative
471  * to the default timeout, we check to see whether an ordered
472  * tagged transaction is appropriate to prevent simple tag
473  * starvation.  Since we'd like to ensure that there is at least
474  * 1/2 of the timeout length left for a starved transaction to
475  * complete after we've sent an ordered tag, we must poll at least
476  * four times in every timeout period.  This takes care of the worst
477  * case where a starved transaction starts during an interval that
478  * meets the requirement "don't send an ordered tag" test so it takes
479  * us two intervals to determine that a tag must be sent.
480  */
481 #ifndef DA_ORDEREDTAG_INTERVAL
482 #define DA_ORDEREDTAG_INTERVAL 4
483 #endif
484 
485 static struct periph_driver dadriver =
486 {
487 	dainit, "da",
488 	TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
489 };
490 
491 PERIPHDRIVER_DECLARE(da, dadriver);
492 
493 #define DA_CDEV_MAJOR 13
494 
495 /* For 2.2-stable support */
496 #ifndef D_DISK
497 #define D_DISK 0
498 #endif
499 
500 static struct cdevsw da_cdevsw = {
501 	/* open */	daopen,
502 	/* close */	daclose,
503 	/* read */	physread,
504 	/* write */	physwrite,
505 	/* ioctl */	daioctl,
506 	/* poll */	nopoll,
507 	/* mmap */	nommap,
508 	/* strategy */	dastrategy,
509 	/* name */	"da",
510 	/* maj */	DA_CDEV_MAJOR,
511 	/* dump */	dadump,
512 	/* psize */	nopsize,
513 	/* flags */	D_DISK,
514 };
515 
516 static struct cdevsw dadisk_cdevsw;
517 
518 static SLIST_HEAD(,da_softc) softc_list;
519 
520 static int
521 daopen(dev_t dev, int flags __unused, int fmt __unused, struct thread *td __unused)
522 {
523 	struct cam_periph *periph;
524 	struct da_softc *softc;
525 	struct scsi_read_capacity_data *rcap;
526 	union  ccb *ccb;
527 	int unit;
528 	int error;
529 	int s;
530 
531 	s = splsoftcam();
532 	periph = (struct cam_periph *)dev->si_drv1;
533 	unit = periph->unit_number;
534 	if (periph == NULL) {
535 		splx(s);
536 		return (ENXIO);
537 	}
538 
539 	softc = (struct da_softc *)periph->softc;
540 
541 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
542 	    ("daopen: dev=%s (unit %d)\n", devtoname(dev),
543 	     unit));
544 
545 	if ((error = cam_periph_lock(periph, PRIBIO|PCATCH)) != 0)
546 		return (error); /* error code from tsleep */
547 
548 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
549 		return(ENXIO);
550 	softc->flags |= DA_FLAG_OPEN;
551 
552 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
553 		/* Invalidate our pack information. */
554 		disk_invalidate(&softc->disk);
555 		softc->flags &= ~DA_FLAG_PACK_INVALID;
556 	}
557 	splx(s);
558 
559 	/* Do a read capacity */
560 	rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
561 							M_TEMP,
562 							M_WAITOK);
563 
564 	ccb = cam_periph_getccb(periph, /*priority*/1);
565 	scsi_read_capacity(&ccb->csio,
566 			   /*retries*/4,
567 			   /*cbfncp*/dadone,
568 			   MSG_SIMPLE_Q_TAG,
569 			   rcap,
570 			   SSD_FULL_SIZE,
571 			   /*timeout*/60000);
572 	ccb->ccb_h.ccb_bp = NULL;
573 
574 	error = cam_periph_runccb(ccb, daerror,
575 				  /*cam_flags*/CAM_RETRY_SELTO,
576 				  /*sense_flags*/SF_RETRY_UA,
577 				  &softc->device_stats);
578 
579 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
580 		cam_release_devq(ccb->ccb_h.path,
581 				 /*relsim_flags*/0,
582 				 /*reduction*/0,
583 				 /*timeout*/0,
584 				 /*getcount_only*/0);
585 	xpt_release_ccb(ccb);
586 
587 	if (error == 0)
588 		dasetgeom(periph, rcap);
589 
590 	free(rcap, M_TEMP);
591 
592 	if (error == 0) {
593 
594 		softc->disk.d_sectorsize = softc->params.secsize;
595 		softc->disk.d_mediasize = softc->params.secsize * (off_t)softc->params.sectors;
596 		/* XXX: these are not actually "firmware" values, so they may be wrong */
597 		softc->disk.d_fwsectors = softc->params.secs_per_track;
598 		softc->disk.d_fwheads = softc->params.heads;
599 
600 		/*
601 		 * Check to see whether or not the blocksize is set yet.
602 		 * If it isn't, set it and then clear the blocksize
603 		 * unavailable flag for the device statistics.
604 		 */
605 		if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0){
606 			softc->device_stats.block_size = softc->params.secsize;
607 			softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
608 		}
609 	}
610 
611 	if (error == 0) {
612 		if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0)
613 			daprevent(periph, PR_PREVENT);
614 	}
615 	cam_periph_unlock(periph);
616 	return (error);
617 }
618 
619 static int
620 daclose(dev_t dev, int flag __unused, int fmt __unused, struct thread *td __unused)
621 {
622 	struct	cam_periph *periph;
623 	struct	da_softc *softc;
624 	int	error;
625 
626 	periph = (struct cam_periph *)dev->si_drv1;
627 	if (periph == NULL)
628 		return (ENXIO);
629 
630 	softc = (struct da_softc *)periph->softc;
631 
632 	if ((error = cam_periph_lock(periph, PRIBIO)) != 0) {
633 		return (error); /* error code from tsleep */
634 	}
635 
636 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
637 		union	ccb *ccb;
638 
639 		ccb = cam_periph_getccb(periph, /*priority*/1);
640 
641 		scsi_synchronize_cache(&ccb->csio,
642 				       /*retries*/1,
643 				       /*cbfcnp*/dadone,
644 				       MSG_SIMPLE_Q_TAG,
645 				       /*begin_lba*/0,/* Cover the whole disk */
646 				       /*lb_count*/0,
647 				       SSD_FULL_SIZE,
648 				       5 * 60 * 1000);
649 
650 		cam_periph_runccb(ccb, /*error_routine*/NULL, /*cam_flags*/0,
651 				  /*sense_flags*/SF_RETRY_UA,
652 				  &softc->device_stats);
653 
654 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
655 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
656 			     CAM_SCSI_STATUS_ERROR) {
657 				int asc, ascq;
658 				int sense_key, error_code;
659 
660 				scsi_extract_sense(&ccb->csio.sense_data,
661 						   &error_code,
662 						   &sense_key,
663 						   &asc, &ascq);
664 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
665 					scsi_sense_print(&ccb->csio);
666 			} else {
667 				xpt_print_path(periph->path);
668 				printf("Synchronize cache failed, status "
669 				       "== 0x%x, scsi status == 0x%x\n",
670 				       ccb->csio.ccb_h.status,
671 				       ccb->csio.scsi_status);
672 			}
673 		}
674 
675 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
676 			cam_release_devq(ccb->ccb_h.path,
677 					 /*relsim_flags*/0,
678 					 /*reduction*/0,
679 					 /*timeout*/0,
680 					 /*getcount_only*/0);
681 
682 		xpt_release_ccb(ccb);
683 
684 	}
685 
686 	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
687 		daprevent(periph, PR_ALLOW);
688 		/*
689 		 * If we've got removeable media, mark the blocksize as
690 		 * unavailable, since it could change when new media is
691 		 * inserted.
692 		 */
693 		softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
694 	}
695 
696 	softc->flags &= ~DA_FLAG_OPEN;
697 	cam_periph_unlock(periph);
698 	cam_periph_release(periph);
699 	return (0);
700 }
701 
702 /*
703  * Actually translate the requested transfer into one the physical driver
704  * can understand.  The transfer is described by a buf and will include
705  * only one physical transfer.
706  */
707 static void
708 dastrategy(struct bio *bp)
709 {
710 	struct cam_periph *periph;
711 	struct da_softc *softc;
712 	int    s;
713 
714 	periph = (struct cam_periph *)bp->bio_dev->si_drv1;
715 	if (periph == NULL) {
716 		biofinish(bp, NULL, ENXIO);
717 		return;
718 	}
719 	softc = (struct da_softc *)periph->softc;
720 #if 0
721 	/*
722 	 * check it's not too big a transfer for our adapter
723 	 */
724 	scsi_minphys(bp,&sd_switch);
725 #endif
726 
727 	/*
728 	 * Mask interrupts so that the pack cannot be invalidated until
729 	 * after we are in the queue.  Otherwise, we might not properly
730 	 * clean up one of the buffers.
731 	 */
732 	s = splbio();
733 
734 	/*
735 	 * If the device has been made invalid, error out
736 	 */
737 	if ((softc->flags & DA_FLAG_PACK_INVALID)) {
738 		splx(s);
739 		biofinish(bp, NULL, ENXIO);
740 		return;
741 	}
742 
743 	/*
744 	 * Place it in the queue of disk activities for this disk
745 	 */
746 	bioqdisksort(&softc->bio_queue, bp);
747 
748 	splx(s);
749 
750 	/*
751 	 * Schedule ourselves for performing the work.
752 	 */
753 	xpt_schedule(periph, /* XXX priority */1);
754 
755 	return;
756 }
757 
758 /* For 2.2-stable support */
759 #ifndef ENOIOCTL
760 #define ENOIOCTL -1
761 #endif
762 
763 static int
764 daioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
765 {
766 	struct cam_periph *periph;
767 	struct da_softc *softc;
768 	int error;
769 
770 	periph = (struct cam_periph *)dev->si_drv1;
771 	if (periph == NULL)
772 		return (ENXIO);
773 
774 	softc = (struct da_softc *)periph->softc;
775 
776 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("daioctl\n"));
777 
778 	if ((error = cam_periph_lock(periph, PRIBIO|PCATCH)) != 0) {
779 		return (error); /* error code from tsleep */
780 	}
781 
782 	error = cam_periph_ioctl(periph, cmd, addr, daerror);
783 
784 	cam_periph_unlock(periph);
785 
786 	return (error);
787 }
788 
789 static int
790 dadump(dev_t dev, void *virtual, vm_offset_t physical, off_t offset, size_t length)
791 {
792 	struct	    cam_periph *periph;
793 	struct	    da_softc *softc;
794 	u_int	    secsize;
795 	struct	    ccb_scsiio csio;
796 
797 	periph = (struct cam_periph *)dev->si_drv1;
798 	if (periph == NULL)
799 		return (ENXIO);
800 	softc = (struct da_softc *)periph->softc;
801 	secsize = softc->params.secsize;
802 
803 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0)
804 		return (ENXIO);
805 
806 	if (length > 0) {
807 		xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
808 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
809 		scsi_read_write(&csio,
810 				/*retries*/1,
811 				dadone,
812 				MSG_ORDERED_Q_TAG,
813 				/*read*/FALSE,
814 				/*byte2*/0,
815 				/*minimum_cmd_size*/ softc->minimum_cmd_size,
816 				offset / secsize,
817 				length / secsize,
818 				/*data_ptr*/(u_int8_t *) virtual,
819 				/*dxfer_len*/length,
820 				/*sense_len*/SSD_FULL_SIZE,
821 				DA_DEFAULT_TIMEOUT * 1000);
822 		xpt_polled_action((union ccb *)&csio);
823 
824 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
825 			printf("Aborting dump due to I/O error.\n");
826 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
827 			     CAM_SCSI_STATUS_ERROR)
828 				scsi_sense_print(&csio);
829 			else
830 				printf("status == 0x%x, scsi status == 0x%x\n",
831 				       csio.ccb_h.status, csio.scsi_status);
832 			return(EIO);
833 		}
834 		return(0);
835 	}
836 
837 	/*
838 	 * Sync the disk cache contents to the physical media.
839 	 */
840 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
841 
842 		xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
843 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
844 		scsi_synchronize_cache(&csio,
845 				       /*retries*/1,
846 				       /*cbfcnp*/dadone,
847 				       MSG_SIMPLE_Q_TAG,
848 				       /*begin_lba*/0,/* Cover the whole disk */
849 				       /*lb_count*/0,
850 				       SSD_FULL_SIZE,
851 				       5 * 60 * 1000);
852 		xpt_polled_action((union ccb *)&csio);
853 
854 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
855 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
856 			     CAM_SCSI_STATUS_ERROR) {
857 				int asc, ascq;
858 				int sense_key, error_code;
859 
860 				scsi_extract_sense(&csio.sense_data,
861 						   &error_code,
862 						   &sense_key,
863 						   &asc, &ascq);
864 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
865 					scsi_sense_print(&csio);
866 			} else {
867 				xpt_print_path(periph->path);
868 				printf("Synchronize cache failed, status "
869 				       "== 0x%x, scsi status == 0x%x\n",
870 				       csio.ccb_h.status, csio.scsi_status);
871 			}
872 		}
873 	}
874 	return (0);
875 }
876 
877 static void
878 dainit(void)
879 {
880 	cam_status status;
881 	struct cam_path *path;
882 
883 	SLIST_INIT(&softc_list);
884 
885 	/*
886 	 * Install a global async callback.  This callback will
887 	 * receive async callbacks like "new device found".
888 	 */
889 	status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
890 				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
891 
892 	if (status == CAM_REQ_CMP) {
893 		struct ccb_setasync csa;
894 
895                 xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
896                 csa.ccb_h.func_code = XPT_SASYNC_CB;
897                 csa.event_enable = AC_FOUND_DEVICE;
898                 csa.callback = daasync;
899                 csa.callback_arg = NULL;
900                 xpt_action((union ccb *)&csa);
901 		status = csa.ccb_h.status;
902                 xpt_free_path(path);
903         }
904 
905 	if (status != CAM_REQ_CMP) {
906 		printf("da: Failed to attach master async callback "
907 		       "due to status 0x%x!\n", status);
908 	} else {
909 
910 		/*
911 		 * Schedule a periodic event to occasionally send an
912 		 * ordered tag to a device.
913 		 */
914 		timeout(dasendorderedtag, NULL,
915 			(DA_DEFAULT_TIMEOUT * hz) / DA_ORDEREDTAG_INTERVAL);
916 
917 		/* Register our shutdown event handler */
918 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown,
919 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
920 		    printf("dainit: shutdown event registration failed!\n");
921 	}
922 }
923 
924 static void
925 daoninvalidate(struct cam_periph *periph)
926 {
927 	int s;
928 	struct da_softc *softc;
929 	struct bio *q_bp;
930 	struct ccb_setasync csa;
931 
932 	softc = (struct da_softc *)periph->softc;
933 
934 	/*
935 	 * De-register any async callbacks.
936 	 */
937 	xpt_setup_ccb(&csa.ccb_h, periph->path,
938 		      /* priority */ 5);
939 	csa.ccb_h.func_code = XPT_SASYNC_CB;
940 	csa.event_enable = 0;
941 	csa.callback = daasync;
942 	csa.callback_arg = periph;
943 	xpt_action((union ccb *)&csa);
944 
945 	softc->flags |= DA_FLAG_PACK_INVALID;
946 
947 	/*
948 	 * Although the oninvalidate() routines are always called at
949 	 * splsoftcam, we need to be at splbio() here to keep the buffer
950 	 * queue from being modified while we traverse it.
951 	 */
952 	s = splbio();
953 
954 	/*
955 	 * Return all queued I/O with ENXIO.
956 	 * XXX Handle any transactions queued to the card
957 	 *     with XPT_ABORT_CCB.
958 	 */
959 	while ((q_bp = bioq_first(&softc->bio_queue)) != NULL){
960 		bioq_remove(&softc->bio_queue, q_bp);
961 		q_bp->bio_resid = q_bp->bio_bcount;
962 		biofinish(q_bp, NULL, ENXIO);
963 	}
964 	splx(s);
965 
966 	SLIST_REMOVE(&softc_list, softc, da_softc, links);
967 
968 	xpt_print_path(periph->path);
969 	printf("lost device\n");
970 }
971 
972 static void
973 dacleanup(struct cam_periph *periph)
974 {
975 	struct da_softc *softc;
976 
977 	softc = (struct da_softc *)periph->softc;
978 
979 	devstat_remove_entry(&softc->device_stats);
980 	xpt_print_path(periph->path);
981 	printf("removing device entry\n");
982 	if (softc->dev) {
983 		disk_destroy(softc->dev);
984 	}
985 	free(softc, M_DEVBUF);
986 }
987 
988 static void
989 daasync(void *callback_arg, u_int32_t code,
990 	struct cam_path *path, void *arg)
991 {
992 	struct cam_periph *periph;
993 
994 	periph = (struct cam_periph *)callback_arg;
995 	switch (code) {
996 	case AC_FOUND_DEVICE:
997 	{
998 		struct ccb_getdev *cgd;
999 		cam_status status;
1000 
1001 		cgd = (struct ccb_getdev *)arg;
1002 		if (cgd == NULL)
1003 			break;
1004 
1005 		if (SID_TYPE(&cgd->inq_data) != T_DIRECT
1006 		    && SID_TYPE(&cgd->inq_data) != T_RBC
1007 		    && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
1008 			break;
1009 
1010 		/*
1011 		 * Allocate a peripheral instance for
1012 		 * this device and start the probe
1013 		 * process.
1014 		 */
1015 		status = cam_periph_alloc(daregister, daoninvalidate,
1016 					  dacleanup, dastart,
1017 					  "da", CAM_PERIPH_BIO,
1018 					  cgd->ccb_h.path, daasync,
1019 					  AC_FOUND_DEVICE, cgd);
1020 
1021 		if (status != CAM_REQ_CMP
1022 		 && status != CAM_REQ_INPROG)
1023 			printf("daasync: Unable to attach to new device "
1024 				"due to status 0x%x\n", status);
1025 		break;
1026 	}
1027 	case AC_SENT_BDR:
1028 	case AC_BUS_RESET:
1029 	{
1030 		struct da_softc *softc;
1031 		struct ccb_hdr *ccbh;
1032 		int s;
1033 
1034 		softc = (struct da_softc *)periph->softc;
1035 		s = splsoftcam();
1036 		/*
1037 		 * Don't fail on the expected unit attention
1038 		 * that will occur.
1039 		 */
1040 		softc->flags |= DA_FLAG_RETRY_UA;
1041 		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1042 			ccbh->ccb_state |= DA_CCB_RETRY_UA;
1043 		splx(s);
1044 		/* FALLTHROUGH*/
1045 	}
1046 	default:
1047 		cam_periph_async(periph, code, path, arg);
1048 		break;
1049 	}
1050 }
1051 
1052 static cam_status
1053 daregister(struct cam_periph *periph, void *arg)
1054 {
1055 	int s;
1056 	struct da_softc *softc;
1057 	struct ccb_setasync csa;
1058 	struct ccb_getdev *cgd;
1059 	caddr_t match;
1060 
1061 	cgd = (struct ccb_getdev *)arg;
1062 	if (periph == NULL) {
1063 		printf("daregister: periph was NULL!!\n");
1064 		return(CAM_REQ_CMP_ERR);
1065 	}
1066 
1067 	if (cgd == NULL) {
1068 		printf("daregister: no getdev CCB, can't register device\n");
1069 		return(CAM_REQ_CMP_ERR);
1070 	}
1071 
1072 	softc = (struct da_softc *)malloc(sizeof(*softc), M_DEVBUF,
1073 	    M_NOWAIT|M_ZERO);
1074 
1075 	if (softc == NULL) {
1076 		printf("daregister: Unable to probe new device. "
1077 		       "Unable to allocate softc\n");
1078 		return(CAM_REQ_CMP_ERR);
1079 	}
1080 
1081 	LIST_INIT(&softc->pending_ccbs);
1082 	softc->state = DA_STATE_PROBE;
1083 	bioq_init(&softc->bio_queue);
1084 	if (SID_IS_REMOVABLE(&cgd->inq_data))
1085 		softc->flags |= DA_FLAG_PACK_REMOVABLE;
1086 	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
1087 		softc->flags |= DA_FLAG_TAGGED_QUEUING;
1088 
1089 	periph->softc = softc;
1090 
1091 	/*
1092 	 * See if this device has any quirks.
1093 	 */
1094 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1095 			       (caddr_t)da_quirk_table,
1096 			       sizeof(da_quirk_table)/sizeof(*da_quirk_table),
1097 			       sizeof(*da_quirk_table), scsi_inquiry_match);
1098 
1099 	if (match != NULL)
1100 		softc->quirks = ((struct da_quirk_entry *)match)->quirks;
1101 	else
1102 		softc->quirks = DA_Q_NONE;
1103 
1104 	if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
1105 		softc->minimum_cmd_size = 10;
1106 	else
1107 		softc->minimum_cmd_size = 6;
1108 
1109 	/*
1110 	 * Block our timeout handler while we
1111 	 * add this softc to the dev list.
1112 	 */
1113 	s = splsoftclock();
1114 	SLIST_INSERT_HEAD(&softc_list, softc, links);
1115 	splx(s);
1116 
1117 	/*
1118 	 * The DA driver supports a blocksize, but
1119 	 * we don't know the blocksize until we do
1120 	 * a read capacity.  So, set a flag to
1121 	 * indicate that the blocksize is
1122 	 * unavailable right now.  We'll clear the
1123 	 * flag as soon as we've done a read capacity.
1124 	 */
1125 	devstat_add_entry(&softc->device_stats, "da",
1126 			  periph->unit_number, 0,
1127 	  		  DEVSTAT_BS_UNAVAILABLE,
1128 			  SID_TYPE(&cgd->inq_data) | DEVSTAT_TYPE_IF_SCSI,
1129 			  DEVSTAT_PRIORITY_DISK);
1130 
1131 	/*
1132 	 * Register this media as a disk
1133 	 */
1134 	softc->dev = disk_create(periph->unit_number, &softc->disk, 0,
1135 	    &da_cdevsw, &dadisk_cdevsw);
1136 	softc->dev->si_drv1 = periph;
1137 
1138 	/*
1139 	 * Add async callbacks for bus reset and
1140 	 * bus device reset calls.  I don't bother
1141 	 * checking if this fails as, in most cases,
1142 	 * the system will function just fine without
1143 	 * them and the only alternative would be to
1144 	 * not attach the device on failure.
1145 	 */
1146 	xpt_setup_ccb(&csa.ccb_h, periph->path, /*priority*/5);
1147 	csa.ccb_h.func_code = XPT_SASYNC_CB;
1148 	csa.event_enable = AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE;
1149 	csa.callback = daasync;
1150 	csa.callback_arg = periph;
1151 	xpt_action((union ccb *)&csa);
1152 	/*
1153 	 * Lock this peripheral until we are setup.
1154 	 * This first call can't block
1155 	 */
1156 	(void)cam_periph_lock(periph, PRIBIO);
1157 	xpt_schedule(periph, /*priority*/5);
1158 
1159 	return(CAM_REQ_CMP);
1160 }
1161 
1162 static void
1163 dastart(struct cam_periph *periph, union ccb *start_ccb)
1164 {
1165 	struct da_softc *softc;
1166 
1167 	softc = (struct da_softc *)periph->softc;
1168 
1169 
1170 	switch (softc->state) {
1171 	case DA_STATE_NORMAL:
1172 	{
1173 		/* Pull a buffer from the queue and get going on it */
1174 		struct bio *bp;
1175 		int s;
1176 
1177 		/*
1178 		 * See if there is a buf with work for us to do..
1179 		 */
1180 		s = splbio();
1181 		bp = bioq_first(&softc->bio_queue);
1182 		if (periph->immediate_priority <= periph->pinfo.priority) {
1183 			CAM_DEBUG_PRINT(CAM_DEBUG_SUBTRACE,
1184 					("queuing for immediate ccb\n"));
1185 			start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
1186 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1187 					  periph_links.sle);
1188 			periph->immediate_priority = CAM_PRIORITY_NONE;
1189 			splx(s);
1190 			wakeup(&periph->ccb_list);
1191 		} else if (bp == NULL) {
1192 			splx(s);
1193 			xpt_release_ccb(start_ccb);
1194 		} else {
1195 			int oldspl;
1196 			u_int8_t tag_code;
1197 
1198 			bioq_remove(&softc->bio_queue, bp);
1199 
1200 			devstat_start_transaction(&softc->device_stats);
1201 
1202 			if ((softc->flags & DA_FLAG_NEED_OTAG) != 0) {
1203 				softc->flags &= ~DA_FLAG_NEED_OTAG;
1204 				softc->ordered_tag_count++;
1205 				tag_code = MSG_ORDERED_Q_TAG;
1206 			} else {
1207 				tag_code = MSG_SIMPLE_Q_TAG;
1208 			}
1209 			if (da_no_6_byte && softc->minimum_cmd_size == 6)
1210 				softc->minimum_cmd_size = 10;
1211 			scsi_read_write(&start_ccb->csio,
1212 					/*retries*/da_retry_count,
1213 					dadone,
1214 					tag_code,
1215 					bp->bio_cmd == BIO_READ,
1216 					/*byte2*/0,
1217 					softc->minimum_cmd_size,
1218 					bp->bio_pblkno,
1219 					bp->bio_bcount / softc->params.secsize,
1220 					bp->bio_data,
1221 					bp->bio_bcount,
1222 					/*sense_len*/SSD_FULL_SIZE,
1223 					da_default_timeout * 1000);
1224 			start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
1225 
1226 			/*
1227 			 * Block out any asyncronous callbacks
1228 			 * while we touch the pending ccb list.
1229 			 */
1230 			oldspl = splcam();
1231 			LIST_INSERT_HEAD(&softc->pending_ccbs,
1232 					 &start_ccb->ccb_h, periph_links.le);
1233 			splx(oldspl);
1234 
1235 			/* We expect a unit attention from this device */
1236 			if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
1237 				start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
1238 				softc->flags &= ~DA_FLAG_RETRY_UA;
1239 			}
1240 
1241 			start_ccb->ccb_h.ccb_bp = bp;
1242 			bp = bioq_first(&softc->bio_queue);
1243 			splx(s);
1244 
1245 			xpt_action(start_ccb);
1246 		}
1247 
1248 		if (bp != NULL) {
1249 			/* Have more work to do, so ensure we stay scheduled */
1250 			xpt_schedule(periph, /* XXX priority */1);
1251 		}
1252 		break;
1253 	}
1254 	case DA_STATE_PROBE:
1255 	{
1256 		struct ccb_scsiio *csio;
1257 		struct scsi_read_capacity_data *rcap;
1258 
1259 		rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1260 								M_TEMP,
1261 								M_NOWAIT);
1262 		if (rcap == NULL) {
1263 			printf("dastart: Couldn't malloc read_capacity data\n");
1264 			/* da_free_periph??? */
1265 			break;
1266 		}
1267 		csio = &start_ccb->csio;
1268 		scsi_read_capacity(csio,
1269 				   /*retries*/4,
1270 				   dadone,
1271 				   MSG_SIMPLE_Q_TAG,
1272 				   rcap,
1273 				   SSD_FULL_SIZE,
1274 				   /*timeout*/5000);
1275 		start_ccb->ccb_h.ccb_bp = NULL;
1276 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE;
1277 		xpt_action(start_ccb);
1278 		break;
1279 	}
1280 	}
1281 }
1282 
1283 static int
1284 cmd6workaround(union ccb *ccb)
1285 {
1286 	struct scsi_rw_6 cmd6;
1287 	struct scsi_rw_10 *cmd10;
1288 	struct da_softc *softc;
1289 	u_int8_t *cdb;
1290 	int frozen;
1291 
1292 	cdb = ccb->csio.cdb_io.cdb_bytes;
1293 
1294 	/* Translation only possible if CDB is an array and cmd is R/W6 */
1295 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
1296 	    (*cdb != READ_6 && *cdb != WRITE_6))
1297 		return 0;
1298 
1299 	xpt_print_path(ccb->ccb_h.path);
1300  	printf("READ(6)/WRITE(6) not supported, "
1301 	       "increasing minimum_cmd_size to 10.\n");
1302  	softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
1303 	softc->minimum_cmd_size = 10;
1304 
1305 	bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
1306 	cmd10 = (struct scsi_rw_10 *)cdb;
1307 	cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
1308 	cmd10->byte2 = 0;
1309 	scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
1310 	cmd10->reserved = 0;
1311 	scsi_ulto2b(cmd6.length, cmd10->length);
1312 	cmd10->control = cmd6.control;
1313 	ccb->csio.cdb_len = sizeof(*cmd10);
1314 
1315 	/* Requeue request, unfreezing queue if necessary */
1316 	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
1317  	ccb->ccb_h.status = CAM_REQUEUE_REQ;
1318 	xpt_action(ccb);
1319 	if (frozen) {
1320 		cam_release_devq(ccb->ccb_h.path,
1321 				 /*relsim_flags*/0,
1322 				 /*reduction*/0,
1323 				 /*timeout*/0,
1324 				 /*getcount_only*/0);
1325 	}
1326 	return (ERESTART);
1327 }
1328 
1329 static void
1330 dadone(struct cam_periph *periph, union ccb *done_ccb)
1331 {
1332 	struct da_softc *softc;
1333 	struct ccb_scsiio *csio;
1334 
1335 	softc = (struct da_softc *)periph->softc;
1336 	csio = &done_ccb->csio;
1337 	switch (csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) {
1338 	case DA_CCB_BUFFER_IO:
1339 	{
1340 		struct bio *bp;
1341 		int    oldspl;
1342 
1343 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1344 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1345 			int error;
1346 			int s;
1347 			int sf;
1348 
1349 			if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
1350 				sf = SF_RETRY_UA;
1351 			else
1352 				sf = 0;
1353 
1354 			error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
1355 			if (error == ERESTART) {
1356 				/*
1357 				 * A retry was scheuled, so
1358 				 * just return.
1359 				 */
1360 				return;
1361 			}
1362 			if (error != 0) {
1363 				struct bio *q_bp;
1364 
1365 				s = splbio();
1366 
1367 				if (error == ENXIO) {
1368 					/*
1369 					 * Catastrophic error.  Mark our pack as
1370 					 * invalid.
1371 					 */
1372 					/* XXX See if this is really a media
1373 					 *     change first.
1374 					 */
1375 					xpt_print_path(periph->path);
1376 					printf("Invalidating pack\n");
1377 					softc->flags |= DA_FLAG_PACK_INVALID;
1378 				}
1379 
1380 				/*
1381 				 * return all queued I/O with EIO, so that
1382 				 * the client can retry these I/Os in the
1383 				 * proper order should it attempt to recover.
1384 				 */
1385 				while ((q_bp = bioq_first(&softc->bio_queue))
1386 					!= NULL) {
1387 					bioq_remove(&softc->bio_queue, q_bp);
1388 					q_bp->bio_resid = q_bp->bio_bcount;
1389 					biofinish(q_bp, NULL, EIO);
1390 				}
1391 				splx(s);
1392 				bp->bio_error = error;
1393 				bp->bio_resid = bp->bio_bcount;
1394 				bp->bio_flags |= BIO_ERROR;
1395 			} else {
1396 				bp->bio_resid = csio->resid;
1397 				bp->bio_error = 0;
1398 				if (bp->bio_resid != 0) {
1399 					/* Short transfer ??? */
1400 #if 0
1401 					if (cmd6workaround(done_ccb)
1402 								== ERESTART)
1403 						return;
1404 #endif
1405 					bp->bio_flags |= BIO_ERROR;
1406 				}
1407 			}
1408 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1409 				cam_release_devq(done_ccb->ccb_h.path,
1410 						 /*relsim_flags*/0,
1411 						 /*reduction*/0,
1412 						 /*timeout*/0,
1413 						 /*getcount_only*/0);
1414 		} else {
1415 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1416 				panic("REQ_CMP with QFRZN");
1417 			bp->bio_resid = csio->resid;
1418 			if (csio->resid > 0) {
1419 				/* Short transfer ??? */
1420 #if 0 /* XXX most of the broken umass devices need this ad-hoc work around */
1421 				if (cmd6workaround(done_ccb) == ERESTART)
1422 					return;
1423 #endif
1424 				bp->bio_flags |= BIO_ERROR;
1425 			}
1426 		}
1427 
1428 		/*
1429 		 * Block out any asyncronous callbacks
1430 		 * while we touch the pending ccb list.
1431 		 */
1432 		oldspl = splcam();
1433 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1434 		splx(oldspl);
1435 
1436 		if (softc->device_stats.busy_count == 0)
1437 			softc->flags |= DA_FLAG_WENT_IDLE;
1438 
1439 		biofinish(bp, &softc->device_stats, 0);
1440 		break;
1441 	}
1442 	case DA_CCB_PROBE:
1443 	{
1444 		struct	   scsi_read_capacity_data *rdcap;
1445 		char	   announce_buf[80];
1446 
1447 		rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1448 
1449 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1450 			struct disk_params *dp;
1451 
1452 			dasetgeom(periph, rdcap);
1453 			dp = &softc->params;
1454 			snprintf(announce_buf, sizeof(announce_buf),
1455 			        "%luMB (%u %u byte sectors: %dH %dS/T %dC)",
1456 				(unsigned long) (((u_int64_t)dp->secsize *
1457 				dp->sectors) / (1024*1024)), dp->sectors,
1458 				dp->secsize, dp->heads, dp->secs_per_track,
1459 				dp->cylinders);
1460 		} else {
1461 			int	error;
1462 
1463 			announce_buf[0] = '\0';
1464 
1465 			/*
1466 			 * Retry any UNIT ATTENTION type errors.  They
1467 			 * are expected at boot.
1468 			 */
1469 			error = daerror(done_ccb, CAM_RETRY_SELTO,
1470 					SF_RETRY_UA|SF_NO_PRINT);
1471 			if (error == ERESTART) {
1472 				/*
1473 				 * A retry was scheuled, so
1474 				 * just return.
1475 				 */
1476 				return;
1477 			} else if (error != 0) {
1478 				struct scsi_sense_data *sense;
1479 				int asc, ascq;
1480 				int sense_key, error_code;
1481 				int have_sense;
1482 				cam_status status;
1483 				struct ccb_getdev cgd;
1484 
1485 				/* Don't wedge this device's queue */
1486 				status = done_ccb->ccb_h.status;
1487 				if ((status & CAM_DEV_QFRZN) != 0)
1488 					cam_release_devq(done_ccb->ccb_h.path,
1489 							 /*relsim_flags*/0,
1490 							 /*reduction*/0,
1491 							 /*timeout*/0,
1492 							 /*getcount_only*/0);
1493 
1494 
1495 				xpt_setup_ccb(&cgd.ccb_h,
1496 					      done_ccb->ccb_h.path,
1497 					      /* priority */ 1);
1498 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1499 				xpt_action((union ccb *)&cgd);
1500 
1501 				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1502 				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1503 				 || ((status & CAM_AUTOSNS_VALID) == 0))
1504 					have_sense = FALSE;
1505 				else
1506 					have_sense = TRUE;
1507 
1508 				if (have_sense) {
1509 					sense = &csio->sense_data;
1510 					scsi_extract_sense(sense, &error_code,
1511 							   &sense_key,
1512 							   &asc, &ascq);
1513 				}
1514 				/*
1515 				 * Attach to anything that claims to be a
1516 				 * direct access or optical disk device,
1517 				 * as long as it doesn't return a "Logical
1518 				 * unit not supported" (0x25) error.
1519 				 */
1520 				if ((have_sense) && (asc != 0x25)
1521 				 && (error_code == SSD_CURRENT_ERROR)) {
1522 					const char *sense_key_desc;
1523 					const char *asc_desc;
1524 
1525 					scsi_sense_desc(sense_key, asc, ascq,
1526 							&cgd.inq_data,
1527 							&sense_key_desc,
1528 							&asc_desc);
1529 					snprintf(announce_buf,
1530 					    sizeof(announce_buf),
1531 						"Attempt to query device "
1532 						"size failed: %s, %s",
1533 						sense_key_desc,
1534 						asc_desc);
1535 				} else {
1536 					if (have_sense)
1537 						scsi_sense_print(
1538 							&done_ccb->csio);
1539 					else {
1540 						xpt_print_path(periph->path);
1541 						printf("got CAM status %#x\n",
1542 						       done_ccb->ccb_h.status);
1543 					}
1544 
1545 					xpt_print_path(periph->path);
1546 					printf("fatal error, failed"
1547 					       " to attach to device\n");
1548 
1549 					/*
1550 					 * Free up resources.
1551 					 */
1552 					cam_periph_invalidate(periph);
1553 				}
1554 			}
1555 		}
1556 		free(rdcap, M_TEMP);
1557 		if (announce_buf[0] != '\0')
1558 			xpt_announce_periph(periph, announce_buf);
1559 		softc->state = DA_STATE_NORMAL;
1560 		/*
1561 		 * Since our peripheral may be invalidated by an error
1562 		 * above or an external event, we must release our CCB
1563 		 * before releasing the probe lock on the peripheral.
1564 		 * The peripheral will only go away once the last lock
1565 		 * is removed, and we need it around for the CCB release
1566 		 * operation.
1567 		 */
1568 		xpt_release_ccb(done_ccb);
1569 		cam_periph_unlock(periph);
1570 		return;
1571 	}
1572 	case DA_CCB_WAITING:
1573 	{
1574 		/* Caller will release the CCB */
1575 		wakeup(&done_ccb->ccb_h.cbfcnp);
1576 		return;
1577 	}
1578 	case DA_CCB_DUMP:
1579 		/* No-op.  We're polling */
1580 		return;
1581 	default:
1582 		break;
1583 	}
1584 	xpt_release_ccb(done_ccb);
1585 }
1586 
1587 static int
1588 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1589 {
1590 	struct da_softc	  *softc;
1591 	struct cam_periph *periph;
1592 	int error, sense_key, error_code, asc, ascq;
1593 
1594 	periph = xpt_path_periph(ccb->ccb_h.path);
1595 	softc = (struct da_softc *)periph->softc;
1596 
1597  	/*
1598 	 * Automatically detect devices that do not support
1599  	 * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
1600  	 */
1601 	error = 0;
1602 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR
1603 	  && ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND) {
1604  		scsi_extract_sense(&ccb->csio.sense_data,
1605 				   &error_code, &sense_key, &asc, &ascq);
1606 		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
1607  			error = cmd6workaround(ccb);
1608 	}
1609 	if (error == ERESTART)
1610 		return (ERESTART);
1611 
1612 	/*
1613 	 * XXX
1614 	 * Until we have a better way of doing pack validation,
1615 	 * don't treat UAs as errors.
1616 	 */
1617 	sense_flags |= SF_RETRY_UA;
1618 	return(cam_periph_error(ccb, cam_flags, sense_flags,
1619 				&softc->saved_ccb));
1620 }
1621 
1622 static void
1623 daprevent(struct cam_periph *periph, int action)
1624 {
1625 	struct	da_softc *softc;
1626 	union	ccb *ccb;
1627 	int	error;
1628 
1629 	softc = (struct da_softc *)periph->softc;
1630 
1631 	if (((action == PR_ALLOW)
1632 	  && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
1633 	 || ((action == PR_PREVENT)
1634 	  && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
1635 		return;
1636 	}
1637 
1638 	ccb = cam_periph_getccb(periph, /*priority*/1);
1639 
1640 	scsi_prevent(&ccb->csio,
1641 		     /*retries*/1,
1642 		     /*cbcfp*/dadone,
1643 		     MSG_SIMPLE_Q_TAG,
1644 		     action,
1645 		     SSD_FULL_SIZE,
1646 		     5000);
1647 
1648 	error = cam_periph_runccb(ccb, /*error_routine*/NULL, CAM_RETRY_SELTO,
1649 				  SF_RETRY_UA, &softc->device_stats);
1650 
1651 	if (error == 0) {
1652 		if (action == PR_ALLOW)
1653 			softc->flags &= ~DA_FLAG_PACK_LOCKED;
1654 		else
1655 			softc->flags |= DA_FLAG_PACK_LOCKED;
1656 	}
1657 
1658 	xpt_release_ccb(ccb);
1659 }
1660 
1661 static void
1662 dasetgeom(struct cam_periph *periph, struct scsi_read_capacity_data * rdcap)
1663 {
1664 	struct ccb_calc_geometry ccg;
1665 	struct da_softc *softc;
1666 	struct disk_params *dp;
1667 
1668 	softc = (struct da_softc *)periph->softc;
1669 
1670 	dp = &softc->params;
1671 	dp->secsize = scsi_4btoul(rdcap->length);
1672 	dp->sectors = scsi_4btoul(rdcap->addr) + 1;
1673 	/*
1674 	 * Have the controller provide us with a geometry
1675 	 * for this disk.  The only time the geometry
1676 	 * matters is when we boot and the controller
1677 	 * is the only one knowledgeable enough to come
1678 	 * up with something that will make this a bootable
1679 	 * device.
1680 	 */
1681 	xpt_setup_ccb(&ccg.ccb_h, periph->path, /*priority*/1);
1682 	ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
1683 	ccg.block_size = dp->secsize;
1684 	ccg.volume_size = dp->sectors;
1685 	ccg.heads = 0;
1686 	ccg.secs_per_track = 0;
1687 	ccg.cylinders = 0;
1688 	xpt_action((union ccb*)&ccg);
1689 	dp->heads = ccg.heads;
1690 	dp->secs_per_track = ccg.secs_per_track;
1691 	dp->cylinders = ccg.cylinders;
1692 }
1693 
1694 static void
1695 dasendorderedtag(void *arg)
1696 {
1697 	struct da_softc *softc;
1698 	int s;
1699 
1700 	for (softc = SLIST_FIRST(&softc_list);
1701 	     softc != NULL;
1702 	     softc = SLIST_NEXT(softc, links)) {
1703 		s = splsoftcam();
1704 		if ((softc->ordered_tag_count == 0)
1705 		 && ((softc->flags & DA_FLAG_WENT_IDLE) == 0)) {
1706 			softc->flags |= DA_FLAG_NEED_OTAG;
1707 		}
1708 		if (softc->device_stats.busy_count > 0)
1709 			softc->flags &= ~DA_FLAG_WENT_IDLE;
1710 
1711 		softc->ordered_tag_count = 0;
1712 		splx(s);
1713 	}
1714 	/* Queue us up again */
1715 	timeout(dasendorderedtag, NULL,
1716 		(da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL);
1717 }
1718 
1719 /*
1720  * Step through all DA peripheral drivers, and if the device is still open,
1721  * sync the disk cache to physical media.
1722  */
1723 static void
1724 dashutdown(void * arg, int howto)
1725 {
1726 	struct cam_periph *periph;
1727 	struct da_softc *softc;
1728 
1729 	TAILQ_FOREACH(periph, &dadriver.units, unit_links) {
1730 		union ccb ccb;
1731 		softc = (struct da_softc *)periph->softc;
1732 
1733 		/*
1734 		 * We only sync the cache if the drive is still open, and
1735 		 * if the drive is capable of it..
1736 		 */
1737 		if (((softc->flags & DA_FLAG_OPEN) == 0)
1738 		 || (softc->quirks & DA_Q_NO_SYNC_CACHE))
1739 			continue;
1740 
1741 		xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/1);
1742 
1743 		ccb.ccb_h.ccb_state = DA_CCB_DUMP;
1744 		scsi_synchronize_cache(&ccb.csio,
1745 				       /*retries*/1,
1746 				       /*cbfcnp*/dadone,
1747 				       MSG_SIMPLE_Q_TAG,
1748 				       /*begin_lba*/0, /* whole disk */
1749 				       /*lb_count*/0,
1750 				       SSD_FULL_SIZE,
1751 				       60 * 60 * 1000);
1752 
1753 		xpt_polled_action(&ccb);
1754 
1755 		if ((ccb.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1756 			if (((ccb.ccb_h.status & CAM_STATUS_MASK) ==
1757 			     CAM_SCSI_STATUS_ERROR)
1758 			 && (ccb.csio.scsi_status == SCSI_STATUS_CHECK_COND)){
1759 				int error_code, sense_key, asc, ascq;
1760 
1761 				scsi_extract_sense(&ccb.csio.sense_data,
1762 						   &error_code, &sense_key,
1763 						   &asc, &ascq);
1764 
1765 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
1766 					scsi_sense_print(&ccb.csio);
1767 			} else {
1768 				xpt_print_path(periph->path);
1769 				printf("Synchronize cache failed, status "
1770 				       "== 0x%x, scsi status == 0x%x\n",
1771 				       ccb.ccb_h.status, ccb.csio.scsi_status);
1772 			}
1773 		}
1774 
1775 		if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
1776 			cam_release_devq(ccb.ccb_h.path,
1777 					 /*relsim_flags*/0,
1778 					 /*reduction*/0,
1779 					 /*timeout*/0,
1780 					 /*getcount_only*/0);
1781 
1782 	}
1783 }
1784 
1785 #else /* !_KERNEL */
1786 
1787 /*
1788  * XXX This is only left out of the kernel build to silence warnings.  If,
1789  * for some reason this function is used in the kernel, the ifdefs should
1790  * be moved so it is included both in the kernel and userland.
1791  */
1792 void
1793 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
1794 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
1795 		 u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
1796 		 u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
1797 		 u_int32_t timeout)
1798 {
1799 	struct scsi_format_unit *scsi_cmd;
1800 
1801 	scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
1802 	scsi_cmd->opcode = FORMAT_UNIT;
1803 	scsi_cmd->byte2 = byte2;
1804 	scsi_ulto2b(ileave, scsi_cmd->interleave);
1805 
1806 	cam_fill_csio(csio,
1807 		      retries,
1808 		      cbfcnp,
1809 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
1810 		      tag_action,
1811 		      data_ptr,
1812 		      dxfer_len,
1813 		      sense_len,
1814 		      sizeof(*scsi_cmd),
1815 		      timeout);
1816 }
1817 
1818 #endif /* _KERNEL */
1819