xref: /freebsd/sys/cam/scsi/scsi_da.c (revision a98ff317388a00b992f1bf8404dee596f9383f5e)
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 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 
34 #ifdef _KERNEL
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/bio.h>
38 #include <sys/sysctl.h>
39 #include <sys/taskqueue.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/conf.h>
43 #include <sys/devicestat.h>
44 #include <sys/eventhandler.h>
45 #include <sys/malloc.h>
46 #include <sys/cons.h>
47 #include <sys/endian.h>
48 #include <sys/proc.h>
49 #include <geom/geom.h>
50 #include <geom/geom_disk.h>
51 #endif /* _KERNEL */
52 
53 #ifndef _KERNEL
54 #include <stdio.h>
55 #include <string.h>
56 #endif /* _KERNEL */
57 
58 #include <cam/cam.h>
59 #include <cam/cam_ccb.h>
60 #include <cam/cam_periph.h>
61 #include <cam/cam_xpt_periph.h>
62 #include <cam/cam_sim.h>
63 
64 #include <cam/scsi/scsi_message.h>
65 
66 #ifndef _KERNEL
67 #include <cam/scsi/scsi_da.h>
68 #endif /* !_KERNEL */
69 
70 #ifdef _KERNEL
71 typedef enum {
72 	DA_STATE_PROBE_RC,
73 	DA_STATE_PROBE_RC16,
74 	DA_STATE_PROBE_LBP,
75 	DA_STATE_PROBE_BLK_LIMITS,
76 	DA_STATE_PROBE_BDC,
77 	DA_STATE_PROBE_ATA,
78 	DA_STATE_NORMAL
79 } da_state;
80 
81 typedef enum {
82 	DA_FLAG_PACK_INVALID	= 0x001,
83 	DA_FLAG_NEW_PACK	= 0x002,
84 	DA_FLAG_PACK_LOCKED	= 0x004,
85 	DA_FLAG_PACK_REMOVABLE	= 0x008,
86 	DA_FLAG_NEED_OTAG	= 0x020,
87 	DA_FLAG_WENT_IDLE	= 0x040,
88 	DA_FLAG_RETRY_UA	= 0x080,
89 	DA_FLAG_OPEN		= 0x100,
90 	DA_FLAG_SCTX_INIT	= 0x200,
91 	DA_FLAG_CAN_RC16	= 0x400,
92 	DA_FLAG_PROBED		= 0x800,
93 	DA_FLAG_DIRTY		= 0x1000
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_Q_4K			= 0x08
102 } da_quirks;
103 
104 #define DA_Q_BIT_STRING		\
105 	"\020"			\
106 	"\001NO_SYNC_CACHE"	\
107 	"\002NO_6_BYTE"		\
108 	"\003NO_PREVENT"	\
109 	"\0044K"
110 
111 typedef enum {
112 	DA_CCB_PROBE_RC		= 0x01,
113 	DA_CCB_PROBE_RC16	= 0x02,
114 	DA_CCB_PROBE_LBP	= 0x03,
115 	DA_CCB_PROBE_BLK_LIMITS	= 0x04,
116 	DA_CCB_PROBE_BDC	= 0x05,
117 	DA_CCB_PROBE_ATA	= 0x06,
118 	DA_CCB_BUFFER_IO	= 0x07,
119 	DA_CCB_WAITING		= 0x08,
120 	DA_CCB_DUMP		= 0x0A,
121 	DA_CCB_DELETE		= 0x0B,
122  	DA_CCB_TUR		= 0x0C,
123 	DA_CCB_TYPE_MASK	= 0x0F,
124 	DA_CCB_RETRY_UA		= 0x10
125 } da_ccb_state;
126 
127 /*
128  * Order here is important for method choice
129  *
130  * We prefer ATA_TRIM as tests run against a Sandforce 2281 SSD attached to
131  * LSI 2008 (mps) controller (FW: v12, Drv: v14) resulted 20% quicker deletes
132  * using ATA_TRIM than the corresponding UNMAP results for a real world mysql
133  * import taking 5mins.
134  *
135  */
136 typedef enum {
137 	DA_DELETE_NONE,
138 	DA_DELETE_DISABLE,
139 	DA_DELETE_ATA_TRIM,
140 	DA_DELETE_UNMAP,
141 	DA_DELETE_WS16,
142 	DA_DELETE_WS10,
143 	DA_DELETE_ZERO,
144 	DA_DELETE_MIN = DA_DELETE_ATA_TRIM,
145 	DA_DELETE_MAX = DA_DELETE_ZERO
146 } da_delete_methods;
147 
148 typedef void da_delete_func_t (struct cam_periph *periph, union ccb *ccb,
149 			      struct bio *bp);
150 static da_delete_func_t da_delete_trim;
151 static da_delete_func_t da_delete_unmap;
152 static da_delete_func_t da_delete_ws;
153 
154 static const void * da_delete_functions[] = {
155 	NULL,
156 	NULL,
157 	da_delete_trim,
158 	da_delete_unmap,
159 	da_delete_ws,
160 	da_delete_ws,
161 	da_delete_ws
162 };
163 
164 static const char *da_delete_method_names[] =
165     { "NONE", "DISABLE", "ATA_TRIM", "UNMAP", "WS16", "WS10", "ZERO" };
166 static const char *da_delete_method_desc[] =
167     { "NONE", "DISABLED", "ATA TRIM", "UNMAP", "WRITE SAME(16) with UNMAP",
168       "WRITE SAME(10) with UNMAP", "ZERO" };
169 
170 /* Offsets into our private area for storing information */
171 #define ccb_state	ppriv_field0
172 #define ccb_bp		ppriv_ptr1
173 
174 struct disk_params {
175 	u_int8_t  heads;
176 	u_int32_t cylinders;
177 	u_int8_t  secs_per_track;
178 	u_int32_t secsize;	/* Number of bytes/sector */
179 	u_int64_t sectors;	/* total number sectors */
180 	u_int     stripesize;
181 	u_int     stripeoffset;
182 };
183 
184 #define UNMAP_RANGE_MAX		0xffffffff
185 #define UNMAP_HEAD_SIZE		8
186 #define UNMAP_RANGE_SIZE	16
187 #define UNMAP_MAX_RANGES	2048 /* Protocol Max is 4095 */
188 #define UNMAP_BUF_SIZE		((UNMAP_MAX_RANGES * UNMAP_RANGE_SIZE) + \
189 				UNMAP_HEAD_SIZE)
190 
191 #define WS10_MAX_BLKS		0xffff
192 #define WS16_MAX_BLKS		0xffffffff
193 #define ATA_TRIM_MAX_RANGES	((UNMAP_BUF_SIZE / \
194 	(ATA_DSM_RANGE_SIZE * ATA_DSM_BLK_SIZE)) * ATA_DSM_BLK_SIZE)
195 
196 struct da_softc {
197 	struct	 bio_queue_head bio_queue;
198 	struct	 bio_queue_head delete_queue;
199 	struct	 bio_queue_head delete_run_queue;
200 	SLIST_ENTRY(da_softc) links;
201 	LIST_HEAD(, ccb_hdr) pending_ccbs;
202 	da_state state;
203 	da_flags flags;
204 	da_quirks quirks;
205 	int	 sort_io_queue;
206 	int	 minimum_cmd_size;
207 	int	 error_inject;
208 	int	 ordered_tag_count;
209 	int	 outstanding_cmds;
210 	int	 trim_max_ranges;
211 	int	 delete_running;
212 	int	 tur;
213 	int	 delete_available;	/* Delete methods possibly available */
214 	uint32_t		unmap_max_ranges;
215 	uint32_t		unmap_max_lba;
216 	uint64_t		ws_max_blks;
217 	da_delete_methods	delete_method;
218 	da_delete_func_t	*delete_func;
219 	struct	 disk_params params;
220 	struct	 disk *disk;
221 	union	 ccb saved_ccb;
222 	struct task		sysctl_task;
223 	struct sysctl_ctx_list	sysctl_ctx;
224 	struct sysctl_oid	*sysctl_tree;
225 	struct callout		sendordered_c;
226 	uint64_t wwpn;
227 	uint8_t	 unmap_buf[UNMAP_BUF_SIZE];
228 	struct scsi_read_capacity_data_long rcaplong;
229 	struct callout		mediapoll_c;
230 };
231 
232 #define dadeleteflag(softc, delete_method, enable)			\
233 	if (enable) {							\
234 		softc->delete_available |= (1 << delete_method);	\
235 	} else {							\
236 		softc->delete_available &= ~(1 << delete_method);	\
237 	}
238 
239 struct da_quirk_entry {
240 	struct scsi_inquiry_pattern inq_pat;
241 	da_quirks quirks;
242 };
243 
244 static const char quantum[] = "QUANTUM";
245 static const char microp[] = "MICROP";
246 
247 static struct da_quirk_entry da_quirk_table[] =
248 {
249 	/* SPI, FC devices */
250 	{
251 		/*
252 		 * Fujitsu M2513A MO drives.
253 		 * Tested devices: M2513A2 firmware versions 1200 & 1300.
254 		 * (dip switch selects whether T_DIRECT or T_OPTICAL device)
255 		 * Reported by: W.Scholten <whs@xs4all.nl>
256 		 */
257 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
258 		/*quirks*/ DA_Q_NO_SYNC_CACHE
259 	},
260 	{
261 		/* See above. */
262 		{T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
263 		/*quirks*/ DA_Q_NO_SYNC_CACHE
264 	},
265 	{
266 		/*
267 		 * This particular Fujitsu drive doesn't like the
268 		 * synchronize cache command.
269 		 * Reported by: Tom Jackson <toj@gorilla.net>
270 		 */
271 		{T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
272 		/*quirks*/ DA_Q_NO_SYNC_CACHE
273 	},
274 	{
275 		/*
276 		 * This drive doesn't like the synchronize cache command
277 		 * either.  Reported by: Matthew Jacob <mjacob@feral.com>
278 		 * in NetBSD PR kern/6027, August 24, 1998.
279 		 */
280 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
281 		/*quirks*/ DA_Q_NO_SYNC_CACHE
282 	},
283 	{
284 		/*
285 		 * This drive doesn't like the synchronize cache command
286 		 * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
287 		 * (PR 8882).
288 		 */
289 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
290 		/*quirks*/ DA_Q_NO_SYNC_CACHE
291 	},
292 	{
293 		/*
294 		 * Doesn't like the synchronize cache command.
295 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
296 		 */
297 		{T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
298 		/*quirks*/ DA_Q_NO_SYNC_CACHE
299 	},
300 	{
301 		/*
302 		 * Doesn't like the synchronize cache command.
303 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
304 		 */
305 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
306 		/*quirks*/ DA_Q_NO_SYNC_CACHE
307 	},
308 	{
309 		/*
310 		 * Doesn't like the synchronize cache command.
311 		 */
312 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
313 		/*quirks*/ DA_Q_NO_SYNC_CACHE
314 	},
315 	{
316 		/*
317 		 * Doesn't like the synchronize cache command.
318 		 * Reported by: walter@pelissero.de
319 		 */
320 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS540S", "*"},
321 		/*quirks*/ DA_Q_NO_SYNC_CACHE
322 	},
323 	{
324 		/*
325 		 * Doesn't work correctly with 6 byte reads/writes.
326 		 * Returns illegal request, and points to byte 9 of the
327 		 * 6-byte CDB.
328 		 * Reported by:  Adam McDougall <bsdx@spawnet.com>
329 		 */
330 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
331 		/*quirks*/ DA_Q_NO_6_BYTE
332 	},
333 	{
334 		/* See above. */
335 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
336 		/*quirks*/ DA_Q_NO_6_BYTE
337 	},
338 	{
339 		/*
340 		 * Doesn't like the synchronize cache command.
341 		 * Reported by: walter@pelissero.de
342 		 */
343 		{T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CP3500*", "*"},
344 		/*quirks*/ DA_Q_NO_SYNC_CACHE
345 	},
346 	{
347 		/*
348 		 * The CISS RAID controllers do not support SYNC_CACHE
349 		 */
350 		{T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"},
351 		/*quirks*/ DA_Q_NO_SYNC_CACHE
352 	},
353 	/* USB mass storage devices supported by umass(4) */
354 	{
355 		/*
356 		 * EXATELECOM (Sigmatel) i-Bead 100/105 USB Flash MP3 Player
357 		 * PR: kern/51675
358 		 */
359 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EXATEL", "i-BEAD10*", "*"},
360 		/*quirks*/ DA_Q_NO_SYNC_CACHE
361 	},
362 	{
363 		/*
364 		 * Power Quotient Int. (PQI) USB flash key
365 		 * PR: kern/53067
366 		 */
367 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "USB Flash Disk*",
368 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
369 	},
370  	{
371  		/*
372  		 * Creative Nomad MUVO mp3 player (USB)
373  		 * PR: kern/53094
374  		 */
375  		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"},
376  		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
377  	},
378 	{
379 		/*
380 		 * Jungsoft NEXDISK USB flash key
381 		 * PR: kern/54737
382 		 */
383 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JUNGSOFT", "NEXDISK*", "*"},
384 		/*quirks*/ DA_Q_NO_SYNC_CACHE
385 	},
386 	{
387 		/*
388 		 * FreeDik USB Mini Data Drive
389 		 * PR: kern/54786
390 		 */
391 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FreeDik*", "Mini Data Drive",
392 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
393 	},
394 	{
395 		/*
396 		 * Sigmatel USB Flash MP3 Player
397 		 * PR: kern/57046
398 		 */
399 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SigmaTel", "MSCN", "*"},
400 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
401 	},
402 	{
403 		/*
404 		 * Neuros USB Digital Audio Computer
405 		 * PR: kern/63645
406 		 */
407 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "NEUROS", "dig. audio comp.",
408 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
409 	},
410 	{
411 		/*
412 		 * SEAGRAND NP-900 MP3 Player
413 		 * PR: kern/64563
414 		 */
415 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SEAGRAND", "NP-900*", "*"},
416 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
417 	},
418 	{
419 		/*
420 		 * iRiver iFP MP3 player (with UMS Firmware)
421 		 * PR: kern/54881, i386/63941, kern/66124
422 		 */
423 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iRiver", "iFP*", "*"},
424 		/*quirks*/ DA_Q_NO_SYNC_CACHE
425  	},
426 	{
427 		/*
428 		 * Frontier Labs NEX IA+ Digital Audio Player, rev 1.10/0.01
429 		 * PR: kern/70158
430 		 */
431 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FL" , "Nex*", "*"},
432 		/*quirks*/ DA_Q_NO_SYNC_CACHE
433 	},
434 	{
435 		/*
436 		 * ZICPlay USB MP3 Player with FM
437 		 * PR: kern/75057
438 		 */
439 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ACTIONS*" , "USB DISK*", "*"},
440 		/*quirks*/ DA_Q_NO_SYNC_CACHE
441 	},
442 	{
443 		/*
444 		 * TEAC USB floppy mechanisms
445 		 */
446 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TEAC" , "FD-05*", "*"},
447 		/*quirks*/ DA_Q_NO_SYNC_CACHE
448 	},
449 	{
450 		/*
451 		 * Kingston DataTraveler II+ USB Pen-Drive.
452 		 * Reported by: Pawel Jakub Dawidek <pjd@FreeBSD.org>
453 		 */
454 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston" , "DataTraveler II+",
455 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
456 	},
457 	{
458 		/*
459 		 * USB DISK Pro PMAP
460 		 * Reported by: jhs
461 		 * PR: usb/96381
462 		 */
463 		{T_DIRECT, SIP_MEDIA_REMOVABLE, " ", "USB DISK Pro", "PMAP"},
464 		/*quirks*/ DA_Q_NO_SYNC_CACHE
465 	},
466 	{
467 		/*
468 		 * Motorola E398 Mobile Phone (TransFlash memory card).
469 		 * Reported by: Wojciech A. Koszek <dunstan@FreeBSD.czest.pl>
470 		 * PR: usb/89889
471 		 */
472 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Motorola" , "Motorola Phone",
473 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
474 	},
475 	{
476 		/*
477 		 * Qware BeatZkey! Pro
478 		 * PR: usb/79164
479 		 */
480 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "GENERIC", "USB DISK DEVICE",
481 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
482 	},
483 	{
484 		/*
485 		 * Time DPA20B 1GB MP3 Player
486 		 * PR: usb/81846
487 		 */
488 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB2.0*", "(FS) FLASH DISK*",
489 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
490 	},
491 	{
492 		/*
493 		 * Samsung USB key 128Mb
494 		 * PR: usb/90081
495 		 */
496 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB-DISK", "FreeDik-FlashUsb",
497 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
498 	},
499 	{
500 		/*
501 		 * Kingston DataTraveler 2.0 USB Flash memory.
502 		 * PR: usb/89196
503 		 */
504 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler 2.0",
505 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
506 	},
507 	{
508 		/*
509 		 * Creative MUVO Slim mp3 player (USB)
510 		 * PR: usb/86131
511 		 */
512 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "MuVo Slim",
513 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
514 		},
515 	{
516 		/*
517 		 * United MP5512 Portable MP3 Player (2-in-1 USB DISK/MP3)
518 		 * PR: usb/80487
519 		 */
520 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "MUSIC DISK",
521 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
522 	},
523 	{
524 		/*
525 		 * SanDisk Micro Cruzer 128MB
526 		 * PR: usb/75970
527 		 */
528 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SanDisk" , "Micro Cruzer",
529 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
530 	},
531 	{
532 		/*
533 		 * TOSHIBA TransMemory USB sticks
534 		 * PR: kern/94660
535 		 */
536 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TOSHIBA", "TransMemory",
537 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
538 	},
539 	{
540 		/*
541 		 * PNY USB Flash keys
542 		 * PR: usb/75578, usb/72344, usb/65436
543 		 */
544 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "*" , "USB DISK*",
545 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
546 	},
547 	{
548 		/*
549 		 * Genesys 6-in-1 Card Reader
550 		 * PR: usb/94647
551 		 */
552 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "STORAGE DEVICE*",
553 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
554 	},
555 	{
556 		/*
557 		 * Rekam Digital CAMERA
558 		 * PR: usb/98713
559 		 */
560 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CAMERA*", "4MP-9J6*",
561 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
562 	},
563 	{
564 		/*
565 		 * iRiver H10 MP3 player
566 		 * PR: usb/102547
567 		 */
568 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "H10*",
569 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
570 	},
571 	{
572 		/*
573 		 * iRiver U10 MP3 player
574 		 * PR: usb/92306
575 		 */
576 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "U10*",
577 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
578 	},
579 	{
580 		/*
581 		 * X-Micro Flash Disk
582 		 * PR: usb/96901
583 		 */
584 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "X-Micro", "Flash Disk",
585 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
586 	},
587 	{
588 		/*
589 		 * EasyMP3 EM732X USB 2.0 Flash MP3 Player
590 		 * PR: usb/96546
591 		 */
592 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EM732X", "MP3 Player*",
593 		"1.00"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
594 	},
595 	{
596 		/*
597 		 * Denver MP3 player
598 		 * PR: usb/107101
599 		 */
600 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "DENVER", "MP3 PLAYER",
601 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
602 	},
603 	{
604 		/*
605 		 * Philips USB Key Audio KEY013
606 		 * PR: usb/68412
607 		 */
608 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "PHILIPS", "Key*", "*"},
609 		/*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
610 	},
611 	{
612 		/*
613 		 * JNC MP3 Player
614 		 * PR: usb/94439
615 		 */
616 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JNC*" , "MP3 Player*",
617 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
618 	},
619 	{
620 		/*
621 		 * SAMSUNG MP0402H
622 		 * PR: usb/108427
623 		 */
624 		{T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "MP0402H", "*"},
625 		/*quirks*/ DA_Q_NO_SYNC_CACHE
626 	},
627 	{
628 		/*
629 		 * I/O Magic USB flash - Giga Bank
630 		 * PR: usb/108810
631 		 */
632 		{T_DIRECT, SIP_MEDIA_FIXED, "GS-Magic", "stor*", "*"},
633 		/*quirks*/ DA_Q_NO_SYNC_CACHE
634 	},
635 	{
636 		/*
637 		 * JoyFly 128mb USB Flash Drive
638 		 * PR: 96133
639 		 */
640 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "Flash Disk*",
641 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
642 	},
643 	{
644 		/*
645 		 * ChipsBnk usb stick
646 		 * PR: 103702
647 		 */
648 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ChipsBnk", "USB*",
649 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
650 	},
651 	{
652 		/*
653 		 * Storcase (Kingston) InfoStation IFS FC2/SATA-R 201A
654 		 * PR: 129858
655 		 */
656 		{T_DIRECT, SIP_MEDIA_FIXED, "IFS", "FC2/SATA-R*",
657 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
658 	},
659 	{
660 		/*
661 		 * Samsung YP-U3 mp3-player
662 		 * PR: 125398
663 		 */
664 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Samsung", "YP-U3",
665 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
666 	},
667 	{
668 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Netac", "OnlyDisk*",
669 		 "2000"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
670 	},
671 	{
672 		/*
673 		 * Sony Cyber-Shot DSC cameras
674 		 * PR: usb/137035
675 		 */
676 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
677 		/*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
678 	},
679 	{
680 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler G3",
681 		 "1.00"}, /*quirks*/ DA_Q_NO_PREVENT
682 	},
683 	/* ATA/SATA devices over SAS/USB/... */
684 	{
685 		/* Hitachi Advanced Format (4k) drives */
686 		{ T_DIRECT, SIP_MEDIA_FIXED, "Hitachi", "H??????????E3*", "*" },
687 		/*quirks*/DA_Q_4K
688 	},
689 	{
690 		/* Samsung Advanced Format (4k) drives */
691 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD155UI*", "*" },
692 		/*quirks*/DA_Q_4K
693 	},
694 	{
695 		/* Samsung Advanced Format (4k) drives */
696 		{ T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD155UI*", "*" },
697 		/*quirks*/DA_Q_4K
698 	},
699 	{
700 		/* Samsung Advanced Format (4k) drives */
701 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD204UI*", "*" },
702 		/*quirks*/DA_Q_4K
703 	},
704 	{
705 		/* Samsung Advanced Format (4k) drives */
706 		{ T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD204UI*", "*" },
707 		/*quirks*/DA_Q_4K
708 	},
709 	{
710 		/* Seagate Barracuda Green Advanced Format (4k) drives */
711 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DL*", "*" },
712 		/*quirks*/DA_Q_4K
713 	},
714 	{
715 		/* Seagate Barracuda Green Advanced Format (4k) drives */
716 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST????DL", "*", "*" },
717 		/*quirks*/DA_Q_4K
718 	},
719 	{
720 		/* Seagate Barracuda Green Advanced Format (4k) drives */
721 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???DM*", "*" },
722 		/*quirks*/DA_Q_4K
723 	},
724 	{
725 		/* Seagate Barracuda Green Advanced Format (4k) drives */
726 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST???DM*", "*", "*" },
727 		/*quirks*/DA_Q_4K
728 	},
729 	{
730 		/* Seagate Barracuda Green Advanced Format (4k) drives */
731 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DM*", "*" },
732 		/*quirks*/DA_Q_4K
733 	},
734 	{
735 		/* Seagate Barracuda Green Advanced Format (4k) drives */
736 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST????DM", "*", "*" },
737 		/*quirks*/DA_Q_4K
738 	},
739 	{
740 		/* Seagate Momentus Advanced Format (4k) drives */
741 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500423AS*", "*" },
742 		/*quirks*/DA_Q_4K
743 	},
744 	{
745 		/* Seagate Momentus Advanced Format (4k) drives */
746 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "3AS*", "*" },
747 		/*quirks*/DA_Q_4K
748 	},
749 	{
750 		/* Seagate Momentus Advanced Format (4k) drives */
751 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500424AS*", "*" },
752 		/*quirks*/DA_Q_4K
753 	},
754 	{
755 		/* Seagate Momentus Advanced Format (4k) drives */
756 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "4AS*", "*" },
757 		/*quirks*/DA_Q_4K
758 	},
759 	{
760 		/* Seagate Momentus Advanced Format (4k) drives */
761 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640423AS*", "*" },
762 		/*quirks*/DA_Q_4K
763 	},
764 	{
765 		/* Seagate Momentus Advanced Format (4k) drives */
766 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "3AS*", "*" },
767 		/*quirks*/DA_Q_4K
768 	},
769 	{
770 		/* Seagate Momentus Advanced Format (4k) drives */
771 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640424AS*", "*" },
772 		/*quirks*/DA_Q_4K
773 	},
774 	{
775 		/* Seagate Momentus Advanced Format (4k) drives */
776 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "4AS*", "*" },
777 		/*quirks*/DA_Q_4K
778 	},
779 	{
780 		/* Seagate Momentus Advanced Format (4k) drives */
781 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750420AS*", "*" },
782 		/*quirks*/DA_Q_4K
783 	},
784 	{
785 		/* Seagate Momentus Advanced Format (4k) drives */
786 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "0AS*", "*" },
787 		/*quirks*/DA_Q_4K
788 	},
789 	{
790 		/* Seagate Momentus Advanced Format (4k) drives */
791 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750422AS*", "*" },
792 		/*quirks*/DA_Q_4K
793 	},
794 	{
795 		/* Seagate Momentus Advanced Format (4k) drives */
796 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "2AS*", "*" },
797 		/*quirks*/DA_Q_4K
798 	},
799 	{
800 		/* Seagate Momentus Advanced Format (4k) drives */
801 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750423AS*", "*" },
802 		/*quirks*/DA_Q_4K
803 	},
804 	{
805 		/* Seagate Momentus Advanced Format (4k) drives */
806 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "3AS*", "*" },
807 		/*quirks*/DA_Q_4K
808 	},
809 	{
810 		/* Seagate Momentus Thin Advanced Format (4k) drives */
811 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???LT*", "*" },
812 		/*quirks*/DA_Q_4K
813 	},
814 	{
815 		/* Seagate Momentus Thin Advanced Format (4k) drives */
816 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST???LT*", "*", "*" },
817 		/*quirks*/DA_Q_4K
818 	},
819 	{
820 		/* WDC Caviar Green Advanced Format (4k) drives */
821 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RS*", "*" },
822 		/*quirks*/DA_Q_4K
823 	},
824 	{
825 		/* WDC Caviar Green Advanced Format (4k) drives */
826 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RS*", "*" },
827 		/*quirks*/DA_Q_4K
828 	},
829 	{
830 		/* WDC Caviar Green Advanced Format (4k) drives */
831 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RX*", "*" },
832 		/*quirks*/DA_Q_4K
833 	},
834 	{
835 		/* WDC Caviar Green Advanced Format (4k) drives */
836 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RX*", "*" },
837 		/*quirks*/DA_Q_4K
838 	},
839 	{
840 		/* WDC Caviar Green Advanced Format (4k) drives */
841 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RS*", "*" },
842 		/*quirks*/DA_Q_4K
843 	},
844 	{
845 		/* WDC Caviar Green Advanced Format (4k) drives */
846 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RS*", "*" },
847 		/*quirks*/DA_Q_4K
848 	},
849 	{
850 		/* WDC Caviar Green Advanced Format (4k) drives */
851 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RX*", "*" },
852 		/*quirks*/DA_Q_4K
853 	},
854 	{
855 		/* WDC Caviar Green Advanced Format (4k) drives */
856 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RX*", "*" },
857 		/*quirks*/DA_Q_4K
858 	},
859 	{
860 		/* WDC Scorpio Black Advanced Format (4k) drives */
861 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PKT*", "*" },
862 		/*quirks*/DA_Q_4K
863 	},
864 	{
865 		/* WDC Scorpio Black Advanced Format (4k) drives */
866 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PKT*", "*" },
867 		/*quirks*/DA_Q_4K
868 	},
869 	{
870 		/* WDC Scorpio Black Advanced Format (4k) drives */
871 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PKT*", "*" },
872 		/*quirks*/DA_Q_4K
873 	},
874 	{
875 		/* WDC Scorpio Black Advanced Format (4k) drives */
876 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PKT*", "*" },
877 		/*quirks*/DA_Q_4K
878 	},
879 	{
880 		/* WDC Scorpio Blue Advanced Format (4k) drives */
881 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PVT*", "*" },
882 		/*quirks*/DA_Q_4K
883 	},
884 	{
885 		/* WDC Scorpio Blue Advanced Format (4k) drives */
886 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PVT*", "*" },
887 		/*quirks*/DA_Q_4K
888 	},
889 	{
890 		/* WDC Scorpio Blue Advanced Format (4k) drives */
891 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PVT*", "*" },
892 		/*quirks*/DA_Q_4K
893 	},
894 	{
895 		/* WDC Scorpio Blue Advanced Format (4k) drives */
896 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PVT*", "*" },
897 		/*quirks*/DA_Q_4K
898 	},
899 	{
900 		/*
901 		 * Olympus FE-210 camera
902 		 */
903 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "FE210*",
904 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
905 	},
906 	{
907 		/*
908 		 * LG UP3S MP3 player
909 		 */
910 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "LG", "UP3S",
911 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
912 	},
913 	{
914 		/*
915 		 * Laser MP3-2GA13 MP3 player
916 		 */
917 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "(HS) Flash Disk",
918 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
919 	},
920 	{
921 		/*
922 		 * LaCie external 250GB Hard drive des by Porsche
923 		 * Submitted by: Ben Stuyts <ben@altesco.nl>
924 		 * PR: 121474
925 		 */
926 		{T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HM250JI", "*"},
927 		/*quirks*/ DA_Q_NO_SYNC_CACHE
928 	},
929 	/* SATA SSDs */
930 	{
931 		/*
932 		 * Corsair Force 2 SSDs
933 		 * 4k optimised & trim only works in 4k requests + 4k aligned
934 		 */
935 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair CSSD-F*", "*" },
936 		/*quirks*/DA_Q_4K
937 	},
938 	{
939 		/*
940 		 * Corsair Force 3 SSDs
941 		 * 4k optimised & trim only works in 4k requests + 4k aligned
942 		 */
943 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair Force 3*", "*" },
944 		/*quirks*/DA_Q_4K
945 	},
946 	{
947 		/*
948 		 * Corsair Force GT SSDs
949 		 * 4k optimised & trim only works in 4k requests + 4k aligned
950 		 */
951 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair Force GT*", "*" },
952 		/*quirks*/DA_Q_4K
953 	},
954 	{
955 		/*
956 		 * Crucial M4 SSDs
957 		 * 4k optimised & trim only works in 4k requests + 4k aligned
958 		 */
959 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "M4-CT???M4SSD2*", "*" },
960 		/*quirks*/DA_Q_4K
961 	},
962 	{
963 		/*
964 		 * Crucial RealSSD C300 SSDs
965 		 * 4k optimised
966 		 */
967 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "C300-CTFDDAC???MAG*",
968 		"*" }, /*quirks*/DA_Q_4K
969 	},
970 	{
971 		/*
972 		 * Intel 320 Series SSDs
973 		 * 4k optimised & trim only works in 4k requests + 4k aligned
974 		 */
975 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSA2CW*", "*" },
976 		/*quirks*/DA_Q_4K
977 	},
978 	{
979 		/*
980 		 * Intel 330 Series SSDs
981 		 * 4k optimised & trim only works in 4k requests + 4k aligned
982 		 */
983 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2CT*", "*" },
984 		/*quirks*/DA_Q_4K
985 	},
986 	{
987 		/*
988 		 * Intel 510 Series SSDs
989 		 * 4k optimised & trim only works in 4k requests + 4k aligned
990 		 */
991 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2MH*", "*" },
992 		/*quirks*/DA_Q_4K
993 	},
994 	{
995 		/*
996 		 * Intel 520 Series SSDs
997 		 * 4k optimised & trim only works in 4k requests + 4k aligned
998 		 */
999 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2BW*", "*" },
1000 		/*quirks*/DA_Q_4K
1001 	},
1002 	{
1003 		/*
1004 		 * Kingston E100 Series SSDs
1005 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1006 		 */
1007 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "KINGSTON SE100S3*", "*" },
1008 		/*quirks*/DA_Q_4K
1009 	},
1010 	{
1011 		/*
1012 		 * Kingston HyperX 3k SSDs
1013 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1014 		 */
1015 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "KINGSTON SH103S3*", "*" },
1016 		/*quirks*/DA_Q_4K
1017 	},
1018 	{
1019 		/*
1020 		 * OCZ Agility 3 SSDs
1021 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1022 		 */
1023 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-AGILITY3*", "*" },
1024 		/*quirks*/DA_Q_4K
1025 	},
1026 	{
1027 		/*
1028 		 * OCZ Deneva R Series SSDs
1029 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1030 		 */
1031 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "DENRSTE251M45*", "*" },
1032 		/*quirks*/DA_Q_4K
1033 	},
1034 	{
1035 		/*
1036 		 * OCZ Vertex 2 SSDs (inc pro series)
1037 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1038 		 */
1039 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ?VERTEX2*", "*" },
1040 		/*quirks*/DA_Q_4K
1041 	},
1042 	{
1043 		/*
1044 		 * OCZ Vertex 3 SSDs
1045 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1046 		 */
1047 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-VERTEX3*", "*" },
1048 		/*quirks*/DA_Q_4K
1049 	},
1050 	{
1051 		/*
1052 		 * OCZ Vertex 4 SSDs
1053 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1054 		 */
1055 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-VERTEX4*", "*" },
1056 		/*quirks*/DA_Q_4K
1057 	},
1058 	{
1059 		/*
1060 		 * Samsung 830 Series SSDs
1061 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1062 		 */
1063 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG SSD 830 Series*", "*" },
1064 		/*quirks*/DA_Q_4K
1065 	},
1066 	{
1067 		/*
1068 		 * SuperTalent TeraDrive CT SSDs
1069 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1070 		 */
1071 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "FTM??CT25H*", "*" },
1072 		/*quirks*/DA_Q_4K
1073 	},
1074 	{
1075 		/*
1076 		 * XceedIOPS SATA SSDs
1077 		 * 4k optimised
1078 		 */
1079 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SG9XCS2D*", "*" },
1080 		/*quirks*/DA_Q_4K
1081 	},
1082 };
1083 
1084 static	disk_strategy_t	dastrategy;
1085 static	dumper_t	dadump;
1086 static	periph_init_t	dainit;
1087 static	void		daasync(void *callback_arg, u_int32_t code,
1088 				struct cam_path *path, void *arg);
1089 static	void		dasysctlinit(void *context, int pending);
1090 static	int		dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
1091 static	int		dadeletemethodsysctl(SYSCTL_HANDLER_ARGS);
1092 static	int		dadeletemaxsysctl(SYSCTL_HANDLER_ARGS);
1093 static	void		dadeletemethodset(struct da_softc *softc,
1094 					  da_delete_methods delete_method);
1095 static	off_t		dadeletemaxsize(struct da_softc *softc,
1096 					da_delete_methods delete_method);
1097 static	void		dadeletemethodchoose(struct da_softc *softc,
1098 					     da_delete_methods default_method);
1099 static	void		daprobedone(struct cam_periph *periph, union ccb *ccb);
1100 
1101 static	periph_ctor_t	daregister;
1102 static	periph_dtor_t	dacleanup;
1103 static	periph_start_t	dastart;
1104 static	periph_oninv_t	daoninvalidate;
1105 static	void		dadone(struct cam_periph *periph,
1106 			       union ccb *done_ccb);
1107 static  int		daerror(union ccb *ccb, u_int32_t cam_flags,
1108 				u_int32_t sense_flags);
1109 static void		daprevent(struct cam_periph *periph, int action);
1110 static void		dareprobe(struct cam_periph *periph);
1111 static void		dasetgeom(struct cam_periph *periph, uint32_t block_len,
1112 				  uint64_t maxsector,
1113 				  struct scsi_read_capacity_data_long *rcaplong,
1114 				  size_t rcap_size);
1115 static timeout_t	dasendorderedtag;
1116 static void		dashutdown(void *arg, int howto);
1117 static timeout_t	damediapoll;
1118 
1119 #ifndef	DA_DEFAULT_POLL_PERIOD
1120 #define	DA_DEFAULT_POLL_PERIOD	3
1121 #endif
1122 
1123 #ifndef DA_DEFAULT_TIMEOUT
1124 #define DA_DEFAULT_TIMEOUT 60	/* Timeout in seconds */
1125 #endif
1126 
1127 #ifndef	DA_DEFAULT_RETRY
1128 #define	DA_DEFAULT_RETRY	4
1129 #endif
1130 
1131 #ifndef	DA_DEFAULT_SEND_ORDERED
1132 #define	DA_DEFAULT_SEND_ORDERED	1
1133 #endif
1134 
1135 #define DA_SIO (softc->sort_io_queue >= 0 ? \
1136     softc->sort_io_queue : cam_sort_io_queues)
1137 
1138 static int da_poll_period = DA_DEFAULT_POLL_PERIOD;
1139 static int da_retry_count = DA_DEFAULT_RETRY;
1140 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
1141 static int da_send_ordered = DA_DEFAULT_SEND_ORDERED;
1142 
1143 static SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
1144             "CAM Direct Access Disk driver");
1145 SYSCTL_INT(_kern_cam_da, OID_AUTO, poll_period, CTLFLAG_RW,
1146            &da_poll_period, 0, "Media polling period in seconds");
1147 TUNABLE_INT("kern.cam.da.poll_period", &da_poll_period);
1148 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
1149            &da_retry_count, 0, "Normal I/O retry count");
1150 TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count);
1151 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
1152            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
1153 TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout);
1154 SYSCTL_INT(_kern_cam_da, OID_AUTO, send_ordered, CTLFLAG_RW,
1155            &da_send_ordered, 0, "Send Ordered Tags");
1156 TUNABLE_INT("kern.cam.da.send_ordered", &da_send_ordered);
1157 
1158 /*
1159  * DA_ORDEREDTAG_INTERVAL determines how often, relative
1160  * to the default timeout, we check to see whether an ordered
1161  * tagged transaction is appropriate to prevent simple tag
1162  * starvation.  Since we'd like to ensure that there is at least
1163  * 1/2 of the timeout length left for a starved transaction to
1164  * complete after we've sent an ordered tag, we must poll at least
1165  * four times in every timeout period.  This takes care of the worst
1166  * case where a starved transaction starts during an interval that
1167  * meets the requirement "don't send an ordered tag" test so it takes
1168  * us two intervals to determine that a tag must be sent.
1169  */
1170 #ifndef DA_ORDEREDTAG_INTERVAL
1171 #define DA_ORDEREDTAG_INTERVAL 4
1172 #endif
1173 
1174 static struct periph_driver dadriver =
1175 {
1176 	dainit, "da",
1177 	TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
1178 };
1179 
1180 PERIPHDRIVER_DECLARE(da, dadriver);
1181 
1182 static MALLOC_DEFINE(M_SCSIDA, "scsi_da", "scsi_da buffers");
1183 
1184 static int
1185 daopen(struct disk *dp)
1186 {
1187 	struct cam_periph *periph;
1188 	struct da_softc *softc;
1189 	int error;
1190 
1191 	periph = (struct cam_periph *)dp->d_drv1;
1192 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
1193 		return (ENXIO);
1194 	}
1195 
1196 	cam_periph_lock(periph);
1197 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
1198 		cam_periph_unlock(periph);
1199 		cam_periph_release(periph);
1200 		return (error);
1201 	}
1202 
1203 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1204 	    ("daopen\n"));
1205 
1206 	softc = (struct da_softc *)periph->softc;
1207 	dareprobe(periph);
1208 
1209 	/* Wait for the disk size update.  */
1210 	error = cam_periph_sleep(periph, &softc->disk->d_mediasize, PRIBIO,
1211 	    "dareprobe", 0);
1212 	if (error != 0)
1213 		xpt_print(periph->path, "unable to retrieve capacity data");
1214 
1215 	if (periph->flags & CAM_PERIPH_INVALID)
1216 		error = ENXIO;
1217 
1218 	if (error == 0 && (softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
1219 	    (softc->quirks & DA_Q_NO_PREVENT) == 0)
1220 		daprevent(periph, PR_PREVENT);
1221 
1222 	if (error == 0) {
1223 		softc->flags &= ~DA_FLAG_PACK_INVALID;
1224 		softc->flags |= DA_FLAG_OPEN;
1225 	}
1226 
1227 	cam_periph_unhold(periph);
1228 	cam_periph_unlock(periph);
1229 
1230 	if (error != 0)
1231 		cam_periph_release(periph);
1232 
1233 	return (error);
1234 }
1235 
1236 static int
1237 daclose(struct disk *dp)
1238 {
1239 	struct	cam_periph *periph;
1240 	struct	da_softc *softc;
1241 	int error;
1242 
1243 	periph = (struct cam_periph *)dp->d_drv1;
1244 	cam_periph_lock(periph);
1245 	if (cam_periph_hold(periph, PRIBIO) != 0) {
1246 		cam_periph_unlock(periph);
1247 		cam_periph_release(periph);
1248 		return (0);
1249 	}
1250 
1251 	softc = (struct da_softc *)periph->softc;
1252 
1253 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1254 	    ("daclose\n"));
1255 
1256 	if ((softc->flags & DA_FLAG_DIRTY) != 0 &&
1257 	    (softc->quirks & DA_Q_NO_SYNC_CACHE) == 0 &&
1258 	    (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
1259 		union	ccb *ccb;
1260 
1261 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1262 
1263 		scsi_synchronize_cache(&ccb->csio,
1264 				       /*retries*/1,
1265 				       /*cbfcnp*/dadone,
1266 				       MSG_SIMPLE_Q_TAG,
1267 				       /*begin_lba*/0,/* Cover the whole disk */
1268 				       /*lb_count*/0,
1269 				       SSD_FULL_SIZE,
1270 				       5 * 60 * 1000);
1271 
1272 		error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
1273 				  /*sense_flags*/SF_RETRY_UA | SF_QUIET_IR,
1274 				  softc->disk->d_devstat);
1275 		if (error == 0)
1276 			softc->flags &= ~DA_FLAG_DIRTY;
1277 		xpt_release_ccb(ccb);
1278 
1279 	}
1280 
1281 	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
1282 		if ((softc->quirks & DA_Q_NO_PREVENT) == 0)
1283 			daprevent(periph, PR_ALLOW);
1284 		/*
1285 		 * If we've got removeable media, mark the blocksize as
1286 		 * unavailable, since it could change when new media is
1287 		 * inserted.
1288 		 */
1289 		softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1290 	}
1291 
1292 	softc->flags &= ~DA_FLAG_OPEN;
1293 	cam_periph_unhold(periph);
1294 	cam_periph_unlock(periph);
1295 	cam_periph_release(periph);
1296 	return (0);
1297 }
1298 
1299 static void
1300 daschedule(struct cam_periph *periph)
1301 {
1302 	struct da_softc *softc = (struct da_softc *)periph->softc;
1303 	uint32_t prio;
1304 
1305 	if (softc->state != DA_STATE_NORMAL)
1306 		return;
1307 
1308 	/* Check if cam_periph_getccb() was called. */
1309 	prio = periph->immediate_priority;
1310 
1311 	/* Check if we have more work to do. */
1312 	if (bioq_first(&softc->bio_queue) ||
1313 	    (!softc->delete_running && bioq_first(&softc->delete_queue)) ||
1314 	    softc->tur) {
1315 		prio = CAM_PRIORITY_NORMAL;
1316 	}
1317 
1318 	/* Schedule CCB if any of above is true. */
1319 	if (prio != CAM_PRIORITY_NONE)
1320 		xpt_schedule(periph, prio);
1321 }
1322 
1323 /*
1324  * Actually translate the requested transfer into one the physical driver
1325  * can understand.  The transfer is described by a buf and will include
1326  * only one physical transfer.
1327  */
1328 static void
1329 dastrategy(struct bio *bp)
1330 {
1331 	struct cam_periph *periph;
1332 	struct da_softc *softc;
1333 
1334 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1335 	softc = (struct da_softc *)periph->softc;
1336 
1337 	cam_periph_lock(periph);
1338 
1339 	/*
1340 	 * If the device has been made invalid, error out
1341 	 */
1342 	if ((softc->flags & DA_FLAG_PACK_INVALID)) {
1343 		cam_periph_unlock(periph);
1344 		biofinish(bp, NULL, ENXIO);
1345 		return;
1346 	}
1347 
1348 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastrategy(%p)\n", bp));
1349 
1350 	/*
1351 	 * Place it in the queue of disk activities for this disk
1352 	 */
1353 	if (bp->bio_cmd == BIO_DELETE) {
1354 		if (bp->bio_bcount == 0)
1355 			biodone(bp);
1356 		else if (DA_SIO)
1357 			bioq_disksort(&softc->delete_queue, bp);
1358 		else
1359 			bioq_insert_tail(&softc->delete_queue, bp);
1360 	} else if (DA_SIO) {
1361 		bioq_disksort(&softc->bio_queue, bp);
1362 	} else {
1363 		bioq_insert_tail(&softc->bio_queue, bp);
1364 	}
1365 
1366 	/*
1367 	 * Schedule ourselves for performing the work.
1368 	 */
1369 	daschedule(periph);
1370 	cam_periph_unlock(periph);
1371 
1372 	return;
1373 }
1374 
1375 static int
1376 dadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
1377 {
1378 	struct	    cam_periph *periph;
1379 	struct	    da_softc *softc;
1380 	u_int	    secsize;
1381 	struct	    ccb_scsiio csio;
1382 	struct	    disk *dp;
1383 	int	    error = 0;
1384 
1385 	dp = arg;
1386 	periph = dp->d_drv1;
1387 	softc = (struct da_softc *)periph->softc;
1388 	cam_periph_lock(periph);
1389 	secsize = softc->params.secsize;
1390 
1391 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
1392 		cam_periph_unlock(periph);
1393 		return (ENXIO);
1394 	}
1395 
1396 	if (length > 0) {
1397 		xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1398 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1399 		scsi_read_write(&csio,
1400 				/*retries*/0,
1401 				dadone,
1402 				MSG_ORDERED_Q_TAG,
1403 				/*read*/SCSI_RW_WRITE,
1404 				/*byte2*/0,
1405 				/*minimum_cmd_size*/ softc->minimum_cmd_size,
1406 				offset / secsize,
1407 				length / secsize,
1408 				/*data_ptr*/(u_int8_t *) virtual,
1409 				/*dxfer_len*/length,
1410 				/*sense_len*/SSD_FULL_SIZE,
1411 				da_default_timeout * 1000);
1412 		xpt_polled_action((union ccb *)&csio);
1413 
1414 		error = cam_periph_error((union ccb *)&csio,
1415 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1416 		if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1417 			cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1418 			    /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1419 		if (error != 0)
1420 			printf("Aborting dump due to I/O error.\n");
1421 		cam_periph_unlock(periph);
1422 		return (error);
1423 	}
1424 
1425 	/*
1426 	 * Sync the disk cache contents to the physical media.
1427 	 */
1428 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
1429 
1430 		xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1431 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1432 		scsi_synchronize_cache(&csio,
1433 				       /*retries*/0,
1434 				       /*cbfcnp*/dadone,
1435 				       MSG_SIMPLE_Q_TAG,
1436 				       /*begin_lba*/0,/* Cover the whole disk */
1437 				       /*lb_count*/0,
1438 				       SSD_FULL_SIZE,
1439 				       5 * 60 * 1000);
1440 		xpt_polled_action((union ccb *)&csio);
1441 
1442 		error = cam_periph_error((union ccb *)&csio,
1443 		    0, SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR, NULL);
1444 		if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1445 			cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1446 			    /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1447 		if (error != 0)
1448 			xpt_print(periph->path, "Synchronize cache failed\n");
1449 	}
1450 	cam_periph_unlock(periph);
1451 	return (error);
1452 }
1453 
1454 static int
1455 dagetattr(struct bio *bp)
1456 {
1457 	int ret;
1458 	struct cam_periph *periph;
1459 
1460 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1461 	cam_periph_lock(periph);
1462 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1463 	    periph->path);
1464 	cam_periph_unlock(periph);
1465 	if (ret == 0)
1466 		bp->bio_completed = bp->bio_length;
1467 	return ret;
1468 }
1469 
1470 static void
1471 dainit(void)
1472 {
1473 	cam_status status;
1474 
1475 	/*
1476 	 * Install a global async callback.  This callback will
1477 	 * receive async callbacks like "new device found".
1478 	 */
1479 	status = xpt_register_async(AC_FOUND_DEVICE, daasync, NULL, NULL);
1480 
1481 	if (status != CAM_REQ_CMP) {
1482 		printf("da: Failed to attach master async callback "
1483 		       "due to status 0x%x!\n", status);
1484 	} else if (da_send_ordered) {
1485 
1486 		/* Register our shutdown event handler */
1487 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown,
1488 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1489 		    printf("dainit: shutdown event registration failed!\n");
1490 	}
1491 }
1492 
1493 /*
1494  * Callback from GEOM, called when it has finished cleaning up its
1495  * resources.
1496  */
1497 static void
1498 dadiskgonecb(struct disk *dp)
1499 {
1500 	struct cam_periph *periph;
1501 
1502 	periph = (struct cam_periph *)dp->d_drv1;
1503 	cam_periph_release(periph);
1504 }
1505 
1506 static void
1507 daoninvalidate(struct cam_periph *periph)
1508 {
1509 	struct da_softc *softc;
1510 
1511 	softc = (struct da_softc *)periph->softc;
1512 
1513 	/*
1514 	 * De-register any async callbacks.
1515 	 */
1516 	xpt_register_async(0, daasync, periph, periph->path);
1517 
1518 	softc->flags |= DA_FLAG_PACK_INVALID;
1519 
1520 	/*
1521 	 * Return all queued I/O with ENXIO.
1522 	 * XXX Handle any transactions queued to the card
1523 	 *     with XPT_ABORT_CCB.
1524 	 */
1525 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
1526 	bioq_flush(&softc->delete_queue, NULL, ENXIO);
1527 
1528 	/*
1529 	 * Tell GEOM that we've gone away, we'll get a callback when it is
1530 	 * done cleaning up its resources.
1531 	 */
1532 	disk_gone(softc->disk);
1533 
1534 	xpt_print(periph->path, "lost device - %d outstanding, %d refs\n",
1535 		  softc->outstanding_cmds, periph->refcount);
1536 }
1537 
1538 static void
1539 dacleanup(struct cam_periph *periph)
1540 {
1541 	struct da_softc *softc;
1542 
1543 	softc = (struct da_softc *)periph->softc;
1544 
1545 	xpt_print(periph->path, "removing device entry\n");
1546 	cam_periph_unlock(periph);
1547 
1548 	/*
1549 	 * If we can't free the sysctl tree, oh well...
1550 	 */
1551 	if ((softc->flags & DA_FLAG_SCTX_INIT) != 0
1552 	    && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
1553 		xpt_print(periph->path, "can't remove sysctl context\n");
1554 	}
1555 
1556 	callout_drain(&softc->mediapoll_c);
1557 	disk_destroy(softc->disk);
1558 	callout_drain(&softc->sendordered_c);
1559 	free(softc, M_DEVBUF);
1560 	cam_periph_lock(periph);
1561 }
1562 
1563 static void
1564 daasync(void *callback_arg, u_int32_t code,
1565 	struct cam_path *path, void *arg)
1566 {
1567 	struct cam_periph *periph;
1568 	struct da_softc *softc;
1569 
1570 	periph = (struct cam_periph *)callback_arg;
1571 	switch (code) {
1572 	case AC_FOUND_DEVICE:
1573 	{
1574 		struct ccb_getdev *cgd;
1575 		cam_status status;
1576 
1577 		cgd = (struct ccb_getdev *)arg;
1578 		if (cgd == NULL)
1579 			break;
1580 
1581 		if (cgd->protocol != PROTO_SCSI)
1582 			break;
1583 
1584 		if (SID_TYPE(&cgd->inq_data) != T_DIRECT
1585 		    && SID_TYPE(&cgd->inq_data) != T_RBC
1586 		    && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
1587 			break;
1588 
1589 		/*
1590 		 * Allocate a peripheral instance for
1591 		 * this device and start the probe
1592 		 * process.
1593 		 */
1594 		status = cam_periph_alloc(daregister, daoninvalidate,
1595 					  dacleanup, dastart,
1596 					  "da", CAM_PERIPH_BIO,
1597 					  cgd->ccb_h.path, daasync,
1598 					  AC_FOUND_DEVICE, cgd);
1599 
1600 		if (status != CAM_REQ_CMP
1601 		 && status != CAM_REQ_INPROG)
1602 			printf("daasync: Unable to attach to new device "
1603 				"due to status 0x%x\n", status);
1604 		return;
1605 	}
1606 	case AC_ADVINFO_CHANGED:
1607 	{
1608 		uintptr_t buftype;
1609 
1610 		buftype = (uintptr_t)arg;
1611 		if (buftype == CDAI_TYPE_PHYS_PATH) {
1612 			struct da_softc *softc;
1613 
1614 			softc = periph->softc;
1615 			disk_attr_changed(softc->disk, "GEOM::physpath",
1616 					  M_NOWAIT);
1617 		}
1618 		break;
1619 	}
1620 	case AC_UNIT_ATTENTION:
1621 	{
1622 		union ccb *ccb;
1623 		int error_code, sense_key, asc, ascq;
1624 
1625 		softc = (struct da_softc *)periph->softc;
1626 		ccb = (union ccb *)arg;
1627 
1628 		/*
1629 		 * Handle all UNIT ATTENTIONs except our own,
1630 		 * as they will be handled by daerror().
1631 		 */
1632 		if (xpt_path_periph(ccb->ccb_h.path) != periph &&
1633 		    scsi_extract_sense_ccb(ccb,
1634 		     &error_code, &sense_key, &asc, &ascq)) {
1635 			if (asc == 0x2A && ascq == 0x09) {
1636 				xpt_print(ccb->ccb_h.path,
1637 				    "capacity data has changed\n");
1638 				dareprobe(periph);
1639 			} else if (asc == 0x28 && ascq == 0x00)
1640 				disk_media_changed(softc->disk, M_NOWAIT);
1641 		}
1642 		cam_periph_async(periph, code, path, arg);
1643 		break;
1644 	}
1645 	case AC_SCSI_AEN:
1646 		softc = (struct da_softc *)periph->softc;
1647 		if (!softc->tur) {
1648 			if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
1649 				softc->tur = 1;
1650 				daschedule(periph);
1651 			}
1652 		}
1653 		/* FALLTHROUGH */
1654 	case AC_SENT_BDR:
1655 	case AC_BUS_RESET:
1656 	{
1657 		struct ccb_hdr *ccbh;
1658 
1659 		softc = (struct da_softc *)periph->softc;
1660 		/*
1661 		 * Don't fail on the expected unit attention
1662 		 * that will occur.
1663 		 */
1664 		softc->flags |= DA_FLAG_RETRY_UA;
1665 		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1666 			ccbh->ccb_state |= DA_CCB_RETRY_UA;
1667 		break;
1668 	}
1669 	default:
1670 		break;
1671 	}
1672 	cam_periph_async(periph, code, path, arg);
1673 }
1674 
1675 static void
1676 dasysctlinit(void *context, int pending)
1677 {
1678 	struct cam_periph *periph;
1679 	struct da_softc *softc;
1680 	char tmpstr[80], tmpstr2[80];
1681 	struct ccb_trans_settings cts;
1682 
1683 	periph = (struct cam_periph *)context;
1684 	/*
1685 	 * periph was held for us when this task was enqueued
1686 	 */
1687 	if (periph->flags & CAM_PERIPH_INVALID) {
1688 		cam_periph_release(periph);
1689 		return;
1690 	}
1691 
1692 	softc = (struct da_softc *)periph->softc;
1693 	snprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
1694 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1695 
1696 	sysctl_ctx_init(&softc->sysctl_ctx);
1697 	softc->flags |= DA_FLAG_SCTX_INIT;
1698 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1699 		SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
1700 		CTLFLAG_RD, 0, tmpstr);
1701 	if (softc->sysctl_tree == NULL) {
1702 		printf("dasysctlinit: unable to allocate sysctl tree\n");
1703 		cam_periph_release(periph);
1704 		return;
1705 	}
1706 
1707 	/*
1708 	 * Now register the sysctl handler, so the user can change the value on
1709 	 * the fly.
1710 	 */
1711 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1712 		OID_AUTO, "delete_method", CTLTYPE_STRING | CTLFLAG_RW,
1713 		softc, 0, dadeletemethodsysctl, "A",
1714 		"BIO_DELETE execution method");
1715 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1716 		OID_AUTO, "delete_max", CTLTYPE_U64 | CTLFLAG_RW,
1717 		softc, 0, dadeletemaxsysctl, "Q",
1718 		"Maximum BIO_DELETE size");
1719 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1720 		OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
1721 		&softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
1722 		"Minimum CDB size");
1723 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1724 		OID_AUTO, "sort_io_queue", CTLFLAG_RW, &softc->sort_io_queue, 0,
1725 		"Sort IO queue to try and optimise disk access patterns");
1726 
1727 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1728 		       SYSCTL_CHILDREN(softc->sysctl_tree),
1729 		       OID_AUTO,
1730 		       "error_inject",
1731 		       CTLFLAG_RW,
1732 		       &softc->error_inject,
1733 		       0,
1734 		       "error_inject leaf");
1735 
1736 
1737 	/*
1738 	 * Add some addressing info.
1739 	 */
1740 	memset(&cts, 0, sizeof (cts));
1741 	xpt_setup_ccb(&cts.ccb_h, periph->path, CAM_PRIORITY_NONE);
1742 	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1743 	cts.type = CTS_TYPE_CURRENT_SETTINGS;
1744 	cam_periph_lock(periph);
1745 	xpt_action((union ccb *)&cts);
1746 	cam_periph_unlock(periph);
1747 	if (cts.ccb_h.status != CAM_REQ_CMP) {
1748 		cam_periph_release(periph);
1749 		return;
1750 	}
1751 	if (cts.protocol == PROTO_SCSI && cts.transport == XPORT_FC) {
1752 		struct ccb_trans_settings_fc *fc = &cts.xport_specific.fc;
1753 		if (fc->valid & CTS_FC_VALID_WWPN) {
1754 			softc->wwpn = fc->wwpn;
1755 			SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1756 			    SYSCTL_CHILDREN(softc->sysctl_tree),
1757 			    OID_AUTO, "wwpn", CTLFLAG_RD,
1758 			    &softc->wwpn, "World Wide Port Name");
1759 		}
1760 	}
1761 	cam_periph_release(periph);
1762 }
1763 
1764 static int
1765 dadeletemaxsysctl(SYSCTL_HANDLER_ARGS)
1766 {
1767 	int error;
1768 	uint64_t value;
1769 	struct da_softc *softc;
1770 
1771 	softc = (struct da_softc *)arg1;
1772 
1773 	value = softc->disk->d_delmaxsize;
1774 	error = sysctl_handle_64(oidp, &value, 0, req);
1775 	if ((error != 0) || (req->newptr == NULL))
1776 		return (error);
1777 
1778 	/* only accept values smaller than the calculated value */
1779 	if (value > dadeletemaxsize(softc, softc->delete_method)) {
1780 		return (EINVAL);
1781 	}
1782 	softc->disk->d_delmaxsize = value;
1783 
1784 	return (0);
1785 }
1786 
1787 static int
1788 dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
1789 {
1790 	int error, value;
1791 
1792 	value = *(int *)arg1;
1793 
1794 	error = sysctl_handle_int(oidp, &value, 0, req);
1795 
1796 	if ((error != 0)
1797 	 || (req->newptr == NULL))
1798 		return (error);
1799 
1800 	/*
1801 	 * Acceptable values here are 6, 10, 12 or 16.
1802 	 */
1803 	if (value < 6)
1804 		value = 6;
1805 	else if ((value > 6)
1806 	      && (value <= 10))
1807 		value = 10;
1808 	else if ((value > 10)
1809 	      && (value <= 12))
1810 		value = 12;
1811 	else if (value > 12)
1812 		value = 16;
1813 
1814 	*(int *)arg1 = value;
1815 
1816 	return (0);
1817 }
1818 
1819 static void
1820 dadeletemethodset(struct da_softc *softc, da_delete_methods delete_method)
1821 {
1822 
1823 
1824 	softc->delete_method = delete_method;
1825 	softc->disk->d_delmaxsize = dadeletemaxsize(softc, delete_method);
1826 	softc->delete_func = da_delete_functions[delete_method];
1827 
1828 	if (softc->delete_method > DA_DELETE_DISABLE)
1829 		softc->disk->d_flags |= DISKFLAG_CANDELETE;
1830 	else
1831 		softc->disk->d_flags &= ~DISKFLAG_CANDELETE;
1832 }
1833 
1834 static off_t
1835 dadeletemaxsize(struct da_softc *softc, da_delete_methods delete_method)
1836 {
1837 	off_t sectors;
1838 
1839 	switch(delete_method) {
1840 	case DA_DELETE_UNMAP:
1841 		sectors = (off_t)softc->unmap_max_lba * softc->unmap_max_ranges;
1842 		break;
1843 	case DA_DELETE_ATA_TRIM:
1844 		sectors = (off_t)ATA_DSM_RANGE_MAX * softc->trim_max_ranges;
1845 		break;
1846 	case DA_DELETE_WS16:
1847 		sectors = (off_t)min(softc->ws_max_blks, WS16_MAX_BLKS);
1848 		break;
1849 	case DA_DELETE_ZERO:
1850 	case DA_DELETE_WS10:
1851 		sectors = (off_t)min(softc->ws_max_blks, WS10_MAX_BLKS);
1852 		break;
1853 	default:
1854 		return 0;
1855 	}
1856 
1857 	return (off_t)softc->params.secsize *
1858 	    min(sectors, (off_t)softc->params.sectors);
1859 }
1860 
1861 static void
1862 daprobedone(struct cam_periph *periph, union ccb *ccb)
1863 {
1864 	struct da_softc *softc;
1865 
1866 	softc = (struct da_softc *)periph->softc;
1867 
1868 	dadeletemethodchoose(softc, DA_DELETE_NONE);
1869 
1870 	if (bootverbose && (softc->flags & DA_FLAG_PROBED) == 0) {
1871 		char buf[80];
1872 		int i, sep;
1873 
1874 		snprintf(buf, sizeof(buf), "Delete methods: <");
1875 		sep = 0;
1876 		for (i = DA_DELETE_MIN; i <= DA_DELETE_MAX; i++) {
1877 			if (softc->delete_available & (1 << i)) {
1878 				if (sep) {
1879 					strlcat(buf, ",", sizeof(buf));
1880 				} else {
1881 				    sep = 1;
1882 				}
1883 				strlcat(buf, da_delete_method_names[i],
1884 				    sizeof(buf));
1885 				if (i == softc->delete_method) {
1886 					strlcat(buf, "(*)", sizeof(buf));
1887 				}
1888 			}
1889 		}
1890 		if (sep == 0) {
1891 			if (softc->delete_method == DA_DELETE_NONE)
1892 				strlcat(buf, "NONE(*)", sizeof(buf));
1893 			else
1894 				strlcat(buf, "DISABLED(*)", sizeof(buf));
1895 		}
1896 		strlcat(buf, ">", sizeof(buf));
1897 		printf("%s%d: %s\n", periph->periph_name,
1898 		    periph->unit_number, buf);
1899 	}
1900 
1901 	/*
1902 	 * Since our peripheral may be invalidated by an error
1903 	 * above or an external event, we must release our CCB
1904 	 * before releasing the probe lock on the peripheral.
1905 	 * The peripheral will only go away once the last lock
1906 	 * is removed, and we need it around for the CCB release
1907 	 * operation.
1908 	 */
1909 	xpt_release_ccb(ccb);
1910 	softc->state = DA_STATE_NORMAL;
1911 	daschedule(periph);
1912 	wakeup(&softc->disk->d_mediasize);
1913 	if ((softc->flags & DA_FLAG_PROBED) == 0) {
1914 		softc->flags |= DA_FLAG_PROBED;
1915 		cam_periph_unhold(periph);
1916 	} else
1917 		cam_periph_release_locked(periph);
1918 }
1919 
1920 static void
1921 dadeletemethodchoose(struct da_softc *softc, da_delete_methods default_method)
1922 {
1923 	int i, delete_method;
1924 
1925 	delete_method = default_method;
1926 
1927 	/*
1928 	 * Use the pre-defined order to choose the best
1929 	 * performing delete.
1930 	 */
1931 	for (i = DA_DELETE_MIN; i <= DA_DELETE_MAX; i++) {
1932 		if (softc->delete_available & (1 << i)) {
1933 			dadeletemethodset(softc, i);
1934 			return;
1935 		}
1936 	}
1937 	dadeletemethodset(softc, delete_method);
1938 }
1939 
1940 static int
1941 dadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
1942 {
1943 	char buf[16];
1944 	const char *p;
1945 	struct da_softc *softc;
1946 	int i, error, value;
1947 
1948 	softc = (struct da_softc *)arg1;
1949 
1950 	value = softc->delete_method;
1951 	if (value < 0 || value > DA_DELETE_MAX)
1952 		p = "UNKNOWN";
1953 	else
1954 		p = da_delete_method_names[value];
1955 	strncpy(buf, p, sizeof(buf));
1956 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1957 	if (error != 0 || req->newptr == NULL)
1958 		return (error);
1959 	for (i = 0; i <= DA_DELETE_MAX; i++) {
1960 		if (!(softc->delete_available & (1 << i)) ||
1961 		    strcmp(buf, da_delete_method_names[i]) != 0)
1962 			continue;
1963 		dadeletemethodset(softc, i);
1964 		return (0);
1965 	}
1966 	return (EINVAL);
1967 }
1968 
1969 static cam_status
1970 daregister(struct cam_periph *periph, void *arg)
1971 {
1972 	struct da_softc *softc;
1973 	struct ccb_pathinq cpi;
1974 	struct ccb_getdev *cgd;
1975 	char tmpstr[80];
1976 	caddr_t match;
1977 
1978 	cgd = (struct ccb_getdev *)arg;
1979 	if (cgd == NULL) {
1980 		printf("daregister: no getdev CCB, can't register device\n");
1981 		return(CAM_REQ_CMP_ERR);
1982 	}
1983 
1984 	softc = (struct da_softc *)malloc(sizeof(*softc), M_DEVBUF,
1985 	    M_NOWAIT|M_ZERO);
1986 
1987 	if (softc == NULL) {
1988 		printf("daregister: Unable to probe new device. "
1989 		       "Unable to allocate softc\n");
1990 		return(CAM_REQ_CMP_ERR);
1991 	}
1992 
1993 	LIST_INIT(&softc->pending_ccbs);
1994 	softc->state = DA_STATE_PROBE_RC;
1995 	bioq_init(&softc->bio_queue);
1996 	bioq_init(&softc->delete_queue);
1997 	bioq_init(&softc->delete_run_queue);
1998 	if (SID_IS_REMOVABLE(&cgd->inq_data))
1999 		softc->flags |= DA_FLAG_PACK_REMOVABLE;
2000 	softc->unmap_max_ranges = UNMAP_MAX_RANGES;
2001 	softc->unmap_max_lba = UNMAP_RANGE_MAX;
2002 	softc->ws_max_blks = WS16_MAX_BLKS;
2003 	softc->trim_max_ranges = ATA_TRIM_MAX_RANGES;
2004 	softc->sort_io_queue = -1;
2005 
2006 	periph->softc = softc;
2007 
2008 	/*
2009 	 * See if this device has any quirks.
2010 	 */
2011 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
2012 			       (caddr_t)da_quirk_table,
2013 			       sizeof(da_quirk_table)/sizeof(*da_quirk_table),
2014 			       sizeof(*da_quirk_table), scsi_inquiry_match);
2015 
2016 	if (match != NULL)
2017 		softc->quirks = ((struct da_quirk_entry *)match)->quirks;
2018 	else
2019 		softc->quirks = DA_Q_NONE;
2020 
2021 	/* Check if the SIM does not want 6 byte commands */
2022 	bzero(&cpi, sizeof(cpi));
2023 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
2024 	cpi.ccb_h.func_code = XPT_PATH_INQ;
2025 	xpt_action((union ccb *)&cpi);
2026 	if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
2027 		softc->quirks |= DA_Q_NO_6_BYTE;
2028 
2029 	TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
2030 
2031 	/*
2032 	 * Take an exclusive refcount on the periph while dastart is called
2033 	 * to finish the probe.  The reference will be dropped in dadone at
2034 	 * the end of probe.
2035 	 */
2036 	(void)cam_periph_hold(periph, PRIBIO);
2037 
2038 	/*
2039 	 * Schedule a periodic event to occasionally send an
2040 	 * ordered tag to a device.
2041 	 */
2042 	callout_init_mtx(&softc->sendordered_c, periph->sim->mtx, 0);
2043 	callout_reset(&softc->sendordered_c,
2044 	    (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
2045 	    dasendorderedtag, softc);
2046 
2047 	cam_periph_unlock(periph);
2048 	/*
2049 	 * RBC devices don't have to support READ(6), only READ(10).
2050 	 */
2051 	if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
2052 		softc->minimum_cmd_size = 10;
2053 	else
2054 		softc->minimum_cmd_size = 6;
2055 
2056 	/*
2057 	 * Load the user's default, if any.
2058 	 */
2059 	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
2060 		 periph->unit_number);
2061 	TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
2062 
2063 	/*
2064 	 * 6, 10, 12 and 16 are the currently permissible values.
2065 	 */
2066 	if (softc->minimum_cmd_size < 6)
2067 		softc->minimum_cmd_size = 6;
2068 	else if ((softc->minimum_cmd_size > 6)
2069 	      && (softc->minimum_cmd_size <= 10))
2070 		softc->minimum_cmd_size = 10;
2071 	else if ((softc->minimum_cmd_size > 10)
2072 	      && (softc->minimum_cmd_size <= 12))
2073 		softc->minimum_cmd_size = 12;
2074 	else if (softc->minimum_cmd_size > 12)
2075 		softc->minimum_cmd_size = 16;
2076 
2077 	/* Predict whether device may support READ CAPACITY(16). */
2078 	if (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC3) {
2079 		softc->flags |= DA_FLAG_CAN_RC16;
2080 		softc->state = DA_STATE_PROBE_RC16;
2081 	}
2082 
2083 	/*
2084 	 * Register this media as a disk.
2085 	 */
2086 	softc->disk = disk_alloc();
2087 	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
2088 			  periph->unit_number, 0,
2089 			  DEVSTAT_BS_UNAVAILABLE,
2090 			  SID_TYPE(&cgd->inq_data) |
2091 			  XPORT_DEVSTAT_TYPE(cpi.transport),
2092 			  DEVSTAT_PRIORITY_DISK);
2093 	softc->disk->d_open = daopen;
2094 	softc->disk->d_close = daclose;
2095 	softc->disk->d_strategy = dastrategy;
2096 	softc->disk->d_dump = dadump;
2097 	softc->disk->d_getattr = dagetattr;
2098 	softc->disk->d_gone = dadiskgonecb;
2099 	softc->disk->d_name = "da";
2100 	softc->disk->d_drv1 = periph;
2101 	if (cpi.maxio == 0)
2102 		softc->disk->d_maxsize = DFLTPHYS;	/* traditional default */
2103 	else if (cpi.maxio > MAXPHYS)
2104 		softc->disk->d_maxsize = MAXPHYS;	/* for safety */
2105 	else
2106 		softc->disk->d_maxsize = cpi.maxio;
2107 	softc->disk->d_unit = periph->unit_number;
2108 	softc->disk->d_flags = 0;
2109 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0)
2110 		softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
2111 	if ((cpi.hba_misc & PIM_UNMAPPED) != 0)
2112 		softc->disk->d_flags |= DISKFLAG_UNMAPPED_BIO;
2113 	cam_strvis(softc->disk->d_descr, cgd->inq_data.vendor,
2114 	    sizeof(cgd->inq_data.vendor), sizeof(softc->disk->d_descr));
2115 	strlcat(softc->disk->d_descr, " ", sizeof(softc->disk->d_descr));
2116 	cam_strvis(&softc->disk->d_descr[strlen(softc->disk->d_descr)],
2117 	    cgd->inq_data.product, sizeof(cgd->inq_data.product),
2118 	    sizeof(softc->disk->d_descr) - strlen(softc->disk->d_descr));
2119 	softc->disk->d_hba_vendor = cpi.hba_vendor;
2120 	softc->disk->d_hba_device = cpi.hba_device;
2121 	softc->disk->d_hba_subvendor = cpi.hba_subvendor;
2122 	softc->disk->d_hba_subdevice = cpi.hba_subdevice;
2123 
2124 	/*
2125 	 * Acquire a reference to the periph before we register with GEOM.
2126 	 * We'll release this reference once GEOM calls us back (via
2127 	 * dadiskgonecb()) telling us that our provider has been freed.
2128 	 */
2129 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
2130 		xpt_print(periph->path, "%s: lost periph during "
2131 			  "registration!\n", __func__);
2132 		cam_periph_lock(periph);
2133 		return (CAM_REQ_CMP_ERR);
2134 	}
2135 
2136 	disk_create(softc->disk, DISK_VERSION);
2137 	cam_periph_lock(periph);
2138 
2139 	/*
2140 	 * Add async callbacks for events of interest.
2141 	 * I don't bother checking if this fails as,
2142 	 * in most cases, the system will function just
2143 	 * fine without them and the only alternative
2144 	 * would be to not attach the device on failure.
2145 	 */
2146 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
2147 	    AC_ADVINFO_CHANGED | AC_SCSI_AEN | AC_UNIT_ATTENTION,
2148 	    daasync, periph, periph->path);
2149 
2150 	/*
2151 	 * Emit an attribute changed notification just in case
2152 	 * physical path information arrived before our async
2153 	 * event handler was registered, but after anyone attaching
2154 	 * to our disk device polled it.
2155 	 */
2156 	disk_attr_changed(softc->disk, "GEOM::physpath", M_NOWAIT);
2157 
2158 	/*
2159 	 * Schedule a periodic media polling events.
2160 	 */
2161 	callout_init_mtx(&softc->mediapoll_c, periph->sim->mtx, 0);
2162 	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) &&
2163 	    (cgd->inq_flags & SID_AEN) == 0 &&
2164 	    da_poll_period != 0)
2165 		callout_reset(&softc->mediapoll_c, da_poll_period * hz,
2166 		    damediapoll, periph);
2167 
2168 	xpt_schedule(periph, CAM_PRIORITY_DEV);
2169 
2170 	return(CAM_REQ_CMP);
2171 }
2172 
2173 static void
2174 dastart(struct cam_periph *periph, union ccb *start_ccb)
2175 {
2176 	struct da_softc *softc;
2177 
2178 	softc = (struct da_softc *)periph->softc;
2179 
2180 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastart\n"));
2181 
2182 skipstate:
2183 	switch (softc->state) {
2184 	case DA_STATE_NORMAL:
2185 	{
2186 		struct bio *bp;
2187 		uint8_t tag_code;
2188 
2189 		/* Execute immediate CCB if waiting. */
2190 		if (periph->immediate_priority <= periph->pinfo.priority) {
2191 			CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2192 					("queuing for immediate ccb\n"));
2193 			start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
2194 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
2195 					  periph_links.sle);
2196 			periph->immediate_priority = CAM_PRIORITY_NONE;
2197 			wakeup(&periph->ccb_list);
2198 			/* May have more work to do, so ensure we stay scheduled */
2199 			daschedule(periph);
2200 			break;
2201 		}
2202 
2203 		/* Run BIO_DELETE if not running yet. */
2204 		if (!softc->delete_running &&
2205 		    (bp = bioq_first(&softc->delete_queue)) != NULL) {
2206 			if (softc->delete_func != NULL) {
2207 				softc->delete_func(periph, start_ccb, bp);
2208 				goto out;
2209 			} else {
2210 				bioq_flush(&softc->delete_queue, NULL, 0);
2211 				/* FALLTHROUGH */
2212 			}
2213 		}
2214 
2215 		/* Run regular command. */
2216 		bp = bioq_takefirst(&softc->bio_queue);
2217 		if (bp == NULL) {
2218 			if (softc->tur) {
2219 				softc->tur = 0;
2220 				scsi_test_unit_ready(&start_ccb->csio,
2221 				     /*retries*/ da_retry_count,
2222 				     dadone,
2223 				     MSG_SIMPLE_Q_TAG,
2224 				     SSD_FULL_SIZE,
2225 				     da_default_timeout * 1000);
2226 				start_ccb->ccb_h.ccb_bp = NULL;
2227 				start_ccb->ccb_h.ccb_state = DA_CCB_TUR;
2228 				xpt_action(start_ccb);
2229 			} else
2230 				xpt_release_ccb(start_ccb);
2231 			break;
2232 		}
2233 		if (softc->tur) {
2234 			softc->tur = 0;
2235 			cam_periph_release_locked(periph);
2236 		}
2237 
2238 		if ((bp->bio_flags & BIO_ORDERED) != 0 ||
2239 		    (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
2240 			softc->flags &= ~DA_FLAG_NEED_OTAG;
2241 			softc->ordered_tag_count++;
2242 			tag_code = MSG_ORDERED_Q_TAG;
2243 		} else {
2244 			tag_code = MSG_SIMPLE_Q_TAG;
2245 		}
2246 
2247 		switch (bp->bio_cmd) {
2248 		case BIO_WRITE:
2249 			softc->flags |= DA_FLAG_DIRTY;
2250 			/* FALLTHROUGH */
2251 		case BIO_READ:
2252 			scsi_read_write(&start_ccb->csio,
2253 					/*retries*/da_retry_count,
2254 					/*cbfcnp*/dadone,
2255 					/*tag_action*/tag_code,
2256 					/*read_op*/(bp->bio_cmd == BIO_READ ?
2257 					SCSI_RW_READ : SCSI_RW_WRITE) |
2258 					((bp->bio_flags & BIO_UNMAPPED) != 0 ?
2259 					SCSI_RW_BIO : 0),
2260 					/*byte2*/0,
2261 					softc->minimum_cmd_size,
2262 					/*lba*/bp->bio_pblkno,
2263 					/*block_count*/bp->bio_bcount /
2264 					softc->params.secsize,
2265 					/*data_ptr*/ (bp->bio_flags &
2266 					BIO_UNMAPPED) != 0 ? (void *)bp :
2267 					bp->bio_data,
2268 					/*dxfer_len*/ bp->bio_bcount,
2269 					/*sense_len*/SSD_FULL_SIZE,
2270 					da_default_timeout * 1000);
2271 			break;
2272 		case BIO_FLUSH:
2273 			/*
2274 			 * BIO_FLUSH doesn't currently communicate
2275 			 * range data, so we synchronize the cache
2276 			 * over the whole disk.  We also force
2277 			 * ordered tag semantics the flush applies
2278 			 * to all previously queued I/O.
2279 			 */
2280 			scsi_synchronize_cache(&start_ccb->csio,
2281 					       /*retries*/1,
2282 					       /*cbfcnp*/dadone,
2283 					       MSG_ORDERED_Q_TAG,
2284 					       /*begin_lba*/0,
2285 					       /*lb_count*/0,
2286 					       SSD_FULL_SIZE,
2287 					       da_default_timeout*1000);
2288 			break;
2289 		}
2290 		start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
2291 
2292 out:
2293 		/*
2294 		 * Block out any asynchronous callbacks
2295 		 * while we touch the pending ccb list.
2296 		 */
2297 		LIST_INSERT_HEAD(&softc->pending_ccbs,
2298 				 &start_ccb->ccb_h, periph_links.le);
2299 		softc->outstanding_cmds++;
2300 
2301 		/* We expect a unit attention from this device */
2302 		if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
2303 			start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
2304 			softc->flags &= ~DA_FLAG_RETRY_UA;
2305 		}
2306 
2307 		start_ccb->ccb_h.ccb_bp = bp;
2308 		xpt_action(start_ccb);
2309 
2310 		/* May have more work to do, so ensure we stay scheduled */
2311 		daschedule(periph);
2312 		break;
2313 	}
2314 	case DA_STATE_PROBE_RC:
2315 	{
2316 		struct scsi_read_capacity_data *rcap;
2317 
2318 		rcap = (struct scsi_read_capacity_data *)
2319 		    malloc(sizeof(*rcap), M_SCSIDA, M_NOWAIT|M_ZERO);
2320 		if (rcap == NULL) {
2321 			printf("dastart: Couldn't malloc read_capacity data\n");
2322 			/* da_free_periph??? */
2323 			break;
2324 		}
2325 		scsi_read_capacity(&start_ccb->csio,
2326 				   /*retries*/da_retry_count,
2327 				   dadone,
2328 				   MSG_SIMPLE_Q_TAG,
2329 				   rcap,
2330 				   SSD_FULL_SIZE,
2331 				   /*timeout*/5000);
2332 		start_ccb->ccb_h.ccb_bp = NULL;
2333 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC;
2334 		xpt_action(start_ccb);
2335 		break;
2336 	}
2337 	case DA_STATE_PROBE_RC16:
2338 	{
2339 		struct scsi_read_capacity_data_long *rcaplong;
2340 
2341 		rcaplong = (struct scsi_read_capacity_data_long *)
2342 			malloc(sizeof(*rcaplong), M_SCSIDA, M_NOWAIT|M_ZERO);
2343 		if (rcaplong == NULL) {
2344 			printf("dastart: Couldn't malloc read_capacity data\n");
2345 			/* da_free_periph??? */
2346 			break;
2347 		}
2348 		scsi_read_capacity_16(&start_ccb->csio,
2349 				      /*retries*/ da_retry_count,
2350 				      /*cbfcnp*/ dadone,
2351 				      /*tag_action*/ MSG_SIMPLE_Q_TAG,
2352 				      /*lba*/ 0,
2353 				      /*reladr*/ 0,
2354 				      /*pmi*/ 0,
2355 				      /*rcap_buf*/ (uint8_t *)rcaplong,
2356 				      /*rcap_buf_len*/ sizeof(*rcaplong),
2357 				      /*sense_len*/ SSD_FULL_SIZE,
2358 				      /*timeout*/ da_default_timeout * 1000);
2359 		start_ccb->ccb_h.ccb_bp = NULL;
2360 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC16;
2361 		xpt_action(start_ccb);
2362 		break;
2363 	}
2364 	case DA_STATE_PROBE_LBP:
2365 	{
2366 		struct scsi_vpd_logical_block_prov *lbp;
2367 
2368 		if (!scsi_vpd_supported_page(periph, SVPD_LBP)) {
2369 			/*
2370 			 * If we get here we don't support any SBC-3 delete
2371 			 * methods with UNMAP as the Logical Block Provisioning
2372 			 * VPD page support is required for devices which
2373 			 * support it according to T10/1799-D Revision 31
2374 			 * however older revisions of the spec don't mandate
2375 			 * this so we currently don't remove these methods
2376 			 * from the available set.
2377 			 */
2378 			softc->state = DA_STATE_PROBE_BLK_LIMITS;
2379 			goto skipstate;
2380 		}
2381 
2382 		lbp = (struct scsi_vpd_logical_block_prov *)
2383 			malloc(sizeof(*lbp), M_SCSIDA, M_NOWAIT|M_ZERO);
2384 
2385 		if (lbp == NULL) {
2386 			printf("dastart: Couldn't malloc lbp data\n");
2387 			/* da_free_periph??? */
2388 			break;
2389 		}
2390 
2391 		scsi_inquiry(&start_ccb->csio,
2392 			     /*retries*/da_retry_count,
2393 			     /*cbfcnp*/dadone,
2394 			     /*tag_action*/MSG_SIMPLE_Q_TAG,
2395 			     /*inq_buf*/(u_int8_t *)lbp,
2396 			     /*inq_len*/sizeof(*lbp),
2397 			     /*evpd*/TRUE,
2398 			     /*page_code*/SVPD_LBP,
2399 			     /*sense_len*/SSD_MIN_SIZE,
2400 			     /*timeout*/da_default_timeout * 1000);
2401 		start_ccb->ccb_h.ccb_bp = NULL;
2402 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_LBP;
2403 		xpt_action(start_ccb);
2404 		break;
2405 	}
2406 	case DA_STATE_PROBE_BLK_LIMITS:
2407 	{
2408 		struct scsi_vpd_block_limits *block_limits;
2409 
2410 		if (!scsi_vpd_supported_page(periph, SVPD_BLOCK_LIMITS)) {
2411 			/* Not supported skip to next probe */
2412 			softc->state = DA_STATE_PROBE_BDC;
2413 			goto skipstate;
2414 		}
2415 
2416 		block_limits = (struct scsi_vpd_block_limits *)
2417 			malloc(sizeof(*block_limits), M_SCSIDA, M_NOWAIT|M_ZERO);
2418 
2419 		if (block_limits == NULL) {
2420 			printf("dastart: Couldn't malloc block_limits data\n");
2421 			/* da_free_periph??? */
2422 			break;
2423 		}
2424 
2425 		scsi_inquiry(&start_ccb->csio,
2426 			     /*retries*/da_retry_count,
2427 			     /*cbfcnp*/dadone,
2428 			     /*tag_action*/MSG_SIMPLE_Q_TAG,
2429 			     /*inq_buf*/(u_int8_t *)block_limits,
2430 			     /*inq_len*/sizeof(*block_limits),
2431 			     /*evpd*/TRUE,
2432 			     /*page_code*/SVPD_BLOCK_LIMITS,
2433 			     /*sense_len*/SSD_MIN_SIZE,
2434 			     /*timeout*/da_default_timeout * 1000);
2435 		start_ccb->ccb_h.ccb_bp = NULL;
2436 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BLK_LIMITS;
2437 		xpt_action(start_ccb);
2438 		break;
2439 	}
2440 	case DA_STATE_PROBE_BDC:
2441 	{
2442 		struct scsi_vpd_block_characteristics *bdc;
2443 
2444 		if (!scsi_vpd_supported_page(periph, SVPD_BDC)) {
2445 			softc->state = DA_STATE_PROBE_ATA;
2446 			goto skipstate;
2447 		}
2448 
2449 		bdc = (struct scsi_vpd_block_characteristics *)
2450 			malloc(sizeof(*bdc), M_SCSIDA, M_NOWAIT|M_ZERO);
2451 
2452 		if (bdc == NULL) {
2453 			printf("dastart: Couldn't malloc bdc data\n");
2454 			/* da_free_periph??? */
2455 			break;
2456 		}
2457 
2458 		scsi_inquiry(&start_ccb->csio,
2459 			     /*retries*/da_retry_count,
2460 			     /*cbfcnp*/dadone,
2461 			     /*tag_action*/MSG_SIMPLE_Q_TAG,
2462 			     /*inq_buf*/(u_int8_t *)bdc,
2463 			     /*inq_len*/sizeof(*bdc),
2464 			     /*evpd*/TRUE,
2465 			     /*page_code*/SVPD_BDC,
2466 			     /*sense_len*/SSD_MIN_SIZE,
2467 			     /*timeout*/da_default_timeout * 1000);
2468 		start_ccb->ccb_h.ccb_bp = NULL;
2469 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BDC;
2470 		xpt_action(start_ccb);
2471 		break;
2472 	}
2473 	case DA_STATE_PROBE_ATA:
2474 	{
2475 		struct ata_params *ata_params;
2476 
2477 		if (!scsi_vpd_supported_page(periph, SVPD_ATA_INFORMATION)) {
2478 			daprobedone(periph, start_ccb);
2479 			break;
2480 		}
2481 
2482 		ata_params = (struct ata_params*)
2483 			malloc(sizeof(*ata_params), M_SCSIDA, M_NOWAIT|M_ZERO);
2484 
2485 		if (ata_params == NULL) {
2486 			printf("dastart: Couldn't malloc ata_params data\n");
2487 			/* da_free_periph??? */
2488 			break;
2489 		}
2490 
2491 		scsi_ata_identify(&start_ccb->csio,
2492 				  /*retries*/da_retry_count,
2493 				  /*cbfcnp*/dadone,
2494                                   /*tag_action*/MSG_SIMPLE_Q_TAG,
2495 				  /*data_ptr*/(u_int8_t *)ata_params,
2496 				  /*dxfer_len*/sizeof(*ata_params),
2497 				  /*sense_len*/SSD_FULL_SIZE,
2498 				  /*timeout*/da_default_timeout * 1000);
2499 		start_ccb->ccb_h.ccb_bp = NULL;
2500 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ATA;
2501 		xpt_action(start_ccb);
2502 		break;
2503 	}
2504 	}
2505 }
2506 
2507 /*
2508  * In each of the methods below, while its the caller's
2509  * responsibility to ensure the request will fit into a
2510  * single device request, we might have changed the delete
2511  * method due to the device incorrectly advertising either
2512  * its supported methods or limits.
2513  *
2514  * To prevent this causing further issues we validate the
2515  * against the methods limits, and warn which would
2516  * otherwise be unnecessary.
2517  */
2518 static void
2519 da_delete_unmap(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
2520 {
2521 	struct da_softc *softc = (struct da_softc *)periph->softc;;
2522 	struct bio *bp1;
2523 	uint8_t *buf = softc->unmap_buf;
2524 	uint64_t lba, lastlba = (uint64_t)-1;
2525 	uint64_t totalcount = 0;
2526 	uint64_t count;
2527 	uint32_t lastcount = 0, c;
2528 	uint32_t off, ranges = 0;
2529 
2530 	/*
2531 	 * Currently this doesn't take the UNMAP
2532 	 * Granularity and Granularity Alignment
2533 	 * fields into account.
2534 	 *
2535 	 * This could result in both unoptimal unmap
2536 	 * requests as as well as UNMAP calls unmapping
2537 	 * fewer LBA's than requested.
2538 	 */
2539 
2540 	softc->delete_running = 1;
2541 	bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
2542 	bp1 = bp;
2543 	do {
2544 		bioq_remove(&softc->delete_queue, bp1);
2545 		if (bp1 != bp)
2546 			bioq_insert_tail(&softc->delete_run_queue, bp1);
2547 		lba = bp1->bio_pblkno;
2548 		count = bp1->bio_bcount / softc->params.secsize;
2549 
2550 		/* Try to extend the previous range. */
2551 		if (lba == lastlba) {
2552 			c = min(count, softc->unmap_max_lba - lastcount);
2553 			lastcount += c;
2554 			off = ((ranges - 1) * UNMAP_RANGE_SIZE) +
2555 			      UNMAP_HEAD_SIZE;
2556 			scsi_ulto4b(lastcount, &buf[off + 8]);
2557 			count -= c;
2558 			lba +=c;
2559 			totalcount += c;
2560 		}
2561 
2562 		while (count > 0) {
2563 			c = min(count, softc->unmap_max_lba);
2564 			if (totalcount + c > softc->unmap_max_lba ||
2565 			    ranges >= softc->unmap_max_ranges) {
2566 				xpt_print(periph->path,
2567 				    "%s issuing short delete %ld > %ld"
2568 				    "|| %d >= %d",
2569 				    da_delete_method_desc[softc->delete_method],
2570 				    totalcount + c, softc->unmap_max_lba,
2571 				    ranges, softc->unmap_max_ranges);
2572 				break;
2573 			}
2574 			off = (ranges * UNMAP_RANGE_SIZE) + UNMAP_HEAD_SIZE;
2575 			scsi_u64to8b(lba, &buf[off + 0]);
2576 			scsi_ulto4b(c, &buf[off + 8]);
2577 			lba += c;
2578 			totalcount += c;
2579 			ranges++;
2580 			count -= c;
2581 			lastcount = c;
2582 		}
2583 		lastlba = lba;
2584 		bp1 = bioq_first(&softc->delete_queue);
2585 		if (bp1 == NULL || ranges >= softc->unmap_max_ranges ||
2586 		    totalcount + bp1->bio_bcount /
2587 		    softc->params.secsize > softc->unmap_max_lba)
2588 			break;
2589 	} while (1);
2590 	scsi_ulto2b(ranges * 16 + 6, &buf[0]);
2591 	scsi_ulto2b(ranges * 16, &buf[2]);
2592 
2593 	scsi_unmap(&ccb->csio,
2594 		   /*retries*/da_retry_count,
2595 		   /*cbfcnp*/dadone,
2596 		   /*tag_action*/MSG_SIMPLE_Q_TAG,
2597 		   /*byte2*/0,
2598 		   /*data_ptr*/ buf,
2599 		   /*dxfer_len*/ ranges * 16 + 8,
2600 		   /*sense_len*/SSD_FULL_SIZE,
2601 		   da_default_timeout * 1000);
2602 	ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2603 }
2604 
2605 static void
2606 da_delete_trim(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
2607 {
2608 	struct da_softc *softc = (struct da_softc *)periph->softc;
2609 	struct bio *bp1;
2610 	uint8_t *buf = softc->unmap_buf;
2611 	uint64_t lastlba = (uint64_t)-1;
2612 	uint64_t count;
2613 	uint64_t lba;
2614 	uint32_t lastcount = 0, c, requestcount;
2615 	int ranges = 0, off, block_count;
2616 
2617 	softc->delete_running = 1;
2618 	bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
2619 	bp1 = bp;
2620 	do {
2621 		bioq_remove(&softc->delete_queue, bp1);
2622 		if (bp1 != bp)
2623 			bioq_insert_tail(&softc->delete_run_queue, bp1);
2624 		lba = bp1->bio_pblkno;
2625 		count = bp1->bio_bcount / softc->params.secsize;
2626 		requestcount = count;
2627 
2628 		/* Try to extend the previous range. */
2629 		if (lba == lastlba) {
2630 			c = min(count, ATA_DSM_RANGE_MAX - lastcount);
2631 			lastcount += c;
2632 			off = (ranges - 1) * 8;
2633 			buf[off + 6] = lastcount & 0xff;
2634 			buf[off + 7] = (lastcount >> 8) & 0xff;
2635 			count -= c;
2636 			lba += c;
2637 		}
2638 
2639 		while (count > 0) {
2640 			c = min(count, ATA_DSM_RANGE_MAX);
2641 			off = ranges * 8;
2642 
2643 			buf[off + 0] = lba & 0xff;
2644 			buf[off + 1] = (lba >> 8) & 0xff;
2645 			buf[off + 2] = (lba >> 16) & 0xff;
2646 			buf[off + 3] = (lba >> 24) & 0xff;
2647 			buf[off + 4] = (lba >> 32) & 0xff;
2648 			buf[off + 5] = (lba >> 40) & 0xff;
2649 			buf[off + 6] = c & 0xff;
2650 			buf[off + 7] = (c >> 8) & 0xff;
2651 			lba += c;
2652 			ranges++;
2653 			count -= c;
2654 			lastcount = c;
2655 			if (count != 0 && ranges == softc->trim_max_ranges) {
2656 				xpt_print(periph->path,
2657 				    "%s issuing short delete %ld > %ld",
2658 				    da_delete_method_desc[softc->delete_method],
2659 				    requestcount,
2660 				    (softc->trim_max_ranges - ranges) *
2661 				    ATA_DSM_RANGE_MAX);
2662 				break;
2663 			}
2664 		}
2665 		lastlba = lba;
2666 		bp1 = bioq_first(&softc->delete_queue);
2667 		if (bp1 == NULL || bp1->bio_bcount / softc->params.secsize >
2668 		    (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX)
2669 			break;
2670 	} while (1);
2671 
2672 	block_count = (ranges + ATA_DSM_BLK_RANGES - 1) / ATA_DSM_BLK_RANGES;
2673 	scsi_ata_trim(&ccb->csio,
2674 		      /*retries*/da_retry_count,
2675 		      /*cbfcnp*/dadone,
2676 		      /*tag_action*/MSG_SIMPLE_Q_TAG,
2677 		      block_count,
2678 		      /*data_ptr*/buf,
2679 		      /*dxfer_len*/block_count * ATA_DSM_BLK_SIZE,
2680 		      /*sense_len*/SSD_FULL_SIZE,
2681 		      da_default_timeout * 1000);
2682 	ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2683 }
2684 
2685 /*
2686  * We calculate ws_max_blks here based off d_delmaxsize instead
2687  * of using softc->ws_max_blks as it is absolute max for the
2688  * device not the protocol max which may well be lower
2689  */
2690 static void
2691 da_delete_ws(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
2692 {
2693 	struct da_softc *softc;
2694 	struct bio *bp1;
2695 	uint64_t ws_max_blks;
2696 	uint64_t lba;
2697 	uint64_t count; /* forward compat with WS32 */
2698 
2699 	softc = (struct da_softc *)periph->softc;
2700 	ws_max_blks = softc->disk->d_delmaxsize / softc->params.secsize;
2701 	softc->delete_running = 1;
2702 	lba = bp->bio_pblkno;
2703 	count = 0;
2704 	bp1 = bp;
2705 	do {
2706 		bioq_remove(&softc->delete_queue, bp1);
2707 		if (bp1 != bp)
2708 			bioq_insert_tail(&softc->delete_run_queue, bp1);
2709 		count += bp1->bio_bcount / softc->params.secsize;
2710 		if (count > ws_max_blks) {
2711 			count = min(count, ws_max_blks);
2712 			xpt_print(periph->path,
2713 			    "%s issuing short delete %ld > %ld",
2714 			    da_delete_method_desc[softc->delete_method],
2715 			    count, ws_max_blks);
2716 			break;
2717 		}
2718 		bp1 = bioq_first(&softc->delete_queue);
2719 		if (bp1 == NULL || lba + count != bp1->bio_pblkno ||
2720 		    count + bp1->bio_bcount /
2721 		    softc->params.secsize > ws_max_blks)
2722 			break;
2723 	} while (1);
2724 
2725 	scsi_write_same(&ccb->csio,
2726 			/*retries*/da_retry_count,
2727 			/*cbfcnp*/dadone,
2728 			/*tag_action*/MSG_SIMPLE_Q_TAG,
2729 			/*byte2*/softc->delete_method ==
2730 			    DA_DELETE_ZERO ? 0 : SWS_UNMAP,
2731 			softc->delete_method == DA_DELETE_WS16 ? 16 : 10,
2732 			/*lba*/lba,
2733 			/*block_count*/count,
2734 			/*data_ptr*/ __DECONST(void *, zero_region),
2735 			/*dxfer_len*/ softc->params.secsize,
2736 			/*sense_len*/SSD_FULL_SIZE,
2737 			da_default_timeout * 1000);
2738 	ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2739 }
2740 
2741 static int
2742 cmd6workaround(union ccb *ccb)
2743 {
2744 	struct scsi_rw_6 cmd6;
2745 	struct scsi_rw_10 *cmd10;
2746 	struct da_softc *softc;
2747 	u_int8_t *cdb;
2748 	struct bio *bp;
2749 	int frozen;
2750 
2751 	cdb = ccb->csio.cdb_io.cdb_bytes;
2752 	softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
2753 
2754 	if (ccb->ccb_h.ccb_state == DA_CCB_DELETE) {
2755 		da_delete_methods old_method = softc->delete_method;
2756 
2757 		/*
2758 		 * Typically there are two reasons for failure here
2759 		 * 1. Delete method was detected as supported but isn't
2760 		 * 2. Delete failed due to invalid params e.g. too big
2761 		 *
2762 		 * While we will attempt to choose an alternative delete method
2763 		 * this may result in short deletes if the existing delete
2764 		 * requests from geom are big for the new method choosen.
2765 		 *
2766 		 * This method assumes that the error which triggered this
2767 		 * will not retry the io otherwise a panic will occur
2768 		 */
2769 		dadeleteflag(softc, old_method, 0);
2770 		dadeletemethodchoose(softc, DA_DELETE_DISABLE);
2771 		if (softc->delete_method == DA_DELETE_DISABLE)
2772 			xpt_print(ccb->ccb_h.path,
2773 				  "%s failed, disabling BIO_DELETE\n",
2774 				  da_delete_method_desc[old_method]);
2775 		else
2776 			xpt_print(ccb->ccb_h.path,
2777 				  "%s failed, switching to %s BIO_DELETE\n",
2778 				  da_delete_method_desc[old_method],
2779 				  da_delete_method_desc[softc->delete_method]);
2780 
2781 		if (DA_SIO) {
2782 			while ((bp = bioq_takefirst(&softc->delete_run_queue))
2783 			    != NULL)
2784 				bioq_disksort(&softc->delete_queue, bp);
2785 		} else {
2786 			while ((bp = bioq_takefirst(&softc->delete_run_queue))
2787 			    != NULL)
2788 				bioq_insert_tail(&softc->delete_queue, bp);
2789 		}
2790 		bioq_insert_tail(&softc->delete_queue,
2791 		    (struct bio *)ccb->ccb_h.ccb_bp);
2792 		ccb->ccb_h.ccb_bp = NULL;
2793 		return (0);
2794 	}
2795 
2796 	/* Detect unsupported PREVENT ALLOW MEDIUM REMOVAL. */
2797 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) == 0 &&
2798 	    (*cdb == PREVENT_ALLOW) &&
2799 	    (softc->quirks & DA_Q_NO_PREVENT) == 0) {
2800 		if (bootverbose)
2801 			xpt_print(ccb->ccb_h.path,
2802 			    "PREVENT ALLOW MEDIUM REMOVAL not supported.\n");
2803 		softc->quirks |= DA_Q_NO_PREVENT;
2804 		return (0);
2805 	}
2806 
2807 	/* Detect unsupported SYNCHRONIZE CACHE(10). */
2808 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) == 0 &&
2809 	    (*cdb == SYNCHRONIZE_CACHE) &&
2810 	    (softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
2811 		if (bootverbose)
2812 			xpt_print(ccb->ccb_h.path,
2813 			    "SYNCHRONIZE CACHE(10) not supported.\n");
2814 		softc->quirks |= DA_Q_NO_SYNC_CACHE;
2815 		return (0);
2816 	}
2817 
2818 	/* Translation only possible if CDB is an array and cmd is R/W6 */
2819 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
2820 	    (*cdb != READ_6 && *cdb != WRITE_6))
2821 		return 0;
2822 
2823 	xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, "
2824 	    "increasing minimum_cmd_size to 10.\n");
2825  	softc->minimum_cmd_size = 10;
2826 
2827 	bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
2828 	cmd10 = (struct scsi_rw_10 *)cdb;
2829 	cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
2830 	cmd10->byte2 = 0;
2831 	scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
2832 	cmd10->reserved = 0;
2833 	scsi_ulto2b(cmd6.length, cmd10->length);
2834 	cmd10->control = cmd6.control;
2835 	ccb->csio.cdb_len = sizeof(*cmd10);
2836 
2837 	/* Requeue request, unfreezing queue if necessary */
2838 	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
2839  	ccb->ccb_h.status = CAM_REQUEUE_REQ;
2840 	xpt_action(ccb);
2841 	if (frozen) {
2842 		cam_release_devq(ccb->ccb_h.path,
2843 				 /*relsim_flags*/0,
2844 				 /*reduction*/0,
2845 				 /*timeout*/0,
2846 				 /*getcount_only*/0);
2847 	}
2848 	return (ERESTART);
2849 }
2850 
2851 static void
2852 dadone(struct cam_periph *periph, union ccb *done_ccb)
2853 {
2854 	struct da_softc *softc;
2855 	struct ccb_scsiio *csio;
2856 	u_int32_t  priority;
2857 	da_ccb_state state;
2858 
2859 	softc = (struct da_softc *)periph->softc;
2860 	priority = done_ccb->ccb_h.pinfo.priority;
2861 
2862 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone\n"));
2863 
2864 	csio = &done_ccb->csio;
2865 	state = csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK;
2866 	switch (state) {
2867 	case DA_CCB_BUFFER_IO:
2868 	case DA_CCB_DELETE:
2869 	{
2870 		struct bio *bp, *bp1;
2871 
2872 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2873 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2874 			int error;
2875 			int sf;
2876 
2877 			if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
2878 				sf = SF_RETRY_UA;
2879 			else
2880 				sf = 0;
2881 
2882 			error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
2883 			if (error == ERESTART) {
2884 				/*
2885 				 * A retry was scheduled, so
2886 				 * just return.
2887 				 */
2888 				return;
2889 			}
2890 			bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2891 			if (error != 0) {
2892 				int queued_error;
2893 
2894 				/*
2895 				 * return all queued I/O with EIO, so that
2896 				 * the client can retry these I/Os in the
2897 				 * proper order should it attempt to recover.
2898 				 */
2899 				queued_error = EIO;
2900 
2901 				if (error == ENXIO
2902 				 && (softc->flags & DA_FLAG_PACK_INVALID)== 0) {
2903 					/*
2904 					 * Catastrophic error.  Mark our pack as
2905 					 * invalid.
2906 					 */
2907 					/*
2908 					 * XXX See if this is really a media
2909 					 * XXX change first?
2910 					 */
2911 					xpt_print(periph->path,
2912 					    "Invalidating pack\n");
2913 					softc->flags |= DA_FLAG_PACK_INVALID;
2914 					queued_error = ENXIO;
2915 				}
2916 				bioq_flush(&softc->bio_queue, NULL,
2917 					   queued_error);
2918 				if (bp != NULL) {
2919 					bp->bio_error = error;
2920 					bp->bio_resid = bp->bio_bcount;
2921 					bp->bio_flags |= BIO_ERROR;
2922 				}
2923 			} else if (bp != NULL) {
2924 				bp->bio_resid = csio->resid;
2925 				bp->bio_error = 0;
2926 				if (bp->bio_resid != 0)
2927 					bp->bio_flags |= BIO_ERROR;
2928 			}
2929 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2930 				cam_release_devq(done_ccb->ccb_h.path,
2931 						 /*relsim_flags*/0,
2932 						 /*reduction*/0,
2933 						 /*timeout*/0,
2934 						 /*getcount_only*/0);
2935 		} else if (bp != NULL) {
2936 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2937 				panic("REQ_CMP with QFRZN");
2938 			bp->bio_resid = csio->resid;
2939 			if (csio->resid > 0)
2940 				bp->bio_flags |= BIO_ERROR;
2941 			if (softc->error_inject != 0) {
2942 				bp->bio_error = softc->error_inject;
2943 				bp->bio_resid = bp->bio_bcount;
2944 				bp->bio_flags |= BIO_ERROR;
2945 				softc->error_inject = 0;
2946 			}
2947 
2948 		}
2949 
2950 		/*
2951 		 * Block out any asynchronous callbacks
2952 		 * while we touch the pending ccb list.
2953 		 */
2954 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
2955 		softc->outstanding_cmds--;
2956 		if (softc->outstanding_cmds == 0)
2957 			softc->flags |= DA_FLAG_WENT_IDLE;
2958 
2959 		if (state == DA_CCB_DELETE) {
2960 			while ((bp1 = bioq_takefirst(&softc->delete_run_queue))
2961 			    != NULL) {
2962 				bp1->bio_resid = bp->bio_resid;
2963 				bp1->bio_error = bp->bio_error;
2964 				if (bp->bio_flags & BIO_ERROR)
2965 					bp1->bio_flags |= BIO_ERROR;
2966 				biodone(bp1);
2967 			}
2968 			softc->delete_running = 0;
2969 			if (bp != NULL)
2970 				biodone(bp);
2971 			daschedule(periph);
2972 		} else if (bp != NULL)
2973 			biodone(bp);
2974 		break;
2975 	}
2976 	case DA_CCB_PROBE_RC:
2977 	case DA_CCB_PROBE_RC16:
2978 	{
2979 		struct	   scsi_read_capacity_data *rdcap;
2980 		struct     scsi_read_capacity_data_long *rcaplong;
2981 		char	   announce_buf[80];
2982 		int	   lbp;
2983 
2984 		lbp = 0;
2985 		rdcap = NULL;
2986 		rcaplong = NULL;
2987 		if (state == DA_CCB_PROBE_RC)
2988 			rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
2989 		else
2990 			rcaplong = (struct scsi_read_capacity_data_long *)
2991 				csio->data_ptr;
2992 
2993 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2994 			struct disk_params *dp;
2995 			uint32_t block_size;
2996 			uint64_t maxsector;
2997 			u_int lbppbe;	/* LB per physical block exponent. */
2998 			u_int lalba;	/* Lowest aligned LBA. */
2999 
3000 			if (state == DA_CCB_PROBE_RC) {
3001 				block_size = scsi_4btoul(rdcap->length);
3002 				maxsector = scsi_4btoul(rdcap->addr);
3003 				lbppbe = 0;
3004 				lalba = 0;
3005 
3006 				/*
3007 				 * According to SBC-2, if the standard 10
3008 				 * byte READ CAPACITY command returns 2^32,
3009 				 * we should issue the 16 byte version of
3010 				 * the command, since the device in question
3011 				 * has more sectors than can be represented
3012 				 * with the short version of the command.
3013 				 */
3014 				if (maxsector == 0xffffffff) {
3015 					free(rdcap, M_SCSIDA);
3016 					xpt_release_ccb(done_ccb);
3017 					softc->state = DA_STATE_PROBE_RC16;
3018 					xpt_schedule(periph, priority);
3019 					return;
3020 				}
3021 			} else {
3022 				block_size = scsi_4btoul(rcaplong->length);
3023 				maxsector = scsi_8btou64(rcaplong->addr);
3024 				lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
3025 				lalba = scsi_2btoul(rcaplong->lalba_lbp);
3026 			}
3027 
3028 			/*
3029 			 * Because GEOM code just will panic us if we
3030 			 * give them an 'illegal' value we'll avoid that
3031 			 * here.
3032 			 */
3033 			if (block_size == 0 && maxsector == 0) {
3034 				block_size = 512;
3035 				maxsector = -1;
3036 			}
3037 			if (block_size >= MAXPHYS || block_size == 0) {
3038 				xpt_print(periph->path,
3039 				    "unsupportable block size %ju\n",
3040 				    (uintmax_t) block_size);
3041 				announce_buf[0] = '\0';
3042 				cam_periph_invalidate(periph);
3043 			} else {
3044 				/*
3045 				 * We pass rcaplong into dasetgeom(),
3046 				 * because it will only use it if it is
3047 				 * non-NULL.
3048 				 */
3049 				dasetgeom(periph, block_size, maxsector,
3050 					  rcaplong, sizeof(*rcaplong));
3051 				lbp = (lalba & SRC16_LBPME_A);
3052 				dp = &softc->params;
3053 				snprintf(announce_buf, sizeof(announce_buf),
3054 				        "%juMB (%ju %u byte sectors: %dH %dS/T "
3055                                         "%dC)", (uintmax_t)
3056 	                                (((uintmax_t)dp->secsize *
3057 				        dp->sectors) / (1024*1024)),
3058 			                (uintmax_t)dp->sectors,
3059 				        dp->secsize, dp->heads,
3060                                         dp->secs_per_track, dp->cylinders);
3061 			}
3062 		} else {
3063 			int	error;
3064 
3065 			announce_buf[0] = '\0';
3066 
3067 			/*
3068 			 * Retry any UNIT ATTENTION type errors.  They
3069 			 * are expected at boot.
3070 			 */
3071 			error = daerror(done_ccb, CAM_RETRY_SELTO,
3072 					SF_RETRY_UA|SF_NO_PRINT);
3073 			if (error == ERESTART) {
3074 				/*
3075 				 * A retry was scheuled, so
3076 				 * just return.
3077 				 */
3078 				return;
3079 			} else if (error != 0) {
3080 				int asc, ascq;
3081 				int sense_key, error_code;
3082 				int have_sense;
3083 				cam_status status;
3084 				struct ccb_getdev cgd;
3085 
3086 				/* Don't wedge this device's queue */
3087 				status = done_ccb->ccb_h.status;
3088 				if ((status & CAM_DEV_QFRZN) != 0)
3089 					cam_release_devq(done_ccb->ccb_h.path,
3090 							 /*relsim_flags*/0,
3091 							 /*reduction*/0,
3092 							 /*timeout*/0,
3093 							 /*getcount_only*/0);
3094 
3095 
3096 				xpt_setup_ccb(&cgd.ccb_h,
3097 					      done_ccb->ccb_h.path,
3098 					      CAM_PRIORITY_NORMAL);
3099 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
3100 				xpt_action((union ccb *)&cgd);
3101 
3102 				if (scsi_extract_sense_ccb(done_ccb,
3103 				    &error_code, &sense_key, &asc, &ascq))
3104 					have_sense = TRUE;
3105 				else
3106 					have_sense = FALSE;
3107 
3108 				/*
3109 				 * If we tried READ CAPACITY(16) and failed,
3110 				 * fallback to READ CAPACITY(10).
3111 				 */
3112 				if ((state == DA_CCB_PROBE_RC16) &&
3113 				    (softc->flags & DA_FLAG_CAN_RC16) &&
3114 				    (((csio->ccb_h.status & CAM_STATUS_MASK) ==
3115 					CAM_REQ_INVALID) ||
3116 				     ((have_sense) &&
3117 				      (error_code == SSD_CURRENT_ERROR) &&
3118 				      (sense_key == SSD_KEY_ILLEGAL_REQUEST)))) {
3119 					softc->flags &= ~DA_FLAG_CAN_RC16;
3120 					free(rdcap, M_SCSIDA);
3121 					xpt_release_ccb(done_ccb);
3122 					softc->state = DA_STATE_PROBE_RC;
3123 					xpt_schedule(periph, priority);
3124 					return;
3125 				} else
3126 				/*
3127 				 * Attach to anything that claims to be a
3128 				 * direct access or optical disk device,
3129 				 * as long as it doesn't return a "Logical
3130 				 * unit not supported" (0x25) error.
3131 				 */
3132 				if ((have_sense) && (asc != 0x25)
3133 				 && (error_code == SSD_CURRENT_ERROR)) {
3134 					const char *sense_key_desc;
3135 					const char *asc_desc;
3136 
3137 					dasetgeom(periph, 512, -1, NULL, 0);
3138 					scsi_sense_desc(sense_key, asc, ascq,
3139 							&cgd.inq_data,
3140 							&sense_key_desc,
3141 							&asc_desc);
3142 					snprintf(announce_buf,
3143 					    sizeof(announce_buf),
3144 						"Attempt to query device "
3145 						"size failed: %s, %s",
3146 						sense_key_desc,
3147 						asc_desc);
3148 				} else {
3149 					if (have_sense)
3150 						scsi_sense_print(
3151 							&done_ccb->csio);
3152 					else {
3153 						xpt_print(periph->path,
3154 						    "got CAM status %#x\n",
3155 						    done_ccb->ccb_h.status);
3156 					}
3157 
3158 					xpt_print(periph->path, "fatal error, "
3159 					    "failed to attach to device\n");
3160 
3161 					/*
3162 					 * Free up resources.
3163 					 */
3164 					cam_periph_invalidate(periph);
3165 				}
3166 			}
3167 		}
3168 		free(csio->data_ptr, M_SCSIDA);
3169 		if (announce_buf[0] != '\0' && ((softc->flags & DA_FLAG_PROBED) == 0)) {
3170 			/*
3171 			 * Create our sysctl variables, now that we know
3172 			 * we have successfully attached.
3173 			 */
3174 			/* increase the refcount */
3175 			if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
3176 				taskqueue_enqueue(taskqueue_thread,
3177 						  &softc->sysctl_task);
3178 				xpt_announce_periph(periph, announce_buf);
3179 				xpt_announce_quirks(periph, softc->quirks,
3180 				    DA_Q_BIT_STRING);
3181 			} else {
3182 				xpt_print(periph->path, "fatal error, "
3183 				    "could not acquire reference count\n");
3184 			}
3185 		}
3186 
3187 		/* Ensure re-probe doesn't see old delete. */
3188 		softc->delete_available = 0;
3189 		if (lbp) {
3190 			/*
3191 			 * Based on older SBC-3 spec revisions
3192 			 * any of the UNMAP methods "may" be
3193 			 * available via LBP given this flag so
3194 			 * we flag all of them as availble and
3195 			 * then remove those which further
3196 			 * probes confirm aren't available
3197 			 * later.
3198 			 *
3199 			 * We could also check readcap(16) p_type
3200 			 * flag to exclude one or more invalid
3201 			 * write same (X) types here
3202 			 */
3203 			dadeleteflag(softc, DA_DELETE_WS16, 1);
3204 			dadeleteflag(softc, DA_DELETE_WS10, 1);
3205 			dadeleteflag(softc, DA_DELETE_ZERO, 1);
3206 			dadeleteflag(softc, DA_DELETE_UNMAP, 1);
3207 
3208 			xpt_release_ccb(done_ccb);
3209 			softc->state = DA_STATE_PROBE_LBP;
3210 			xpt_schedule(periph, priority);
3211 			return;
3212 		}
3213 
3214 		xpt_release_ccb(done_ccb);
3215 		softc->state = DA_STATE_PROBE_BDC;
3216 		xpt_schedule(periph, priority);
3217 		return;
3218 	}
3219 	case DA_CCB_PROBE_LBP:
3220 	{
3221 		struct scsi_vpd_logical_block_prov *lbp;
3222 
3223 		lbp = (struct scsi_vpd_logical_block_prov *)csio->data_ptr;
3224 
3225 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3226 			/*
3227 			 * T10/1799-D Revision 31 states at least one of these
3228 			 * must be supported but we don't currently enforce this.
3229 			 */
3230 			dadeleteflag(softc, DA_DELETE_WS16,
3231 				     (lbp->flags & SVPD_LBP_WS16));
3232 			dadeleteflag(softc, DA_DELETE_WS10,
3233 				     (lbp->flags & SVPD_LBP_WS10));
3234 			dadeleteflag(softc, DA_DELETE_ZERO,
3235 				     (lbp->flags & SVPD_LBP_WS10));
3236 			dadeleteflag(softc, DA_DELETE_UNMAP,
3237 				     (lbp->flags & SVPD_LBP_UNMAP));
3238 
3239 			if (lbp->flags & SVPD_LBP_UNMAP) {
3240 				free(lbp, M_SCSIDA);
3241 				xpt_release_ccb(done_ccb);
3242 				softc->state = DA_STATE_PROBE_BLK_LIMITS;
3243 				xpt_schedule(periph, priority);
3244 				return;
3245 			}
3246 		} else {
3247 			int error;
3248 			error = daerror(done_ccb, CAM_RETRY_SELTO,
3249 					SF_RETRY_UA|SF_NO_PRINT);
3250 			if (error == ERESTART)
3251 				return;
3252 			else if (error != 0) {
3253 				if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3254 					/* Don't wedge this device's queue */
3255 					cam_release_devq(done_ccb->ccb_h.path,
3256 							 /*relsim_flags*/0,
3257 							 /*reduction*/0,
3258 							 /*timeout*/0,
3259 							 /*getcount_only*/0);
3260 				}
3261 
3262 				/*
3263 				 * Failure indicates we don't support any SBC-3
3264 				 * delete methods with UNMAP
3265 				 */
3266 			}
3267 		}
3268 
3269 		free(lbp, M_SCSIDA);
3270 		xpt_release_ccb(done_ccb);
3271 		softc->state = DA_STATE_PROBE_BDC;
3272 		xpt_schedule(periph, priority);
3273 		return;
3274 	}
3275 	case DA_CCB_PROBE_BLK_LIMITS:
3276 	{
3277 		struct scsi_vpd_block_limits *block_limits;
3278 
3279 		block_limits = (struct scsi_vpd_block_limits *)csio->data_ptr;
3280 
3281 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3282 			uint32_t max_unmap_lba_cnt = scsi_4btoul(
3283 				block_limits->max_unmap_lba_cnt);
3284 			uint32_t max_unmap_blk_cnt = scsi_4btoul(
3285 				block_limits->max_unmap_blk_cnt);
3286 			uint64_t ws_max_blks = scsi_8btou64(
3287 				block_limits->max_write_same_length);
3288 			/*
3289 			 * We should already support UNMAP but we check lba
3290 			 * and block count to be sure
3291 			 */
3292 			if (max_unmap_lba_cnt != 0x00L &&
3293 			    max_unmap_blk_cnt != 0x00L) {
3294 				softc->unmap_max_lba = max_unmap_lba_cnt;
3295 				softc->unmap_max_ranges = min(max_unmap_blk_cnt,
3296 					UNMAP_MAX_RANGES);
3297 			} else {
3298 				/*
3299 				 * Unexpected UNMAP limits which means the
3300 				 * device doesn't actually support UNMAP
3301 				 */
3302 				dadeleteflag(softc, DA_DELETE_UNMAP, 0);
3303 			}
3304 
3305 			if (ws_max_blks != 0x00L)
3306 				softc->ws_max_blks = ws_max_blks;
3307 		} else {
3308 			int error;
3309 			error = daerror(done_ccb, CAM_RETRY_SELTO,
3310 					SF_RETRY_UA|SF_NO_PRINT);
3311 			if (error == ERESTART)
3312 				return;
3313 			else if (error != 0) {
3314 				if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3315 					/* Don't wedge this device's queue */
3316 					cam_release_devq(done_ccb->ccb_h.path,
3317 							 /*relsim_flags*/0,
3318 							 /*reduction*/0,
3319 							 /*timeout*/0,
3320 							 /*getcount_only*/0);
3321 				}
3322 
3323 				/*
3324 				 * Failure here doesn't mean UNMAP is not
3325 				 * supported as this is an optional page.
3326 				 */
3327 				softc->unmap_max_lba = 1;
3328 				softc->unmap_max_ranges = 1;
3329 			}
3330 		}
3331 
3332 		free(block_limits, M_SCSIDA);
3333 		xpt_release_ccb(done_ccb);
3334 		softc->state = DA_STATE_PROBE_BDC;
3335 		xpt_schedule(periph, priority);
3336 		return;
3337 	}
3338 	case DA_CCB_PROBE_BDC:
3339 	{
3340 		struct scsi_vpd_block_characteristics *bdc;
3341 
3342 		bdc = (struct scsi_vpd_block_characteristics *)csio->data_ptr;
3343 
3344 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3345 			/*
3346 			 * Disable queue sorting for non-rotational media
3347 			 * by default.
3348 			 */
3349 			if (scsi_2btoul(bdc->medium_rotation_rate) ==
3350 			    SVPD_BDC_RATE_NONE_ROTATING)
3351 				softc->sort_io_queue = 0;
3352 		} else {
3353 			int error;
3354 			error = daerror(done_ccb, CAM_RETRY_SELTO,
3355 					SF_RETRY_UA|SF_NO_PRINT);
3356 			if (error == ERESTART)
3357 				return;
3358 			else if (error != 0) {
3359 				if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3360 					/* Don't wedge this device's queue */
3361 					cam_release_devq(done_ccb->ccb_h.path,
3362 							 /*relsim_flags*/0,
3363 							 /*reduction*/0,
3364 							 /*timeout*/0,
3365 							 /*getcount_only*/0);
3366 				}
3367 			}
3368 		}
3369 
3370 		free(bdc, M_SCSIDA);
3371 		xpt_release_ccb(done_ccb);
3372 		softc->state = DA_STATE_PROBE_ATA;
3373 		xpt_schedule(periph, priority);
3374 		return;
3375 	}
3376 	case DA_CCB_PROBE_ATA:
3377 	{
3378 		int i;
3379 		struct ata_params *ata_params;
3380 		int16_t *ptr;
3381 
3382 		ata_params = (struct ata_params *)csio->data_ptr;
3383 		ptr = (uint16_t *)ata_params;
3384 
3385 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3386 			for (i = 0; i < sizeof(*ata_params) / 2; i++)
3387 				ptr[i] = le16toh(ptr[i]);
3388 			if (ata_params->support_dsm & ATA_SUPPORT_DSM_TRIM) {
3389 				dadeleteflag(softc, DA_DELETE_ATA_TRIM, 1);
3390 				if (ata_params->max_dsm_blocks != 0)
3391 					softc->trim_max_ranges = min(
3392 					  softc->trim_max_ranges,
3393 					  ata_params->max_dsm_blocks *
3394 					  ATA_DSM_BLK_RANGES);
3395 			}
3396 			/*
3397 			 * Disable queue sorting for non-rotational media
3398 			 * by default.
3399 			 */
3400 			if (ata_params->media_rotation_rate == 1)
3401 				softc->sort_io_queue = 0;
3402 		} else {
3403 			int error;
3404 			error = daerror(done_ccb, CAM_RETRY_SELTO,
3405 					SF_RETRY_UA|SF_NO_PRINT);
3406 			if (error == ERESTART)
3407 				return;
3408 			else if (error != 0) {
3409 				if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3410 					/* Don't wedge this device's queue */
3411 					cam_release_devq(done_ccb->ccb_h.path,
3412 							 /*relsim_flags*/0,
3413 							 /*reduction*/0,
3414 							 /*timeout*/0,
3415 							 /*getcount_only*/0);
3416 				}
3417 			}
3418 		}
3419 
3420 		free(ata_params, M_SCSIDA);
3421 		daprobedone(periph, done_ccb);
3422 		return;
3423 	}
3424 	case DA_CCB_WAITING:
3425 	{
3426 		/* Caller will release the CCB */
3427 		wakeup(&done_ccb->ccb_h.cbfcnp);
3428 		return;
3429 	}
3430 	case DA_CCB_DUMP:
3431 		/* No-op.  We're polling */
3432 		return;
3433 	case DA_CCB_TUR:
3434 	{
3435 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3436 
3437 			if (daerror(done_ccb, CAM_RETRY_SELTO,
3438 			    SF_RETRY_UA | SF_NO_RECOVERY | SF_NO_PRINT) ==
3439 			    ERESTART)
3440 				return;
3441 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3442 				cam_release_devq(done_ccb->ccb_h.path,
3443 						 /*relsim_flags*/0,
3444 						 /*reduction*/0,
3445 						 /*timeout*/0,
3446 						 /*getcount_only*/0);
3447 		}
3448 		xpt_release_ccb(done_ccb);
3449 		cam_periph_release_locked(periph);
3450 		return;
3451 	}
3452 	default:
3453 		break;
3454 	}
3455 	xpt_release_ccb(done_ccb);
3456 }
3457 
3458 static void
3459 dareprobe(struct cam_periph *periph)
3460 {
3461 	struct da_softc	  *softc;
3462 	cam_status status;
3463 
3464 	softc = (struct da_softc *)periph->softc;
3465 
3466 	/* Probe in progress; don't interfere. */
3467 	if (softc->state != DA_STATE_NORMAL)
3468 		return;
3469 
3470 	status = cam_periph_acquire(periph);
3471 	KASSERT(status == CAM_REQ_CMP,
3472 	    ("dareprobe: cam_periph_acquire failed"));
3473 
3474 	if (softc->flags & DA_FLAG_CAN_RC16)
3475 		softc->state = DA_STATE_PROBE_RC16;
3476 	else
3477 		softc->state = DA_STATE_PROBE_RC;
3478 
3479 	xpt_schedule(periph, CAM_PRIORITY_DEV);
3480 }
3481 
3482 static int
3483 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3484 {
3485 	struct da_softc	  *softc;
3486 	struct cam_periph *periph;
3487 	int error, error_code, sense_key, asc, ascq;
3488 
3489 	periph = xpt_path_periph(ccb->ccb_h.path);
3490 	softc = (struct da_softc *)periph->softc;
3491 
3492  	/*
3493 	 * Automatically detect devices that do not support
3494  	 * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
3495  	 */
3496 	error = 0;
3497 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
3498 		error = cmd6workaround(ccb);
3499 	} else if (scsi_extract_sense_ccb(ccb,
3500 	    &error_code, &sense_key, &asc, &ascq)) {
3501 		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
3502  			error = cmd6workaround(ccb);
3503 		/*
3504 		 * If the target replied with CAPACITY DATA HAS CHANGED UA,
3505 		 * query the capacity and notify upper layers.
3506 		 */
3507 		else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3508 		    asc == 0x2A && ascq == 0x09) {
3509 			xpt_print(periph->path, "capacity data has changed\n");
3510 			dareprobe(periph);
3511 			sense_flags |= SF_NO_PRINT;
3512 		} else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3513 		    asc == 0x28 && ascq == 0x00)
3514 			disk_media_changed(softc->disk, M_NOWAIT);
3515 		else if (sense_key == SSD_KEY_NOT_READY &&
3516 		    asc == 0x3a && (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
3517 			softc->flags |= DA_FLAG_PACK_INVALID;
3518 			disk_media_gone(softc->disk, M_NOWAIT);
3519 		}
3520 	}
3521 	if (error == ERESTART)
3522 		return (ERESTART);
3523 
3524 	/*
3525 	 * XXX
3526 	 * Until we have a better way of doing pack validation,
3527 	 * don't treat UAs as errors.
3528 	 */
3529 	sense_flags |= SF_RETRY_UA;
3530 	return(cam_periph_error(ccb, cam_flags, sense_flags,
3531 				&softc->saved_ccb));
3532 }
3533 
3534 static void
3535 damediapoll(void *arg)
3536 {
3537 	struct cam_periph *periph = arg;
3538 	struct da_softc *softc = periph->softc;
3539 
3540 	if (!softc->tur && softc->outstanding_cmds == 0) {
3541 		if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
3542 			softc->tur = 1;
3543 			daschedule(periph);
3544 		}
3545 	}
3546 	/* Queue us up again */
3547 	if (da_poll_period != 0)
3548 		callout_schedule(&softc->mediapoll_c, da_poll_period * hz);
3549 }
3550 
3551 static void
3552 daprevent(struct cam_periph *periph, int action)
3553 {
3554 	struct	da_softc *softc;
3555 	union	ccb *ccb;
3556 	int	error;
3557 
3558 	softc = (struct da_softc *)periph->softc;
3559 
3560 	if (((action == PR_ALLOW)
3561 	  && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
3562 	 || ((action == PR_PREVENT)
3563 	  && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
3564 		return;
3565 	}
3566 
3567 	ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3568 
3569 	scsi_prevent(&ccb->csio,
3570 		     /*retries*/1,
3571 		     /*cbcfp*/dadone,
3572 		     MSG_SIMPLE_Q_TAG,
3573 		     action,
3574 		     SSD_FULL_SIZE,
3575 		     5000);
3576 
3577 	error = cam_periph_runccb(ccb, daerror, CAM_RETRY_SELTO,
3578 	    SF_RETRY_UA | SF_NO_PRINT, softc->disk->d_devstat);
3579 
3580 	if (error == 0) {
3581 		if (action == PR_ALLOW)
3582 			softc->flags &= ~DA_FLAG_PACK_LOCKED;
3583 		else
3584 			softc->flags |= DA_FLAG_PACK_LOCKED;
3585 	}
3586 
3587 	xpt_release_ccb(ccb);
3588 }
3589 
3590 static void
3591 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector,
3592 	  struct scsi_read_capacity_data_long *rcaplong, size_t rcap_len)
3593 {
3594 	struct ccb_calc_geometry ccg;
3595 	struct da_softc *softc;
3596 	struct disk_params *dp;
3597 	u_int lbppbe, lalba;
3598 	int error;
3599 
3600 	softc = (struct da_softc *)periph->softc;
3601 
3602 	dp = &softc->params;
3603 	dp->secsize = block_len;
3604 	dp->sectors = maxsector + 1;
3605 	if (rcaplong != NULL) {
3606 		lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
3607 		lalba = scsi_2btoul(rcaplong->lalba_lbp);
3608 		lalba &= SRC16_LALBA_A;
3609 	} else {
3610 		lbppbe = 0;
3611 		lalba = 0;
3612 	}
3613 
3614 	if (lbppbe > 0) {
3615 		dp->stripesize = block_len << lbppbe;
3616 		dp->stripeoffset = (dp->stripesize - block_len * lalba) %
3617 		    dp->stripesize;
3618 	} else if (softc->quirks & DA_Q_4K) {
3619 		dp->stripesize = 4096;
3620 		dp->stripeoffset = 0;
3621 	} else {
3622 		dp->stripesize = 0;
3623 		dp->stripeoffset = 0;
3624 	}
3625 	/*
3626 	 * Have the controller provide us with a geometry
3627 	 * for this disk.  The only time the geometry
3628 	 * matters is when we boot and the controller
3629 	 * is the only one knowledgeable enough to come
3630 	 * up with something that will make this a bootable
3631 	 * device.
3632 	 */
3633 	xpt_setup_ccb(&ccg.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3634 	ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
3635 	ccg.block_size = dp->secsize;
3636 	ccg.volume_size = dp->sectors;
3637 	ccg.heads = 0;
3638 	ccg.secs_per_track = 0;
3639 	ccg.cylinders = 0;
3640 	xpt_action((union ccb*)&ccg);
3641 	if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3642 		/*
3643 		 * We don't know what went wrong here- but just pick
3644 		 * a geometry so we don't have nasty things like divide
3645 		 * by zero.
3646 		 */
3647 		dp->heads = 255;
3648 		dp->secs_per_track = 255;
3649 		dp->cylinders = dp->sectors / (255 * 255);
3650 		if (dp->cylinders == 0) {
3651 			dp->cylinders = 1;
3652 		}
3653 	} else {
3654 		dp->heads = ccg.heads;
3655 		dp->secs_per_track = ccg.secs_per_track;
3656 		dp->cylinders = ccg.cylinders;
3657 	}
3658 
3659 	/*
3660 	 * If the user supplied a read capacity buffer, and if it is
3661 	 * different than the previous buffer, update the data in the EDT.
3662 	 * If it's the same, we don't bother.  This avoids sending an
3663 	 * update every time someone opens this device.
3664 	 */
3665 	if ((rcaplong != NULL)
3666 	 && (bcmp(rcaplong, &softc->rcaplong,
3667 		  min(sizeof(softc->rcaplong), rcap_len)) != 0)) {
3668 		struct ccb_dev_advinfo cdai;
3669 
3670 		xpt_setup_ccb(&cdai.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3671 		cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
3672 		cdai.buftype = CDAI_TYPE_RCAPLONG;
3673 		cdai.flags |= CDAI_FLAG_STORE;
3674 		cdai.bufsiz = rcap_len;
3675 		cdai.buf = (uint8_t *)rcaplong;
3676 		xpt_action((union ccb *)&cdai);
3677 		if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
3678 			cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
3679 		if (cdai.ccb_h.status != CAM_REQ_CMP) {
3680 			xpt_print(periph->path, "%s: failed to set read "
3681 				  "capacity advinfo\n", __func__);
3682 			/* Use cam_error_print() to decode the status */
3683 			cam_error_print((union ccb *)&cdai, CAM_ESF_CAM_STATUS,
3684 					CAM_EPF_ALL);
3685 		} else {
3686 			bcopy(rcaplong, &softc->rcaplong,
3687 			      min(sizeof(softc->rcaplong), rcap_len));
3688 		}
3689 	}
3690 
3691 	softc->disk->d_sectorsize = softc->params.secsize;
3692 	softc->disk->d_mediasize = softc->params.secsize * (off_t)softc->params.sectors;
3693 	softc->disk->d_stripesize = softc->params.stripesize;
3694 	softc->disk->d_stripeoffset = softc->params.stripeoffset;
3695 	/* XXX: these are not actually "firmware" values, so they may be wrong */
3696 	softc->disk->d_fwsectors = softc->params.secs_per_track;
3697 	softc->disk->d_fwheads = softc->params.heads;
3698 	softc->disk->d_devstat->block_size = softc->params.secsize;
3699 	softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
3700 
3701 	error = disk_resize(softc->disk, M_NOWAIT);
3702 	if (error != 0)
3703 		xpt_print(periph->path, "disk_resize(9) failed, error = %d\n", error);
3704 }
3705 
3706 static void
3707 dasendorderedtag(void *arg)
3708 {
3709 	struct da_softc *softc = arg;
3710 
3711 	if (da_send_ordered) {
3712 		if ((softc->ordered_tag_count == 0)
3713 		 && ((softc->flags & DA_FLAG_WENT_IDLE) == 0)) {
3714 			softc->flags |= DA_FLAG_NEED_OTAG;
3715 		}
3716 		if (softc->outstanding_cmds > 0)
3717 			softc->flags &= ~DA_FLAG_WENT_IDLE;
3718 
3719 		softc->ordered_tag_count = 0;
3720 	}
3721 	/* Queue us up again */
3722 	callout_reset(&softc->sendordered_c,
3723 	    (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
3724 	    dasendorderedtag, softc);
3725 }
3726 
3727 /*
3728  * Step through all DA peripheral drivers, and if the device is still open,
3729  * sync the disk cache to physical media.
3730  */
3731 static void
3732 dashutdown(void * arg, int howto)
3733 {
3734 	struct cam_periph *periph;
3735 	struct da_softc *softc;
3736 	union ccb *ccb;
3737 	int error;
3738 
3739 	CAM_PERIPH_FOREACH(periph, &dadriver) {
3740 		softc = (struct da_softc *)periph->softc;
3741 		if (SCHEDULER_STOPPED()) {
3742 			/* If we paniced with the lock held, do not recurse. */
3743 			if (!cam_periph_owned(periph) &&
3744 			    (softc->flags & DA_FLAG_OPEN)) {
3745 				dadump(softc->disk, NULL, 0, 0, 0);
3746 			}
3747 			continue;
3748 		}
3749 		cam_periph_lock(periph);
3750 
3751 		/*
3752 		 * We only sync the cache if the drive is still open, and
3753 		 * if the drive is capable of it..
3754 		 */
3755 		if (((softc->flags & DA_FLAG_OPEN) == 0)
3756 		 || (softc->quirks & DA_Q_NO_SYNC_CACHE)) {
3757 			cam_periph_unlock(periph);
3758 			continue;
3759 		}
3760 
3761 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3762 		scsi_synchronize_cache(&ccb->csio,
3763 				       /*retries*/0,
3764 				       /*cbfcnp*/dadone,
3765 				       MSG_SIMPLE_Q_TAG,
3766 				       /*begin_lba*/0, /* whole disk */
3767 				       /*lb_count*/0,
3768 				       SSD_FULL_SIZE,
3769 				       60 * 60 * 1000);
3770 
3771 		error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
3772 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR,
3773 		    softc->disk->d_devstat);
3774 		if (error != 0)
3775 			xpt_print(periph->path, "Synchronize cache failed\n");
3776 		xpt_release_ccb(ccb);
3777 		cam_periph_unlock(periph);
3778 	}
3779 }
3780 
3781 #else /* !_KERNEL */
3782 
3783 /*
3784  * XXX This is only left out of the kernel build to silence warnings.  If,
3785  * for some reason this function is used in the kernel, the ifdefs should
3786  * be moved so it is included both in the kernel and userland.
3787  */
3788 void
3789 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
3790 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
3791 		 u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
3792 		 u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
3793 		 u_int32_t timeout)
3794 {
3795 	struct scsi_format_unit *scsi_cmd;
3796 
3797 	scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
3798 	scsi_cmd->opcode = FORMAT_UNIT;
3799 	scsi_cmd->byte2 = byte2;
3800 	scsi_ulto2b(ileave, scsi_cmd->interleave);
3801 
3802 	cam_fill_csio(csio,
3803 		      retries,
3804 		      cbfcnp,
3805 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
3806 		      tag_action,
3807 		      data_ptr,
3808 		      dxfer_len,
3809 		      sense_len,
3810 		      sizeof(*scsi_cmd),
3811 		      timeout);
3812 }
3813 
3814 #endif /* _KERNEL */
3815