xref: /dragonfly/sys/bus/cam/scsi/scsi_da.c (revision 9f3fc534)
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: src/sys/cam/scsi/scsi_da.c,v 1.42.2.46 2003/10/21 22:18:19 thomas Exp $
29  * $DragonFly: src/sys/bus/cam/scsi/scsi_da.c,v 1.59 2008/08/29 20:08:40 dillon Exp $
30  */
31 
32 #include <sys/param.h>
33 #include <sys/bootmaj.h>
34 
35 #ifdef _KERNEL
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/buf.h>
39 #include <sys/sysctl.h>
40 #include <sys/taskqueue.h>
41 #include <sys/lock.h>
42 #include <sys/conf.h>
43 #include <sys/devicestat.h>
44 #include <sys/disk.h>
45 #include <sys/dtype.h>
46 #include <sys/eventhandler.h>
47 #include <sys/malloc.h>
48 #include <sys/cons.h>
49 #include <sys/proc.h>
50 #include <sys/buf2.h>
51 #include <sys/thread2.h>
52 #endif /* _KERNEL */
53 
54 #ifdef _KERNEL
55 #include <vm/pmap.h>
56 #endif
57 
58 #ifndef _KERNEL
59 #include <stdio.h>
60 #include <string.h>
61 #endif /* _KERNEL */
62 
63 #include "../cam.h"
64 #include "../cam_ccb.h"
65 #include "../cam_extend.h"
66 #include "../cam_periph.h"
67 #include "../cam_xpt_periph.h"
68 #include "../cam_sim.h"
69 
70 #include "scsi_message.h"
71 
72 #ifndef _KERNEL
73 #include "scsi_da.h"
74 #endif /* !_KERNEL */
75 
76 #ifdef _KERNEL
77 typedef enum {
78 	DA_STATE_PROBE,
79 	DA_STATE_PROBE2,
80 	DA_STATE_NORMAL
81 } da_state;
82 
83 typedef enum {
84 	DA_FLAG_PACK_INVALID	= 0x001,
85 	DA_FLAG_NEW_PACK	= 0x002,
86 	DA_FLAG_PACK_LOCKED	= 0x004,
87 	DA_FLAG_PACK_REMOVABLE	= 0x008,
88 	DA_FLAG_TAGGED_QUEUING	= 0x010,
89 	DA_FLAG_NEED_OTAG	= 0x020,
90 	DA_FLAG_WENT_IDLE	= 0x040,
91 	DA_FLAG_RETRY_UA	= 0x080,
92 	DA_FLAG_OPEN		= 0x100,
93 	DA_FLAG_SCTX_INIT	= 0x200
94 } da_flags;
95 
96 typedef enum {
97 	DA_Q_NONE		= 0x00,
98 	DA_Q_NO_SYNC_CACHE	= 0x01,
99 	DA_Q_NO_6_BYTE		= 0x02,
100 	DA_Q_NO_PREVENT		= 0x04
101 } da_quirks;
102 
103 typedef enum {
104 	DA_CCB_PROBE		= 0x01,
105 	DA_CCB_PROBE2		= 0x02,
106 	DA_CCB_BUFFER_IO	= 0x03,
107 	DA_CCB_WAITING		= 0x04,
108 	DA_CCB_DUMP		= 0x05,
109 	DA_CCB_TYPE_MASK	= 0x0F,
110 	DA_CCB_RETRY_UA		= 0x10
111 } da_ccb_state;
112 
113 /* Offsets into our private area for storing information */
114 #define ccb_state	ppriv_field0
115 #define ccb_bio		ppriv_ptr1
116 
117 struct disk_params {
118 	u_int8_t  heads;
119 	u_int32_t cylinders;
120 	u_int8_t  secs_per_track;
121 	u_int32_t secsize;	/* Number of bytes/sector */
122 	u_int64_t sectors;	/* total number sectors */
123 };
124 
125 struct da_softc {
126 	struct	 bio_queue_head bio_queue;
127 	struct	 devstat device_stats;
128 	SLIST_ENTRY(da_softc) links;
129 	LIST_HEAD(, ccb_hdr) pending_ccbs;
130 	da_state state;
131 	da_flags flags;
132 	da_quirks quirks;
133 	int	 minimum_cmd_size;
134 	int	 ordered_tag_count;
135 	int	 outstanding_cmds;
136 	struct	 disk_params params;
137 	struct	 disk disk;
138 	union	 ccb saved_ccb;
139 	struct task		sysctl_task;
140 	struct sysctl_ctx_list	sysctl_ctx;
141 	struct sysctl_oid	*sysctl_tree;
142 	struct callout		sendordered_c;
143 };
144 
145 struct da_quirk_entry {
146 	struct scsi_inquiry_pattern inq_pat;
147 	da_quirks quirks;
148 };
149 
150 static const char quantum[] = "QUANTUM";
151 static const char microp[] = "MICROP";
152 
153 static struct da_quirk_entry da_quirk_table[] =
154 {
155 	/* SPI, FC devices */
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 		 * This drive doesn't like the synchronize cache command
183 		 * either.  Reported by: Matthew Jacob <mjacob@feral.com>
184 		 * in NetBSD PR kern/6027, August 24, 1998.
185 		 */
186 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
187 		/*quirks*/ DA_Q_NO_SYNC_CACHE
188 	},
189 	{
190 		/*
191 		 * This drive doesn't like the synchronize cache command
192 		 * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
193 		 * (PR 8882).
194 		 */
195 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
196 		/*quirks*/ DA_Q_NO_SYNC_CACHE
197 	},
198 	{
199 		/*
200 		 * Doesn't like the synchronize cache command.
201 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
202 		 */
203 		{T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
204 		/*quirks*/ DA_Q_NO_SYNC_CACHE
205 	},
206 	{
207 		/*
208 		 * Doesn't like the synchronize cache command.
209 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
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 like the synchronize cache command.
224 		 * Reported by: walter@pelissero.de
225 		 */
226 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS540S", "*"},
227 		/*quirks*/ DA_Q_NO_SYNC_CACHE
228 	},
229 	{
230 		/*
231 		 * Doesn't work correctly with 6 byte reads/writes.
232 		 * Returns illegal request, and points to byte 9 of the
233 		 * 6-byte CDB.
234 		 * Reported by:  Adam McDougall <bsdx@spawnet.com>
235 		 */
236 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
237 		/*quirks*/ DA_Q_NO_6_BYTE
238 	},
239 	{
240 		/* See above. */
241 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
242 		/*quirks*/ DA_Q_NO_6_BYTE
243 	},
244 	{
245 		/*
246 		 * Doesn't like the synchronize cache command.
247 		 * Reported by: walter@pelissero.de
248 		 */
249 		{T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CP3500*", "*"},
250 		/*quirks*/ DA_Q_NO_SYNC_CACHE
251 	},
252 	{
253 		/*
254 		 * The CISS RAID controllers do not support SYNC_CACHE
255 		 */
256 		{T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"},
257 		/*quirks*/ DA_Q_NO_SYNC_CACHE
258 	},
259 	/* USB mass storage devices supported by umass(4) */
260 	{
261 		/*
262 		 * EXATELECOM (Sigmatel) i-Bead 100/105 USB Flash MP3 Player
263 		 * PR: kern/51675
264 		 */
265 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EXATEL", "i-BEAD10*", "*"},
266 		/*quirks*/ DA_Q_NO_SYNC_CACHE
267 	},
268 	{
269 		/*
270 		 * Power Quotient Int. (PQI) USB flash key
271 		 * PR: kern/53067
272 		 */
273 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "USB Flash Disk*",
274 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
275 	},
276  	{
277  		/*
278  		 * Creative Nomad MUVO mp3 player (USB)
279  		 * PR: kern/53094
280  		 */
281  		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"},
282  		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
283  	},
284 	{
285 		/*
286 		 * Jungsoft NEXDISK USB flash key
287 		 * PR: kern/54737
288 		 */
289 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JUNGSOFT", "NEXDISK*", "*"},
290 		/*quirks*/ DA_Q_NO_SYNC_CACHE
291 	},
292 	{
293 		/*
294 		 * FreeDik USB Mini Data Drive
295 		 * PR: kern/54786
296 		 */
297 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FreeDik*", "Mini Data Drive",
298 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
299 	},
300 	{
301 		/*
302 		 * Sigmatel USB Flash MP3 Player
303 		 * PR: kern/57046
304 		 */
305 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SigmaTel", "MSCN", "*"},
306 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
307 	},
308 	{
309 		/*
310 		 * Neuros USB Digital Audio Computer
311 		 * PR: kern/63645
312 		 */
313 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "NEUROS", "dig. audio comp.",
314 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
315 	},
316 	{
317 		/*
318 		 * SEAGRAND NP-900 MP3 Player
319 		 * PR: kern/64563
320 		 */
321 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SEAGRAND", "NP-900*", "*"},
322 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
323 	},
324 	{
325 		/*
326 		 * iRiver iFP MP3 player (with UMS Firmware)
327 		 * PR: kern/54881, i386/63941, kern/66124
328 		 */
329 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iRiver", "iFP*", "*"},
330 		/*quirks*/ DA_Q_NO_SYNC_CACHE
331  	},
332 	{
333 		/*
334 		 * Frontier Labs NEX IA+ Digital Audio Player, rev 1.10/0.01
335 		 * PR: kern/70158
336 		 */
337 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FL" , "Nex*", "*"},
338 		/*quirks*/ DA_Q_NO_SYNC_CACHE
339 	},
340 	{
341 		/*
342 		 * ZICPlay USB MP3 Player with FM
343 		 * PR: kern/75057
344 		 */
345 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ACTIONS*" , "USB DISK*", "*"},
346 		/*quirks*/ DA_Q_NO_SYNC_CACHE
347 	},
348 	{
349 		/*
350 		 * TEAC USB floppy mechanisms
351 		 */
352 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TEAC" , "FD-05*", "*"},
353 		/*quirks*/ DA_Q_NO_SYNC_CACHE
354 	},
355 	{
356 		/*
357 		 * Kingston DataTraveler II+ USB Pen-Drive.
358 		 * Reported by: Pawel Jakub Dawidek <pjd@FreeBSD.org>
359 		 */
360 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston" , "DataTraveler II+",
361 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
362 	},
363 	{
364 		/*
365 		 * Motorola E398 Mobile Phone (TransFlash memory card).
366 		 * Reported by: Wojciech A. Koszek <dunstan@FreeBSD.czest.pl>
367 		 * PR: usb/89889
368 		 */
369 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Motorola" , "Motorola Phone",
370 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
371 	},
372 	{
373 		/*
374 		 * Qware BeatZkey! Pro
375 		 * PR: usb/79164
376 		 */
377 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "GENERIC", "USB DISK DEVICE",
378 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
379 	},
380 	{
381 		/*
382 		 * Time DPA20B 1GB MP3 Player
383 		 * PR: usb/81846
384 		 */
385 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB2.0*", "(FS) FLASH DISK*",
386 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
387 	},
388 	{
389 		/*
390 		 * Samsung USB key 128Mb
391 		 * PR: usb/90081
392 		 */
393 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB-DISK", "FreeDik-FlashUsb",
394 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
395 	},
396 	{
397 		/*
398 		 * Kingston DataTraveler 2.0 USB Flash memory.
399 		 * PR: usb/89196
400 		 */
401 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler 2.0",
402 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
403 	},
404 	{
405 		/*
406 		 * Creative MUVO Slim mp3 player (USB)
407 		 * PR: usb/86131
408 		 */
409 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "MuVo Slim",
410 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
411 		},
412 	{
413 		/*
414 		 * United MP5512 Portable MP3 Player (2-in-1 USB DISK/MP3)
415 		 * PR: usb/80487
416 		 */
417 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "MUSIC DISK",
418 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
419 	},
420 	{
421 		/*
422 		 * SanDisk Micro Cruzer 128MB
423 		 * PR: usb/75970
424 		 */
425 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SanDisk" , "Micro Cruzer",
426 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
427 	},
428 	{
429 		/*
430 		 * TOSHIBA TransMemory USB sticks
431 		 * PR: kern/94660
432 		 */
433 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TOSHIBA", "TransMemory",
434 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
435 	},
436 	{
437 		/*
438 		 * PNY USB Flash keys
439 		 * PR: usb/75578, usb/72344, usb/65436
440 		 */
441 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "*" , "USB DISK*",
442 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
443 	},
444 	{
445 		/*
446 		 * Genesys 6-in-1 Card Reader
447 		 * PR: usb/94647
448 		 */
449 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "STORAGE DEVICE*",
450 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
451 	},
452 	{
453 		/*
454 		 * Rekam Digital CAMERA
455 		 * PR: usb/98713
456 		 */
457 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CAMERA*", "4MP-9J6*",
458 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
459 	},
460 	{
461 		/*
462 		 * iRiver H10 MP3 player
463 		 * PR: usb/102547
464 		 */
465 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "H10*",
466 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
467 	},
468 	{
469 		/*
470 		 * iRiver U10 MP3 player
471 		 * PR: usb/92306
472 		 */
473 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "U10*",
474 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
475 	},
476 	{
477 		/*
478 		 * X-Micro Flash Disk
479 		 * PR: usb/96901
480 		 */
481 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "X-Micro", "Flash Disk",
482 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
483 	},
484 	{
485 		/*
486 		 * EasyMP3 EM732X USB 2.0 Flash MP3 Player
487 		 * PR: usb/96546
488 		 */
489 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EM732X", "MP3 Player*",
490 		"1.00"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
491 	},
492 	{
493 		/*
494 		 * Denver MP3 player
495 		 * PR: usb/107101
496 		 */
497 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "DENVER", "MP3 PLAYER",
498 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
499 	},
500 	{
501 		/*
502 		 * Philips USB Key Audio KEY013
503 		 * PR: usb/68412
504 		 */
505 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "PHILIPS", "Key*", "*"},
506 		/*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
507 	},
508 	{
509 		/*
510 		 * JNC MP3 Player
511 		 * PR: usb/94439
512 		 */
513 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JNC*" , "MP3 Player*",
514 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
515 	},
516 	{
517 		/*
518 		 * SAMSUNG MP0402H
519 		 * PR: usb/108427
520 		 */
521 		{T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "MP0402H", "*"},
522 		/*quirks*/ DA_Q_NO_SYNC_CACHE
523 	},
524 	{
525 		/*
526 		 * I/O Magic USB flash - Giga Bank
527 		 * PR: usb/108810
528 		 */
529 		{T_DIRECT, SIP_MEDIA_FIXED, "GS-Magic", "stor*", "*"},
530 		/*quirks*/ DA_Q_NO_SYNC_CACHE
531 	},
532 	{
533 		/*
534 		 * JoyFly 128mb USB Flash Drive
535 		 * PR: 96133
536 		 */
537 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "Flash Disk*",
538 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
539 	},
540 	{
541 		/*
542 		 * ChipsBnk usb stick
543 		 * PR: 103702
544 		 */
545 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ChipsBnk", "USB*",
546 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
547 	},
548 	{
549 		/*
550 		 * Samsung YP-U3 mp3-player
551 		 * PR: 125398
552 		 */
553 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Samsung", "YP-U3",
554 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
555 	},
556 	{
557 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Netac", "OnlyDisk*",
558 		"2000"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
559 	},
560 	{
561 		/*
562 		 * USB 2.0 (HS) Flash Disk MP3 player
563 		 */
564 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "(HS) Flash Disk", "*"},
565 		/*quirks*/ DA_Q_NO_SYNC_CACHE
566 	},
567 };
568 
569 static	d_open_t	daopen;
570 static	d_close_t	daclose;
571 static	d_strategy_t	dastrategy;
572 static	d_dump_t	dadump;
573 static	periph_init_t	dainit;
574 static	void		daasync(void *callback_arg, u_int32_t code,
575 				struct cam_path *path, void *arg);
576 static	int		dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
577 static	periph_ctor_t	daregister;
578 static	periph_dtor_t	dacleanup;
579 static	periph_start_t	dastart;
580 static	periph_oninv_t	daoninvalidate;
581 static	void		dadone(struct cam_periph *periph,
582 			       union ccb *done_ccb);
583 static  int		daerror(union ccb *ccb, u_int32_t cam_flags,
584 				u_int32_t sense_flags);
585 static void		daprevent(struct cam_periph *periph, int action);
586 static int		dagetcapacity(struct cam_periph *periph);
587 static void		dasetgeom(struct cam_periph *periph, uint32_t block_len,
588 				  uint64_t maxsector);
589 
590 static timeout_t	dasendorderedtag;
591 static void		dashutdown(void *arg, int howto);
592 
593 #ifndef DA_DEFAULT_TIMEOUT
594 #define DA_DEFAULT_TIMEOUT 60	/* Timeout in seconds */
595 #endif
596 
597 #ifndef	DA_DEFAULT_RETRY
598 #define	DA_DEFAULT_RETRY	4
599 #endif
600 
601 #ifndef	DA_DEFAULT_SEND_ORDERED
602 #define	DA_DEFAULT_SEND_ORDERED	1
603 #endif
604 
605 static int da_retry_count = DA_DEFAULT_RETRY;
606 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
607 static int da_send_ordered = DA_DEFAULT_SEND_ORDERED;
608 static struct callout dasendorderedtag_ch;
609 
610 SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
611             "CAM Direct Access Disk driver");
612 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
613            &da_retry_count, 0, "Normal I/O retry count");
614 TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count);
615 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
616            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
617 TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout);
618 SYSCTL_INT(_kern_cam_da, OID_AUTO, da_send_ordered, CTLFLAG_RW,
619            &da_send_ordered, 0, "Send Ordered Tags");
620 TUNABLE_INT("kern.cam.da.da_send_ordered", &da_send_ordered);
621 
622 /*
623  * DA_ORDEREDTAG_INTERVAL determines how often, relative
624  * to the default timeout, we check to see whether an ordered
625  * tagged transaction is appropriate to prevent simple tag
626  * starvation.  Since we'd like to ensure that there is at least
627  * 1/2 of the timeout length left for a starved transaction to
628  * complete after we've sent an ordered tag, we must poll at least
629  * four times in every timeout period.  This takes care of the worst
630  * case where a starved transaction starts during an interval that
631  * meets the requirement "don't send an ordered tag" test so it takes
632  * us two intervals to determine that a tag must be sent.
633  */
634 #ifndef DA_ORDEREDTAG_INTERVAL
635 #define DA_ORDEREDTAG_INTERVAL 4
636 #endif
637 
638 static struct periph_driver dadriver =
639 {
640 	dainit, "da",
641 	TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
642 };
643 
644 PERIPHDRIVER_DECLARE(da, dadriver);
645 
646 static struct dev_ops da_ops = {
647 	{ "da", DA_CDEV_MAJOR, D_DISK },
648 	.d_open =	daopen,
649 	.d_close =	daclose,
650 	.d_read =	physread,
651 	.d_write =	physwrite,
652 	.d_strategy =	dastrategy,
653 	.d_dump =	dadump
654 };
655 
656 static struct extend_array *daperiphs;
657 
658 MALLOC_DEFINE(M_SCSIDA, "scsi_da", "scsi_da buffers");
659 
660 static int
661 daopen(struct dev_open_args *ap)
662 {
663 	cdev_t dev = ap->a_head.a_dev;
664 	struct cam_periph *periph;
665 	struct da_softc *softc;
666 	struct disk_info info;
667 	int unit;
668 	int error;
669 
670 	unit = dkunit(dev);
671 	periph = cam_extend_get(daperiphs, unit);
672 	if (periph == NULL) {
673 		return (ENXIO);
674 	}
675 
676 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
677 		return(ENXIO);
678 	}
679 
680 	cam_periph_lock(periph);
681 	if ((error = cam_periph_hold(periph, PCATCH)) != 0) {
682 		cam_periph_unlock(periph);
683 		cam_periph_release(periph);
684 		return (error);
685 	}
686 
687 	unit = periph->unit_number;
688 	softc = (struct da_softc *)periph->softc;
689 	softc->flags |= DA_FLAG_OPEN;
690 
691 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
692 	    ("daopen: dev=%s (unit %d)\n", devtoname(dev),
693 	     unit));
694 
695 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
696 		/* Invalidate our pack information. */
697 		disk_invalidate(&softc->disk);
698 		softc->flags &= ~DA_FLAG_PACK_INVALID;
699 	}
700 
701 	error = dagetcapacity(periph);
702 
703 #if 0
704 	/* Do a read capacity */
705 	{
706 		struct scsi_read_capacity_data *rcap;
707 		union  ccb *ccb;
708 
709 		rcap = kmalloc(sizeof(*rcap), M_SCSIDA, M_INTWAIT | M_ZERO);
710 
711 		ccb = cam_periph_getccb(periph, /*priority*/1);
712 		scsi_read_capacity(&ccb->csio,
713 				   /*retries*/1,
714 				   /*cbfncp*/dadone,
715 				   MSG_SIMPLE_Q_TAG,
716 				   rcap,
717 				   SSD_FULL_SIZE,
718 				   /*timeout*/60000);
719 		ccb->ccb_h.ccb_bio = NULL;
720 
721 		error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
722 					  /*sense_flags*/SF_RETRY_UA |
723 							 SF_RETRY_SELTO,
724 					  &softc->device_stats);
725 
726 		xpt_release_ccb(ccb);
727 
728 		if (error == 0) {
729 			dasetgeom(periph, rcap);
730 		}
731 
732 		kfree(rcap, M_SCSIDA);
733 	}
734 #endif
735 
736 	if (error == 0) {
737 		struct ccb_getdev cgd;
738 
739 		/* Build disk information structure */
740 		bzero(&info, sizeof(info));
741 		info.d_type = DTYPE_SCSI;
742 
743 		/*
744 		 * Grab the inquiry data to get the vendor and product names.
745 		 * Put them in the typename and packname for the label.
746 		 */
747 		xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1);
748 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
749 		xpt_action((union ccb *)&cgd);
750 
751 #if 0
752 		strncpy(label->d_typename, cgd.inq_data.vendor,
753 			min(SID_VENDOR_SIZE, sizeof(label->d_typename)));
754 		strncpy(label->d_packname, cgd.inq_data.product,
755 			min(SID_PRODUCT_SIZE, sizeof(label->d_packname)));
756 #endif
757 
758 		/*
759 		 * Mandatory fields
760 		 */
761 		info.d_media_blksize = softc->params.secsize;
762 		info.d_media_blocks = softc->params.sectors;
763 		info.d_media_size = 0;
764 
765 		/*
766 		 * Optional fields
767 		 */
768 		info.d_secpertrack = softc->params.secs_per_track;
769 		info.d_nheads = softc->params.heads;
770 		info.d_ncylinders = softc->params.cylinders;
771 		info.d_secpercyl = softc->params.heads *
772 				   softc->params.secs_per_track;
773 		disk_setdiskinfo(&softc->disk, &info);
774 
775 		/*
776 		 * Check to see whether or not the blocksize is set yet.
777 		 * If it isn't, set it and then clear the blocksize
778 		 * unavailable flag for the device statistics.
779 		 */
780 		if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0){
781 			softc->device_stats.block_size = softc->params.secsize;
782 			softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
783 		}
784 	}
785 
786 	if (error == 0) {
787 		if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
788 		    (softc->quirks & DA_Q_NO_PREVENT) == 0)
789 			daprevent(periph, PR_PREVENT);
790 	} else {
791 		softc->flags &= ~DA_FLAG_OPEN;
792 		cam_periph_release(periph);
793 	}
794 	cam_periph_unhold(periph, 1);
795 	return (error);
796 }
797 
798 static int
799 daclose(struct dev_close_args *ap)
800 {
801 	cdev_t dev = ap->a_head.a_dev;
802 	struct	cam_periph *periph;
803 	struct	da_softc *softc;
804 	int	unit;
805 	int	error;
806 
807 	unit = dkunit(dev);
808 	periph = cam_extend_get(daperiphs, unit);
809 	if (periph == NULL)
810 		return (ENXIO);
811 
812 	cam_periph_lock(periph);
813 	if ((error = cam_periph_hold(periph, 0)) != 0) {
814 		cam_periph_unlock(periph);
815 		cam_periph_release(periph);
816 		return (error);
817 	}
818 
819 	softc = (struct da_softc *)periph->softc;
820 
821 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
822 		union	ccb *ccb;
823 
824 		ccb = cam_periph_getccb(periph, /*priority*/1);
825 
826 		scsi_synchronize_cache(&ccb->csio,
827 				       /*retries*/1,
828 				       /*cbfcnp*/dadone,
829 				       MSG_SIMPLE_Q_TAG,
830 				       /*begin_lba*/0,/* Cover the whole disk */
831 				       /*lb_count*/0,
832 				       SSD_FULL_SIZE,
833 				       5 * 60 * 1000);
834 
835 		cam_periph_runccb(ccb, /*error_routine*/NULL, /*cam_flags*/0,
836 				  /*sense_flags*/SF_RETRY_UA,
837 				  &softc->device_stats);
838 
839 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
840 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
841 			     CAM_SCSI_STATUS_ERROR) {
842 				int asc, ascq;
843 				int sense_key, error_code;
844 
845 				scsi_extract_sense(&ccb->csio.sense_data,
846 						   &error_code,
847 						   &sense_key,
848 						   &asc, &ascq);
849 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
850 					scsi_sense_print(&ccb->csio);
851 			} else {
852 				xpt_print(periph->path, "Synchronize cache "
853 				    "failed, status == 0x%x, scsi status == "
854 				    "0x%x\n", ccb->csio.ccb_h.status,
855 				    ccb->csio.scsi_status);
856 			}
857 		}
858 
859 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
860 			cam_release_devq(ccb->ccb_h.path,
861 					 /*relsim_flags*/0,
862 					 /*reduction*/0,
863 					 /*timeout*/0,
864 					 /*getcount_only*/0);
865 
866 		xpt_release_ccb(ccb);
867 
868 	}
869 
870 	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
871 		if ((softc->quirks & DA_Q_NO_PREVENT) == 0)
872 			daprevent(periph, PR_ALLOW);
873 		/*
874 		 * If we've got removeable media, mark the blocksize as
875 		 * unavailable, since it could change when new media is
876 		 * inserted.
877 		 */
878 		softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
879 	}
880 
881 	/*
882 	 * Don't compound any ref counting software bugs with more.
883 	 */
884 	if (softc->flags & DA_FLAG_OPEN) {
885 		softc->flags &= ~DA_FLAG_OPEN;
886 		cam_periph_release(periph);
887 	} else {
888 		xpt_print(periph->path,
889 			  "daclose() called on an already closed device!\n");
890 	}
891 	cam_periph_unhold(periph, 1);
892 	return (0);
893 }
894 
895 /*
896  * Actually translate the requested transfer into one the physical driver
897  * can understand.  The transfer is described by a buf and will include
898  * only one physical transfer.
899  */
900 static int
901 dastrategy(struct dev_strategy_args *ap)
902 {
903 	cdev_t dev = ap->a_head.a_dev;
904 	struct bio *bio = ap->a_bio;
905 	struct buf *bp = bio->bio_buf;
906 	struct cam_periph *periph;
907 	struct da_softc *softc;
908 	u_int  unit;
909 	u_int  part;
910 
911 	unit = dkunit(dev);
912 	part = dkpart(dev);
913 	periph = cam_extend_get(daperiphs, unit);
914 	if (periph == NULL) {
915 		bp->b_error = ENXIO;
916 		goto bad;
917 	}
918 	softc = (struct da_softc *)periph->softc;
919 
920 	cam_periph_lock(periph);
921 
922 #if 0
923 	/*
924 	 * check it's not too big a transfer for our adapter
925 	 */
926 	scsi_minphys(bp, &sd_switch);
927 #endif
928 
929 	/*
930 	 * Mask interrupts so that the pack cannot be invalidated until
931 	 * after we are in the queue.  Otherwise, we might not properly
932 	 * clean up one of the buffers.
933 	 */
934 
935 	/*
936 	 * If the device has been made invalid, error out
937 	 */
938 	if ((softc->flags & DA_FLAG_PACK_INVALID)) {
939 		cam_periph_unlock(periph);
940 		bp->b_error = ENXIO;
941 		goto bad;
942 	}
943 
944 	/*
945 	 * Place it in the queue of disk activities for this disk
946 	 */
947 	bioqdisksort(&softc->bio_queue, bio);
948 
949 	/*
950 	 * Schedule ourselves for performing the work.
951 	 */
952 	xpt_schedule(periph, /* XXX priority */1);
953 	cam_periph_unlock(periph);
954 
955 	return(0);
956 bad:
957 	bp->b_flags |= B_ERROR;
958 
959 	/*
960 	 * Correctly set the buf to indicate a completed xfer
961 	 */
962 	bp->b_resid = bp->b_bcount;
963 	biodone(bio);
964 	return(0);
965 }
966 
967 static int
968 dadump(struct dev_dump_args *ap)
969 {
970 	cdev_t dev = ap->a_head.a_dev;
971 	struct	    cam_periph *periph;
972 	struct	    da_softc *softc;
973 	u_int	    unit;
974 	long	    blkcnt;
975 	vm_paddr_t  addr;
976 	struct	    ccb_scsiio csio;
977 	int         dumppages = MAXDUMPPGS;
978 	int         i;
979 
980 	/* toss any characters present prior to dump */
981 	while (cncheckc() != -1)
982 		;
983 
984 	unit = dkunit(dev);
985 	periph = cam_extend_get(daperiphs, unit);
986 	if (periph == NULL) {
987 		return (ENXIO);
988 	}
989 	softc = (struct da_softc *)periph->softc;
990 
991 	cam_periph_lock(periph);
992 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
993 		cam_periph_unlock(periph);
994 		return (ENXIO);
995 	}
996 
997 	addr = 0;	/* starting address */
998 	blkcnt = howmany(PAGE_SIZE, ap->a_secsize);
999 
1000 	while (ap->a_count > 0) {
1001 		caddr_t va = NULL;
1002 
1003 		if ((ap->a_count / blkcnt) < dumppages)
1004 			dumppages = ap->a_count / blkcnt;
1005 
1006 		for (i = 0; i < dumppages; ++i) {
1007 			vm_paddr_t a = addr + (i * PAGE_SIZE);
1008 			if (is_physical_memory(a))
1009 				va = pmap_kenter_temporary(trunc_page(a), i);
1010 			else
1011 				va = pmap_kenter_temporary(trunc_page(0), i);
1012 		}
1013 
1014 		xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
1015 		csio.ccb_h.flags |= CAM_POLLED;
1016 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1017 		scsi_read_write(&csio,
1018 				/*retries*/1,
1019 				dadone,
1020 				MSG_ORDERED_Q_TAG,
1021 				/*read*/FALSE,
1022 				/*byte2*/0,
1023 				/*minimum_cmd_size*/ softc->minimum_cmd_size,
1024 				ap->a_blkno,
1025 				blkcnt * dumppages,
1026 				/*data_ptr*/(u_int8_t *) va,
1027 				/*dxfer_len*/blkcnt * ap->a_secsize * dumppages,
1028 				/*sense_len*/SSD_FULL_SIZE,
1029 				DA_DEFAULT_TIMEOUT * 1000);
1030 		xpt_polled_action((union ccb *)&csio);
1031 
1032 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1033 			kprintf("Aborting dump due to I/O error.\n");
1034 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
1035 			     CAM_SCSI_STATUS_ERROR)
1036 				scsi_sense_print(&csio);
1037 			else
1038 				kprintf("status == 0x%x, scsi status == 0x%x\n",
1039 				       csio.ccb_h.status, csio.scsi_status);
1040 			return(EIO);
1041 		}
1042 
1043 		if (dumpstatus(addr, (off_t)ap->a_count * softc->params.secsize) < 0)
1044 			return (EINTR);
1045 
1046 		/* update block count */
1047 		ap->a_count -= blkcnt * dumppages;
1048 		ap->a_blkno += blkcnt * dumppages;
1049 		addr += PAGE_SIZE * dumppages;
1050 	}
1051 
1052 	/*
1053 	 * Sync the disk cache contents to the physical media.
1054 	 */
1055 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
1056 
1057 		xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
1058 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1059 		scsi_synchronize_cache(&csio,
1060 				       /*retries*/1,
1061 				       /*cbfcnp*/dadone,
1062 				       MSG_SIMPLE_Q_TAG,
1063 				       /*begin_lba*/0,/* Cover the whole disk */
1064 				       /*lb_count*/0,
1065 				       SSD_FULL_SIZE,
1066 				       5 * 60 * 1000);
1067 		xpt_polled_action((union ccb *)&csio);
1068 
1069 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1070 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
1071 			     CAM_SCSI_STATUS_ERROR) {
1072 				int asc, ascq;
1073 				int sense_key, error_code;
1074 
1075 				scsi_extract_sense(&csio.sense_data,
1076 						   &error_code,
1077 						   &sense_key,
1078 						   &asc, &ascq);
1079 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
1080 					scsi_sense_print(&csio);
1081 			} else {
1082 				xpt_print(periph->path, "Synchronize cache "
1083 				    "failed, status == 0x%x, scsi status == "
1084 				    "0x%x\n", csio.ccb_h.status,
1085 				    csio.scsi_status);
1086 			}
1087 		}
1088 	}
1089 	cam_periph_unlock(periph);
1090 	return (0);
1091 }
1092 
1093 static void
1094 dainit(void)
1095 {
1096 	cam_status status;
1097 
1098 	/*
1099 	 * Create our extend array for storing the devices we attach to.
1100 	 */
1101 	daperiphs = cam_extend_new();
1102 	if (daperiphs == NULL) {
1103 		kprintf("da: Failed to alloc extend array!\n");
1104 		return;
1105 	}
1106 
1107 	callout_init(&dasendorderedtag_ch);
1108 
1109 	/*
1110 	 * Install a global async callback.  This callback will
1111 	 * receive async callbacks like "new device found".
1112 	 */
1113 	status = xpt_register_async(AC_FOUND_DEVICE, daasync, NULL, NULL);
1114 
1115 	if (status != CAM_REQ_CMP) {
1116 		kprintf("da: Failed to attach master async callback "
1117 		       "due to status 0x%x!\n", status);
1118 	} else if (da_send_ordered) {
1119 
1120 		/* Register our shutdown event handler */
1121 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown,
1122 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1123 		    kprintf("dainit: shutdown event registration failed!\n");
1124 	}
1125 }
1126 
1127 static void
1128 daoninvalidate(struct cam_periph *periph)
1129 {
1130 	struct da_softc *softc;
1131 	struct bio *q_bio;
1132 	struct buf *q_bp;
1133 
1134 	softc = (struct da_softc *)periph->softc;
1135 
1136 	/*
1137 	 * De-register any async callbacks.
1138 	 */
1139 	xpt_register_async(0, daasync, periph, periph->path);
1140 
1141 	softc->flags |= DA_FLAG_PACK_INVALID;
1142 
1143 	/*
1144 	 * Return all queued I/O with ENXIO.
1145 	 * XXX Handle any transactions queued to the card
1146 	 *     with XPT_ABORT_CCB.
1147 	 */
1148 	while ((q_bio = bioq_first(&softc->bio_queue)) != NULL){
1149 		bioq_remove(&softc->bio_queue, q_bio);
1150 		q_bp = q_bio->bio_buf;
1151 		q_bp->b_resid = q_bp->b_bcount;
1152 		q_bp->b_error = ENXIO;
1153 		q_bp->b_flags |= B_ERROR;
1154 		biodone(q_bio);
1155 	}
1156 	xpt_print(periph->path, "lost device\n");
1157 }
1158 
1159 static void
1160 dacleanup(struct cam_periph *periph)
1161 {
1162 	struct da_softc *softc;
1163 
1164 	softc = (struct da_softc *)periph->softc;
1165 
1166 	devstat_remove_entry(&softc->device_stats);
1167 	cam_extend_release(daperiphs, periph->unit_number);
1168 	xpt_print(periph->path, "removing device entry\n");
1169 	/*
1170 	 * If we can't free the sysctl tree, oh well...
1171 	 */
1172 	if ((softc->flags & DA_FLAG_SCTX_INIT) != 0
1173 	    && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
1174 		xpt_print(periph->path, "can't remove sysctl context\n");
1175 	}
1176 	periph->softc = NULL;
1177 	if (softc->disk.d_rawdev) {
1178 		cam_periph_unlock(periph);
1179 		disk_destroy(&softc->disk);
1180 		cam_periph_lock(periph);
1181 	}
1182 
1183 	callout_stop(&softc->sendordered_c);
1184 	kfree(softc, M_DEVBUF);
1185 }
1186 
1187 static void
1188 daasync(void *callback_arg, u_int32_t code,
1189 	struct cam_path *path, void *arg)
1190 {
1191 	struct cam_periph *periph;
1192 
1193 	periph = (struct cam_periph *)callback_arg;
1194 
1195 	switch (code) {
1196 	case AC_FOUND_DEVICE:
1197 	{
1198 		struct ccb_getdev *cgd;
1199 		struct cam_sim *sim;
1200 		cam_status status;
1201 
1202 		cgd = (struct ccb_getdev *)arg;
1203 		if (cgd == NULL)
1204 			break;
1205 
1206 		if (SID_TYPE(&cgd->inq_data) != T_DIRECT
1207 		    && SID_TYPE(&cgd->inq_data) != T_RBC
1208 		    && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
1209 			break;
1210 
1211 		/*
1212 		 * Don't complain if a valid peripheral is already attached.
1213 		 */
1214 		periph = cam_periph_find(cgd->ccb_h.path, "da");
1215 		if (periph && (periph->flags & CAM_PERIPH_INVALID) == 0)
1216 			break;
1217 
1218 		/*
1219 		 * Allocate a peripheral instance for
1220 		 * this device and start the probe
1221 		 * process.
1222 		 */
1223 		sim = xpt_path_sim(cgd->ccb_h.path);
1224 		status = cam_periph_alloc(daregister, daoninvalidate,
1225 					  dacleanup, dastart,
1226 					  "da", CAM_PERIPH_BIO,
1227 					  cgd->ccb_h.path, daasync,
1228 					  AC_FOUND_DEVICE, cgd);
1229 
1230 		if (status != CAM_REQ_CMP && status != CAM_REQ_INPROG) {
1231 			kprintf("daasync: Unable to attach to new device "
1232 				"due to status 0x%x\n", status);
1233 		}
1234 		break;
1235 	}
1236 	case AC_SENT_BDR:
1237 	case AC_BUS_RESET:
1238 	{
1239 		struct da_softc *softc;
1240 		struct ccb_hdr *ccbh;
1241 
1242 		softc = (struct da_softc *)periph->softc;
1243 		/*
1244 		 * Don't fail on the expected unit attention
1245 		 * that will occur.
1246 		 */
1247 		softc->flags |= DA_FLAG_RETRY_UA;
1248 		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1249 			ccbh->ccb_state |= DA_CCB_RETRY_UA;
1250 		/* FALLTHROUGH*/
1251 	}
1252 	default:
1253 		cam_periph_async(periph, code, path, arg);
1254 		break;
1255 	}
1256 }
1257 
1258 static void
1259 dasysctlinit(void *context, int pending)
1260 {
1261 	struct cam_periph *periph;
1262 	struct da_softc *softc;
1263 	char tmpstr[80], tmpstr2[80];
1264 
1265 	periph = (struct cam_periph *)context;
1266 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
1267 		return;
1268 
1269 	softc = (struct da_softc *)periph->softc;
1270 	ksnprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
1271 	ksnprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1272 
1273 	sysctl_ctx_init(&softc->sysctl_ctx);
1274 	softc->flags |= DA_FLAG_SCTX_INIT;
1275 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1276 		SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
1277 		CTLFLAG_RD, 0, tmpstr);
1278 	if (softc->sysctl_tree == NULL) {
1279 		kprintf("dasysctlinit: unable to allocate sysctl tree\n");
1280 		cam_periph_release(periph);
1281 		return;
1282 	}
1283 
1284 	/*
1285 	 * Now register the sysctl handler, so the user can the value on
1286 	 * the fly.
1287 	 */
1288 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1289 		OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
1290 		&softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
1291 		"Minimum CDB size");
1292 
1293 	cam_periph_release(periph);
1294 }
1295 
1296 static int
1297 dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
1298 {
1299 	int error, value;
1300 
1301 	value = *(int *)arg1;
1302 
1303 	error = sysctl_handle_int(oidp, &value, 0, req);
1304 
1305 	if ((error != 0)
1306 	 || (req->newptr == NULL))
1307 		return (error);
1308 
1309 	/*
1310 	 * Acceptable values here are 6, 10 or 12, or 16.
1311 	 */
1312 	if (value < 6)
1313 		value = 6;
1314 	else if ((value > 6)
1315 	      && (value <= 10))
1316 		value = 10;
1317 	else if ((value > 10)
1318 	      && (value <= 12))
1319 		value = 12;
1320 	else if (value > 12)
1321 		value = 16;
1322 
1323 	*(int *)arg1 = value;
1324 
1325 	return (0);
1326 }
1327 
1328 static cam_status
1329 daregister(struct cam_periph *periph, void *arg)
1330 {
1331 	struct da_softc *softc;
1332 	struct ccb_pathinq cpi;
1333 	struct ccb_getdev *cgd;
1334 	char tmpstr[80];
1335 	caddr_t match;
1336 
1337 	cgd = (struct ccb_getdev *)arg;
1338 	if (periph == NULL) {
1339 		kprintf("daregister: periph was NULL!!\n");
1340 		return(CAM_REQ_CMP_ERR);
1341 	}
1342 
1343 	if (cgd == NULL) {
1344 		kprintf("daregister: no getdev CCB, can't register device\n");
1345 		return(CAM_REQ_CMP_ERR);
1346 	}
1347 
1348 	softc = kmalloc(sizeof(*softc), M_DEVBUF, M_INTWAIT | M_ZERO);
1349 	LIST_INIT(&softc->pending_ccbs);
1350 	softc->state = DA_STATE_PROBE;
1351 	bioq_init(&softc->bio_queue);
1352 	if (SID_IS_REMOVABLE(&cgd->inq_data))
1353 		softc->flags |= DA_FLAG_PACK_REMOVABLE;
1354 	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
1355 		softc->flags |= DA_FLAG_TAGGED_QUEUING;
1356 
1357 	periph->softc = softc;
1358 
1359 	cam_extend_set(daperiphs, periph->unit_number, periph);
1360 
1361 	/*
1362 	 * See if this device has any quirks.
1363 	 */
1364 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1365 			       (caddr_t)da_quirk_table,
1366 			       sizeof(da_quirk_table)/sizeof(*da_quirk_table),
1367 			       sizeof(*da_quirk_table), scsi_inquiry_match);
1368 
1369 	if (match != NULL)
1370 		softc->quirks = ((struct da_quirk_entry *)match)->quirks;
1371 	else
1372 		softc->quirks = DA_Q_NONE;
1373 
1374 	TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
1375 
1376 	/* Check if the SIM does not want 6 byte commands */
1377 	xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1);
1378 	cpi.ccb_h.func_code = XPT_PATH_INQ;
1379 	xpt_action((union ccb *)&cpi);
1380 	if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
1381 		softc->quirks |= DA_Q_NO_6_BYTE;
1382 
1383 	/*
1384 	 * RBC devices don't have to support READ(6), only READ(10).
1385 	 */
1386 	if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
1387 		softc->minimum_cmd_size = 10;
1388 	else
1389 		softc->minimum_cmd_size = 6;
1390 
1391 	/*
1392 	 * Load the user's default, if any.
1393 	 */
1394 	ksnprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
1395 		 periph->unit_number);
1396 	TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
1397 
1398 	/*
1399 	 * 6, 10, 12, and 16 are the currently permissible values.
1400 	 */
1401 	if (softc->minimum_cmd_size < 6)
1402 		softc->minimum_cmd_size = 6;
1403 	else if ((softc->minimum_cmd_size > 6)
1404 	      && (softc->minimum_cmd_size <= 10))
1405 		softc->minimum_cmd_size = 10;
1406 	else if ((softc->minimum_cmd_size > 10)
1407 	      && (softc->minimum_cmd_size <= 12))
1408 		softc->minimum_cmd_size = 12;
1409 	else if (softc->minimum_cmd_size > 12)
1410 		softc->minimum_cmd_size = 16;
1411 
1412 	/*
1413 	 * The DA driver supports a blocksize, but
1414 	 * we don't know the blocksize until we do
1415 	 * a read capacity.  So, set a flag to
1416 	 * indicate that the blocksize is
1417 	 * unavailable right now.  We'll clear the
1418 	 * flag as soon as we've done a read capacity.
1419 	 */
1420 	devstat_add_entry(&softc->device_stats, "da",
1421 			  periph->unit_number, 0,
1422 	  		  DEVSTAT_BS_UNAVAILABLE,
1423 			  SID_TYPE(&cgd->inq_data) | DEVSTAT_TYPE_IF_SCSI,
1424 			  DEVSTAT_PRIORITY_DISK);
1425 
1426 	/*
1427 	 * Register this media as a disk
1428 	 */
1429 
1430 	CAM_SIM_UNLOCK(periph->sim);
1431 	disk_create(periph->unit_number, &softc->disk, &da_ops);
1432 	softc->disk.d_rawdev->si_iosize_max = MAXPHYS;
1433 	CAM_SIM_LOCK(periph->sim);
1434 
1435 	/*
1436 	 * Add async callbacks for bus reset and
1437 	 * bus device reset calls.  I don't bother
1438 	 * checking if this fails as, in most cases,
1439 	 * the system will function just fine without
1440 	 * them and the only alternative would be to
1441 	 * not attach the device on failure.
1442 	 */
1443 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE,
1444 			   daasync, periph, periph->path);
1445 
1446 	/*
1447 	 * Take an exclusive refcount on the periph while dastart is called
1448 	 * to finish the probe.  The reference will be dropped in dadone at
1449 	 * the end of probe.
1450 	 */
1451 	cam_periph_hold(periph, 0);
1452 	xpt_schedule(periph, /*priority*/5);
1453 
1454 	/*
1455 	 * Schedule a periodic event to occasionally send an
1456 	 * ordered tag to a device.
1457 	 */
1458 	callout_init(&softc->sendordered_c);
1459 	callout_reset(&softc->sendordered_c,
1460 	    (DA_DEFAULT_TIMEOUT * hz) / DA_ORDEREDTAG_INTERVAL,
1461 	    dasendorderedtag, softc);
1462 
1463 	return(CAM_REQ_CMP);
1464 }
1465 
1466 static void
1467 dastart(struct cam_periph *periph, union ccb *start_ccb)
1468 {
1469 	struct da_softc *softc;
1470 
1471 	softc = (struct da_softc *)periph->softc;
1472 
1473 	switch (softc->state) {
1474 	case DA_STATE_NORMAL:
1475 	{
1476 		/* Pull a buffer from the queue and get going on it */
1477 		struct bio *bio;
1478 		struct buf *bp;
1479 		u_int8_t tag_code;
1480 
1481 		/*
1482 		 * See if there is a buf with work for us to do..
1483 		 */
1484 		bio = bioq_first(&softc->bio_queue);
1485 		if (periph->immediate_priority <= periph->pinfo.priority) {
1486 			CAM_DEBUG_PRINT(CAM_DEBUG_SUBTRACE,
1487 					("queuing for immediate ccb\n"));
1488 			start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
1489 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1490 					  periph_links.sle);
1491 			periph->immediate_priority = CAM_PRIORITY_NONE;
1492 			wakeup(&periph->ccb_list);
1493 			if (bio != NULL) {
1494 				/*
1495 				 * Have more work to do, so ensure we stay
1496 				 * scheduled
1497 				 */
1498 				xpt_schedule(periph, /* XXX priority */1);
1499 			}
1500 			break;
1501 		}
1502 		if (bio == NULL) {
1503 			xpt_release_ccb(start_ccb);
1504 			break;
1505 		}
1506 
1507 		/*
1508 		 * We can queue new work.
1509 		 */
1510 		bioq_remove(&softc->bio_queue, bio);
1511 		bp = bio->bio_buf;
1512 
1513 		devstat_start_transaction(&softc->device_stats);
1514 
1515 		if ((bp->b_flags & B_ORDERED) != 0 ||
1516 		    (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
1517 			softc->flags &= ~DA_FLAG_NEED_OTAG;
1518 			softc->ordered_tag_count++;
1519 			tag_code = MSG_ORDERED_Q_TAG;
1520 		} else {
1521 			tag_code = MSG_SIMPLE_Q_TAG;
1522 		}
1523 
1524 		switch(bp->b_cmd) {
1525 		case BUF_CMD_READ:
1526 		case BUF_CMD_WRITE:
1527 			/*
1528 			 * Block read/write op
1529 			 */
1530 			KKASSERT(bio->bio_offset % softc->params.secsize == 0);
1531 
1532 			scsi_read_write(
1533 				&start_ccb->csio,
1534 				da_retry_count,		/* retries */
1535 				dadone,
1536 				tag_code,
1537 				(bp->b_cmd == BUF_CMD_READ),
1538 				0,			/* byte2 */
1539 				softc->minimum_cmd_size,
1540 				bio->bio_offset / softc->params.secsize,
1541 				bp->b_bcount / softc->params.secsize,
1542 				bp->b_data,
1543 				bp->b_bcount,
1544 				SSD_FULL_SIZE,		/* sense_len */
1545 				da_default_timeout * 1000
1546 			);
1547 			break;
1548 		case BUF_CMD_FLUSH:
1549 			scsi_synchronize_cache(
1550 				&start_ccb->csio,
1551 				1,			/* retries */
1552 				dadone,			/* cbfcnp */
1553 				MSG_SIMPLE_Q_TAG,
1554 				0,			/* lba */
1555 				0,			/* count (whole disk) */
1556 				SSD_FULL_SIZE,
1557 				da_default_timeout*1000	/* timeout */
1558 			);
1559 			break;
1560 		default:
1561 			panic("dastart: unrecognized bio cmd %d", bp->b_cmd);
1562 			break; /* NOT REACHED */
1563 		}
1564 
1565 		/*
1566 		 * Block out any asyncronous callbacks
1567 		 * while we touch the pending ccb list.
1568 		 */
1569 		start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
1570 		LIST_INSERT_HEAD(&softc->pending_ccbs,
1571 				 &start_ccb->ccb_h, periph_links.le);
1572 		softc->outstanding_cmds++;
1573 
1574 		/* We expect a unit attention from this device */
1575 		if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
1576 			start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
1577 			softc->flags &= ~DA_FLAG_RETRY_UA;
1578 		}
1579 
1580 		start_ccb->ccb_h.ccb_bio = bio;
1581 		xpt_action(start_ccb);
1582 
1583 		/*
1584 		 * Be sure we stay scheduled if we have more work to do.
1585 		 */
1586 		bio = bioq_first(&softc->bio_queue);
1587 		if (bio != NULL)
1588 			xpt_schedule(periph, 1);
1589 		break;
1590 	}
1591 	case DA_STATE_PROBE:
1592 	{
1593 		struct ccb_scsiio *csio;
1594 		struct scsi_read_capacity_data *rcap;
1595 
1596 		rcap = kmalloc(sizeof(*rcap), M_SCSIDA, M_INTWAIT | M_ZERO);
1597 		csio = &start_ccb->csio;
1598 		scsi_read_capacity(csio,
1599 				   /*retries*/4,
1600 				   dadone,
1601 				   MSG_SIMPLE_Q_TAG,
1602 				   rcap,
1603 				   SSD_FULL_SIZE,
1604 				   /*timeout*/5000);
1605 		start_ccb->ccb_h.ccb_bio = NULL;
1606 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE;
1607 		xpt_action(start_ccb);
1608 		break;
1609 	}
1610 	case DA_STATE_PROBE2:
1611 	{
1612 		struct ccb_scsiio *csio;
1613 		struct scsi_read_capacity_data_16 *rcaplong;
1614 
1615 		rcaplong = kmalloc(sizeof(*rcaplong), M_SCSIDA,
1616 				   M_INTWAIT | M_ZERO);
1617 		if (rcaplong == NULL) {
1618 			kprintf("dastart: Couldn't allocate read_capacity\n");
1619 			/* da_free_periph??? */
1620 			break;
1621 		}
1622 		csio = &start_ccb->csio;
1623 		scsi_read_capacity_16(csio,
1624 				    /*retries*/ 4,
1625 				    /*cbfcnp*/ dadone,
1626 				    /*tag_action*/ MSG_SIMPLE_Q_TAG,
1627 				    /*lba*/ 0,
1628 				    /*reladr*/ 0,
1629 				    /*pmi*/ 0,
1630 				    rcaplong,
1631 				    /*sense_len*/ SSD_FULL_SIZE,
1632 				    /*timeout*/ 60000);
1633 		start_ccb->ccb_h.ccb_bio = NULL;
1634 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE2;
1635 		xpt_action(start_ccb);
1636 		break;
1637 	}
1638 	}
1639 }
1640 
1641 static int
1642 cmd6workaround(union ccb *ccb)
1643 {
1644 	struct scsi_rw_6 cmd6;
1645 	struct scsi_rw_10 *cmd10;
1646 	struct da_softc *softc;
1647 	u_int8_t *cdb;
1648 	int frozen;
1649 
1650 	cdb = ccb->csio.cdb_io.cdb_bytes;
1651 
1652 	/* Translation only possible if CDB is an array and cmd is R/W6 */
1653 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
1654 	    (*cdb != READ_6 && *cdb != WRITE_6))
1655 		return 0;
1656 
1657 	xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, "
1658 	    "increasing minimum_cmd_size to 10.\n");
1659  	softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
1660 	softc->minimum_cmd_size = 10;
1661 
1662 	bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
1663 	cmd10 = (struct scsi_rw_10 *)cdb;
1664 	cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
1665 	cmd10->byte2 = 0;
1666 	scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
1667 	cmd10->reserved = 0;
1668 	scsi_ulto2b(cmd6.length, cmd10->length);
1669 	cmd10->control = cmd6.control;
1670 	ccb->csio.cdb_len = sizeof(*cmd10);
1671 
1672 	/* Requeue request, unfreezing queue if necessary */
1673 	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
1674  	ccb->ccb_h.status = CAM_REQUEUE_REQ;
1675 	xpt_action(ccb);
1676 	if (frozen) {
1677 		cam_release_devq(ccb->ccb_h.path,
1678 				 /*relsim_flags*/0,
1679 				 /*reduction*/0,
1680 				 /*timeout*/0,
1681 				 /*getcount_only*/0);
1682 	}
1683 	return (ERESTART);
1684 }
1685 
1686 static void
1687 dadone(struct cam_periph *periph, union ccb *done_ccb)
1688 {
1689 	struct da_softc *softc;
1690 	struct ccb_scsiio *csio;
1691 
1692 	softc = (struct da_softc *)periph->softc;
1693 	csio = &done_ccb->csio;
1694 	switch (csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) {
1695 	case DA_CCB_BUFFER_IO:
1696 	{
1697 		struct buf *bp;
1698 		struct bio *bio;
1699 
1700 		bio = (struct bio *)done_ccb->ccb_h.ccb_bio;
1701 		bp = bio->bio_buf;
1702 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1703 			int error;
1704 			int sf;
1705 
1706 			if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
1707 				sf = SF_RETRY_UA;
1708 			else
1709 				sf = 0;
1710 
1711 			error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
1712 			if (error == ERESTART) {
1713 				/*
1714 				 * A retry was scheuled, so
1715 				 * just return.
1716 				 */
1717 				return;
1718 			}
1719 			if (error != 0) {
1720 				struct bio *q_bio;
1721 				struct buf *q_bp;
1722 
1723 				if (error == ENXIO) {
1724 					/*
1725 					 * Catastrophic error.  Mark our pack as
1726 					 * invalid.
1727 					 */
1728 					/*
1729 					 * XXX See if this is really a media
1730 					 * XXX change first?
1731 					 */
1732 					xpt_print(periph->path,
1733 					    "Invalidating pack\n");
1734 					softc->flags |= DA_FLAG_PACK_INVALID;
1735 				}
1736 
1737 				/*
1738 				 * return all queued I/O with EIO, so that
1739 				 * the client can retry these I/Os in the
1740 				 * proper order should it attempt to recover.
1741 				 */
1742 				while ((q_bio = bioq_first(&softc->bio_queue))
1743 					!= NULL) {
1744 					bioq_remove(&softc->bio_queue, q_bio);
1745 					q_bp = q_bio->bio_buf;
1746 					q_bp->b_resid = q_bp->b_bcount;
1747 					q_bp->b_error = EIO;
1748 					q_bp->b_flags |= B_ERROR;
1749 					biodone(q_bio);
1750 				}
1751 				bp->b_error = error;
1752 				bp->b_resid = bp->b_bcount;
1753 				bp->b_flags |= B_ERROR;
1754 			} else {
1755 				bp->b_resid = csio->resid;
1756 				bp->b_error = 0;
1757 				if (bp->b_resid != 0)
1758 					bp->b_flags |= B_ERROR;
1759 			}
1760 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1761 				cam_release_devq(done_ccb->ccb_h.path,
1762 						 /*relsim_flags*/0,
1763 						 /*reduction*/0,
1764 						 /*timeout*/0,
1765 						 /*getcount_only*/0);
1766 		} else {
1767 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1768 				panic("REQ_CMP with QFRZN");
1769 			bp->b_resid = csio->resid;
1770 			if (csio->resid > 0)
1771 				bp->b_flags |= B_ERROR;
1772 		}
1773 
1774 		/*
1775 		 * Block out any asyncronous callbacks
1776 		 * while we touch the pending ccb list.
1777 		 */
1778 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1779 		softc->outstanding_cmds--;
1780 		if (softc->outstanding_cmds == 0)
1781 			softc->flags |= DA_FLAG_WENT_IDLE;
1782 
1783 		devstat_end_transaction_buf(&softc->device_stats, bp);
1784 		biodone(bio);
1785 		break;
1786 	}
1787 	case DA_CCB_PROBE:
1788 	case DA_CCB_PROBE2:
1789 	{
1790 		struct	   scsi_read_capacity_data *rdcap;
1791 		struct     scsi_read_capacity_data_16 *rcaplong;
1792 		char	   announce_buf[80];
1793 
1794 		rdcap = NULL;
1795 		rcaplong = NULL;
1796 		if (softc->state == DA_STATE_PROBE)
1797 			rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
1798 		else
1799 			rcaplong = (struct scsi_read_capacity_data_16 *)
1800 				    csio->data_ptr;
1801 
1802 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1803 			struct disk_params *dp;
1804 			uint32_t block_size;
1805 			uint64_t maxsector;
1806 
1807 			if (softc->state == DA_STATE_PROBE) {
1808 				block_size = scsi_4btoul(rdcap->length);
1809 				maxsector = scsi_4btoul(rdcap->addr);
1810 
1811 				/*
1812 				 * According to SBC-2, if the standard 10
1813 				 * byte READ CAPACITY command returns 2^32,
1814 				 * we should issue the 16 byte version of
1815 				 * the command, since the device in question
1816 				 * has more sectors than can be represented
1817 				 * with the short version of the command.
1818 				 */
1819 				if (maxsector == 0xffffffff) {
1820 					softc->state = DA_STATE_PROBE2;
1821 					kfree(rdcap, M_SCSIDA);
1822 					xpt_release_ccb(done_ccb);
1823 					xpt_schedule(periph, /*priority*/5);
1824 					return;
1825 				}
1826 			} else {
1827 				block_size = scsi_4btoul(rcaplong->length);
1828 				maxsector = scsi_8btou64(rcaplong->addr);
1829 			}
1830 			dasetgeom(periph, block_size, maxsector);
1831 			dp = &softc->params;
1832 			ksnprintf(announce_buf, sizeof(announce_buf),
1833 				"%juMB (%ju %u byte sectors: %dH %dS/T %dC)",
1834 				(uintmax_t) (((uintmax_t)dp->secsize *
1835 				dp->sectors) / (1024*1024)),
1836 				(uintmax_t)dp->sectors,
1837 				dp->secsize, dp->heads, dp->secs_per_track,
1838 				dp->cylinders);
1839 		} else {
1840 			int	error;
1841 
1842 			announce_buf[0] = '\0';
1843 
1844 			/*
1845 			 * Retry any UNIT ATTENTION type errors.  They
1846 			 * are expected at boot.
1847 			 */
1848 			error = daerror(done_ccb, CAM_RETRY_SELTO,
1849 					SF_RETRY_UA|SF_NO_PRINT);
1850 			if (error == ERESTART) {
1851 				/*
1852 				 * A retry was scheuled, so
1853 				 * just return.
1854 				 */
1855 				return;
1856 			} else if (error != 0) {
1857 				struct scsi_sense_data *sense;
1858 				int asc, ascq;
1859 				int sense_key, error_code;
1860 				int have_sense;
1861 				cam_status status;
1862 				struct ccb_getdev cgd;
1863 
1864 				/* Don't wedge this device's queue */
1865 				status = done_ccb->ccb_h.status;
1866 				if ((status & CAM_DEV_QFRZN) != 0)
1867 					cam_release_devq(done_ccb->ccb_h.path,
1868 							 /*relsim_flags*/0,
1869 							 /*reduction*/0,
1870 							 /*timeout*/0,
1871 							 /*getcount_only*/0);
1872 
1873 
1874 				xpt_setup_ccb(&cgd.ccb_h,
1875 					      done_ccb->ccb_h.path,
1876 					      /* priority */ 1);
1877 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1878 				xpt_action((union ccb *)&cgd);
1879 
1880 				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1881 				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1882 				 || ((status & CAM_AUTOSNS_VALID) == 0))
1883 					have_sense = FALSE;
1884 				else
1885 					have_sense = TRUE;
1886 
1887 				if (have_sense) {
1888 					sense = &csio->sense_data;
1889 					scsi_extract_sense(sense, &error_code,
1890 							   &sense_key,
1891 							   &asc, &ascq);
1892 				}
1893 				/*
1894 				 * Attach to anything that claims to be a
1895 				 * direct access or optical disk device,
1896 				 * as long as it doesn't return a "Logical
1897 				 * unit not supported" (0x25) error.
1898 				 */
1899 				if ((have_sense) && (asc != 0x25)
1900 				 && (error_code == SSD_CURRENT_ERROR)) {
1901 					const char *sense_key_desc;
1902 					const char *asc_desc;
1903 
1904 					scsi_sense_desc(sense_key, asc, ascq,
1905 							&cgd.inq_data,
1906 							&sense_key_desc,
1907 							&asc_desc);
1908 					ksnprintf(announce_buf,
1909 					    sizeof(announce_buf),
1910 						"Attempt to query device "
1911 						"size failed: %s, %s",
1912 						sense_key_desc,
1913 						asc_desc);
1914 				} else {
1915 					if (have_sense)
1916 						scsi_sense_print(
1917 							&done_ccb->csio);
1918 					else {
1919 						xpt_print(periph->path,
1920 						    "got CAM status %#x\n",
1921 						    done_ccb->ccb_h.status);
1922 					}
1923 
1924 					xpt_print(periph->path, "fatal error, "
1925 					    "failed to attach to device\n");
1926 
1927 					/*
1928 					 * Free up resources.
1929 					 */
1930 					cam_periph_invalidate(periph);
1931 				}
1932 			}
1933 		}
1934 		kfree(csio->data_ptr, M_SCSIDA);
1935 		if (announce_buf[0] != '\0') {
1936 			xpt_announce_periph(periph, announce_buf);
1937 			/*
1938 			 * Create our sysctl variables, now that we know
1939 			 * we have successfully attached.
1940 			 */
1941 			taskqueue_enqueue(taskqueue_thread[mycpuid],
1942 			    &softc->sysctl_task);
1943 		}
1944 		softc->state = DA_STATE_NORMAL;
1945 		/*
1946 		 * Since our peripheral may be invalidated by an error
1947 		 * above or an external event, we must release our CCB
1948 		 * before releasing the probe lock on the peripheral.
1949 		 * The peripheral will only go away once the last lock
1950 		 * is removed, and we need it around for the CCB release
1951 		 * operation.
1952 		 */
1953 		xpt_release_ccb(done_ccb);
1954 		cam_periph_unhold(periph, 0);
1955 		return;
1956 	}
1957 	case DA_CCB_WAITING:
1958 	{
1959 		/* Caller will release the CCB */
1960 		wakeup(&done_ccb->ccb_h.cbfcnp);
1961 		return;
1962 	}
1963 	case DA_CCB_DUMP:
1964 		/* No-op.  We're polling */
1965 		return;
1966 	default:
1967 		break;
1968 	}
1969 	xpt_release_ccb(done_ccb);
1970 }
1971 
1972 static int
1973 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1974 {
1975 	struct da_softc	  *softc;
1976 	struct cam_periph *periph;
1977 	int error;
1978 
1979 	periph = xpt_path_periph(ccb->ccb_h.path);
1980 	softc = (struct da_softc *)periph->softc;
1981 
1982  	/*
1983 	 * Automatically detect devices that do not support
1984  	 * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
1985  	 */
1986 	error = 0;
1987 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
1988 		error = cmd6workaround(ccb);
1989 	} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
1990 		   CAM_SCSI_STATUS_ERROR)
1991 	 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
1992 	 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
1993 	 && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0)
1994 	 && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
1995 		int sense_key, error_code, asc, ascq;
1996 
1997  		scsi_extract_sense(&ccb->csio.sense_data,
1998 				   &error_code, &sense_key, &asc, &ascq);
1999 		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
2000  			error = cmd6workaround(ccb);
2001 	}
2002 	if (error == ERESTART)
2003 		return (ERESTART);
2004 
2005 	/*
2006 	 * XXX
2007 	 * Until we have a better way of doing pack validation,
2008 	 * don't treat UAs as errors.
2009 	 */
2010 	sense_flags |= SF_RETRY_UA;
2011 	return(cam_periph_error(ccb, cam_flags, sense_flags,
2012 				&softc->saved_ccb));
2013 }
2014 
2015 static void
2016 daprevent(struct cam_periph *periph, int action)
2017 {
2018 	struct	da_softc *softc;
2019 	union	ccb *ccb;
2020 	int	error;
2021 
2022 	softc = (struct da_softc *)periph->softc;
2023 
2024 	if (((action == PR_ALLOW)
2025 	  && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
2026 	 || ((action == PR_PREVENT)
2027 	  && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
2028 		return;
2029 	}
2030 
2031 	ccb = cam_periph_getccb(periph, /*priority*/1);
2032 
2033 	scsi_prevent(&ccb->csio,
2034 		     /*retries*/1,
2035 		     /*cbcfp*/dadone,
2036 		     MSG_SIMPLE_Q_TAG,
2037 		     action,
2038 		     SSD_FULL_SIZE,
2039 		     5000);
2040 
2041 	error = cam_periph_runccb(ccb, /*error_routine*/NULL, CAM_RETRY_SELTO,
2042 				  SF_RETRY_UA, &softc->device_stats);
2043 
2044 	if (error == 0) {
2045 		if (action == PR_ALLOW)
2046 			softc->flags &= ~DA_FLAG_PACK_LOCKED;
2047 		else
2048 			softc->flags |= DA_FLAG_PACK_LOCKED;
2049 	}
2050 
2051 	xpt_release_ccb(ccb);
2052 }
2053 
2054 static int
2055 dagetcapacity(struct cam_periph *periph)
2056 {
2057 	struct da_softc *softc;
2058 	union ccb *ccb;
2059 	struct scsi_read_capacity_data *rcap;
2060 	struct scsi_read_capacity_data_16 *rcaplong;
2061 	uint32_t block_len;
2062 	uint64_t maxsector;
2063 	int error;
2064 
2065 	softc = (struct da_softc *)periph->softc;
2066 	block_len = 0;
2067 	maxsector = 0;
2068 	error = 0;
2069 
2070 	/* Do a read capacity */
2071 	rcap = (struct scsi_read_capacity_data *)kmalloc(sizeof(*rcaplong),
2072 							 M_SCSIDA, M_INTWAIT);
2073 
2074 	ccb = cam_periph_getccb(periph, /*priority*/1);
2075 	scsi_read_capacity(&ccb->csio,
2076 			   /*retries*/4,
2077 			   /*cbfncp*/dadone,
2078 			   MSG_SIMPLE_Q_TAG,
2079 			   rcap,
2080 			   SSD_FULL_SIZE,
2081 			   /*timeout*/60000);
2082 	ccb->ccb_h.ccb_bio = NULL;
2083 
2084 	error = cam_periph_runccb(ccb, daerror,
2085 				  /*cam_flags*/CAM_RETRY_SELTO,
2086 				  /*sense_flags*/SF_RETRY_UA,
2087 				  &softc->device_stats);
2088 
2089 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2090 		cam_release_devq(ccb->ccb_h.path,
2091 				 /*relsim_flags*/0,
2092 				 /*reduction*/0,
2093 				 /*timeout*/0,
2094 				 /*getcount_only*/0);
2095 
2096 	if (error == 0) {
2097 		block_len = scsi_4btoul(rcap->length);
2098 		maxsector = scsi_4btoul(rcap->addr);
2099 
2100 		if (maxsector != 0xffffffff)
2101 			goto done;
2102 	} else
2103 		goto done;
2104 
2105 	rcaplong = (struct scsi_read_capacity_data_16 *)rcap;
2106 
2107 	scsi_read_capacity_16(&ccb->csio,
2108 			      /*retries*/ 4,
2109 			      /*cbfcnp*/ dadone,
2110 			      /*tag_action*/ MSG_SIMPLE_Q_TAG,
2111 			      /*lba*/ 0,
2112 			      /*reladr*/ 0,
2113 			      /*pmi*/ 0,
2114 			      rcaplong,
2115 			      /*sense_len*/ SSD_FULL_SIZE,
2116 			      /*timeout*/ 60000);
2117 	ccb->ccb_h.ccb_bio = NULL;
2118 
2119 	error = cam_periph_runccb(ccb, daerror,
2120 				  /*cam_flags*/CAM_RETRY_SELTO,
2121 				  /*sense_flags*/SF_RETRY_UA,
2122 				  &softc->device_stats);
2123 
2124 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2125 		cam_release_devq(ccb->ccb_h.path,
2126 				 /*relsim_flags*/0,
2127 				 /*reduction*/0,
2128 				 /*timeout*/0,
2129 				 /*getcount_only*/0);
2130 
2131 	if (error == 0) {
2132 		block_len = scsi_4btoul(rcaplong->length);
2133 		maxsector = scsi_8btou64(rcaplong->addr);
2134 	}
2135 
2136 done:
2137 
2138 	if (error == 0)
2139 		dasetgeom(periph, block_len, maxsector);
2140 
2141 	xpt_release_ccb(ccb);
2142 
2143 	kfree(rcap, M_SCSIDA);
2144 
2145 	return (error);
2146 }
2147 
2148 static void
2149 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector)
2150 {
2151 	struct ccb_calc_geometry ccg;
2152 	struct da_softc *softc;
2153 	struct disk_params *dp;
2154 
2155 	softc = (struct da_softc *)periph->softc;
2156 
2157 	dp = &softc->params;
2158 	dp->secsize = block_len;
2159 	dp->sectors = maxsector + 1;
2160 	/*
2161 	 * Have the controller provide us with a geometry
2162 	 * for this disk.  The only time the geometry
2163 	 * matters is when we boot and the controller
2164 	 * is the only one knowledgeable enough to come
2165 	 * up with something that will make this a bootable
2166 	 * device.
2167 	 */
2168 	xpt_setup_ccb(&ccg.ccb_h, periph->path, /*priority*/1);
2169 	ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
2170 	ccg.block_size = dp->secsize;
2171 	ccg.volume_size = dp->sectors;
2172 	ccg.heads = 0;
2173 	ccg.secs_per_track = 0;
2174 	ccg.cylinders = 0;
2175 	xpt_action((union ccb*)&ccg);
2176 	if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2177 		/*
2178 		 * We don't know what went wrong here- but just pick
2179 		 * a geometry so we don't have nasty things like divide
2180 		 * by zero.
2181 		 */
2182 		dp->heads = 255;
2183 		dp->secs_per_track = 255;
2184 		dp->cylinders = dp->sectors / (255 * 255);
2185 		if (dp->cylinders == 0) {
2186 			dp->cylinders = 1;
2187 		}
2188 	} else {
2189 		dp->heads = ccg.heads;
2190 		dp->secs_per_track = ccg.secs_per_track;
2191 		dp->cylinders = ccg.cylinders;
2192 	}
2193 }
2194 
2195 static void
2196 dasendorderedtag(void *arg)
2197 {
2198 	struct da_softc *softc = arg;
2199 
2200 	if (da_send_ordered) {
2201 		if ((softc->ordered_tag_count == 0)
2202 		 && ((softc->flags & DA_FLAG_WENT_IDLE) == 0)) {
2203 			softc->flags |= DA_FLAG_NEED_OTAG;
2204 		}
2205 		if (softc->outstanding_cmds > 0)
2206 			softc->flags &= ~DA_FLAG_WENT_IDLE;
2207 
2208 		softc->ordered_tag_count = 0;
2209 	}
2210 	/* Queue us up again */
2211 	callout_reset(&softc->sendordered_c,
2212 	    (DA_DEFAULT_TIMEOUT * hz) / DA_ORDEREDTAG_INTERVAL,
2213 	    dasendorderedtag, softc);
2214 }
2215 
2216 /*
2217  * Step through all DA peripheral drivers, and if the device is still open,
2218  * sync the disk cache to physical media.
2219  */
2220 static void
2221 dashutdown(void * arg, int howto)
2222 {
2223 	struct cam_periph *periph;
2224 	struct da_softc *softc;
2225 
2226 	TAILQ_FOREACH(periph, &dadriver.units, unit_links) {
2227 		union ccb ccb;
2228 
2229 		cam_periph_lock(periph);
2230 		softc = (struct da_softc *)periph->softc;
2231 
2232 		/*
2233 		 * We only sync the cache if the drive is still open, and
2234 		 * if the drive is capable of it..
2235 		 */
2236 		if (((softc->flags & DA_FLAG_OPEN) == 0)
2237 		 || (softc->quirks & DA_Q_NO_SYNC_CACHE)) {
2238 			cam_periph_unlock(periph);
2239 			continue;
2240 		}
2241 
2242 		xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/1);
2243 
2244 		ccb.ccb_h.ccb_state = DA_CCB_DUMP;
2245 		scsi_synchronize_cache(&ccb.csio,
2246 				       /*retries*/1,
2247 				       /*cbfcnp*/dadone,
2248 				       MSG_SIMPLE_Q_TAG,
2249 				       /*begin_lba*/0, /* whole disk */
2250 				       /*lb_count*/0,
2251 				       SSD_FULL_SIZE,
2252 				       60 * 60 * 1000);
2253 
2254 		xpt_polled_action(&ccb);
2255 
2256 		if ((ccb.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2257 			if (((ccb.ccb_h.status & CAM_STATUS_MASK) ==
2258 			     CAM_SCSI_STATUS_ERROR)
2259 			 && (ccb.csio.scsi_status == SCSI_STATUS_CHECK_COND)){
2260 				int error_code, sense_key, asc, ascq;
2261 
2262 				scsi_extract_sense(&ccb.csio.sense_data,
2263 						   &error_code, &sense_key,
2264 						   &asc, &ascq);
2265 
2266 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
2267 					scsi_sense_print(&ccb.csio);
2268 			} else {
2269 				xpt_print(periph->path, "Synchronize "
2270 				    "cache failed, status == 0x%x, scsi status "
2271 				    "== 0x%x\n", ccb.ccb_h.status,
2272 				    ccb.csio.scsi_status);
2273 			}
2274 		}
2275 
2276 		if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
2277 			cam_release_devq(ccb.ccb_h.path,
2278 					 /*relsim_flags*/0,
2279 					 /*reduction*/0,
2280 					 /*timeout*/0,
2281 					 /*getcount_only*/0);
2282 
2283 		cam_periph_unlock(periph);
2284 	}
2285 }
2286 
2287 #else /* !_KERNEL */
2288 
2289 /*
2290  * XXX This is only left out of the kernel build to silence warnings.  If,
2291  * for some reason this function is used in the kernel, the ifdefs should
2292  * be moved so it is included both in the kernel and userland.
2293  */
2294 void
2295 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
2296 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
2297 		 u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
2298 		 u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
2299 		 u_int32_t timeout)
2300 {
2301 	struct scsi_format_unit *scsi_cmd;
2302 
2303 	scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
2304 	scsi_cmd->opcode = FORMAT_UNIT;
2305 	scsi_cmd->byte2 = byte2;
2306 	scsi_ulto2b(ileave, scsi_cmd->interleave);
2307 
2308 	cam_fill_csio(csio,
2309 		      retries,
2310 		      cbfcnp,
2311 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
2312 		      tag_action,
2313 		      data_ptr,
2314 		      dxfer_len,
2315 		      sense_len,
2316 		      sizeof(*scsi_cmd),
2317 		      timeout);
2318 }
2319 
2320 #endif /* _KERNEL */
2321