xref: /freebsd/sys/cam/scsi/scsi_da.c (revision 1dfcff294e44d4b45813288ef4095c36abb22f0e)
1 /*-
2  * Implementation of SCSI Direct Access Peripheral driver for CAM.
3  *
4  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
5  *
6  * Copyright (c) 1997 Justin T. Gibbs.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification, immediately at the beginning of the file.
15  * 2. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/param.h>
35 
36 #ifdef _KERNEL
37 #include "opt_da.h"
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/bio.h>
41 #include <sys/sysctl.h>
42 #include <sys/taskqueue.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/conf.h>
46 #include <sys/devicestat.h>
47 #include <sys/eventhandler.h>
48 #include <sys/malloc.h>
49 #include <sys/cons.h>
50 #include <sys/endian.h>
51 #include <sys/proc.h>
52 #include <sys/reboot.h>
53 #include <sys/sbuf.h>
54 #include <geom/geom.h>
55 #include <geom/geom_disk.h>
56 #include <machine/atomic.h>
57 #endif /* _KERNEL */
58 
59 #ifndef _KERNEL
60 #include <stdio.h>
61 #include <string.h>
62 #endif /* _KERNEL */
63 
64 #include <cam/cam.h>
65 #include <cam/cam_ccb.h>
66 #include <cam/cam_periph.h>
67 #include <cam/cam_xpt_periph.h>
68 #ifdef _KERNEL
69 #include <cam/cam_xpt_internal.h>
70 #endif /* _KERNEL */
71 #include <cam/cam_sim.h>
72 #include <cam/cam_iosched.h>
73 
74 #include <cam/scsi/scsi_message.h>
75 #include <cam/scsi/scsi_da.h>
76 
77 #ifdef _KERNEL
78 /*
79  * Note that there are probe ordering dependencies here.  The order isn't
80  * controlled by this enumeration, but by explicit state transitions in
81  * dastart() and dadone().  Here are some of the dependencies:
82  *
83  * 1. RC should come first, before RC16, unless there is evidence that RC16
84  *    is supported.
85  * 2. BDC needs to come before any of the ATA probes, or the ZONE probe.
86  * 3. The ATA probes should go in this order:
87  *    ATA -> LOGDIR -> IDDIR -> SUP -> ATA_ZONE
88  */
89 typedef enum {
90 	DA_STATE_PROBE_WP,
91 	DA_STATE_PROBE_RC,
92 	DA_STATE_PROBE_RC16,
93 	DA_STATE_PROBE_LBP,
94 	DA_STATE_PROBE_BLK_LIMITS,
95 	DA_STATE_PROBE_BDC,
96 	DA_STATE_PROBE_ATA,
97 	DA_STATE_PROBE_ATA_LOGDIR,
98 	DA_STATE_PROBE_ATA_IDDIR,
99 	DA_STATE_PROBE_ATA_SUP,
100 	DA_STATE_PROBE_ATA_ZONE,
101 	DA_STATE_PROBE_ZONE,
102 	DA_STATE_NORMAL
103 } da_state;
104 
105 typedef enum {
106 	DA_FLAG_PACK_INVALID	= 0x000001,
107 	DA_FLAG_NEW_PACK	= 0x000002,
108 	DA_FLAG_PACK_LOCKED	= 0x000004,
109 	DA_FLAG_PACK_REMOVABLE	= 0x000008,
110 	DA_FLAG_ROTATING	= 0x000010,
111 	DA_FLAG_NEED_OTAG	= 0x000020,
112 	DA_FLAG_WAS_OTAG	= 0x000040,
113 	DA_FLAG_RETRY_UA	= 0x000080,
114 	DA_FLAG_OPEN		= 0x000100,
115 	DA_FLAG_SCTX_INIT	= 0x000200,
116 	DA_FLAG_CAN_RC16	= 0x000400,
117 	DA_FLAG_PROBED		= 0x000800,
118 	DA_FLAG_DIRTY		= 0x001000,
119 	DA_FLAG_ANNOUNCED	= 0x002000,
120 	DA_FLAG_CAN_ATA_DMA	= 0x004000,
121 	DA_FLAG_CAN_ATA_LOG	= 0x008000,
122 	DA_FLAG_CAN_ATA_IDLOG	= 0x010000,
123 	DA_FLAG_CAN_ATA_SUPCAP	= 0x020000,
124 	DA_FLAG_CAN_ATA_ZONE	= 0x040000,
125 	DA_FLAG_TUR_PENDING	= 0x080000,
126 	DA_FLAG_UNMAPPEDIO	= 0x100000
127 } da_flags;
128 #define DA_FLAG_STRING		\
129 	"\020"			\
130 	"\001PACK_INVALID"	\
131 	"\002NEW_PACK"		\
132 	"\003PACK_LOCKED"	\
133 	"\004PACK_REMOVABLE"	\
134 	"\005ROTATING"		\
135 	"\006NEED_OTAG"		\
136 	"\007WAS_OTAG"		\
137 	"\010RETRY_UA"		\
138 	"\011OPEN"		\
139 	"\012SCTX_INIT"		\
140 	"\013CAN_RC16"		\
141 	"\014PROBED"		\
142 	"\015DIRTY"		\
143 	"\016ANNOUCNED"		\
144 	"\017CAN_ATA_DMA"	\
145 	"\020CAN_ATA_LOG"	\
146 	"\021CAN_ATA_IDLOG"	\
147 	"\022CAN_ATA_SUPACP"	\
148 	"\023CAN_ATA_ZONE"	\
149 	"\024TUR_PENDING"	\
150 	"\025UNMAPPEDIO"
151 
152 typedef enum {
153 	DA_Q_NONE		= 0x00,
154 	DA_Q_NO_SYNC_CACHE	= 0x01,
155 	DA_Q_NO_6_BYTE		= 0x02,
156 	DA_Q_NO_PREVENT		= 0x04,
157 	DA_Q_4K			= 0x08,
158 	DA_Q_NO_RC16		= 0x10,
159 	DA_Q_NO_UNMAP		= 0x20,
160 	DA_Q_RETRY_BUSY		= 0x40,
161 	DA_Q_SMR_DM		= 0x80,
162 	DA_Q_STRICT_UNMAP	= 0x100,
163 	DA_Q_128KB		= 0x200
164 } da_quirks;
165 
166 #define DA_Q_BIT_STRING		\
167 	"\020"			\
168 	"\001NO_SYNC_CACHE"	\
169 	"\002NO_6_BYTE"		\
170 	"\003NO_PREVENT"	\
171 	"\0044K"		\
172 	"\005NO_RC16"		\
173 	"\006NO_UNMAP"		\
174 	"\007RETRY_BUSY"	\
175 	"\010SMR_DM"		\
176 	"\011STRICT_UNMAP"	\
177 	"\012128KB"
178 
179 typedef enum {
180 	DA_CCB_PROBE_RC		= 0x01,
181 	DA_CCB_PROBE_RC16	= 0x02,
182 	DA_CCB_PROBE_LBP	= 0x03,
183 	DA_CCB_PROBE_BLK_LIMITS	= 0x04,
184 	DA_CCB_PROBE_BDC	= 0x05,
185 	DA_CCB_PROBE_ATA	= 0x06,
186 	DA_CCB_BUFFER_IO	= 0x07,
187 	DA_CCB_DUMP		= 0x0A,
188 	DA_CCB_DELETE		= 0x0B,
189 	DA_CCB_TUR		= 0x0C,
190 	DA_CCB_PROBE_ZONE	= 0x0D,
191 	DA_CCB_PROBE_ATA_LOGDIR	= 0x0E,
192 	DA_CCB_PROBE_ATA_IDDIR	= 0x0F,
193 	DA_CCB_PROBE_ATA_SUP	= 0x10,
194 	DA_CCB_PROBE_ATA_ZONE	= 0x11,
195 	DA_CCB_PROBE_WP		= 0x12,
196 	DA_CCB_TYPE_MASK	= 0x1F,
197 	DA_CCB_RETRY_UA		= 0x20
198 } da_ccb_state;
199 
200 /*
201  * Order here is important for method choice
202  *
203  * We prefer ATA_TRIM as tests run against a Sandforce 2281 SSD attached to
204  * LSI 2008 (mps) controller (FW: v12, Drv: v14) resulted 20% quicker deletes
205  * using ATA_TRIM than the corresponding UNMAP results for a real world mysql
206  * import taking 5mins.
207  *
208  */
209 typedef enum {
210 	DA_DELETE_NONE,
211 	DA_DELETE_DISABLE,
212 	DA_DELETE_ATA_TRIM,
213 	DA_DELETE_UNMAP,
214 	DA_DELETE_WS16,
215 	DA_DELETE_WS10,
216 	DA_DELETE_ZERO,
217 	DA_DELETE_MIN = DA_DELETE_ATA_TRIM,
218 	DA_DELETE_MAX = DA_DELETE_ZERO
219 } da_delete_methods;
220 
221 /*
222  * For SCSI, host managed drives show up as a separate device type.  For
223  * ATA, host managed drives also have a different device signature.
224  * XXX KDM figure out the ATA host managed signature.
225  */
226 typedef enum {
227 	DA_ZONE_NONE		= 0x00,
228 	DA_ZONE_DRIVE_MANAGED	= 0x01,
229 	DA_ZONE_HOST_AWARE	= 0x02,
230 	DA_ZONE_HOST_MANAGED	= 0x03
231 } da_zone_mode;
232 
233 /*
234  * We distinguish between these interface cases in addition to the drive type:
235  * o ATA drive behind a SCSI translation layer that knows about ZBC/ZAC
236  * o ATA drive behind a SCSI translation layer that does not know about
237  *   ZBC/ZAC, and so needs to be managed via ATA passthrough.  In this
238  *   case, we would need to share the ATA code with the ada(4) driver.
239  * o SCSI drive.
240  */
241 typedef enum {
242 	DA_ZONE_IF_SCSI,
243 	DA_ZONE_IF_ATA_PASS,
244 	DA_ZONE_IF_ATA_SAT,
245 } da_zone_interface;
246 
247 typedef enum {
248 	DA_ZONE_FLAG_RZ_SUP		= 0x0001,
249 	DA_ZONE_FLAG_OPEN_SUP		= 0x0002,
250 	DA_ZONE_FLAG_CLOSE_SUP		= 0x0004,
251 	DA_ZONE_FLAG_FINISH_SUP		= 0x0008,
252 	DA_ZONE_FLAG_RWP_SUP		= 0x0010,
253 	DA_ZONE_FLAG_SUP_MASK		= (DA_ZONE_FLAG_RZ_SUP |
254 					   DA_ZONE_FLAG_OPEN_SUP |
255 					   DA_ZONE_FLAG_CLOSE_SUP |
256 					   DA_ZONE_FLAG_FINISH_SUP |
257 					   DA_ZONE_FLAG_RWP_SUP),
258 	DA_ZONE_FLAG_URSWRZ		= 0x0020,
259 	DA_ZONE_FLAG_OPT_SEQ_SET	= 0x0040,
260 	DA_ZONE_FLAG_OPT_NONSEQ_SET	= 0x0080,
261 	DA_ZONE_FLAG_MAX_SEQ_SET	= 0x0100,
262 	DA_ZONE_FLAG_SET_MASK		= (DA_ZONE_FLAG_OPT_SEQ_SET |
263 					   DA_ZONE_FLAG_OPT_NONSEQ_SET |
264 					   DA_ZONE_FLAG_MAX_SEQ_SET)
265 } da_zone_flags;
266 
267 static struct da_zone_desc {
268 	da_zone_flags value;
269 	const char *desc;
270 } da_zone_desc_table[] = {
271 	{DA_ZONE_FLAG_RZ_SUP, "Report Zones" },
272 	{DA_ZONE_FLAG_OPEN_SUP, "Open" },
273 	{DA_ZONE_FLAG_CLOSE_SUP, "Close" },
274 	{DA_ZONE_FLAG_FINISH_SUP, "Finish" },
275 	{DA_ZONE_FLAG_RWP_SUP, "Reset Write Pointer" },
276 };
277 
278 typedef void da_delete_func_t (struct cam_periph *periph, union ccb *ccb,
279 			      struct bio *bp);
280 static da_delete_func_t da_delete_trim;
281 static da_delete_func_t da_delete_unmap;
282 static da_delete_func_t da_delete_ws;
283 
284 static const void * da_delete_functions[] = {
285 	NULL,
286 	NULL,
287 	da_delete_trim,
288 	da_delete_unmap,
289 	da_delete_ws,
290 	da_delete_ws,
291 	da_delete_ws
292 };
293 
294 static const char *da_delete_method_names[] =
295     { "NONE", "DISABLE", "ATA_TRIM", "UNMAP", "WS16", "WS10", "ZERO" };
296 static const char *da_delete_method_desc[] =
297     { "NONE", "DISABLED", "ATA TRIM", "UNMAP", "WRITE SAME(16) with UNMAP",
298       "WRITE SAME(10) with UNMAP", "ZERO" };
299 
300 /* Offsets into our private area for storing information */
301 #define ccb_state	ppriv_field0
302 #define ccb_bp		ppriv_ptr1
303 
304 struct disk_params {
305 	u_int8_t  heads;
306 	u_int32_t cylinders;
307 	u_int8_t  secs_per_track;
308 	u_int32_t secsize;	/* Number of bytes/sector */
309 	u_int64_t sectors;	/* total number sectors */
310 	u_int     stripesize;
311 	u_int     stripeoffset;
312 };
313 
314 #define UNMAP_RANGE_MAX		0xffffffff
315 #define UNMAP_HEAD_SIZE		8
316 #define UNMAP_RANGE_SIZE	16
317 #define UNMAP_MAX_RANGES	2048 /* Protocol Max is 4095 */
318 #define UNMAP_BUF_SIZE		((UNMAP_MAX_RANGES * UNMAP_RANGE_SIZE) + \
319 				UNMAP_HEAD_SIZE)
320 
321 #define WS10_MAX_BLKS		0xffff
322 #define WS16_MAX_BLKS		0xffffffff
323 #define ATA_TRIM_MAX_RANGES	((UNMAP_BUF_SIZE / \
324 	(ATA_DSM_RANGE_SIZE * ATA_DSM_BLK_SIZE)) * ATA_DSM_BLK_SIZE)
325 
326 #define DA_WORK_TUR		(1 << 16)
327 
328 typedef enum {
329 	DA_REF_OPEN = 1,
330 	DA_REF_OPEN_HOLD,
331 	DA_REF_CLOSE_HOLD,
332 	DA_REF_PROBE_HOLD,
333 	DA_REF_TUR,
334 	DA_REF_GEOM,
335 	DA_REF_SYSCTL,
336 	DA_REF_REPROBE,
337 	DA_REF_MAX		/* KEEP LAST */
338 } da_ref_token;
339 
340 struct da_softc {
341 	struct   cam_iosched_softc *cam_iosched;
342 	struct	 bio_queue_head delete_run_queue;
343 	LIST_HEAD(, ccb_hdr) pending_ccbs;
344 	int	 refcount;		/* Active xpt_action() calls */
345 	da_state state;
346 	da_flags flags;
347 	da_quirks quirks;
348 	int	 minimum_cmd_size;
349 	int	 mode_page;
350 	int	 error_inject;
351 	int	 trim_max_ranges;
352 	int	 delete_available;	/* Delete methods possibly available */
353 	da_zone_mode			zone_mode;
354 	da_zone_interface		zone_interface;
355 	da_zone_flags			zone_flags;
356 	struct ata_gp_log_dir		ata_logdir;
357 	int				valid_logdir_len;
358 	struct ata_identify_log_pages	ata_iddir;
359 	int				valid_iddir_len;
360 	uint64_t			optimal_seq_zones;
361 	uint64_t			optimal_nonseq_zones;
362 	uint64_t			max_seq_zones;
363 	u_int			maxio;
364 	uint32_t		unmap_max_ranges;
365 	uint32_t		unmap_max_lba; /* Max LBAs in UNMAP req */
366 	uint32_t		unmap_gran;
367 	uint32_t		unmap_gran_align;
368 	uint64_t		ws_max_blks;
369 	uint64_t		trim_count;
370 	uint64_t		trim_ranges;
371 	uint64_t		trim_lbas;
372 	da_delete_methods	delete_method_pref;
373 	da_delete_methods	delete_method;
374 	da_delete_func_t	*delete_func;
375 	int			p_type;
376 	struct	 disk_params params;
377 	struct	 disk *disk;
378 	struct task		sysctl_task;
379 	struct sysctl_ctx_list	sysctl_ctx;
380 	struct sysctl_oid	*sysctl_tree;
381 	struct callout		sendordered_c;
382 	uint64_t wwpn;
383 	uint8_t	 unmap_buf[UNMAP_BUF_SIZE];
384 	struct scsi_read_capacity_data_long rcaplong;
385 	struct callout		mediapoll_c;
386 	int			ref_flags[DA_REF_MAX];
387 #ifdef CAM_IO_STATS
388 	struct sysctl_ctx_list	sysctl_stats_ctx;
389 	struct sysctl_oid	*sysctl_stats_tree;
390 	u_int	errors;
391 	u_int	timeouts;
392 	u_int	invalidations;
393 #endif
394 #define DA_ANNOUNCETMP_SZ 160
395 	char			announce_temp[DA_ANNOUNCETMP_SZ];
396 #define DA_ANNOUNCE_SZ 400
397 	char			announcebuf[DA_ANNOUNCE_SZ];
398 };
399 
400 #define dadeleteflag(softc, delete_method, enable)			\
401 	if (enable) {							\
402 		softc->delete_available |= (1 << delete_method);	\
403 	} else {							\
404 		softc->delete_available &= ~(1 << delete_method);	\
405 	}
406 
407 static uma_zone_t da_ccb_zone;
408 
409 struct da_quirk_entry {
410 	struct scsi_inquiry_pattern inq_pat;
411 	da_quirks quirks;
412 };
413 
414 static const char quantum[] = "QUANTUM";
415 static const char microp[] = "MICROP";
416 
417 static struct da_quirk_entry da_quirk_table[] =
418 {
419 	/* SPI, FC devices */
420 	{
421 		/*
422 		 * Fujitsu M2513A MO drives.
423 		 * Tested devices: M2513A2 firmware versions 1200 & 1300.
424 		 * (dip switch selects whether T_DIRECT or T_OPTICAL device)
425 		 * Reported by: W.Scholten <whs@xs4all.nl>
426 		 */
427 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
428 		/*quirks*/ DA_Q_NO_SYNC_CACHE
429 	},
430 	{
431 		/* See above. */
432 		{T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
433 		/*quirks*/ DA_Q_NO_SYNC_CACHE
434 	},
435 	{
436 		/*
437 		 * This particular Fujitsu drive doesn't like the
438 		 * synchronize cache command.
439 		 * Reported by: Tom Jackson <toj@gorilla.net>
440 		 */
441 		{T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
442 		/*quirks*/ DA_Q_NO_SYNC_CACHE
443 	},
444 	{
445 		/*
446 		 * This drive doesn't like the synchronize cache command
447 		 * either.  Reported by: Matthew Jacob <mjacob@feral.com>
448 		 * in NetBSD PR kern/6027, August 24, 1998.
449 		 */
450 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
451 		/*quirks*/ DA_Q_NO_SYNC_CACHE
452 	},
453 	{
454 		/*
455 		 * This drive doesn't like the synchronize cache command
456 		 * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
457 		 * (PR 8882).
458 		 */
459 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
460 		/*quirks*/ DA_Q_NO_SYNC_CACHE
461 	},
462 	{
463 		/*
464 		 * Doesn't like the synchronize cache command.
465 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
466 		 */
467 		{T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
468 		/*quirks*/ DA_Q_NO_SYNC_CACHE
469 	},
470 	{
471 		/*
472 		 * Doesn't like the synchronize cache command.
473 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
474 		 */
475 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
476 		/*quirks*/ DA_Q_NO_SYNC_CACHE
477 	},
478 	{
479 		/*
480 		 * Doesn't like the synchronize cache command.
481 		 */
482 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
483 		/*quirks*/ DA_Q_NO_SYNC_CACHE
484 	},
485 	{
486 		/*
487 		 * Doesn't like the synchronize cache command.
488 		 * Reported by: walter@pelissero.de
489 		 */
490 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS540S", "*"},
491 		/*quirks*/ DA_Q_NO_SYNC_CACHE
492 	},
493 	{
494 		/*
495 		 * Doesn't work correctly with 6 byte reads/writes.
496 		 * Returns illegal request, and points to byte 9 of the
497 		 * 6-byte CDB.
498 		 * Reported by:  Adam McDougall <bsdx@spawnet.com>
499 		 */
500 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
501 		/*quirks*/ DA_Q_NO_6_BYTE
502 	},
503 	{
504 		/* See above. */
505 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
506 		/*quirks*/ DA_Q_NO_6_BYTE
507 	},
508 	{
509 		/*
510 		 * Doesn't like the synchronize cache command.
511 		 * Reported by: walter@pelissero.de
512 		 */
513 		{T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CP3500*", "*"},
514 		/*quirks*/ DA_Q_NO_SYNC_CACHE
515 	},
516 	{
517 		/*
518 		 * The CISS RAID controllers do not support SYNC_CACHE
519 		 */
520 		{T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"},
521 		/*quirks*/ DA_Q_NO_SYNC_CACHE
522 	},
523 	{
524 		/*
525 		 * The STEC SSDs sometimes hang on UNMAP.
526 		 */
527 		{T_DIRECT, SIP_MEDIA_FIXED, "STEC", "*", "*"},
528 		/*quirks*/ DA_Q_NO_UNMAP
529 	},
530 	{
531 		/*
532 		 * VMware returns BUSY status when storage has transient
533 		 * connectivity problems, so better wait.
534 		 * Also VMware returns odd errors on misaligned UNMAPs.
535 		 */
536 		{T_DIRECT, SIP_MEDIA_FIXED, "VMware*", "*", "*"},
537 		/*quirks*/ DA_Q_RETRY_BUSY | DA_Q_STRICT_UNMAP
538 	},
539 	/* USB mass storage devices supported by umass(4) */
540 	{
541 		/*
542 		 * EXATELECOM (Sigmatel) i-Bead 100/105 USB Flash MP3 Player
543 		 * PR: kern/51675
544 		 */
545 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EXATEL", "i-BEAD10*", "*"},
546 		/*quirks*/ DA_Q_NO_SYNC_CACHE
547 	},
548 	{
549 		/*
550 		 * Power Quotient Int. (PQI) USB flash key
551 		 * PR: kern/53067
552 		 */
553 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "USB Flash Disk*",
554 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
555 	},
556 	{
557 		/*
558 		 * Creative Nomad MUVO mp3 player (USB)
559 		 * PR: kern/53094
560 		 */
561 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"},
562 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
563 	},
564 	{
565 		/*
566 		 * Jungsoft NEXDISK USB flash key
567 		 * PR: kern/54737
568 		 */
569 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JUNGSOFT", "NEXDISK*", "*"},
570 		/*quirks*/ DA_Q_NO_SYNC_CACHE
571 	},
572 	{
573 		/*
574 		 * FreeDik USB Mini Data Drive
575 		 * PR: kern/54786
576 		 */
577 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FreeDik*", "Mini Data Drive",
578 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
579 	},
580 	{
581 		/*
582 		 * Sigmatel USB Flash MP3 Player
583 		 * PR: kern/57046
584 		 */
585 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SigmaTel", "MSCN", "*"},
586 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
587 	},
588 	{
589 		/*
590 		 * Neuros USB Digital Audio Computer
591 		 * PR: kern/63645
592 		 */
593 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "NEUROS", "dig. audio comp.",
594 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
595 	},
596 	{
597 		/*
598 		 * SEAGRAND NP-900 MP3 Player
599 		 * PR: kern/64563
600 		 */
601 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SEAGRAND", "NP-900*", "*"},
602 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
603 	},
604 	{
605 		/*
606 		 * iRiver iFP MP3 player (with UMS Firmware)
607 		 * PR: kern/54881, i386/63941, kern/66124
608 		 */
609 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iRiver", "iFP*", "*"},
610 		/*quirks*/ DA_Q_NO_SYNC_CACHE
611 	},
612 	{
613 		/*
614 		 * Frontier Labs NEX IA+ Digital Audio Player, rev 1.10/0.01
615 		 * PR: kern/70158
616 		 */
617 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FL" , "Nex*", "*"},
618 		/*quirks*/ DA_Q_NO_SYNC_CACHE
619 	},
620 	{
621 		/*
622 		 * ZICPlay USB MP3 Player with FM
623 		 * PR: kern/75057
624 		 */
625 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ACTIONS*" , "USB DISK*", "*"},
626 		/*quirks*/ DA_Q_NO_SYNC_CACHE
627 	},
628 	{
629 		/*
630 		 * TEAC USB floppy mechanisms
631 		 */
632 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TEAC" , "FD-05*", "*"},
633 		/*quirks*/ DA_Q_NO_SYNC_CACHE
634 	},
635 	{
636 		/*
637 		 * Kingston DataTraveler II+ USB Pen-Drive.
638 		 * Reported by: Pawel Jakub Dawidek <pjd@FreeBSD.org>
639 		 */
640 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston" , "DataTraveler II+",
641 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
642 	},
643 	{
644 		/*
645 		 * USB DISK Pro PMAP
646 		 * Reported by: jhs
647 		 * PR: usb/96381
648 		 */
649 		{T_DIRECT, SIP_MEDIA_REMOVABLE, " ", "USB DISK Pro", "PMAP"},
650 		/*quirks*/ DA_Q_NO_SYNC_CACHE
651 	},
652 	{
653 		/*
654 		 * Motorola E398 Mobile Phone (TransFlash memory card).
655 		 * Reported by: Wojciech A. Koszek <dunstan@FreeBSD.czest.pl>
656 		 * PR: usb/89889
657 		 */
658 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Motorola" , "Motorola Phone",
659 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
660 	},
661 	{
662 		/*
663 		 * Qware BeatZkey! Pro
664 		 * PR: usb/79164
665 		 */
666 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "GENERIC", "USB DISK DEVICE",
667 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
668 	},
669 	{
670 		/*
671 		 * Time DPA20B 1GB MP3 Player
672 		 * PR: usb/81846
673 		 */
674 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB2.0*", "(FS) FLASH DISK*",
675 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
676 	},
677 	{
678 		/*
679 		 * Samsung USB key 128Mb
680 		 * PR: usb/90081
681 		 */
682 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB-DISK", "FreeDik-FlashUsb",
683 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
684 	},
685 	{
686 		/*
687 		 * Kingston DataTraveler 2.0 USB Flash memory.
688 		 * PR: usb/89196
689 		 */
690 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler 2.0",
691 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
692 	},
693 	{
694 		/*
695 		 * Creative MUVO Slim mp3 player (USB)
696 		 * PR: usb/86131
697 		 */
698 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "MuVo Slim",
699 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
700 		},
701 	{
702 		/*
703 		 * United MP5512 Portable MP3 Player (2-in-1 USB DISK/MP3)
704 		 * PR: usb/80487
705 		 */
706 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "MUSIC DISK",
707 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
708 	},
709 	{
710 		/*
711 		 * SanDisk Micro Cruzer 128MB
712 		 * PR: usb/75970
713 		 */
714 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SanDisk" , "Micro Cruzer",
715 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
716 	},
717 	{
718 		/*
719 		 * TOSHIBA TransMemory USB sticks
720 		 * PR: kern/94660
721 		 */
722 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TOSHIBA", "TransMemory",
723 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
724 	},
725 	{
726 		/*
727 		 * PNY USB 3.0 Flash Drives
728 		*/
729 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "PNY", "USB 3.0 FD*",
730 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_RC16
731 	},
732 	{
733 		/*
734 		 * PNY USB Flash keys
735 		 * PR: usb/75578, usb/72344, usb/65436
736 		 */
737 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "*" , "USB DISK*",
738 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
739 	},
740 	{
741 		/*
742 		 * Genesys GL3224
743 		 */
744 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "STORAGE DEVICE*",
745 		"120?"}, /*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_4K | DA_Q_NO_RC16
746 	},
747 	{
748 		/*
749 		 * Genesys 6-in-1 Card Reader
750 		 * PR: usb/94647
751 		 */
752 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "STORAGE DEVICE*",
753 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
754 	},
755 	{
756 		/*
757 		 * Rekam Digital CAMERA
758 		 * PR: usb/98713
759 		 */
760 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CAMERA*", "4MP-9J6*",
761 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
762 	},
763 	{
764 		/*
765 		 * iRiver H10 MP3 player
766 		 * PR: usb/102547
767 		 */
768 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "H10*",
769 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
770 	},
771 	{
772 		/*
773 		 * iRiver U10 MP3 player
774 		 * PR: usb/92306
775 		 */
776 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "U10*",
777 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
778 	},
779 	{
780 		/*
781 		 * X-Micro Flash Disk
782 		 * PR: usb/96901
783 		 */
784 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "X-Micro", "Flash Disk",
785 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
786 	},
787 	{
788 		/*
789 		 * EasyMP3 EM732X USB 2.0 Flash MP3 Player
790 		 * PR: usb/96546
791 		 */
792 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EM732X", "MP3 Player*",
793 		"1.00"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
794 	},
795 	{
796 		/*
797 		 * Denver MP3 player
798 		 * PR: usb/107101
799 		 */
800 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "DENVER", "MP3 PLAYER",
801 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
802 	},
803 	{
804 		/*
805 		 * Philips USB Key Audio KEY013
806 		 * PR: usb/68412
807 		 */
808 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "PHILIPS", "Key*", "*"},
809 		/*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
810 	},
811 	{
812 		/*
813 		 * JNC MP3 Player
814 		 * PR: usb/94439
815 		 */
816 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JNC*" , "MP3 Player*",
817 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
818 	},
819 	{
820 		/*
821 		 * SAMSUNG MP0402H
822 		 * PR: usb/108427
823 		 */
824 		{T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "MP0402H", "*"},
825 		/*quirks*/ DA_Q_NO_SYNC_CACHE
826 	},
827 	{
828 		/*
829 		 * I/O Magic USB flash - Giga Bank
830 		 * PR: usb/108810
831 		 */
832 		{T_DIRECT, SIP_MEDIA_FIXED, "GS-Magic", "stor*", "*"},
833 		/*quirks*/ DA_Q_NO_SYNC_CACHE
834 	},
835 	{
836 		/*
837 		 * JoyFly 128mb USB Flash Drive
838 		 * PR: 96133
839 		 */
840 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "Flash Disk*",
841 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
842 	},
843 	{
844 		/*
845 		 * ChipsBnk usb stick
846 		 * PR: 103702
847 		 */
848 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ChipsBnk", "USB*",
849 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
850 	},
851 	{
852 		/*
853 		 * Storcase (Kingston) InfoStation IFS FC2/SATA-R 201A
854 		 * PR: 129858
855 		 */
856 		{T_DIRECT, SIP_MEDIA_FIXED, "IFS", "FC2/SATA-R*",
857 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
858 	},
859 	{
860 		/*
861 		 * Samsung YP-U3 mp3-player
862 		 * PR: 125398
863 		 */
864 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Samsung", "YP-U3",
865 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
866 	},
867 	{
868 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Netac", "OnlyDisk*",
869 		 "2000"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
870 	},
871 	{
872 		/*
873 		 * Sony Cyber-Shot DSC cameras
874 		 * PR: usb/137035
875 		 */
876 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
877 		/*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
878 	},
879 	{
880 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler G3",
881 		 "1.00"}, /*quirks*/ DA_Q_NO_PREVENT
882 	},
883 	{
884 		/* At least several Transcent USB sticks lie on RC16. */
885 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JetFlash", "Transcend*",
886 		 "*"}, /*quirks*/ DA_Q_NO_RC16
887 	},
888 	{
889 		/*
890 		 * I-O Data USB Flash Disk
891 		 * PR: usb/211716
892 		 */
893 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "I-O DATA", "USB Flash Disk*",
894 		 "*"}, /*quirks*/ DA_Q_NO_RC16
895 	},
896 	{
897 		/*
898 		 * SLC CHIPFANCIER USB drives
899 		 * PR: usb/234503 (RC10 right, RC16 wrong)
900 		 * 16GB, 32GB and 128GB confirmed to have same issue
901 		 */
902 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "*SLC", "CHIPFANCIER",
903 		 "*"}, /*quirks*/ DA_Q_NO_RC16
904        },
905 	/* ATA/SATA devices over SAS/USB/... */
906 	{
907 		/* Sandisk X400 */
908 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SanDisk SD8SB8U1*", "*" },
909 		/*quirks*/DA_Q_128KB
910 	},
911 	{
912 		/* Hitachi Advanced Format (4k) drives */
913 		{ T_DIRECT, SIP_MEDIA_FIXED, "Hitachi", "H??????????E3*", "*" },
914 		/*quirks*/DA_Q_4K
915 	},
916 	{
917 		/* Micron Advanced Format (4k) drives */
918 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Micron 5100 MTFDDAK*", "*" },
919 		/*quirks*/DA_Q_4K
920 	},
921 	{
922 		/* Samsung Advanced Format (4k) drives */
923 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD155UI*", "*" },
924 		/*quirks*/DA_Q_4K
925 	},
926 	{
927 		/* Samsung Advanced Format (4k) drives */
928 		{ T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD155UI*", "*" },
929 		/*quirks*/DA_Q_4K
930 	},
931 	{
932 		/* Samsung Advanced Format (4k) drives */
933 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD204UI*", "*" },
934 		/*quirks*/DA_Q_4K
935 	},
936 	{
937 		/* Samsung Advanced Format (4k) drives */
938 		{ T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD204UI*", "*" },
939 		/*quirks*/DA_Q_4K
940 	},
941 	{
942 		/* Seagate Barracuda Green Advanced Format (4k) drives */
943 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DL*", "*" },
944 		/*quirks*/DA_Q_4K
945 	},
946 	{
947 		/* Seagate Barracuda Green Advanced Format (4k) drives */
948 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST????DL", "*", "*" },
949 		/*quirks*/DA_Q_4K
950 	},
951 	{
952 		/* Seagate Barracuda Green Advanced Format (4k) drives */
953 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???DM*", "*" },
954 		/*quirks*/DA_Q_4K
955 	},
956 	{
957 		/* Seagate Barracuda Green Advanced Format (4k) drives */
958 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST???DM*", "*", "*" },
959 		/*quirks*/DA_Q_4K
960 	},
961 	{
962 		/* Seagate Barracuda Green Advanced Format (4k) drives */
963 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DM*", "*" },
964 		/*quirks*/DA_Q_4K
965 	},
966 	{
967 		/* Seagate Barracuda Green Advanced Format (4k) drives */
968 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST????DM", "*", "*" },
969 		/*quirks*/DA_Q_4K
970 	},
971 	{
972 		/* Seagate Momentus Advanced Format (4k) drives */
973 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500423AS*", "*" },
974 		/*quirks*/DA_Q_4K
975 	},
976 	{
977 		/* Seagate Momentus Advanced Format (4k) drives */
978 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "3AS*", "*" },
979 		/*quirks*/DA_Q_4K
980 	},
981 	{
982 		/* Seagate Momentus Advanced Format (4k) drives */
983 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500424AS*", "*" },
984 		/*quirks*/DA_Q_4K
985 	},
986 	{
987 		/* Seagate Momentus Advanced Format (4k) drives */
988 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "4AS*", "*" },
989 		/*quirks*/DA_Q_4K
990 	},
991 	{
992 		/* Seagate Momentus Advanced Format (4k) drives */
993 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640423AS*", "*" },
994 		/*quirks*/DA_Q_4K
995 	},
996 	{
997 		/* Seagate Momentus Advanced Format (4k) drives */
998 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "3AS*", "*" },
999 		/*quirks*/DA_Q_4K
1000 	},
1001 	{
1002 		/* Seagate Momentus Advanced Format (4k) drives */
1003 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640424AS*", "*" },
1004 		/*quirks*/DA_Q_4K
1005 	},
1006 	{
1007 		/* Seagate Momentus Advanced Format (4k) drives */
1008 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "4AS*", "*" },
1009 		/*quirks*/DA_Q_4K
1010 	},
1011 	{
1012 		/* Seagate Momentus Advanced Format (4k) drives */
1013 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750420AS*", "*" },
1014 		/*quirks*/DA_Q_4K
1015 	},
1016 	{
1017 		/* Seagate Momentus Advanced Format (4k) drives */
1018 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "0AS*", "*" },
1019 		/*quirks*/DA_Q_4K
1020 	},
1021 	{
1022 		/* Seagate Momentus Advanced Format (4k) drives */
1023 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750422AS*", "*" },
1024 		/*quirks*/DA_Q_4K
1025 	},
1026 	{
1027 		/* Seagate Momentus Advanced Format (4k) drives */
1028 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "2AS*", "*" },
1029 		/*quirks*/DA_Q_4K
1030 	},
1031 	{
1032 		/* Seagate Momentus Advanced Format (4k) drives */
1033 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750423AS*", "*" },
1034 		/*quirks*/DA_Q_4K
1035 	},
1036 	{
1037 		/* Seagate Momentus Advanced Format (4k) drives */
1038 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "3AS*", "*" },
1039 		/*quirks*/DA_Q_4K
1040 	},
1041 	{
1042 		/* Seagate Momentus Thin Advanced Format (4k) drives */
1043 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???LT*", "*" },
1044 		/*quirks*/DA_Q_4K
1045 	},
1046 	{
1047 		/* Seagate Momentus Thin Advanced Format (4k) drives */
1048 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST???LT*", "*", "*" },
1049 		/*quirks*/DA_Q_4K
1050 	},
1051 	{
1052 		/* WDC Caviar Green Advanced Format (4k) drives */
1053 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RS*", "*" },
1054 		/*quirks*/DA_Q_4K
1055 	},
1056 	{
1057 		/* WDC Caviar Green Advanced Format (4k) drives */
1058 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RS*", "*" },
1059 		/*quirks*/DA_Q_4K
1060 	},
1061 	{
1062 		/* WDC Caviar Green Advanced Format (4k) drives */
1063 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RX*", "*" },
1064 		/*quirks*/DA_Q_4K
1065 	},
1066 	{
1067 		/* WDC Caviar Green Advanced Format (4k) drives */
1068 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RX*", "*" },
1069 		/*quirks*/DA_Q_4K
1070 	},
1071 	{
1072 		/* WDC Caviar Green Advanced Format (4k) drives */
1073 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RS*", "*" },
1074 		/*quirks*/DA_Q_4K
1075 	},
1076 	{
1077 		/* WDC Caviar Green Advanced Format (4k) drives */
1078 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RS*", "*" },
1079 		/*quirks*/DA_Q_4K
1080 	},
1081 	{
1082 		/* WDC Caviar Green Advanced Format (4k) drives */
1083 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RX*", "*" },
1084 		/*quirks*/DA_Q_4K
1085 	},
1086 	{
1087 		/* WDC Caviar Green Advanced Format (4k) drives */
1088 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RX*", "*" },
1089 		/*quirks*/DA_Q_4K
1090 	},
1091 	{
1092 		/* WDC Scorpio Black Advanced Format (4k) drives */
1093 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PKT*", "*" },
1094 		/*quirks*/DA_Q_4K
1095 	},
1096 	{
1097 		/* WDC Scorpio Black Advanced Format (4k) drives */
1098 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PKT*", "*" },
1099 		/*quirks*/DA_Q_4K
1100 	},
1101 	{
1102 		/* WDC Scorpio Black Advanced Format (4k) drives */
1103 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PKT*", "*" },
1104 		/*quirks*/DA_Q_4K
1105 	},
1106 	{
1107 		/* WDC Scorpio Black Advanced Format (4k) drives */
1108 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PKT*", "*" },
1109 		/*quirks*/DA_Q_4K
1110 	},
1111 	{
1112 		/* WDC Scorpio Blue Advanced Format (4k) drives */
1113 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PVT*", "*" },
1114 		/*quirks*/DA_Q_4K
1115 	},
1116 	{
1117 		/* WDC Scorpio Blue Advanced Format (4k) drives */
1118 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PVT*", "*" },
1119 		/*quirks*/DA_Q_4K
1120 	},
1121 	{
1122 		/* WDC Scorpio Blue Advanced Format (4k) drives */
1123 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PVT*", "*" },
1124 		/*quirks*/DA_Q_4K
1125 	},
1126 	{
1127 		/* WDC Scorpio Blue Advanced Format (4k) drives */
1128 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PVT*", "*" },
1129 		/*quirks*/DA_Q_4K
1130 	},
1131 	{
1132 		/*
1133 		 * Olympus digital cameras (C-3040ZOOM, C-2040ZOOM, C-1)
1134 		 * PR: usb/97472
1135 		 */
1136 		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "C*", "*"},
1137 		/*quirks*/ DA_Q_NO_6_BYTE | DA_Q_NO_SYNC_CACHE
1138 	},
1139 	{
1140 		/*
1141 		 * Olympus digital cameras (D-370)
1142 		 * PR: usb/97472
1143 		 */
1144 		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "D*", "*"},
1145 		/*quirks*/ DA_Q_NO_6_BYTE
1146 	},
1147 	{
1148 		/*
1149 		 * Olympus digital cameras (E-100RS, E-10).
1150 		 * PR: usb/97472
1151 		 */
1152 		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "E*", "*"},
1153 		/*quirks*/ DA_Q_NO_6_BYTE | DA_Q_NO_SYNC_CACHE
1154 	},
1155 	{
1156 		/*
1157 		 * Olympus FE-210 camera
1158 		 */
1159 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "FE210*",
1160 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
1161 	},
1162 	{
1163 		/*
1164 		* Pentax Digital Camera
1165 		* PR: usb/93389
1166 		*/
1167 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "PENTAX", "DIGITAL CAMERA",
1168 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
1169 	},
1170 	{
1171 		/*
1172 		 * LG UP3S MP3 player
1173 		 */
1174 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "LG", "UP3S",
1175 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
1176 	},
1177 	{
1178 		/*
1179 		 * Laser MP3-2GA13 MP3 player
1180 		 */
1181 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "(HS) Flash Disk",
1182 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
1183 	},
1184 	{
1185 		/*
1186 		 * LaCie external 250GB Hard drive des by Porsche
1187 		 * Submitted by: Ben Stuyts <ben@altesco.nl>
1188 		 * PR: 121474
1189 		 */
1190 		{T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HM250JI", "*"},
1191 		/*quirks*/ DA_Q_NO_SYNC_CACHE
1192 	},
1193 	/* SATA SSDs */
1194 	{
1195 		/*
1196 		 * Corsair Force 2 SSDs
1197 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1198 		 */
1199 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair CSSD-F*", "*" },
1200 		/*quirks*/DA_Q_4K
1201 	},
1202 	{
1203 		/*
1204 		 * Corsair Force 3 SSDs
1205 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1206 		 */
1207 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair Force 3*", "*" },
1208 		/*quirks*/DA_Q_4K
1209 	},
1210         {
1211 		/*
1212 		 * Corsair Neutron GTX SSDs
1213 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1214 		 */
1215 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Neutron GTX*", "*" },
1216 		/*quirks*/DA_Q_4K
1217 	},
1218 	{
1219 		/*
1220 		 * Corsair Force GT & GS SSDs
1221 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1222 		 */
1223 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair Force G*", "*" },
1224 		/*quirks*/DA_Q_4K
1225 	},
1226 	{
1227 		/*
1228 		 * Crucial M4 SSDs
1229 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1230 		 */
1231 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "M4-CT???M4SSD2*", "*" },
1232 		/*quirks*/DA_Q_4K
1233 	},
1234 	{
1235 		/*
1236 		 * Crucial RealSSD C300 SSDs
1237 		 * 4k optimised
1238 		 */
1239 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "C300-CTFDDAC???MAG*",
1240 		"*" }, /*quirks*/DA_Q_4K
1241 	},
1242 	{
1243 		/*
1244 		 * Intel 320 Series SSDs
1245 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1246 		 */
1247 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSA2CW*", "*" },
1248 		/*quirks*/DA_Q_4K
1249 	},
1250 	{
1251 		/*
1252 		 * Intel 330 Series SSDs
1253 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1254 		 */
1255 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2CT*", "*" },
1256 		/*quirks*/DA_Q_4K
1257 	},
1258 	{
1259 		/*
1260 		 * Intel 510 Series SSDs
1261 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1262 		 */
1263 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2MH*", "*" },
1264 		/*quirks*/DA_Q_4K
1265 	},
1266 	{
1267 		/*
1268 		 * Intel 520 Series SSDs
1269 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1270 		 */
1271 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2BW*", "*" },
1272 		/*quirks*/DA_Q_4K
1273 	},
1274 	{
1275 		/*
1276 		 * Intel S3610 Series SSDs
1277 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1278 		 */
1279 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2BX*", "*" },
1280 		/*quirks*/DA_Q_4K
1281 	},
1282 	{
1283 		/*
1284 		 * Intel X25-M Series SSDs
1285 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1286 		 */
1287 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSA2M*", "*" },
1288 		/*quirks*/DA_Q_4K
1289 	},
1290 	{
1291 		/*
1292 		 * Kingston E100 Series SSDs
1293 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1294 		 */
1295 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "KINGSTON SE100S3*", "*" },
1296 		/*quirks*/DA_Q_4K
1297 	},
1298 	{
1299 		/*
1300 		 * Kingston HyperX 3k SSDs
1301 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1302 		 */
1303 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "KINGSTON SH103S3*", "*" },
1304 		/*quirks*/DA_Q_4K
1305 	},
1306 	{
1307 		/*
1308 		 * Marvell SSDs (entry taken from OpenSolaris)
1309 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1310 		 */
1311 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "MARVELL SD88SA02*", "*" },
1312 		/*quirks*/DA_Q_4K
1313 	},
1314 	{
1315 		/*
1316 		 * OCZ Agility 2 SSDs
1317 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1318 		 */
1319 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY2*", "*" },
1320 		/*quirks*/DA_Q_4K
1321 	},
1322 	{
1323 		/*
1324 		 * OCZ Agility 3 SSDs
1325 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1326 		 */
1327 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-AGILITY3*", "*" },
1328 		/*quirks*/DA_Q_4K
1329 	},
1330 	{
1331 		/*
1332 		 * OCZ Deneva R Series SSDs
1333 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1334 		 */
1335 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "DENRSTE251M45*", "*" },
1336 		/*quirks*/DA_Q_4K
1337 	},
1338 	{
1339 		/*
1340 		 * OCZ Vertex 2 SSDs (inc pro series)
1341 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1342 		 */
1343 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ?VERTEX2*", "*" },
1344 		/*quirks*/DA_Q_4K
1345 	},
1346 	{
1347 		/*
1348 		 * OCZ Vertex 3 SSDs
1349 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1350 		 */
1351 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-VERTEX3*", "*" },
1352 		/*quirks*/DA_Q_4K
1353 	},
1354 	{
1355 		/*
1356 		 * OCZ Vertex 4 SSDs
1357 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1358 		 */
1359 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-VERTEX4*", "*" },
1360 		/*quirks*/DA_Q_4K
1361 	},
1362 	{
1363 		/*
1364 		 * Samsung 750 Series SSDs
1365 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1366 		 */
1367 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Samsung SSD 750*", "*" },
1368 		/*quirks*/DA_Q_4K
1369 	},
1370 	{
1371 		/*
1372 		 * Samsung 830 Series SSDs
1373 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1374 		 */
1375 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG SSD 830 Series*", "*" },
1376 		/*quirks*/DA_Q_4K
1377 	},
1378 	{
1379 		/*
1380 		 * Samsung 840 SSDs
1381 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1382 		 */
1383 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Samsung SSD 840*", "*" },
1384 		/*quirks*/DA_Q_4K
1385 	},
1386 	{
1387 		/*
1388 		 * Samsung 845 SSDs
1389 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1390 		 */
1391 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Samsung SSD 845*", "*" },
1392 		/*quirks*/DA_Q_4K
1393 	},
1394 	{
1395 		/*
1396 		 * Samsung 850 SSDs
1397 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1398 		 */
1399 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Samsung SSD 850*", "*" },
1400 		/*quirks*/DA_Q_4K
1401 	},
1402 	{
1403 		/*
1404 		 * Samsung 843T Series SSDs (MZ7WD*)
1405 		 * Samsung PM851 Series SSDs (MZ7TE*)
1406 		 * Samsung PM853T Series SSDs (MZ7GE*)
1407 		 * Samsung SM863 Series SSDs (MZ7KM*)
1408 		 * 4k optimised
1409 		 */
1410 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG MZ7*", "*" },
1411 		/*quirks*/DA_Q_4K
1412 	},
1413 	{
1414 		/*
1415 		 * Same as for SAMSUNG MZ7* but enable the quirks for SSD
1416 		 * starting with MZ7* too
1417 		 */
1418 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "MZ7*", "*" },
1419 		/*quirks*/DA_Q_4K
1420 	},
1421 	{
1422 		/*
1423                  * Same as above but enable the quirks for SSD SAMSUNG MZ7*
1424                  * connected via SATA-to-SAS interposer and because of this
1425                  * starting without "ATA"
1426 		 */
1427 		{ T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "MZ7*", "*" },
1428 		/*quirks*/DA_Q_4K
1429 	},
1430 	{
1431 		/*
1432 		 * SuperTalent TeraDrive CT SSDs
1433 		 * 4k optimised & trim only works in 4k requests + 4k aligned
1434 		 */
1435 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "FTM??CT25H*", "*" },
1436 		/*quirks*/DA_Q_4K
1437 	},
1438 	{
1439 		/*
1440 		 * XceedIOPS SATA SSDs
1441 		 * 4k optimised
1442 		 */
1443 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SG9XCS2D*", "*" },
1444 		/*quirks*/DA_Q_4K
1445 	},
1446 	{
1447 		/*
1448 		 * Hama Innostor USB-Stick
1449 		 */
1450 		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "Innostor", "Innostor*", "*" },
1451 		/*quirks*/DA_Q_NO_RC16
1452 	},
1453 	{
1454 		/*
1455 		 * Seagate Lamarr 8TB Shingled Magnetic Recording (SMR)
1456 		 * Drive Managed SATA hard drive.  This drive doesn't report
1457 		 * in firmware that it is a drive managed SMR drive.
1458 		 */
1459 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST8000AS000[23]*", "*" },
1460 		/*quirks*/DA_Q_SMR_DM
1461 	},
1462 	{
1463 		/*
1464 		 * MX-ES USB Drive by Mach Xtreme
1465 		 */
1466 		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "MX", "MXUB3*", "*"},
1467 		/*quirks*/DA_Q_NO_RC16
1468 	},
1469 };
1470 
1471 static	disk_strategy_t	dastrategy;
1472 static	dumper_t	dadump;
1473 static	periph_init_t	dainit;
1474 static	void		daasync(void *callback_arg, u_int32_t code,
1475 				struct cam_path *path, void *arg);
1476 static	void		dasysctlinit(void *context, int pending);
1477 static	int		dasysctlsofttimeout(SYSCTL_HANDLER_ARGS);
1478 static	int		dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
1479 static	int		dadeletemethodsysctl(SYSCTL_HANDLER_ARGS);
1480 static	int		dabitsysctl(SYSCTL_HANDLER_ARGS);
1481 static	int		daflagssysctl(SYSCTL_HANDLER_ARGS);
1482 static	int		dazonemodesysctl(SYSCTL_HANDLER_ARGS);
1483 static	int		dazonesupsysctl(SYSCTL_HANDLER_ARGS);
1484 static	int		dadeletemaxsysctl(SYSCTL_HANDLER_ARGS);
1485 static	void		dadeletemethodset(struct da_softc *softc,
1486 					  da_delete_methods delete_method);
1487 static	off_t		dadeletemaxsize(struct da_softc *softc,
1488 					da_delete_methods delete_method);
1489 static	void		dadeletemethodchoose(struct da_softc *softc,
1490 					     da_delete_methods default_method);
1491 static	void		daprobedone(struct cam_periph *periph, union ccb *ccb);
1492 
1493 static	periph_ctor_t	daregister;
1494 static	periph_dtor_t	dacleanup;
1495 static	periph_start_t	dastart;
1496 static	periph_oninv_t	daoninvalidate;
1497 static	void		dazonedone(struct cam_periph *periph, union ccb *ccb);
1498 static	void		dadone(struct cam_periph *periph,
1499 			       union ccb *done_ccb);
1500 static void		dadone_probewp(struct cam_periph *periph,
1501 				       union ccb *done_ccb);
1502 static void		dadone_proberc(struct cam_periph *periph,
1503 				       union ccb *done_ccb);
1504 static void		dadone_probelbp(struct cam_periph *periph,
1505 					union ccb *done_ccb);
1506 static void		dadone_probeblklimits(struct cam_periph *periph,
1507 					      union ccb *done_ccb);
1508 static void		dadone_probebdc(struct cam_periph *periph,
1509 					union ccb *done_ccb);
1510 static void		dadone_probeata(struct cam_periph *periph,
1511 					union ccb *done_ccb);
1512 static void		dadone_probeatalogdir(struct cam_periph *periph,
1513 					      union ccb *done_ccb);
1514 static void		dadone_probeataiddir(struct cam_periph *periph,
1515 					     union ccb *done_ccb);
1516 static void		dadone_probeatasup(struct cam_periph *periph,
1517 					   union ccb *done_ccb);
1518 static void		dadone_probeatazone(struct cam_periph *periph,
1519 					    union ccb *done_ccb);
1520 static void		dadone_probezone(struct cam_periph *periph,
1521 					 union ccb *done_ccb);
1522 static void		dadone_tur(struct cam_periph *periph,
1523 				   union ccb *done_ccb);
1524 static  int		daerror(union ccb *ccb, u_int32_t cam_flags,
1525 				u_int32_t sense_flags);
1526 static void		daprevent(struct cam_periph *periph, int action);
1527 static void		dareprobe(struct cam_periph *periph);
1528 static void		dasetgeom(struct cam_periph *periph, uint32_t block_len,
1529 				  uint64_t maxsector,
1530 				  struct scsi_read_capacity_data_long *rcaplong,
1531 				  size_t rcap_size);
1532 static callout_func_t	dasendorderedtag;
1533 static void		dashutdown(void *arg, int howto);
1534 static callout_func_t	damediapoll;
1535 
1536 #ifndef	DA_DEFAULT_POLL_PERIOD
1537 #define	DA_DEFAULT_POLL_PERIOD	3
1538 #endif
1539 
1540 #ifndef DA_DEFAULT_TIMEOUT
1541 #define DA_DEFAULT_TIMEOUT 60	/* Timeout in seconds */
1542 #endif
1543 
1544 #ifndef DA_DEFAULT_SOFTTIMEOUT
1545 #define DA_DEFAULT_SOFTTIMEOUT	0
1546 #endif
1547 
1548 #ifndef	DA_DEFAULT_RETRY
1549 #define	DA_DEFAULT_RETRY	4
1550 #endif
1551 
1552 #ifndef	DA_DEFAULT_SEND_ORDERED
1553 #define	DA_DEFAULT_SEND_ORDERED	1
1554 #endif
1555 
1556 static int da_poll_period = DA_DEFAULT_POLL_PERIOD;
1557 static int da_retry_count = DA_DEFAULT_RETRY;
1558 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
1559 static sbintime_t da_default_softtimeout = DA_DEFAULT_SOFTTIMEOUT;
1560 static int da_send_ordered = DA_DEFAULT_SEND_ORDERED;
1561 static int da_disable_wp_detection = 0;
1562 static int da_enable_biospeedup = 1;
1563 static int da_enable_uma_ccbs = 1;
1564 
1565 static SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1566     "CAM Direct Access Disk driver");
1567 SYSCTL_INT(_kern_cam_da, OID_AUTO, poll_period, CTLFLAG_RWTUN,
1568            &da_poll_period, 0, "Media polling period in seconds");
1569 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RWTUN,
1570            &da_retry_count, 0, "Normal I/O retry count");
1571 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RWTUN,
1572            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
1573 SYSCTL_INT(_kern_cam_da, OID_AUTO, send_ordered, CTLFLAG_RWTUN,
1574            &da_send_ordered, 0, "Send Ordered Tags");
1575 SYSCTL_INT(_kern_cam_da, OID_AUTO, disable_wp_detection, CTLFLAG_RWTUN,
1576            &da_disable_wp_detection, 0,
1577 	   "Disable detection of write-protected disks");
1578 SYSCTL_INT(_kern_cam_da, OID_AUTO, enable_biospeedup, CTLFLAG_RDTUN,
1579 	    &da_enable_biospeedup, 0, "Enable BIO_SPEEDUP processing");
1580 SYSCTL_INT(_kern_cam_da, OID_AUTO, enable_uma_ccbs, CTLFLAG_RWTUN,
1581 	    &da_enable_uma_ccbs, 0, "Use UMA for CCBs");
1582 
1583 SYSCTL_PROC(_kern_cam_da, OID_AUTO, default_softtimeout,
1584     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
1585     dasysctlsofttimeout, "I",
1586     "Soft I/O timeout (ms)");
1587 TUNABLE_INT64("kern.cam.da.default_softtimeout", &da_default_softtimeout);
1588 
1589 /*
1590  * DA_ORDEREDTAG_INTERVAL determines how often, relative
1591  * to the default timeout, we check to see whether an ordered
1592  * tagged transaction is appropriate to prevent simple tag
1593  * starvation.  Since we'd like to ensure that there is at least
1594  * 1/2 of the timeout length left for a starved transaction to
1595  * complete after we've sent an ordered tag, we must poll at least
1596  * four times in every timeout period.  This takes care of the worst
1597  * case where a starved transaction starts during an interval that
1598  * meets the requirement "don't send an ordered tag" test so it takes
1599  * us two intervals to determine that a tag must be sent.
1600  */
1601 #ifndef DA_ORDEREDTAG_INTERVAL
1602 #define DA_ORDEREDTAG_INTERVAL 4
1603 #endif
1604 
1605 static struct periph_driver dadriver =
1606 {
1607 	dainit, "da",
1608 	TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
1609 };
1610 
1611 PERIPHDRIVER_DECLARE(da, dadriver);
1612 
1613 static MALLOC_DEFINE(M_SCSIDA, "scsi_da", "scsi_da buffers");
1614 
1615 /*
1616  * This driver takes out references / holds in well defined pairs, never
1617  * recursively. These macros / inline functions enforce those rules. They
1618  * are only enabled with DA_TRACK_REFS or INVARIANTS. If DA_TRACK_REFS is
1619  * defined to be 2 or larger, the tracking also includes debug printfs.
1620  */
1621 #if defined(DA_TRACK_REFS) || defined(INVARIANTS)
1622 
1623 #ifndef DA_TRACK_REFS
1624 #define DA_TRACK_REFS 1
1625 #endif
1626 
1627 #if DA_TRACK_REFS > 1
1628 static const char *da_ref_text[] = {
1629 	"bogus",
1630 	"open",
1631 	"open hold",
1632 	"close hold",
1633 	"reprobe hold",
1634 	"Test Unit Ready",
1635 	"Geom",
1636 	"sysctl",
1637 	"reprobe",
1638 	"max -- also bogus"
1639 };
1640 
1641 #define DA_PERIPH_PRINT(periph, msg, args...)		\
1642 	CAM_PERIPH_PRINT(periph, msg, ##args)
1643 #else
1644 #define DA_PERIPH_PRINT(periph, msg, args...)
1645 #endif
1646 
1647 static inline void
1648 token_sanity(da_ref_token token)
1649 {
1650 	if ((unsigned)token >= DA_REF_MAX)
1651 		panic("Bad token value passed in %d\n", token);
1652 }
1653 
1654 static inline int
1655 da_periph_hold(struct cam_periph *periph, int priority, da_ref_token token)
1656 {
1657 	int err = cam_periph_hold(periph, priority);
1658 
1659 	token_sanity(token);
1660 	DA_PERIPH_PRINT(periph, "Holding device %s (%d): %d\n",
1661 	    da_ref_text[token], token, err);
1662 	if (err == 0) {
1663 		int cnt;
1664 		struct da_softc *softc = periph->softc;
1665 
1666 		cnt = atomic_fetchadd_int(&softc->ref_flags[token], 1);
1667 		if (cnt != 0)
1668 			panic("Re-holding for reason %d, cnt = %d", token, cnt);
1669 	}
1670 	return (err);
1671 }
1672 
1673 static inline void
1674 da_periph_unhold(struct cam_periph *periph, da_ref_token token)
1675 {
1676 	int cnt;
1677 	struct da_softc *softc = periph->softc;
1678 
1679 	token_sanity(token);
1680 	DA_PERIPH_PRINT(periph, "Unholding device %s (%d)\n",
1681 	    da_ref_text[token], token);
1682 	cnt = atomic_fetchadd_int(&softc->ref_flags[token], -1);
1683 	if (cnt != 1)
1684 		panic("Unholding %d with cnt = %d", token, cnt);
1685 	cam_periph_unhold(periph);
1686 }
1687 
1688 static inline int
1689 da_periph_acquire(struct cam_periph *periph, da_ref_token token)
1690 {
1691 	int err = cam_periph_acquire(periph);
1692 
1693 	token_sanity(token);
1694 	DA_PERIPH_PRINT(periph, "acquiring device %s (%d): %d\n",
1695 	    da_ref_text[token], token, err);
1696 	if (err == 0) {
1697 		int cnt;
1698 		struct da_softc *softc = periph->softc;
1699 
1700 		cnt = atomic_fetchadd_int(&softc->ref_flags[token], 1);
1701 		if (cnt != 0)
1702 			panic("Re-refing for reason %d, cnt = %d", token, cnt);
1703 	}
1704 	return (err);
1705 }
1706 
1707 static inline void
1708 da_periph_release(struct cam_periph *periph, da_ref_token token)
1709 {
1710 	int cnt;
1711 	struct da_softc *softc = periph->softc;
1712 
1713 	token_sanity(token);
1714 	DA_PERIPH_PRINT(periph, "releasing device %s (%d)\n",
1715 	    da_ref_text[token], token);
1716 	cnt = atomic_fetchadd_int(&softc->ref_flags[token], -1);
1717 	if (cnt != 1)
1718 		panic("Releasing %d with cnt = %d", token, cnt);
1719 	cam_periph_release(periph);
1720 }
1721 
1722 static inline void
1723 da_periph_release_locked(struct cam_periph *periph, da_ref_token token)
1724 {
1725 	int cnt;
1726 	struct da_softc *softc = periph->softc;
1727 
1728 	token_sanity(token);
1729 	DA_PERIPH_PRINT(periph, "releasing device (locked) %s (%d)\n",
1730 	    da_ref_text[token], token);
1731 	cnt = atomic_fetchadd_int(&softc->ref_flags[token], -1);
1732 	if (cnt != 1)
1733 		panic("releasing (locked) %d with cnt = %d", token, cnt);
1734 	cam_periph_release_locked(periph);
1735 }
1736 
1737 #define cam_periph_hold POISON
1738 #define cam_periph_unhold POISON
1739 #define cam_periph_acquire POISON
1740 #define cam_periph_release POISON
1741 #define cam_periph_release_locked POISON
1742 
1743 #else
1744 #define	da_periph_hold(periph, prio, token)	cam_periph_hold((periph), (prio))
1745 #define da_periph_unhold(periph, token)		cam_periph_unhold((periph))
1746 #define da_periph_acquire(periph, token)	cam_periph_acquire((periph))
1747 #define da_periph_release(periph, token)	cam_periph_release((periph))
1748 #define da_periph_release_locked(periph, token)	cam_periph_release_locked((periph))
1749 #endif
1750 
1751 static int
1752 daopen(struct disk *dp)
1753 {
1754 	struct cam_periph *periph;
1755 	struct da_softc *softc;
1756 	int error;
1757 
1758 	periph = (struct cam_periph *)dp->d_drv1;
1759 	if (da_periph_acquire(periph, DA_REF_OPEN) != 0) {
1760 		return (ENXIO);
1761 	}
1762 
1763 	cam_periph_lock(periph);
1764 	if ((error = da_periph_hold(periph, PRIBIO|PCATCH, DA_REF_OPEN_HOLD)) != 0) {
1765 		cam_periph_unlock(periph);
1766 		da_periph_release(periph, DA_REF_OPEN);
1767 		return (error);
1768 	}
1769 
1770 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1771 	    ("daopen\n"));
1772 
1773 	softc = (struct da_softc *)periph->softc;
1774 	dareprobe(periph);
1775 
1776 	/* Wait for the disk size update.  */
1777 	error = cam_periph_sleep(periph, &softc->disk->d_mediasize, PRIBIO,
1778 	    "dareprobe", 0);
1779 	if (error != 0)
1780 		xpt_print(periph->path, "unable to retrieve capacity data\n");
1781 
1782 	if (periph->flags & CAM_PERIPH_INVALID)
1783 		error = ENXIO;
1784 
1785 	if (error == 0 && (softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
1786 	    (softc->quirks & DA_Q_NO_PREVENT) == 0)
1787 		daprevent(periph, PR_PREVENT);
1788 
1789 	if (error == 0) {
1790 		softc->flags &= ~DA_FLAG_PACK_INVALID;
1791 		softc->flags |= DA_FLAG_OPEN;
1792 	}
1793 
1794 	da_periph_unhold(periph, DA_REF_OPEN_HOLD);
1795 	cam_periph_unlock(periph);
1796 
1797 	if (error != 0)
1798 		da_periph_release(periph, DA_REF_OPEN);
1799 
1800 	return (error);
1801 }
1802 
1803 static int
1804 daclose(struct disk *dp)
1805 {
1806 	struct	cam_periph *periph;
1807 	struct	da_softc *softc;
1808 	union	ccb *ccb;
1809 
1810 	periph = (struct cam_periph *)dp->d_drv1;
1811 	softc = (struct da_softc *)periph->softc;
1812 	cam_periph_lock(periph);
1813 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1814 	    ("daclose\n"));
1815 
1816 	if (da_periph_hold(periph, PRIBIO, DA_REF_CLOSE_HOLD) == 0) {
1817 		/* Flush disk cache. */
1818 		if ((softc->flags & DA_FLAG_DIRTY) != 0 &&
1819 		    (softc->quirks & DA_Q_NO_SYNC_CACHE) == 0 &&
1820 		    (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
1821 			ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1822 			scsi_synchronize_cache(&ccb->csio, /*retries*/1,
1823 			    /*cbfcnp*/NULL, MSG_SIMPLE_Q_TAG,
1824 			    /*begin_lba*/0, /*lb_count*/0, SSD_FULL_SIZE,
1825 			    5 * 60 * 1000);
1826 			cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
1827 			    /*sense_flags*/SF_RETRY_UA | SF_QUIET_IR,
1828 			    softc->disk->d_devstat);
1829 			softc->flags &= ~DA_FLAG_DIRTY;
1830 			xpt_release_ccb(ccb);
1831 		}
1832 
1833 		/* Allow medium removal. */
1834 		if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
1835 		    (softc->quirks & DA_Q_NO_PREVENT) == 0)
1836 			daprevent(periph, PR_ALLOW);
1837 
1838 		da_periph_unhold(periph, DA_REF_CLOSE_HOLD);
1839 	}
1840 
1841 	/*
1842 	 * If we've got removable media, mark the blocksize as
1843 	 * unavailable, since it could change when new media is
1844 	 * inserted.
1845 	 */
1846 	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0)
1847 		softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1848 
1849 	softc->flags &= ~DA_FLAG_OPEN;
1850 	while (softc->refcount != 0)
1851 		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "daclose", 1);
1852 	cam_periph_unlock(periph);
1853 	da_periph_release(periph, DA_REF_OPEN);
1854 	return (0);
1855 }
1856 
1857 static void
1858 daschedule(struct cam_periph *periph)
1859 {
1860 	struct da_softc *softc = (struct da_softc *)periph->softc;
1861 
1862 	if (softc->state != DA_STATE_NORMAL)
1863 		return;
1864 
1865 	cam_iosched_schedule(softc->cam_iosched, periph);
1866 }
1867 
1868 /*
1869  * Actually translate the requested transfer into one the physical driver
1870  * can understand.  The transfer is described by a buf and will include
1871  * only one physical transfer.
1872  */
1873 static void
1874 dastrategy(struct bio *bp)
1875 {
1876 	struct cam_periph *periph;
1877 	struct da_softc *softc;
1878 
1879 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1880 	softc = (struct da_softc *)periph->softc;
1881 
1882 	cam_periph_lock(periph);
1883 
1884 	/*
1885 	 * If the device has been made invalid, error out
1886 	 */
1887 	if ((softc->flags & DA_FLAG_PACK_INVALID)) {
1888 		cam_periph_unlock(periph);
1889 		biofinish(bp, NULL, ENXIO);
1890 		return;
1891 	}
1892 
1893 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastrategy(%p)\n", bp));
1894 
1895 	/*
1896 	 * Zone commands must be ordered, because they can depend on the
1897 	 * effects of previously issued commands, and they may affect
1898 	 * commands after them.
1899 	 */
1900 	if (bp->bio_cmd == BIO_ZONE)
1901 		bp->bio_flags |= BIO_ORDERED;
1902 
1903 	/*
1904 	 * Place it in the queue of disk activities for this disk
1905 	 */
1906 	cam_iosched_queue_work(softc->cam_iosched, bp);
1907 
1908 	/*
1909 	 * Schedule ourselves for performing the work.
1910 	 */
1911 	daschedule(periph);
1912 	cam_periph_unlock(periph);
1913 
1914 	return;
1915 }
1916 
1917 static int
1918 dadump(void *arg, void *virtual, off_t offset, size_t length)
1919 {
1920 	struct	    cam_periph *periph;
1921 	struct	    da_softc *softc;
1922 	u_int	    secsize;
1923 	struct	    ccb_scsiio csio;
1924 	struct	    disk *dp;
1925 	int	    error = 0;
1926 
1927 	dp = arg;
1928 	periph = dp->d_drv1;
1929 	softc = (struct da_softc *)periph->softc;
1930 	secsize = softc->params.secsize;
1931 
1932 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0)
1933 		return (ENXIO);
1934 
1935 	memset(&csio, 0, sizeof(csio));
1936 	if (length > 0) {
1937 		xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1938 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1939 		scsi_read_write(&csio,
1940 				/*retries*/0,
1941 				/*cbfcnp*/NULL,
1942 				MSG_ORDERED_Q_TAG,
1943 				/*read*/SCSI_RW_WRITE,
1944 				/*byte2*/0,
1945 				/*minimum_cmd_size*/ softc->minimum_cmd_size,
1946 				offset / secsize,
1947 				length / secsize,
1948 				/*data_ptr*/(u_int8_t *) virtual,
1949 				/*dxfer_len*/length,
1950 				/*sense_len*/SSD_FULL_SIZE,
1951 				da_default_timeout * 1000);
1952 		error = cam_periph_runccb((union ccb *)&csio, cam_periph_error,
1953 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1954 		if (error != 0)
1955 			printf("Aborting dump due to I/O error.\n");
1956 		return (error);
1957 	}
1958 
1959 	/*
1960 	 * Sync the disk cache contents to the physical media.
1961 	 */
1962 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
1963 		xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1964 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1965 		scsi_synchronize_cache(&csio,
1966 				       /*retries*/0,
1967 				       /*cbfcnp*/NULL,
1968 				       MSG_SIMPLE_Q_TAG,
1969 				       /*begin_lba*/0,/* Cover the whole disk */
1970 				       /*lb_count*/0,
1971 				       SSD_FULL_SIZE,
1972 				       5 * 1000);
1973 		error = cam_periph_runccb((union ccb *)&csio, cam_periph_error,
1974 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1975 		if (error != 0)
1976 			xpt_print(periph->path, "Synchronize cache failed\n");
1977 	}
1978 	return (error);
1979 }
1980 
1981 static int
1982 dagetattr(struct bio *bp)
1983 {
1984 	int ret;
1985 	struct cam_periph *periph;
1986 
1987 	if (g_handleattr_int(bp, "GEOM::canspeedup", da_enable_biospeedup))
1988 		return (EJUSTRETURN);
1989 
1990 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1991 	cam_periph_lock(periph);
1992 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1993 	    periph->path);
1994 	cam_periph_unlock(periph);
1995 	if (ret == 0)
1996 		bp->bio_completed = bp->bio_length;
1997 	return ret;
1998 }
1999 
2000 static void
2001 dainit(void)
2002 {
2003 	cam_status status;
2004 
2005 	da_ccb_zone = uma_zcreate("da_ccb",
2006 	    sizeof(struct ccb_scsiio), NULL, NULL, NULL, NULL,
2007 	    UMA_ALIGN_PTR, 0);
2008 
2009 	/*
2010 	 * Install a global async callback.  This callback will
2011 	 * receive async callbacks like "new device found".
2012 	 */
2013 	status = xpt_register_async(AC_FOUND_DEVICE, daasync, NULL, NULL);
2014 
2015 	if (status != CAM_REQ_CMP) {
2016 		printf("da: Failed to attach master async callback "
2017 		       "due to status 0x%x!\n", status);
2018 	} else if (da_send_ordered) {
2019 		/* Register our shutdown event handler */
2020 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown,
2021 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
2022 		    printf("dainit: shutdown event registration failed!\n");
2023 	}
2024 }
2025 
2026 /*
2027  * Callback from GEOM, called when it has finished cleaning up its
2028  * resources.
2029  */
2030 static void
2031 dadiskgonecb(struct disk *dp)
2032 {
2033 	struct cam_periph *periph;
2034 
2035 	periph = (struct cam_periph *)dp->d_drv1;
2036 	da_periph_release(periph, DA_REF_GEOM);
2037 }
2038 
2039 static void
2040 daoninvalidate(struct cam_periph *periph)
2041 {
2042 	struct da_softc *softc;
2043 
2044 	cam_periph_assert(periph, MA_OWNED);
2045 	softc = (struct da_softc *)periph->softc;
2046 
2047 	/*
2048 	 * De-register any async callbacks.
2049 	 */
2050 	xpt_register_async(0, daasync, periph, periph->path);
2051 
2052 	softc->flags |= DA_FLAG_PACK_INVALID;
2053 #ifdef CAM_IO_STATS
2054 	softc->invalidations++;
2055 #endif
2056 
2057 	/*
2058 	 * Return all queued I/O with ENXIO. Transactions may be queued up here
2059 	 * for retry (since we are called while there's other transactions
2060 	 * pending). Any requests in the hardware will drain before dacleanup
2061 	 * is called.
2062 	 */
2063 	cam_iosched_flush(softc->cam_iosched, NULL, ENXIO);
2064 
2065 	/*
2066 	 * Tell GEOM that we've gone away, we'll get a callback when it is
2067 	 * done cleaning up its resources.
2068 	 */
2069 	disk_gone(softc->disk);
2070 }
2071 
2072 static void
2073 dacleanup(struct cam_periph *periph)
2074 {
2075 	struct da_softc *softc;
2076 
2077 	softc = (struct da_softc *)periph->softc;
2078 
2079 	cam_periph_unlock(periph);
2080 
2081 	cam_iosched_fini(softc->cam_iosched);
2082 
2083 	/*
2084 	 * If we can't free the sysctl tree, oh well...
2085 	 */
2086 	if ((softc->flags & DA_FLAG_SCTX_INIT) != 0) {
2087 #ifdef CAM_IO_STATS
2088 		if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0)
2089 			xpt_print(periph->path,
2090 			    "can't remove sysctl stats context\n");
2091 #endif
2092 		if (sysctl_ctx_free(&softc->sysctl_ctx) != 0)
2093 			xpt_print(periph->path,
2094 			    "can't remove sysctl context\n");
2095 	}
2096 
2097 	callout_drain(&softc->mediapoll_c);
2098 	disk_destroy(softc->disk);
2099 	callout_drain(&softc->sendordered_c);
2100 	free(softc, M_DEVBUF);
2101 	cam_periph_lock(periph);
2102 }
2103 
2104 static void
2105 daasync(void *callback_arg, u_int32_t code,
2106 	struct cam_path *path, void *arg)
2107 {
2108 	struct cam_periph *periph;
2109 	struct da_softc *softc;
2110 
2111 	periph = (struct cam_periph *)callback_arg;
2112 	switch (code) {
2113 	case AC_FOUND_DEVICE:	/* callback to create periph, no locking yet */
2114 	{
2115 		struct ccb_getdev *cgd;
2116 		cam_status status;
2117 
2118 		cgd = (struct ccb_getdev *)arg;
2119 		if (cgd == NULL)
2120 			break;
2121 
2122 		if (cgd->protocol != PROTO_SCSI)
2123 			break;
2124 		if (SID_QUAL(&cgd->inq_data) != SID_QUAL_LU_CONNECTED)
2125 			break;
2126 		if (SID_TYPE(&cgd->inq_data) != T_DIRECT
2127 		    && SID_TYPE(&cgd->inq_data) != T_RBC
2128 		    && SID_TYPE(&cgd->inq_data) != T_OPTICAL
2129 		    && SID_TYPE(&cgd->inq_data) != T_ZBC_HM)
2130 			break;
2131 
2132 		/*
2133 		 * Allocate a peripheral instance for
2134 		 * this device and start the probe
2135 		 * process.
2136 		 */
2137 		status = cam_periph_alloc(daregister, daoninvalidate,
2138 					  dacleanup, dastart,
2139 					  "da", CAM_PERIPH_BIO,
2140 					  path, daasync,
2141 					  AC_FOUND_DEVICE, cgd);
2142 
2143 		if (status != CAM_REQ_CMP
2144 		 && status != CAM_REQ_INPROG)
2145 			printf("daasync: Unable to attach to new device "
2146 				"due to status 0x%x\n", status);
2147 		return;
2148 	}
2149 	case AC_ADVINFO_CHANGED:	/* Doesn't touch periph */
2150 	{
2151 		uintptr_t buftype;
2152 
2153 		buftype = (uintptr_t)arg;
2154 		if (buftype == CDAI_TYPE_PHYS_PATH) {
2155 			struct da_softc *softc;
2156 
2157 			softc = periph->softc;
2158 			disk_attr_changed(softc->disk, "GEOM::physpath",
2159 					  M_NOWAIT);
2160 		}
2161 		break;
2162 	}
2163 	case AC_UNIT_ATTENTION:		/* Called for this path: periph locked */
2164 	{
2165 		union ccb *ccb;
2166 		int error_code, sense_key, asc, ascq;
2167 
2168 		softc = (struct da_softc *)periph->softc;
2169 		ccb = (union ccb *)arg;
2170 
2171 		/*
2172 		 * Handle all UNIT ATTENTIONs except our own, as they will be
2173 		 * handled by daerror().
2174 		 */
2175 		if (xpt_path_periph(ccb->ccb_h.path) != periph &&
2176 		    scsi_extract_sense_ccb(ccb,
2177 		     &error_code, &sense_key, &asc, &ascq)) {
2178 			if (asc == 0x2A && ascq == 0x09) {
2179 				xpt_print(ccb->ccb_h.path,
2180 				    "Capacity data has changed\n");
2181 				cam_periph_assert(periph, MA_OWNED);
2182 				softc->flags &= ~DA_FLAG_PROBED;
2183 				dareprobe(periph);
2184 			} else if (asc == 0x28 && ascq == 0x00) {
2185 				cam_periph_assert(periph, MA_OWNED);
2186 				softc->flags &= ~DA_FLAG_PROBED;
2187 				disk_media_changed(softc->disk, M_NOWAIT);
2188 			} else if (asc == 0x3F && ascq == 0x03) {
2189 				xpt_print(ccb->ccb_h.path,
2190 				    "INQUIRY data has changed\n");
2191 				cam_periph_assert(periph, MA_OWNED);
2192 				softc->flags &= ~DA_FLAG_PROBED;
2193 				dareprobe(periph);
2194 			}
2195 		}
2196 		break;
2197 	}
2198 	case AC_SCSI_AEN:		/* Called for this path: periph locked */
2199 		/*
2200 		 * Appears to be currently unused for SCSI devices, only ata SIMs
2201 		 * generate this.
2202 		 */
2203 		cam_periph_assert(periph, MA_OWNED);
2204 		softc = (struct da_softc *)periph->softc;
2205 		if (!cam_iosched_has_work_flags(softc->cam_iosched, DA_WORK_TUR) &&
2206 		    (softc->flags & DA_FLAG_TUR_PENDING) == 0) {
2207 			if (da_periph_acquire(periph, DA_REF_TUR) == 0) {
2208 				cam_iosched_set_work_flags(softc->cam_iosched, DA_WORK_TUR);
2209 				daschedule(periph);
2210 			}
2211 		}
2212 		/* FALLTHROUGH */
2213 	case AC_SENT_BDR:		/* Called for this path: periph locked */
2214 	case AC_BUS_RESET:		/* Called for this path: periph locked */
2215 	{
2216 		struct ccb_hdr *ccbh;
2217 
2218 		cam_periph_assert(periph, MA_OWNED);
2219 		softc = (struct da_softc *)periph->softc;
2220 		/*
2221 		 * Don't fail on the expected unit attention
2222 		 * that will occur.
2223 		 */
2224 		softc->flags |= DA_FLAG_RETRY_UA;
2225 		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
2226 			ccbh->ccb_state |= DA_CCB_RETRY_UA;
2227 		break;
2228 	}
2229 	case AC_INQ_CHANGED:		/* Called for this path: periph locked */
2230 		cam_periph_assert(periph, MA_OWNED);
2231 		softc = (struct da_softc *)periph->softc;
2232 		softc->flags &= ~DA_FLAG_PROBED;
2233 		dareprobe(periph);
2234 		break;
2235 	default:
2236 		break;
2237 	}
2238 	cam_periph_async(periph, code, path, arg);
2239 }
2240 
2241 static void
2242 dasysctlinit(void *context, int pending)
2243 {
2244 	struct cam_periph *periph;
2245 	struct da_softc *softc;
2246 	char tmpstr[32], tmpstr2[16];
2247 	struct ccb_trans_settings cts;
2248 
2249 	periph = (struct cam_periph *)context;
2250 	/*
2251 	 * periph was held for us when this task was enqueued
2252 	 */
2253 	if (periph->flags & CAM_PERIPH_INVALID) {
2254 		da_periph_release(periph, DA_REF_SYSCTL);
2255 		return;
2256 	}
2257 
2258 	softc = (struct da_softc *)periph->softc;
2259 	snprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
2260 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
2261 
2262 	sysctl_ctx_init(&softc->sysctl_ctx);
2263 	cam_periph_lock(periph);
2264 	softc->flags |= DA_FLAG_SCTX_INIT;
2265 	cam_periph_unlock(periph);
2266 	softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
2267 		SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
2268 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr, "device_index");
2269 	if (softc->sysctl_tree == NULL) {
2270 		printf("dasysctlinit: unable to allocate sysctl tree\n");
2271 		da_periph_release(periph, DA_REF_SYSCTL);
2272 		return;
2273 	}
2274 
2275 	/*
2276 	 * Now register the sysctl handler, so the user can change the value on
2277 	 * the fly.
2278 	 */
2279 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2280 		OID_AUTO, "delete_method",
2281 		CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
2282 		softc, 0, dadeletemethodsysctl, "A",
2283 		"BIO_DELETE execution method");
2284 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2285 		OID_AUTO, "delete_max",
2286 		CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
2287 		softc, 0, dadeletemaxsysctl, "Q",
2288 		"Maximum BIO_DELETE size");
2289 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2290 		OID_AUTO, "minimum_cmd_size",
2291 		CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2292 		&softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
2293 		"Minimum CDB size");
2294 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
2295 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
2296 		"trim_count", CTLFLAG_RD, &softc->trim_count,
2297 		"Total number of unmap/dsm commands sent");
2298 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
2299 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
2300 		"trim_ranges", CTLFLAG_RD, &softc->trim_ranges,
2301 		"Total number of ranges in unmap/dsm commands");
2302 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
2303 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
2304 		"trim_lbas", CTLFLAG_RD, &softc->trim_lbas,
2305 		"Total lbas in the unmap/dsm commands sent");
2306 
2307 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2308 		OID_AUTO, "zone_mode",
2309 		CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
2310 		softc, 0, dazonemodesysctl, "A",
2311 		"Zone Mode");
2312 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2313 		OID_AUTO, "zone_support",
2314 		CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
2315 		softc, 0, dazonesupsysctl, "A",
2316 		"Zone Support");
2317 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
2318 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
2319 		"optimal_seq_zones", CTLFLAG_RD, &softc->optimal_seq_zones,
2320 		"Optimal Number of Open Sequential Write Preferred Zones");
2321 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
2322 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
2323 		"optimal_nonseq_zones", CTLFLAG_RD,
2324 		&softc->optimal_nonseq_zones,
2325 		"Optimal Number of Non-Sequentially Written Sequential Write "
2326 		"Preferred Zones");
2327 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
2328 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
2329 		"max_seq_zones", CTLFLAG_RD, &softc->max_seq_zones,
2330 		"Maximum Number of Open Sequential Write Required Zones");
2331 
2332 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
2333 		       SYSCTL_CHILDREN(softc->sysctl_tree),
2334 		       OID_AUTO,
2335 		       "error_inject",
2336 		       CTLFLAG_RW,
2337 		       &softc->error_inject,
2338 		       0,
2339 		       "error_inject leaf");
2340 
2341 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
2342 		       SYSCTL_CHILDREN(softc->sysctl_tree),
2343 		       OID_AUTO,
2344 		       "p_type",
2345 		       CTLFLAG_RD,
2346 		       &softc->p_type,
2347 		       0,
2348 		       "DIF protection type");
2349 
2350 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2351 	    OID_AUTO, "flags", CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
2352 	    softc, 0, daflagssysctl, "A",
2353 	    "Flags for drive");
2354 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2355 	    OID_AUTO, "rotating", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
2356 	    &softc->flags, (u_int)DA_FLAG_ROTATING, dabitsysctl, "I",
2357 	    "Rotating media *DEPRECATED* gone in FreeBSD 14");
2358 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2359 	    OID_AUTO, "unmapped_io", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
2360 	    &softc->flags, (u_int)DA_FLAG_UNMAPPEDIO, dabitsysctl, "I",
2361 	    "Unmapped I/O support *DEPRECATED* gone in FreeBSD 14");
2362 
2363 #ifdef CAM_TEST_FAILURE
2364 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2365 		OID_AUTO, "invalidate", CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
2366 		periph, 0, cam_periph_invalidate_sysctl, "I",
2367 		"Write 1 to invalidate the drive immediately");
2368 #endif
2369 
2370 	/*
2371 	 * Add some addressing info.
2372 	 */
2373 	memset(&cts, 0, sizeof (cts));
2374 	xpt_setup_ccb(&cts.ccb_h, periph->path, CAM_PRIORITY_NONE);
2375 	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
2376 	cts.type = CTS_TYPE_CURRENT_SETTINGS;
2377 	cam_periph_lock(periph);
2378 	xpt_action((union ccb *)&cts);
2379 	cam_periph_unlock(periph);
2380 	if (cts.ccb_h.status != CAM_REQ_CMP) {
2381 		da_periph_release(periph, DA_REF_SYSCTL);
2382 		return;
2383 	}
2384 	if (cts.protocol == PROTO_SCSI && cts.transport == XPORT_FC) {
2385 		struct ccb_trans_settings_fc *fc = &cts.xport_specific.fc;
2386 		if (fc->valid & CTS_FC_VALID_WWPN) {
2387 			softc->wwpn = fc->wwpn;
2388 			SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
2389 			    SYSCTL_CHILDREN(softc->sysctl_tree),
2390 			    OID_AUTO, "wwpn", CTLFLAG_RD,
2391 			    &softc->wwpn, "World Wide Port Name");
2392 		}
2393 	}
2394 
2395 #ifdef CAM_IO_STATS
2396 	/*
2397 	 * Now add some useful stats.
2398 	 * XXX These should live in cam_periph and be common to all periphs
2399 	 */
2400 	softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx,
2401 	    SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats",
2402 	    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "Statistics");
2403 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
2404 		       SYSCTL_CHILDREN(softc->sysctl_stats_tree),
2405 		       OID_AUTO,
2406 		       "errors",
2407 		       CTLFLAG_RD,
2408 		       &softc->errors,
2409 		       0,
2410 		       "Transport errors reported by the SIM");
2411 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
2412 		       SYSCTL_CHILDREN(softc->sysctl_stats_tree),
2413 		       OID_AUTO,
2414 		       "timeouts",
2415 		       CTLFLAG_RD,
2416 		       &softc->timeouts,
2417 		       0,
2418 		       "Device timeouts reported by the SIM");
2419 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
2420 		       SYSCTL_CHILDREN(softc->sysctl_stats_tree),
2421 		       OID_AUTO,
2422 		       "pack_invalidations",
2423 		       CTLFLAG_RD,
2424 		       &softc->invalidations,
2425 		       0,
2426 		       "Device pack invalidations");
2427 #endif
2428 
2429 	cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx,
2430 	    softc->sysctl_tree);
2431 
2432 	da_periph_release(periph, DA_REF_SYSCTL);
2433 }
2434 
2435 static int
2436 dadeletemaxsysctl(SYSCTL_HANDLER_ARGS)
2437 {
2438 	int error;
2439 	uint64_t value;
2440 	struct da_softc *softc;
2441 
2442 	softc = (struct da_softc *)arg1;
2443 
2444 	value = softc->disk->d_delmaxsize;
2445 	error = sysctl_handle_64(oidp, &value, 0, req);
2446 	if ((error != 0) || (req->newptr == NULL))
2447 		return (error);
2448 
2449 	/* only accept values smaller than the calculated value */
2450 	if (value > dadeletemaxsize(softc, softc->delete_method)) {
2451 		return (EINVAL);
2452 	}
2453 	softc->disk->d_delmaxsize = value;
2454 
2455 	return (0);
2456 }
2457 
2458 static int
2459 dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
2460 {
2461 	int error, value;
2462 
2463 	value = *(int *)arg1;
2464 
2465 	error = sysctl_handle_int(oidp, &value, 0, req);
2466 
2467 	if ((error != 0)
2468 	 || (req->newptr == NULL))
2469 		return (error);
2470 
2471 	/*
2472 	 * Acceptable values here are 6, 10, 12 or 16.
2473 	 */
2474 	if (value < 6)
2475 		value = 6;
2476 	else if ((value > 6)
2477 	      && (value <= 10))
2478 		value = 10;
2479 	else if ((value > 10)
2480 	      && (value <= 12))
2481 		value = 12;
2482 	else if (value > 12)
2483 		value = 16;
2484 
2485 	*(int *)arg1 = value;
2486 
2487 	return (0);
2488 }
2489 
2490 static int
2491 dasysctlsofttimeout(SYSCTL_HANDLER_ARGS)
2492 {
2493 	sbintime_t value;
2494 	int error;
2495 
2496 	value = da_default_softtimeout / SBT_1MS;
2497 
2498 	error = sysctl_handle_int(oidp, (int *)&value, 0, req);
2499 	if ((error != 0) || (req->newptr == NULL))
2500 		return (error);
2501 
2502 	/* XXX Should clip this to a reasonable level */
2503 	if (value > da_default_timeout * 1000)
2504 		return (EINVAL);
2505 
2506 	da_default_softtimeout = value * SBT_1MS;
2507 	return (0);
2508 }
2509 
2510 static void
2511 dadeletemethodset(struct da_softc *softc, da_delete_methods delete_method)
2512 {
2513 
2514 	softc->delete_method = delete_method;
2515 	softc->disk->d_delmaxsize = dadeletemaxsize(softc, delete_method);
2516 	softc->delete_func = da_delete_functions[delete_method];
2517 
2518 	if (softc->delete_method > DA_DELETE_DISABLE)
2519 		softc->disk->d_flags |= DISKFLAG_CANDELETE;
2520 	else
2521 		softc->disk->d_flags &= ~DISKFLAG_CANDELETE;
2522 }
2523 
2524 static off_t
2525 dadeletemaxsize(struct da_softc *softc, da_delete_methods delete_method)
2526 {
2527 	off_t sectors;
2528 
2529 	switch(delete_method) {
2530 	case DA_DELETE_UNMAP:
2531 		sectors = (off_t)softc->unmap_max_lba;
2532 		break;
2533 	case DA_DELETE_ATA_TRIM:
2534 		sectors = (off_t)ATA_DSM_RANGE_MAX * softc->trim_max_ranges;
2535 		break;
2536 	case DA_DELETE_WS16:
2537 		sectors = omin(softc->ws_max_blks, WS16_MAX_BLKS);
2538 		break;
2539 	case DA_DELETE_ZERO:
2540 	case DA_DELETE_WS10:
2541 		sectors = omin(softc->ws_max_blks, WS10_MAX_BLKS);
2542 		break;
2543 	default:
2544 		return 0;
2545 	}
2546 
2547 	return (off_t)softc->params.secsize *
2548 	    omin(sectors, softc->params.sectors);
2549 }
2550 
2551 static void
2552 daprobedone(struct cam_periph *periph, union ccb *ccb)
2553 {
2554 	struct da_softc *softc;
2555 
2556 	softc = (struct da_softc *)periph->softc;
2557 
2558 	cam_periph_assert(periph, MA_OWNED);
2559 
2560 	dadeletemethodchoose(softc, DA_DELETE_NONE);
2561 
2562 	if (bootverbose && (softc->flags & DA_FLAG_ANNOUNCED) == 0) {
2563 		char buf[80];
2564 		int i, sep;
2565 
2566 		snprintf(buf, sizeof(buf), "Delete methods: <");
2567 		sep = 0;
2568 		for (i = 0; i <= DA_DELETE_MAX; i++) {
2569 			if ((softc->delete_available & (1 << i)) == 0 &&
2570 			    i != softc->delete_method)
2571 				continue;
2572 			if (sep)
2573 				strlcat(buf, ",", sizeof(buf));
2574 			strlcat(buf, da_delete_method_names[i],
2575 			    sizeof(buf));
2576 			if (i == softc->delete_method)
2577 				strlcat(buf, "(*)", sizeof(buf));
2578 			sep = 1;
2579 		}
2580 		strlcat(buf, ">", sizeof(buf));
2581 		printf("%s%d: %s\n", periph->periph_name,
2582 		    periph->unit_number, buf);
2583 	}
2584 	if ((softc->disk->d_flags & DISKFLAG_WRITE_PROTECT) != 0 &&
2585 	    (softc->flags & DA_FLAG_ANNOUNCED) == 0) {
2586 		printf("%s%d: Write Protected\n", periph->periph_name,
2587 		    periph->unit_number);
2588 	}
2589 
2590 	/*
2591 	 * Since our peripheral may be invalidated by an error
2592 	 * above or an external event, we must release our CCB
2593 	 * before releasing the probe lock on the peripheral.
2594 	 * The peripheral will only go away once the last lock
2595 	 * is removed, and we need it around for the CCB release
2596 	 * operation.
2597 	 */
2598 	xpt_release_ccb(ccb);
2599 	softc->state = DA_STATE_NORMAL;
2600 	softc->flags |= DA_FLAG_PROBED;
2601 	daschedule(periph);
2602 	wakeup(&softc->disk->d_mediasize);
2603 	if ((softc->flags & DA_FLAG_ANNOUNCED) == 0) {
2604 		softc->flags |= DA_FLAG_ANNOUNCED;
2605 		da_periph_unhold(periph, DA_REF_PROBE_HOLD);
2606 	} else
2607 		da_periph_release_locked(periph, DA_REF_REPROBE);
2608 }
2609 
2610 static void
2611 dadeletemethodchoose(struct da_softc *softc, da_delete_methods default_method)
2612 {
2613 	int i, methods;
2614 
2615 	/* If available, prefer the method requested by user. */
2616 	i = softc->delete_method_pref;
2617 	methods = softc->delete_available | (1 << DA_DELETE_DISABLE);
2618 	if (methods & (1 << i)) {
2619 		dadeletemethodset(softc, i);
2620 		return;
2621 	}
2622 
2623 	/* Use the pre-defined order to choose the best performing delete. */
2624 	for (i = DA_DELETE_MIN; i <= DA_DELETE_MAX; i++) {
2625 		if (i == DA_DELETE_ZERO)
2626 			continue;
2627 		if (softc->delete_available & (1 << i)) {
2628 			dadeletemethodset(softc, i);
2629 			return;
2630 		}
2631 	}
2632 
2633 	/* Fallback to default. */
2634 	dadeletemethodset(softc, default_method);
2635 }
2636 
2637 static int
2638 dabitsysctl(SYSCTL_HANDLER_ARGS)
2639 {
2640 	u_int *flags = arg1;
2641 	u_int test = arg2;
2642 	int tmpout, error;
2643 
2644 	tmpout = !!(*flags & test);
2645 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
2646 	if (error || !req->newptr)
2647 		return (error);
2648 
2649 	return (EPERM);
2650 }
2651 
2652 static int
2653 daflagssysctl(SYSCTL_HANDLER_ARGS)
2654 {
2655 	struct sbuf sbuf;
2656 	struct da_softc *softc = arg1;
2657 	int error;
2658 
2659 	sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
2660 	if (softc->flags != 0)
2661 		sbuf_printf(&sbuf, "0x%b", (unsigned)softc->flags, DA_FLAG_STRING);
2662 	else
2663 		sbuf_printf(&sbuf, "0");
2664 	error = sbuf_finish(&sbuf);
2665 	sbuf_delete(&sbuf);
2666 
2667 	return (error);
2668 }
2669 
2670 static int
2671 dadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
2672 {
2673 	char buf[16];
2674 	const char *p;
2675 	struct da_softc *softc;
2676 	int i, error, value;
2677 
2678 	softc = (struct da_softc *)arg1;
2679 
2680 	value = softc->delete_method;
2681 	if (value < 0 || value > DA_DELETE_MAX)
2682 		p = "UNKNOWN";
2683 	else
2684 		p = da_delete_method_names[value];
2685 	strncpy(buf, p, sizeof(buf));
2686 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2687 	if (error != 0 || req->newptr == NULL)
2688 		return (error);
2689 	for (i = 0; i <= DA_DELETE_MAX; i++) {
2690 		if (strcmp(buf, da_delete_method_names[i]) == 0)
2691 			break;
2692 	}
2693 	if (i > DA_DELETE_MAX)
2694 		return (EINVAL);
2695 	softc->delete_method_pref = i;
2696 	dadeletemethodchoose(softc, DA_DELETE_NONE);
2697 	return (0);
2698 }
2699 
2700 static int
2701 dazonemodesysctl(SYSCTL_HANDLER_ARGS)
2702 {
2703 	char tmpbuf[40];
2704 	struct da_softc *softc;
2705 	int error;
2706 
2707 	softc = (struct da_softc *)arg1;
2708 
2709 	switch (softc->zone_mode) {
2710 	case DA_ZONE_DRIVE_MANAGED:
2711 		snprintf(tmpbuf, sizeof(tmpbuf), "Drive Managed");
2712 		break;
2713 	case DA_ZONE_HOST_AWARE:
2714 		snprintf(tmpbuf, sizeof(tmpbuf), "Host Aware");
2715 		break;
2716 	case DA_ZONE_HOST_MANAGED:
2717 		snprintf(tmpbuf, sizeof(tmpbuf), "Host Managed");
2718 		break;
2719 	case DA_ZONE_NONE:
2720 	default:
2721 		snprintf(tmpbuf, sizeof(tmpbuf), "Not Zoned");
2722 		break;
2723 	}
2724 
2725 	error = sysctl_handle_string(oidp, tmpbuf, sizeof(tmpbuf), req);
2726 
2727 	return (error);
2728 }
2729 
2730 static int
2731 dazonesupsysctl(SYSCTL_HANDLER_ARGS)
2732 {
2733 	char tmpbuf[180];
2734 	struct da_softc *softc;
2735 	struct sbuf sb;
2736 	int error, first;
2737 	unsigned int i;
2738 
2739 	softc = (struct da_softc *)arg1;
2740 
2741 	error = 0;
2742 	first = 1;
2743 	sbuf_new(&sb, tmpbuf, sizeof(tmpbuf), 0);
2744 
2745 	for (i = 0; i < sizeof(da_zone_desc_table) /
2746 	     sizeof(da_zone_desc_table[0]); i++) {
2747 		if (softc->zone_flags & da_zone_desc_table[i].value) {
2748 			if (first == 0)
2749 				sbuf_printf(&sb, ", ");
2750 			else
2751 				first = 0;
2752 			sbuf_cat(&sb, da_zone_desc_table[i].desc);
2753 		}
2754 	}
2755 
2756 	if (first == 1)
2757 		sbuf_printf(&sb, "None");
2758 
2759 	sbuf_finish(&sb);
2760 
2761 	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
2762 
2763 	return (error);
2764 }
2765 
2766 static cam_status
2767 daregister(struct cam_periph *periph, void *arg)
2768 {
2769 	struct da_softc *softc;
2770 	struct ccb_pathinq cpi;
2771 	struct ccb_getdev *cgd;
2772 	char tmpstr[80];
2773 	caddr_t match;
2774 	int quirks;
2775 
2776 	cgd = (struct ccb_getdev *)arg;
2777 	if (cgd == NULL) {
2778 		printf("daregister: no getdev CCB, can't register device\n");
2779 		return(CAM_REQ_CMP_ERR);
2780 	}
2781 
2782 	softc = (struct da_softc *)malloc(sizeof(*softc), M_DEVBUF,
2783 	    M_NOWAIT|M_ZERO);
2784 
2785 	if (softc == NULL) {
2786 		printf("daregister: Unable to probe new device. "
2787 		       "Unable to allocate softc\n");
2788 		return(CAM_REQ_CMP_ERR);
2789 	}
2790 
2791 	if (cam_iosched_init(&softc->cam_iosched, periph) != 0) {
2792 		printf("daregister: Unable to probe new device. "
2793 		       "Unable to allocate iosched memory\n");
2794 		free(softc, M_DEVBUF);
2795 		return(CAM_REQ_CMP_ERR);
2796 	}
2797 
2798 	LIST_INIT(&softc->pending_ccbs);
2799 	softc->state = DA_STATE_PROBE_WP;
2800 	bioq_init(&softc->delete_run_queue);
2801 	if (SID_IS_REMOVABLE(&cgd->inq_data))
2802 		softc->flags |= DA_FLAG_PACK_REMOVABLE;
2803 	softc->unmap_max_ranges = UNMAP_MAX_RANGES;
2804 	softc->unmap_max_lba = UNMAP_RANGE_MAX;
2805 	softc->unmap_gran = 0;
2806 	softc->unmap_gran_align = 0;
2807 	softc->ws_max_blks = WS16_MAX_BLKS;
2808 	softc->trim_max_ranges = ATA_TRIM_MAX_RANGES;
2809 	softc->flags |= DA_FLAG_ROTATING;
2810 
2811 	periph->softc = softc;
2812 
2813 	/*
2814 	 * See if this device has any quirks.
2815 	 */
2816 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
2817 			       (caddr_t)da_quirk_table,
2818 			       nitems(da_quirk_table),
2819 			       sizeof(*da_quirk_table), scsi_inquiry_match);
2820 
2821 	if (match != NULL)
2822 		softc->quirks = ((struct da_quirk_entry *)match)->quirks;
2823 	else
2824 		softc->quirks = DA_Q_NONE;
2825 
2826 	/* Check if the SIM does not want 6 byte commands */
2827 	xpt_path_inq(&cpi, periph->path);
2828 	if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
2829 		softc->quirks |= DA_Q_NO_6_BYTE;
2830 
2831 	/* Override quirks if tunable is set */
2832 	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.quirks",
2833 		 periph->unit_number);
2834 	quirks = softc->quirks;
2835 	TUNABLE_INT_FETCH(tmpstr, &quirks);
2836 	softc->quirks = quirks;
2837 
2838 	if (SID_TYPE(&cgd->inq_data) == T_ZBC_HM)
2839 		softc->zone_mode = DA_ZONE_HOST_MANAGED;
2840 	else if (softc->quirks & DA_Q_SMR_DM)
2841 		softc->zone_mode = DA_ZONE_DRIVE_MANAGED;
2842 	else
2843 		softc->zone_mode = DA_ZONE_NONE;
2844 
2845 	if (softc->zone_mode != DA_ZONE_NONE) {
2846 		if (scsi_vpd_supported_page(periph, SVPD_ATA_INFORMATION)) {
2847 			if (scsi_vpd_supported_page(periph, SVPD_ZONED_BDC))
2848 				softc->zone_interface = DA_ZONE_IF_ATA_SAT;
2849 			else
2850 				softc->zone_interface = DA_ZONE_IF_ATA_PASS;
2851 		} else
2852 			softc->zone_interface = DA_ZONE_IF_SCSI;
2853 	}
2854 
2855 	TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
2856 
2857 	/*
2858 	 * Let XPT know we can use UMA-allocated CCBs.
2859 	 */
2860 	if (da_enable_uma_ccbs) {
2861 		KASSERT(da_ccb_zone != NULL,
2862 		    ("%s: NULL da_ccb_zone", __func__));
2863 		periph->ccb_zone = da_ccb_zone;
2864 	}
2865 
2866 	/*
2867 	 * Take an exclusive section lock on the periph while dastart is called
2868 	 * to finish the probe.  The lock will be dropped in dadone at the end
2869 	 * of probe. This locks out daopen and daclose from racing with the
2870 	 * probe.
2871 	 *
2872 	 * XXX if cam_periph_hold returns an error, we don't hold a refcount.
2873 	 */
2874 	(void)da_periph_hold(periph, PRIBIO, DA_REF_PROBE_HOLD);
2875 
2876 	/*
2877 	 * Schedule a periodic event to occasionally send an
2878 	 * ordered tag to a device.
2879 	 */
2880 	callout_init_mtx(&softc->sendordered_c, cam_periph_mtx(periph), 0);
2881 	callout_reset_sbt(&softc->sendordered_c,
2882 	    SBT_1S / DA_ORDEREDTAG_INTERVAL * da_default_timeout, 0,
2883 	    dasendorderedtag, periph, C_PREL(1));
2884 
2885 	cam_periph_unlock(periph);
2886 	/*
2887 	 * RBC devices don't have to support READ(6), only READ(10).
2888 	 */
2889 	if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
2890 		softc->minimum_cmd_size = 10;
2891 	else
2892 		softc->minimum_cmd_size = 6;
2893 
2894 	/*
2895 	 * Load the user's default, if any.
2896 	 */
2897 	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
2898 		 periph->unit_number);
2899 	TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
2900 
2901 	/*
2902 	 * 6, 10, 12 and 16 are the currently permissible values.
2903 	 */
2904 	if (softc->minimum_cmd_size > 12)
2905 		softc->minimum_cmd_size = 16;
2906 	else if (softc->minimum_cmd_size > 10)
2907 		softc->minimum_cmd_size = 12;
2908 	else if (softc->minimum_cmd_size > 6)
2909 		softc->minimum_cmd_size = 10;
2910 	else
2911 		softc->minimum_cmd_size = 6;
2912 
2913 	/* On first PROBE_WP request all more pages, then adjust. */
2914 	softc->mode_page = SMS_ALL_PAGES_PAGE;
2915 
2916 	/* Predict whether device may support READ CAPACITY(16). */
2917 	if (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC3 &&
2918 	    (softc->quirks & DA_Q_NO_RC16) == 0) {
2919 		softc->flags |= DA_FLAG_CAN_RC16;
2920 	}
2921 
2922 	/*
2923 	 * Register this media as a disk.
2924 	 */
2925 	softc->disk = disk_alloc();
2926 	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
2927 			  periph->unit_number, 0,
2928 			  DEVSTAT_BS_UNAVAILABLE,
2929 			  SID_TYPE(&cgd->inq_data) |
2930 			  XPORT_DEVSTAT_TYPE(cpi.transport),
2931 			  DEVSTAT_PRIORITY_DISK);
2932 	softc->disk->d_open = daopen;
2933 	softc->disk->d_close = daclose;
2934 	softc->disk->d_strategy = dastrategy;
2935 	if (cam_sim_pollable(periph->sim))
2936 		softc->disk->d_dump = dadump;
2937 	softc->disk->d_getattr = dagetattr;
2938 	softc->disk->d_gone = dadiskgonecb;
2939 	softc->disk->d_name = "da";
2940 	softc->disk->d_drv1 = periph;
2941 	if (cpi.maxio == 0)
2942 		softc->maxio = DFLTPHYS;	/* traditional default */
2943 	else if (cpi.maxio > maxphys)
2944 		softc->maxio = maxphys;		/* for safety */
2945 	else
2946 		softc->maxio = cpi.maxio;
2947 	if (softc->quirks & DA_Q_128KB)
2948 		softc->maxio = min(softc->maxio, 128 * 1024);
2949 	softc->disk->d_maxsize = softc->maxio;
2950 	softc->disk->d_unit = periph->unit_number;
2951 	softc->disk->d_flags = DISKFLAG_DIRECT_COMPLETION | DISKFLAG_CANZONE;
2952 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0)
2953 		softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
2954 	if ((cpi.hba_misc & PIM_UNMAPPED) != 0) {
2955 		softc->flags |= DA_FLAG_UNMAPPEDIO;
2956 		softc->disk->d_flags |= DISKFLAG_UNMAPPED_BIO;
2957 	}
2958 	cam_strvis(softc->disk->d_descr, cgd->inq_data.vendor,
2959 	    sizeof(cgd->inq_data.vendor), sizeof(softc->disk->d_descr));
2960 	strlcat(softc->disk->d_descr, " ", sizeof(softc->disk->d_descr));
2961 	cam_strvis(&softc->disk->d_descr[strlen(softc->disk->d_descr)],
2962 	    cgd->inq_data.product, sizeof(cgd->inq_data.product),
2963 	    sizeof(softc->disk->d_descr) - strlen(softc->disk->d_descr));
2964 	softc->disk->d_hba_vendor = cpi.hba_vendor;
2965 	softc->disk->d_hba_device = cpi.hba_device;
2966 	softc->disk->d_hba_subvendor = cpi.hba_subvendor;
2967 	softc->disk->d_hba_subdevice = cpi.hba_subdevice;
2968 	snprintf(softc->disk->d_attachment, sizeof(softc->disk->d_attachment),
2969 	    "%s%d", cpi.dev_name, cpi.unit_number);
2970 
2971 	/*
2972 	 * Acquire a reference to the periph before we register with GEOM.
2973 	 * We'll release this reference once GEOM calls us back (via
2974 	 * dadiskgonecb()) telling us that our provider has been freed.
2975 	 */
2976 	if (da_periph_acquire(periph, DA_REF_GEOM) != 0) {
2977 		xpt_print(periph->path, "%s: lost periph during "
2978 			  "registration!\n", __func__);
2979 		cam_periph_lock(periph);
2980 		return (CAM_REQ_CMP_ERR);
2981 	}
2982 
2983 	disk_create(softc->disk, DISK_VERSION);
2984 	cam_periph_lock(periph);
2985 
2986 	/*
2987 	 * Add async callbacks for events of interest.
2988 	 * I don't bother checking if this fails as,
2989 	 * in most cases, the system will function just
2990 	 * fine without them and the only alternative
2991 	 * would be to not attach the device on failure.
2992 	 */
2993 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
2994 	    AC_ADVINFO_CHANGED | AC_SCSI_AEN | AC_UNIT_ATTENTION |
2995 	    AC_INQ_CHANGED, daasync, periph, periph->path);
2996 
2997 	/*
2998 	 * Emit an attribute changed notification just in case
2999 	 * physical path information arrived before our async
3000 	 * event handler was registered, but after anyone attaching
3001 	 * to our disk device polled it.
3002 	 */
3003 	disk_attr_changed(softc->disk, "GEOM::physpath", M_NOWAIT);
3004 
3005 	/*
3006 	 * Schedule a periodic media polling events.
3007 	 */
3008 	callout_init_mtx(&softc->mediapoll_c, cam_periph_mtx(periph), 0);
3009 	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) &&
3010 	    (cgd->inq_flags & SID_AEN) == 0 &&
3011 	    da_poll_period != 0) {
3012 		callout_reset_sbt(&softc->mediapoll_c, da_poll_period * SBT_1S,
3013 		    0, damediapoll, periph, C_PREL(1));
3014 	}
3015 
3016 	xpt_schedule(periph, CAM_PRIORITY_DEV);
3017 
3018 	return(CAM_REQ_CMP);
3019 }
3020 
3021 static int
3022 da_zone_bio_to_scsi(int disk_zone_cmd)
3023 {
3024 	switch (disk_zone_cmd) {
3025 	case DISK_ZONE_OPEN:
3026 		return ZBC_OUT_SA_OPEN;
3027 	case DISK_ZONE_CLOSE:
3028 		return ZBC_OUT_SA_CLOSE;
3029 	case DISK_ZONE_FINISH:
3030 		return ZBC_OUT_SA_FINISH;
3031 	case DISK_ZONE_RWP:
3032 		return ZBC_OUT_SA_RWP;
3033 	}
3034 
3035 	return -1;
3036 }
3037 
3038 static int
3039 da_zone_cmd(struct cam_periph *periph, union ccb *ccb, struct bio *bp,
3040 	    int *queue_ccb)
3041 {
3042 	struct da_softc *softc;
3043 	int error;
3044 
3045 	error = 0;
3046 
3047 	if (bp->bio_cmd != BIO_ZONE) {
3048 		error = EINVAL;
3049 		goto bailout;
3050 	}
3051 
3052 	softc = periph->softc;
3053 
3054 	switch (bp->bio_zone.zone_cmd) {
3055 	case DISK_ZONE_OPEN:
3056 	case DISK_ZONE_CLOSE:
3057 	case DISK_ZONE_FINISH:
3058 	case DISK_ZONE_RWP: {
3059 		int zone_flags;
3060 		int zone_sa;
3061 		uint64_t lba;
3062 
3063 		zone_sa = da_zone_bio_to_scsi(bp->bio_zone.zone_cmd);
3064 		if (zone_sa == -1) {
3065 			xpt_print(periph->path, "Cannot translate zone "
3066 			    "cmd %#x to SCSI\n", bp->bio_zone.zone_cmd);
3067 			error = EINVAL;
3068 			goto bailout;
3069 		}
3070 
3071 		zone_flags = 0;
3072 		lba = bp->bio_zone.zone_params.rwp.id;
3073 
3074 		if (bp->bio_zone.zone_params.rwp.flags &
3075 		    DISK_ZONE_RWP_FLAG_ALL)
3076 			zone_flags |= ZBC_OUT_ALL;
3077 
3078 		if (softc->zone_interface != DA_ZONE_IF_ATA_PASS) {
3079 			scsi_zbc_out(&ccb->csio,
3080 				     /*retries*/ da_retry_count,
3081 				     /*cbfcnp*/ dadone,
3082 				     /*tag_action*/ MSG_SIMPLE_Q_TAG,
3083 				     /*service_action*/ zone_sa,
3084 				     /*zone_id*/ lba,
3085 				     /*zone_flags*/ zone_flags,
3086 				     /*data_ptr*/ NULL,
3087 				     /*dxfer_len*/ 0,
3088 				     /*sense_len*/ SSD_FULL_SIZE,
3089 				     /*timeout*/ da_default_timeout * 1000);
3090 		} else {
3091 			/*
3092 			 * Note that in this case, even though we can
3093 			 * technically use NCQ, we don't bother for several
3094 			 * reasons:
3095 			 * 1. It hasn't been tested on a SAT layer that
3096 			 *    supports it.  This is new as of SAT-4.
3097 			 * 2. Even when there is a SAT layer that supports
3098 			 *    it, that SAT layer will also probably support
3099 			 *    ZBC -> ZAC translation, since they are both
3100 			 *    in the SAT-4 spec.
3101 			 * 3. Translation will likely be preferable to ATA
3102 			 *    passthrough.  LSI / Avago at least single
3103 			 *    steps ATA passthrough commands in the HBA,
3104 			 *    regardless of protocol, so unless that
3105 			 *    changes, there is a performance penalty for
3106 			 *    doing ATA passthrough no matter whether
3107 			 *    you're using NCQ/FPDMA, DMA or PIO.
3108 			 * 4. It requires a 32-byte CDB, which at least at
3109 			 *    this point in CAM requires a CDB pointer, which
3110 			 *    would require us to allocate an additional bit
3111 			 *    of storage separate from the CCB.
3112 			 */
3113 			error = scsi_ata_zac_mgmt_out(&ccb->csio,
3114 			    /*retries*/ da_retry_count,
3115 			    /*cbfcnp*/ dadone,
3116 			    /*tag_action*/ MSG_SIMPLE_Q_TAG,
3117 			    /*use_ncq*/ 0,
3118 			    /*zm_action*/ zone_sa,
3119 			    /*zone_id*/ lba,
3120 			    /*zone_flags*/ zone_flags,
3121 			    /*data_ptr*/ NULL,
3122 			    /*dxfer_len*/ 0,
3123 			    /*cdb_storage*/ NULL,
3124 			    /*cdb_storage_len*/ 0,
3125 			    /*sense_len*/ SSD_FULL_SIZE,
3126 			    /*timeout*/ da_default_timeout * 1000);
3127 			if (error != 0) {
3128 				error = EINVAL;
3129 				xpt_print(periph->path,
3130 				    "scsi_ata_zac_mgmt_out() returned an "
3131 				    "error!");
3132 				goto bailout;
3133 			}
3134 		}
3135 		*queue_ccb = 1;
3136 
3137 		break;
3138 	}
3139 	case DISK_ZONE_REPORT_ZONES: {
3140 		uint8_t *rz_ptr;
3141 		uint32_t num_entries, alloc_size;
3142 		struct disk_zone_report *rep;
3143 
3144 		rep = &bp->bio_zone.zone_params.report;
3145 
3146 		num_entries = rep->entries_allocated;
3147 		if (num_entries == 0) {
3148 			xpt_print(periph->path, "No entries allocated for "
3149 			    "Report Zones request\n");
3150 			error = EINVAL;
3151 			goto bailout;
3152 		}
3153 		alloc_size = sizeof(struct scsi_report_zones_hdr) +
3154 		    (sizeof(struct scsi_report_zones_desc) * num_entries);
3155 		alloc_size = min(alloc_size, softc->disk->d_maxsize);
3156 		rz_ptr = malloc(alloc_size, M_SCSIDA, M_NOWAIT | M_ZERO);
3157 		if (rz_ptr == NULL) {
3158 			xpt_print(periph->path, "Unable to allocate memory "
3159 			   "for Report Zones request\n");
3160 			error = ENOMEM;
3161 			goto bailout;
3162 		}
3163 
3164 		if (softc->zone_interface != DA_ZONE_IF_ATA_PASS) {
3165 			scsi_zbc_in(&ccb->csio,
3166 				    /*retries*/ da_retry_count,
3167 				    /*cbcfnp*/ dadone,
3168 				    /*tag_action*/ MSG_SIMPLE_Q_TAG,
3169 				    /*service_action*/ ZBC_IN_SA_REPORT_ZONES,
3170 				    /*zone_start_lba*/ rep->starting_id,
3171 				    /*zone_options*/ rep->rep_options,
3172 				    /*data_ptr*/ rz_ptr,
3173 				    /*dxfer_len*/ alloc_size,
3174 				    /*sense_len*/ SSD_FULL_SIZE,
3175 				    /*timeout*/ da_default_timeout * 1000);
3176 		} else {
3177 			/*
3178 			 * Note that in this case, even though we can
3179 			 * technically use NCQ, we don't bother for several
3180 			 * reasons:
3181 			 * 1. It hasn't been tested on a SAT layer that
3182 			 *    supports it.  This is new as of SAT-4.
3183 			 * 2. Even when there is a SAT layer that supports
3184 			 *    it, that SAT layer will also probably support
3185 			 *    ZBC -> ZAC translation, since they are both
3186 			 *    in the SAT-4 spec.
3187 			 * 3. Translation will likely be preferable to ATA
3188 			 *    passthrough.  LSI / Avago at least single
3189 			 *    steps ATA passthrough commands in the HBA,
3190 			 *    regardless of protocol, so unless that
3191 			 *    changes, there is a performance penalty for
3192 			 *    doing ATA passthrough no matter whether
3193 			 *    you're using NCQ/FPDMA, DMA or PIO.
3194 			 * 4. It requires a 32-byte CDB, which at least at
3195 			 *    this point in CAM requires a CDB pointer, which
3196 			 *    would require us to allocate an additional bit
3197 			 *    of storage separate from the CCB.
3198 			 */
3199 			error = scsi_ata_zac_mgmt_in(&ccb->csio,
3200 			    /*retries*/ da_retry_count,
3201 			    /*cbcfnp*/ dadone,
3202 			    /*tag_action*/ MSG_SIMPLE_Q_TAG,
3203 			    /*use_ncq*/ 0,
3204 			    /*zm_action*/ ATA_ZM_REPORT_ZONES,
3205 			    /*zone_id*/ rep->starting_id,
3206 			    /*zone_flags*/ rep->rep_options,
3207 			    /*data_ptr*/ rz_ptr,
3208 			    /*dxfer_len*/ alloc_size,
3209 			    /*cdb_storage*/ NULL,
3210 			    /*cdb_storage_len*/ 0,
3211 			    /*sense_len*/ SSD_FULL_SIZE,
3212 			    /*timeout*/ da_default_timeout * 1000);
3213 			if (error != 0) {
3214 				error = EINVAL;
3215 				xpt_print(periph->path,
3216 				    "scsi_ata_zac_mgmt_in() returned an "
3217 				    "error!");
3218 				goto bailout;
3219 			}
3220 		}
3221 
3222 		/*
3223 		 * For BIO_ZONE, this isn't normally needed.  However, it
3224 		 * is used by devstat_end_transaction_bio() to determine
3225 		 * how much data was transferred.
3226 		 */
3227 		/*
3228 		 * XXX KDM we have a problem.  But I'm not sure how to fix
3229 		 * it.  devstat uses bio_bcount - bio_resid to calculate
3230 		 * the amount of data transferred.   The GEOM disk code
3231 		 * uses bio_length - bio_resid to calculate the amount of
3232 		 * data in bio_completed.  We have different structure
3233 		 * sizes above and below the ada(4) driver.  So, if we
3234 		 * use the sizes above, the amount transferred won't be
3235 		 * quite accurate for devstat.  If we use different sizes
3236 		 * for bio_bcount and bio_length (above and below
3237 		 * respectively), then the residual needs to match one or
3238 		 * the other.  Everything is calculated after the bio
3239 		 * leaves the driver, so changing the values around isn't
3240 		 * really an option.  For now, just set the count to the
3241 		 * passed in length.  This means that the calculations
3242 		 * above (e.g. bio_completed) will be correct, but the
3243 		 * amount of data reported to devstat will be slightly
3244 		 * under or overstated.
3245 		 */
3246 		bp->bio_bcount = bp->bio_length;
3247 
3248 		*queue_ccb = 1;
3249 
3250 		break;
3251 	}
3252 	case DISK_ZONE_GET_PARAMS: {
3253 		struct disk_zone_disk_params *params;
3254 
3255 		params = &bp->bio_zone.zone_params.disk_params;
3256 		bzero(params, sizeof(*params));
3257 
3258 		switch (softc->zone_mode) {
3259 		case DA_ZONE_DRIVE_MANAGED:
3260 			params->zone_mode = DISK_ZONE_MODE_DRIVE_MANAGED;
3261 			break;
3262 		case DA_ZONE_HOST_AWARE:
3263 			params->zone_mode = DISK_ZONE_MODE_HOST_AWARE;
3264 			break;
3265 		case DA_ZONE_HOST_MANAGED:
3266 			params->zone_mode = DISK_ZONE_MODE_HOST_MANAGED;
3267 			break;
3268 		default:
3269 		case DA_ZONE_NONE:
3270 			params->zone_mode = DISK_ZONE_MODE_NONE;
3271 			break;
3272 		}
3273 
3274 		if (softc->zone_flags & DA_ZONE_FLAG_URSWRZ)
3275 			params->flags |= DISK_ZONE_DISK_URSWRZ;
3276 
3277 		if (softc->zone_flags & DA_ZONE_FLAG_OPT_SEQ_SET) {
3278 			params->optimal_seq_zones = softc->optimal_seq_zones;
3279 			params->flags |= DISK_ZONE_OPT_SEQ_SET;
3280 		}
3281 
3282 		if (softc->zone_flags & DA_ZONE_FLAG_OPT_NONSEQ_SET) {
3283 			params->optimal_nonseq_zones =
3284 			    softc->optimal_nonseq_zones;
3285 			params->flags |= DISK_ZONE_OPT_NONSEQ_SET;
3286 		}
3287 
3288 		if (softc->zone_flags & DA_ZONE_FLAG_MAX_SEQ_SET) {
3289 			params->max_seq_zones = softc->max_seq_zones;
3290 			params->flags |= DISK_ZONE_MAX_SEQ_SET;
3291 		}
3292 		if (softc->zone_flags & DA_ZONE_FLAG_RZ_SUP)
3293 			params->flags |= DISK_ZONE_RZ_SUP;
3294 
3295 		if (softc->zone_flags & DA_ZONE_FLAG_OPEN_SUP)
3296 			params->flags |= DISK_ZONE_OPEN_SUP;
3297 
3298 		if (softc->zone_flags & DA_ZONE_FLAG_CLOSE_SUP)
3299 			params->flags |= DISK_ZONE_CLOSE_SUP;
3300 
3301 		if (softc->zone_flags & DA_ZONE_FLAG_FINISH_SUP)
3302 			params->flags |= DISK_ZONE_FINISH_SUP;
3303 
3304 		if (softc->zone_flags & DA_ZONE_FLAG_RWP_SUP)
3305 			params->flags |= DISK_ZONE_RWP_SUP;
3306 		break;
3307 	}
3308 	default:
3309 		break;
3310 	}
3311 bailout:
3312 	return (error);
3313 }
3314 
3315 static void
3316 dastart(struct cam_periph *periph, union ccb *start_ccb)
3317 {
3318 	struct da_softc *softc;
3319 
3320 	cam_periph_assert(periph, MA_OWNED);
3321 	softc = (struct da_softc *)periph->softc;
3322 
3323 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastart\n"));
3324 
3325 skipstate:
3326 	switch (softc->state) {
3327 	case DA_STATE_NORMAL:
3328 	{
3329 		struct bio *bp;
3330 		uint8_t tag_code;
3331 
3332 more:
3333 		bp = cam_iosched_next_bio(softc->cam_iosched);
3334 		if (bp == NULL) {
3335 			if (cam_iosched_has_work_flags(softc->cam_iosched,
3336 			    DA_WORK_TUR)) {
3337 				softc->flags |= DA_FLAG_TUR_PENDING;
3338 				cam_iosched_clr_work_flags(softc->cam_iosched,
3339 				    DA_WORK_TUR);
3340 				scsi_test_unit_ready(&start_ccb->csio,
3341 				     /*retries*/ da_retry_count,
3342 				     dadone_tur,
3343 				     MSG_SIMPLE_Q_TAG,
3344 				     SSD_FULL_SIZE,
3345 				     da_default_timeout * 1000);
3346 				start_ccb->ccb_h.ccb_bp = NULL;
3347 				start_ccb->ccb_h.ccb_state = DA_CCB_TUR;
3348 				xpt_action(start_ccb);
3349 			} else
3350 				xpt_release_ccb(start_ccb);
3351 			break;
3352 		}
3353 
3354 		if (bp->bio_cmd == BIO_DELETE) {
3355 			if (softc->delete_func != NULL) {
3356 				softc->delete_func(periph, start_ccb, bp);
3357 				goto out;
3358 			} else {
3359 				/*
3360 				 * Not sure this is possible, but failsafe by
3361 				 * lying and saying "sure, done."
3362 				 */
3363 				biofinish(bp, NULL, 0);
3364 				goto more;
3365 			}
3366 		}
3367 
3368 		if (cam_iosched_has_work_flags(softc->cam_iosched,
3369 		    DA_WORK_TUR)) {
3370 			cam_iosched_clr_work_flags(softc->cam_iosched,
3371 			    DA_WORK_TUR);
3372 			da_periph_release_locked(periph, DA_REF_TUR);
3373 		}
3374 
3375 		if ((bp->bio_flags & BIO_ORDERED) != 0 ||
3376 		    (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
3377 			softc->flags &= ~DA_FLAG_NEED_OTAG;
3378 			softc->flags |= DA_FLAG_WAS_OTAG;
3379 			tag_code = MSG_ORDERED_Q_TAG;
3380 		} else {
3381 			tag_code = MSG_SIMPLE_Q_TAG;
3382 		}
3383 
3384 		switch (bp->bio_cmd) {
3385 		case BIO_WRITE:
3386 		case BIO_READ:
3387 		{
3388 			void *data_ptr;
3389 			int rw_op;
3390 
3391 			biotrack(bp, __func__);
3392 
3393 			if (bp->bio_cmd == BIO_WRITE) {
3394 				softc->flags |= DA_FLAG_DIRTY;
3395 				rw_op = SCSI_RW_WRITE;
3396 			} else {
3397 				rw_op = SCSI_RW_READ;
3398 			}
3399 
3400 			data_ptr = bp->bio_data;
3401 			if ((bp->bio_flags & (BIO_UNMAPPED|BIO_VLIST)) != 0) {
3402 				rw_op |= SCSI_RW_BIO;
3403 				data_ptr = bp;
3404 			}
3405 
3406 			scsi_read_write(&start_ccb->csio,
3407 					/*retries*/da_retry_count,
3408 					/*cbfcnp*/dadone,
3409 					/*tag_action*/tag_code,
3410 					rw_op,
3411 					/*byte2*/0,
3412 					softc->minimum_cmd_size,
3413 					/*lba*/bp->bio_pblkno,
3414 					/*block_count*/bp->bio_bcount /
3415 					softc->params.secsize,
3416 					data_ptr,
3417 					/*dxfer_len*/ bp->bio_bcount,
3418 					/*sense_len*/SSD_FULL_SIZE,
3419 					da_default_timeout * 1000);
3420 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
3421 			start_ccb->csio.bio = bp;
3422 #endif
3423 			break;
3424 		}
3425 		case BIO_FLUSH:
3426 			/*
3427 			 * If we don't support sync cache, or the disk
3428 			 * isn't dirty, FLUSH is a no-op.  Use the
3429 			 * allocated CCB for the next bio if one is
3430 			 * available.
3431 			 */
3432 			if ((softc->quirks & DA_Q_NO_SYNC_CACHE) != 0 ||
3433 			    (softc->flags & DA_FLAG_DIRTY) == 0) {
3434 				biodone(bp);
3435 				goto skipstate;
3436 			}
3437 
3438 			/*
3439 			 * BIO_FLUSH doesn't currently communicate
3440 			 * range data, so we synchronize the cache
3441 			 * over the whole disk.
3442 			 */
3443 			scsi_synchronize_cache(&start_ccb->csio,
3444 					       /*retries*/1,
3445 					       /*cbfcnp*/dadone,
3446 					       /*tag_action*/tag_code,
3447 					       /*begin_lba*/0,
3448 					       /*lb_count*/0,
3449 					       SSD_FULL_SIZE,
3450 					       da_default_timeout*1000);
3451 			/*
3452 			 * Clear the dirty flag before sending the command.
3453 			 * Either this sync cache will be successful, or it
3454 			 * will fail after a retry.  If it fails, it is
3455 			 * unlikely to be successful if retried later, so
3456 			 * we'll save ourselves time by just marking the
3457 			 * device clean.
3458 			 */
3459 			softc->flags &= ~DA_FLAG_DIRTY;
3460 			break;
3461 		case BIO_ZONE: {
3462 			int error, queue_ccb;
3463 
3464 			queue_ccb = 0;
3465 
3466 			error = da_zone_cmd(periph, start_ccb, bp,&queue_ccb);
3467 			if ((error != 0)
3468 			 || (queue_ccb == 0)) {
3469 				biofinish(bp, NULL, error);
3470 				xpt_release_ccb(start_ccb);
3471 				return;
3472 			}
3473 			break;
3474 		}
3475 		default:
3476 			biofinish(bp, NULL, EOPNOTSUPP);
3477 			xpt_release_ccb(start_ccb);
3478 			return;
3479 		}
3480 		start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
3481 		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
3482 		start_ccb->ccb_h.softtimeout = sbttotv(da_default_softtimeout);
3483 
3484 out:
3485 		LIST_INSERT_HEAD(&softc->pending_ccbs,
3486 				 &start_ccb->ccb_h, periph_links.le);
3487 
3488 		/* We expect a unit attention from this device */
3489 		if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
3490 			start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
3491 			softc->flags &= ~DA_FLAG_RETRY_UA;
3492 		}
3493 
3494 		start_ccb->ccb_h.ccb_bp = bp;
3495 		softc->refcount++;
3496 		cam_periph_unlock(periph);
3497 		xpt_action(start_ccb);
3498 		cam_periph_lock(periph);
3499 
3500 		/* May have more work to do, so ensure we stay scheduled */
3501 		daschedule(periph);
3502 		break;
3503 	}
3504 	case DA_STATE_PROBE_WP:
3505 	{
3506 		void  *mode_buf;
3507 		int    mode_buf_len;
3508 
3509 		if (da_disable_wp_detection || softc->mode_page < 0) {
3510 			if ((softc->flags & DA_FLAG_CAN_RC16) != 0)
3511 				softc->state = DA_STATE_PROBE_RC16;
3512 			else
3513 				softc->state = DA_STATE_PROBE_RC;
3514 			goto skipstate;
3515 		}
3516 		mode_buf_len = 192;
3517 		mode_buf = malloc(mode_buf_len, M_SCSIDA, M_NOWAIT);
3518 		if (mode_buf == NULL) {
3519 			xpt_print(periph->path, "Unable to send mode sense - "
3520 			    "malloc failure\n");
3521 			if ((softc->flags & DA_FLAG_CAN_RC16) != 0)
3522 				softc->state = DA_STATE_PROBE_RC16;
3523 			else
3524 				softc->state = DA_STATE_PROBE_RC;
3525 			goto skipstate;
3526 		}
3527 		scsi_mode_sense_len(&start_ccb->csio,
3528 				    /*retries*/ da_retry_count,
3529 				    /*cbfcnp*/ dadone_probewp,
3530 				    /*tag_action*/ MSG_SIMPLE_Q_TAG,
3531 				    /*dbd*/ FALSE,
3532 				    /*pc*/ SMS_PAGE_CTRL_CURRENT,
3533 				    /*page*/ softc->mode_page,
3534 				    /*param_buf*/ mode_buf,
3535 				    /*param_len*/ mode_buf_len,
3536 				    /*minimum_cmd_size*/ softc->minimum_cmd_size,
3537 				    /*sense_len*/ SSD_FULL_SIZE,
3538 				    /*timeout*/ da_default_timeout * 1000);
3539 		start_ccb->ccb_h.ccb_bp = NULL;
3540 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_WP;
3541 		xpt_action(start_ccb);
3542 		break;
3543 	}
3544 	case DA_STATE_PROBE_RC:
3545 	{
3546 		struct scsi_read_capacity_data *rcap;
3547 
3548 		rcap = (struct scsi_read_capacity_data *)
3549 		    malloc(sizeof(*rcap), M_SCSIDA, M_NOWAIT|M_ZERO);
3550 		if (rcap == NULL) {
3551 			printf("dastart: Couldn't malloc read_capacity data\n");
3552 			/* da_free_periph??? */
3553 			break;
3554 		}
3555 		scsi_read_capacity(&start_ccb->csio,
3556 				   /*retries*/da_retry_count,
3557 				   dadone_proberc,
3558 				   MSG_SIMPLE_Q_TAG,
3559 				   rcap,
3560 				   SSD_FULL_SIZE,
3561 				   /*timeout*/5000);
3562 		start_ccb->ccb_h.ccb_bp = NULL;
3563 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC;
3564 		xpt_action(start_ccb);
3565 		break;
3566 	}
3567 	case DA_STATE_PROBE_RC16:
3568 	{
3569 		struct scsi_read_capacity_data_long *rcaplong;
3570 
3571 		rcaplong = (struct scsi_read_capacity_data_long *)
3572 			malloc(sizeof(*rcaplong), M_SCSIDA, M_NOWAIT|M_ZERO);
3573 		if (rcaplong == NULL) {
3574 			printf("dastart: Couldn't malloc read_capacity data\n");
3575 			/* da_free_periph??? */
3576 			break;
3577 		}
3578 		scsi_read_capacity_16(&start_ccb->csio,
3579 				      /*retries*/ da_retry_count,
3580 				      /*cbfcnp*/ dadone_proberc,
3581 				      /*tag_action*/ MSG_SIMPLE_Q_TAG,
3582 				      /*lba*/ 0,
3583 				      /*reladr*/ 0,
3584 				      /*pmi*/ 0,
3585 				      /*rcap_buf*/ (uint8_t *)rcaplong,
3586 				      /*rcap_buf_len*/ sizeof(*rcaplong),
3587 				      /*sense_len*/ SSD_FULL_SIZE,
3588 				      /*timeout*/ da_default_timeout * 1000);
3589 		start_ccb->ccb_h.ccb_bp = NULL;
3590 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC16;
3591 		xpt_action(start_ccb);
3592 		break;
3593 	}
3594 	case DA_STATE_PROBE_LBP:
3595 	{
3596 		struct scsi_vpd_logical_block_prov *lbp;
3597 
3598 		if (!scsi_vpd_supported_page(periph, SVPD_LBP)) {
3599 			/*
3600 			 * If we get here we don't support any SBC-3 delete
3601 			 * methods with UNMAP as the Logical Block Provisioning
3602 			 * VPD page support is required for devices which
3603 			 * support it according to T10/1799-D Revision 31
3604 			 * however older revisions of the spec don't mandate
3605 			 * this so we currently don't remove these methods
3606 			 * from the available set.
3607 			 */
3608 			softc->state = DA_STATE_PROBE_BLK_LIMITS;
3609 			goto skipstate;
3610 		}
3611 
3612 		lbp = (struct scsi_vpd_logical_block_prov *)
3613 			malloc(sizeof(*lbp), M_SCSIDA, M_NOWAIT|M_ZERO);
3614 
3615 		if (lbp == NULL) {
3616 			printf("dastart: Couldn't malloc lbp data\n");
3617 			/* da_free_periph??? */
3618 			break;
3619 		}
3620 
3621 		scsi_inquiry(&start_ccb->csio,
3622 			     /*retries*/da_retry_count,
3623 			     /*cbfcnp*/dadone_probelbp,
3624 			     /*tag_action*/MSG_SIMPLE_Q_TAG,
3625 			     /*inq_buf*/(u_int8_t *)lbp,
3626 			     /*inq_len*/sizeof(*lbp),
3627 			     /*evpd*/TRUE,
3628 			     /*page_code*/SVPD_LBP,
3629 			     /*sense_len*/SSD_MIN_SIZE,
3630 			     /*timeout*/da_default_timeout * 1000);
3631 		start_ccb->ccb_h.ccb_bp = NULL;
3632 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_LBP;
3633 		xpt_action(start_ccb);
3634 		break;
3635 	}
3636 	case DA_STATE_PROBE_BLK_LIMITS:
3637 	{
3638 		struct scsi_vpd_block_limits *block_limits;
3639 
3640 		if (!scsi_vpd_supported_page(periph, SVPD_BLOCK_LIMITS)) {
3641 			/* Not supported skip to next probe */
3642 			softc->state = DA_STATE_PROBE_BDC;
3643 			goto skipstate;
3644 		}
3645 
3646 		block_limits = (struct scsi_vpd_block_limits *)
3647 			malloc(sizeof(*block_limits), M_SCSIDA, M_NOWAIT|M_ZERO);
3648 
3649 		if (block_limits == NULL) {
3650 			printf("dastart: Couldn't malloc block_limits data\n");
3651 			/* da_free_periph??? */
3652 			break;
3653 		}
3654 
3655 		scsi_inquiry(&start_ccb->csio,
3656 			     /*retries*/da_retry_count,
3657 			     /*cbfcnp*/dadone_probeblklimits,
3658 			     /*tag_action*/MSG_SIMPLE_Q_TAG,
3659 			     /*inq_buf*/(u_int8_t *)block_limits,
3660 			     /*inq_len*/sizeof(*block_limits),
3661 			     /*evpd*/TRUE,
3662 			     /*page_code*/SVPD_BLOCK_LIMITS,
3663 			     /*sense_len*/SSD_MIN_SIZE,
3664 			     /*timeout*/da_default_timeout * 1000);
3665 		start_ccb->ccb_h.ccb_bp = NULL;
3666 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BLK_LIMITS;
3667 		xpt_action(start_ccb);
3668 		break;
3669 	}
3670 	case DA_STATE_PROBE_BDC:
3671 	{
3672 		struct scsi_vpd_block_device_characteristics *bdc;
3673 
3674 		if (!scsi_vpd_supported_page(periph, SVPD_BDC)) {
3675 			softc->state = DA_STATE_PROBE_ATA;
3676 			goto skipstate;
3677 		}
3678 
3679 		bdc = (struct scsi_vpd_block_device_characteristics *)
3680 			malloc(sizeof(*bdc), M_SCSIDA, M_NOWAIT|M_ZERO);
3681 
3682 		if (bdc == NULL) {
3683 			printf("dastart: Couldn't malloc bdc data\n");
3684 			/* da_free_periph??? */
3685 			break;
3686 		}
3687 
3688 		scsi_inquiry(&start_ccb->csio,
3689 			     /*retries*/da_retry_count,
3690 			     /*cbfcnp*/dadone_probebdc,
3691 			     /*tag_action*/MSG_SIMPLE_Q_TAG,
3692 			     /*inq_buf*/(u_int8_t *)bdc,
3693 			     /*inq_len*/sizeof(*bdc),
3694 			     /*evpd*/TRUE,
3695 			     /*page_code*/SVPD_BDC,
3696 			     /*sense_len*/SSD_MIN_SIZE,
3697 			     /*timeout*/da_default_timeout * 1000);
3698 		start_ccb->ccb_h.ccb_bp = NULL;
3699 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BDC;
3700 		xpt_action(start_ccb);
3701 		break;
3702 	}
3703 	case DA_STATE_PROBE_ATA:
3704 	{
3705 		struct ata_params *ata_params;
3706 
3707 		if (!scsi_vpd_supported_page(periph, SVPD_ATA_INFORMATION)) {
3708 			if ((softc->zone_mode == DA_ZONE_HOST_AWARE)
3709 			 || (softc->zone_mode == DA_ZONE_HOST_MANAGED)) {
3710 				/*
3711 				 * Note that if the ATA VPD page isn't
3712 				 * supported, we aren't talking to an ATA
3713 				 * device anyway.  Support for that VPD
3714 				 * page is mandatory for SCSI to ATA (SAT)
3715 				 * translation layers.
3716 				 */
3717 				softc->state = DA_STATE_PROBE_ZONE;
3718 				goto skipstate;
3719 			}
3720 			daprobedone(periph, start_ccb);
3721 			break;
3722 		}
3723 
3724 		ata_params = &periph->path->device->ident_data;
3725 
3726 		scsi_ata_identify(&start_ccb->csio,
3727 				  /*retries*/da_retry_count,
3728 				  /*cbfcnp*/dadone_probeata,
3729                                   /*tag_action*/MSG_SIMPLE_Q_TAG,
3730 				  /*data_ptr*/(u_int8_t *)ata_params,
3731 				  /*dxfer_len*/sizeof(*ata_params),
3732 				  /*sense_len*/SSD_FULL_SIZE,
3733 				  /*timeout*/da_default_timeout * 1000);
3734 		start_ccb->ccb_h.ccb_bp = NULL;
3735 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ATA;
3736 		xpt_action(start_ccb);
3737 		break;
3738 	}
3739 	case DA_STATE_PROBE_ATA_LOGDIR:
3740 	{
3741 		struct ata_gp_log_dir *log_dir;
3742 		int retval;
3743 
3744 		retval = 0;
3745 
3746 		if ((softc->flags & DA_FLAG_CAN_ATA_LOG) == 0) {
3747 			/*
3748 			 * If we don't have log support, not much point in
3749 			 * trying to probe zone support.
3750 			 */
3751 			daprobedone(periph, start_ccb);
3752 			break;
3753 		}
3754 
3755 		/*
3756 		 * If we have an ATA device (the SCSI ATA Information VPD
3757 		 * page should be present and the ATA identify should have
3758 		 * succeeded) and it supports logs, ask for the log directory.
3759 		 */
3760 
3761 		log_dir = malloc(sizeof(*log_dir), M_SCSIDA, M_NOWAIT|M_ZERO);
3762 		if (log_dir == NULL) {
3763 			xpt_print(periph->path, "Couldn't malloc log_dir "
3764 			    "data\n");
3765 			daprobedone(periph, start_ccb);
3766 			break;
3767 		}
3768 
3769 		retval = scsi_ata_read_log(&start_ccb->csio,
3770 		    /*retries*/ da_retry_count,
3771 		    /*cbfcnp*/ dadone_probeatalogdir,
3772 		    /*tag_action*/ MSG_SIMPLE_Q_TAG,
3773 		    /*log_address*/ ATA_LOG_DIRECTORY,
3774 		    /*page_number*/ 0,
3775 		    /*block_count*/ 1,
3776 		    /*protocol*/ softc->flags & DA_FLAG_CAN_ATA_DMA ?
3777 				 AP_PROTO_DMA : AP_PROTO_PIO_IN,
3778 		    /*data_ptr*/ (uint8_t *)log_dir,
3779 		    /*dxfer_len*/ sizeof(*log_dir),
3780 		    /*sense_len*/ SSD_FULL_SIZE,
3781 		    /*timeout*/ da_default_timeout * 1000);
3782 
3783 		if (retval != 0) {
3784 			xpt_print(periph->path, "scsi_ata_read_log() failed!");
3785 			free(log_dir, M_SCSIDA);
3786 			daprobedone(periph, start_ccb);
3787 			break;
3788 		}
3789 		start_ccb->ccb_h.ccb_bp = NULL;
3790 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ATA_LOGDIR;
3791 		xpt_action(start_ccb);
3792 		break;
3793 	}
3794 	case DA_STATE_PROBE_ATA_IDDIR:
3795 	{
3796 		struct ata_identify_log_pages *id_dir;
3797 		int retval;
3798 
3799 		retval = 0;
3800 
3801 		/*
3802 		 * Check here to see whether the Identify Device log is
3803 		 * supported in the directory of logs.  If so, continue
3804 		 * with requesting the log of identify device pages.
3805 		 */
3806 		if ((softc->flags & DA_FLAG_CAN_ATA_IDLOG) == 0) {
3807 			daprobedone(periph, start_ccb);
3808 			break;
3809 		}
3810 
3811 		id_dir = malloc(sizeof(*id_dir), M_SCSIDA, M_NOWAIT | M_ZERO);
3812 		if (id_dir == NULL) {
3813 			xpt_print(periph->path, "Couldn't malloc id_dir "
3814 			    "data\n");
3815 			daprobedone(periph, start_ccb);
3816 			break;
3817 		}
3818 
3819 		retval = scsi_ata_read_log(&start_ccb->csio,
3820 		    /*retries*/ da_retry_count,
3821 		    /*cbfcnp*/ dadone_probeataiddir,
3822 		    /*tag_action*/ MSG_SIMPLE_Q_TAG,
3823 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
3824 		    /*page_number*/ ATA_IDL_PAGE_LIST,
3825 		    /*block_count*/ 1,
3826 		    /*protocol*/ softc->flags & DA_FLAG_CAN_ATA_DMA ?
3827 				 AP_PROTO_DMA : AP_PROTO_PIO_IN,
3828 		    /*data_ptr*/ (uint8_t *)id_dir,
3829 		    /*dxfer_len*/ sizeof(*id_dir),
3830 		    /*sense_len*/ SSD_FULL_SIZE,
3831 		    /*timeout*/ da_default_timeout * 1000);
3832 
3833 		if (retval != 0) {
3834 			xpt_print(periph->path, "scsi_ata_read_log() failed!");
3835 			free(id_dir, M_SCSIDA);
3836 			daprobedone(periph, start_ccb);
3837 			break;
3838 		}
3839 		start_ccb->ccb_h.ccb_bp = NULL;
3840 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ATA_IDDIR;
3841 		xpt_action(start_ccb);
3842 		break;
3843 	}
3844 	case DA_STATE_PROBE_ATA_SUP:
3845 	{
3846 		struct ata_identify_log_sup_cap *sup_cap;
3847 		int retval;
3848 
3849 		retval = 0;
3850 
3851 		/*
3852 		 * Check here to see whether the Supported Capabilities log
3853 		 * is in the list of Identify Device logs.
3854 		 */
3855 		if ((softc->flags & DA_FLAG_CAN_ATA_SUPCAP) == 0) {
3856 			daprobedone(periph, start_ccb);
3857 			break;
3858 		}
3859 
3860 		sup_cap = malloc(sizeof(*sup_cap), M_SCSIDA, M_NOWAIT|M_ZERO);
3861 		if (sup_cap == NULL) {
3862 			xpt_print(periph->path, "Couldn't malloc sup_cap "
3863 			    "data\n");
3864 			daprobedone(periph, start_ccb);
3865 			break;
3866 		}
3867 
3868 		retval = scsi_ata_read_log(&start_ccb->csio,
3869 		    /*retries*/ da_retry_count,
3870 		    /*cbfcnp*/ dadone_probeatasup,
3871 		    /*tag_action*/ MSG_SIMPLE_Q_TAG,
3872 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
3873 		    /*page_number*/ ATA_IDL_SUP_CAP,
3874 		    /*block_count*/ 1,
3875 		    /*protocol*/ softc->flags & DA_FLAG_CAN_ATA_DMA ?
3876 				 AP_PROTO_DMA : AP_PROTO_PIO_IN,
3877 		    /*data_ptr*/ (uint8_t *)sup_cap,
3878 		    /*dxfer_len*/ sizeof(*sup_cap),
3879 		    /*sense_len*/ SSD_FULL_SIZE,
3880 		    /*timeout*/ da_default_timeout * 1000);
3881 
3882 		if (retval != 0) {
3883 			xpt_print(periph->path, "scsi_ata_read_log() failed!");
3884 			free(sup_cap, M_SCSIDA);
3885 			daprobedone(periph, start_ccb);
3886 			break;
3887 		}
3888 
3889 		start_ccb->ccb_h.ccb_bp = NULL;
3890 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ATA_SUP;
3891 		xpt_action(start_ccb);
3892 		break;
3893 	}
3894 	case DA_STATE_PROBE_ATA_ZONE:
3895 	{
3896 		struct ata_zoned_info_log *ata_zone;
3897 		int retval;
3898 
3899 		retval = 0;
3900 
3901 		/*
3902 		 * Check here to see whether the zoned device information
3903 		 * page is supported.  If so, continue on to request it.
3904 		 * If not, skip to DA_STATE_PROBE_LOG or done.
3905 		 */
3906 		if ((softc->flags & DA_FLAG_CAN_ATA_ZONE) == 0) {
3907 			daprobedone(periph, start_ccb);
3908 			break;
3909 		}
3910 		ata_zone = malloc(sizeof(*ata_zone), M_SCSIDA,
3911 				  M_NOWAIT|M_ZERO);
3912 		if (ata_zone == NULL) {
3913 			xpt_print(periph->path, "Couldn't malloc ata_zone "
3914 			    "data\n");
3915 			daprobedone(periph, start_ccb);
3916 			break;
3917 		}
3918 
3919 		retval = scsi_ata_read_log(&start_ccb->csio,
3920 		    /*retries*/ da_retry_count,
3921 		    /*cbfcnp*/ dadone_probeatazone,
3922 		    /*tag_action*/ MSG_SIMPLE_Q_TAG,
3923 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
3924 		    /*page_number*/ ATA_IDL_ZDI,
3925 		    /*block_count*/ 1,
3926 		    /*protocol*/ softc->flags & DA_FLAG_CAN_ATA_DMA ?
3927 				 AP_PROTO_DMA : AP_PROTO_PIO_IN,
3928 		    /*data_ptr*/ (uint8_t *)ata_zone,
3929 		    /*dxfer_len*/ sizeof(*ata_zone),
3930 		    /*sense_len*/ SSD_FULL_SIZE,
3931 		    /*timeout*/ da_default_timeout * 1000);
3932 
3933 		if (retval != 0) {
3934 			xpt_print(periph->path, "scsi_ata_read_log() failed!");
3935 			free(ata_zone, M_SCSIDA);
3936 			daprobedone(periph, start_ccb);
3937 			break;
3938 		}
3939 		start_ccb->ccb_h.ccb_bp = NULL;
3940 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ATA_ZONE;
3941 		xpt_action(start_ccb);
3942 
3943 		break;
3944 	}
3945 	case DA_STATE_PROBE_ZONE:
3946 	{
3947 		struct scsi_vpd_zoned_bdc *bdc;
3948 
3949 		/*
3950 		 * Note that this page will be supported for SCSI protocol
3951 		 * devices that support ZBC (SMR devices), as well as ATA
3952 		 * protocol devices that are behind a SAT (SCSI to ATA
3953 		 * Translation) layer that supports converting ZBC commands
3954 		 * to their ZAC equivalents.
3955 		 */
3956 		if (!scsi_vpd_supported_page(periph, SVPD_ZONED_BDC)) {
3957 			daprobedone(periph, start_ccb);
3958 			break;
3959 		}
3960 		bdc = (struct scsi_vpd_zoned_bdc *)
3961 			malloc(sizeof(*bdc), M_SCSIDA, M_NOWAIT|M_ZERO);
3962 
3963 		if (bdc == NULL) {
3964 			xpt_release_ccb(start_ccb);
3965 			xpt_print(periph->path, "Couldn't malloc zone VPD "
3966 			    "data\n");
3967 			break;
3968 		}
3969 		scsi_inquiry(&start_ccb->csio,
3970 			     /*retries*/da_retry_count,
3971 			     /*cbfcnp*/dadone_probezone,
3972 			     /*tag_action*/MSG_SIMPLE_Q_TAG,
3973 			     /*inq_buf*/(u_int8_t *)bdc,
3974 			     /*inq_len*/sizeof(*bdc),
3975 			     /*evpd*/TRUE,
3976 			     /*page_code*/SVPD_ZONED_BDC,
3977 			     /*sense_len*/SSD_FULL_SIZE,
3978 			     /*timeout*/da_default_timeout * 1000);
3979 		start_ccb->ccb_h.ccb_bp = NULL;
3980 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ZONE;
3981 		xpt_action(start_ccb);
3982 		break;
3983 	}
3984 	}
3985 }
3986 
3987 /*
3988  * In each of the methods below, while its the caller's
3989  * responsibility to ensure the request will fit into a
3990  * single device request, we might have changed the delete
3991  * method due to the device incorrectly advertising either
3992  * its supported methods or limits.
3993  *
3994  * To prevent this causing further issues we validate the
3995  * against the methods limits, and warn which would
3996  * otherwise be unnecessary.
3997  */
3998 static void
3999 da_delete_unmap(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
4000 {
4001 	struct da_softc *softc = (struct da_softc *)periph->softc;
4002 	struct bio *bp1;
4003 	uint8_t *buf = softc->unmap_buf;
4004 	struct scsi_unmap_desc *d = (void *)&buf[UNMAP_HEAD_SIZE];
4005 	uint64_t lba, lastlba = (uint64_t)-1;
4006 	uint64_t totalcount = 0;
4007 	uint64_t count;
4008 	uint32_t c, lastcount = 0, ranges = 0;
4009 
4010 	/*
4011 	 * Currently this doesn't take the UNMAP
4012 	 * Granularity and Granularity Alignment
4013 	 * fields into account.
4014 	 *
4015 	 * This could result in both unoptimal unmap
4016 	 * requests as as well as UNMAP calls unmapping
4017 	 * fewer LBA's than requested.
4018 	 */
4019 
4020 	bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
4021 	bp1 = bp;
4022 	do {
4023 		/*
4024 		 * Note: ada and da are different in how they store the
4025 		 * pending bp's in a trim. ada stores all of them in the
4026 		 * trim_req.bps. da stores all but the first one in the
4027 		 * delete_run_queue. ada then completes all the bps in
4028 		 * its adadone() loop. da completes all the bps in the
4029 		 * delete_run_queue in dadone, and relies on the biodone
4030 		 * after to complete. This should be reconciled since there's
4031 		 * no real reason to do it differently. XXX
4032 		 */
4033 		if (bp1 != bp)
4034 			bioq_insert_tail(&softc->delete_run_queue, bp1);
4035 		lba = bp1->bio_pblkno;
4036 		count = bp1->bio_bcount / softc->params.secsize;
4037 
4038 		/* Try to extend the previous range. */
4039 		if (lba == lastlba) {
4040 			c = omin(count, UNMAP_RANGE_MAX - lastcount);
4041 			lastlba += c;
4042 			lastcount += c;
4043 			scsi_ulto4b(lastcount, d[ranges - 1].length);
4044 			count -= c;
4045 			lba += c;
4046 			totalcount += c;
4047 		} else if ((softc->quirks & DA_Q_STRICT_UNMAP) &&
4048 		    softc->unmap_gran != 0) {
4049 			/* Align length of the previous range. */
4050 			if ((c = lastcount % softc->unmap_gran) != 0) {
4051 				if (lastcount <= c) {
4052 					totalcount -= lastcount;
4053 					lastlba = (uint64_t)-1;
4054 					lastcount = 0;
4055 					ranges--;
4056 				} else {
4057 					totalcount -= c;
4058 					lastlba -= c;
4059 					lastcount -= c;
4060 					scsi_ulto4b(lastcount,
4061 					    d[ranges - 1].length);
4062 				}
4063 			}
4064 			/* Align beginning of the new range. */
4065 			c = (lba - softc->unmap_gran_align) % softc->unmap_gran;
4066 			if (c != 0) {
4067 				c = softc->unmap_gran - c;
4068 				if (count <= c) {
4069 					count = 0;
4070 				} else {
4071 					lba += c;
4072 					count -= c;
4073 				}
4074 			}
4075 		}
4076 
4077 		while (count > 0) {
4078 			c = omin(count, UNMAP_RANGE_MAX);
4079 			if (totalcount + c > softc->unmap_max_lba ||
4080 			    ranges >= softc->unmap_max_ranges) {
4081 				xpt_print(periph->path,
4082 				    "%s issuing short delete %ld > %ld"
4083 				    "|| %d >= %d",
4084 				    da_delete_method_desc[softc->delete_method],
4085 				    totalcount + c, softc->unmap_max_lba,
4086 				    ranges, softc->unmap_max_ranges);
4087 				break;
4088 			}
4089 			scsi_u64to8b(lba, d[ranges].lba);
4090 			scsi_ulto4b(c, d[ranges].length);
4091 			lba += c;
4092 			totalcount += c;
4093 			ranges++;
4094 			count -= c;
4095 			lastlba = lba;
4096 			lastcount = c;
4097 		}
4098 		bp1 = cam_iosched_next_trim(softc->cam_iosched);
4099 		if (bp1 == NULL)
4100 			break;
4101 		if (ranges >= softc->unmap_max_ranges ||
4102 		    totalcount + bp1->bio_bcount /
4103 		    softc->params.secsize > softc->unmap_max_lba) {
4104 			cam_iosched_put_back_trim(softc->cam_iosched, bp1);
4105 			break;
4106 		}
4107 	} while (1);
4108 
4109 	/* Align length of the last range. */
4110 	if ((softc->quirks & DA_Q_STRICT_UNMAP) && softc->unmap_gran != 0 &&
4111 	    (c = lastcount % softc->unmap_gran) != 0) {
4112 		if (lastcount <= c)
4113 			ranges--;
4114 		else
4115 			scsi_ulto4b(lastcount - c, d[ranges - 1].length);
4116 	}
4117 
4118 	scsi_ulto2b(ranges * 16 + 6, &buf[0]);
4119 	scsi_ulto2b(ranges * 16, &buf[2]);
4120 
4121 	scsi_unmap(&ccb->csio,
4122 		   /*retries*/da_retry_count,
4123 		   /*cbfcnp*/dadone,
4124 		   /*tag_action*/MSG_SIMPLE_Q_TAG,
4125 		   /*byte2*/0,
4126 		   /*data_ptr*/ buf,
4127 		   /*dxfer_len*/ ranges * 16 + 8,
4128 		   /*sense_len*/SSD_FULL_SIZE,
4129 		   da_default_timeout * 1000);
4130 	ccb->ccb_h.ccb_state = DA_CCB_DELETE;
4131 	ccb->ccb_h.flags |= CAM_UNLOCKED;
4132 	softc->trim_count++;
4133 	softc->trim_ranges += ranges;
4134 	softc->trim_lbas += totalcount;
4135 	cam_iosched_submit_trim(softc->cam_iosched);
4136 }
4137 
4138 static void
4139 da_delete_trim(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
4140 {
4141 	struct da_softc *softc = (struct da_softc *)periph->softc;
4142 	struct bio *bp1;
4143 	uint8_t *buf = softc->unmap_buf;
4144 	uint64_t lastlba = (uint64_t)-1;
4145 	uint64_t count;
4146 	uint64_t lba;
4147 	uint32_t lastcount = 0, c, requestcount;
4148 	int ranges = 0, off, block_count;
4149 
4150 	bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
4151 	bp1 = bp;
4152 	do {
4153 		if (bp1 != bp)//XXX imp XXX
4154 			bioq_insert_tail(&softc->delete_run_queue, bp1);
4155 		lba = bp1->bio_pblkno;
4156 		count = bp1->bio_bcount / softc->params.secsize;
4157 		requestcount = count;
4158 
4159 		/* Try to extend the previous range. */
4160 		if (lba == lastlba) {
4161 			c = omin(count, ATA_DSM_RANGE_MAX - lastcount);
4162 			lastcount += c;
4163 			off = (ranges - 1) * 8;
4164 			buf[off + 6] = lastcount & 0xff;
4165 			buf[off + 7] = (lastcount >> 8) & 0xff;
4166 			count -= c;
4167 			lba += c;
4168 		}
4169 
4170 		while (count > 0) {
4171 			c = omin(count, ATA_DSM_RANGE_MAX);
4172 			off = ranges * 8;
4173 
4174 			buf[off + 0] = lba & 0xff;
4175 			buf[off + 1] = (lba >> 8) & 0xff;
4176 			buf[off + 2] = (lba >> 16) & 0xff;
4177 			buf[off + 3] = (lba >> 24) & 0xff;
4178 			buf[off + 4] = (lba >> 32) & 0xff;
4179 			buf[off + 5] = (lba >> 40) & 0xff;
4180 			buf[off + 6] = c & 0xff;
4181 			buf[off + 7] = (c >> 8) & 0xff;
4182 			lba += c;
4183 			ranges++;
4184 			count -= c;
4185 			lastcount = c;
4186 			if (count != 0 && ranges == softc->trim_max_ranges) {
4187 				xpt_print(periph->path,
4188 				    "%s issuing short delete %ld > %ld\n",
4189 				    da_delete_method_desc[softc->delete_method],
4190 				    requestcount,
4191 				    (softc->trim_max_ranges - ranges) *
4192 				    ATA_DSM_RANGE_MAX);
4193 				break;
4194 			}
4195 		}
4196 		lastlba = lba;
4197 		bp1 = cam_iosched_next_trim(softc->cam_iosched);
4198 		if (bp1 == NULL)
4199 			break;
4200 		if (bp1->bio_bcount / softc->params.secsize >
4201 		    (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX) {
4202 			cam_iosched_put_back_trim(softc->cam_iosched, bp1);
4203 			break;
4204 		}
4205 	} while (1);
4206 
4207 	block_count = howmany(ranges, ATA_DSM_BLK_RANGES);
4208 	scsi_ata_trim(&ccb->csio,
4209 		      /*retries*/da_retry_count,
4210 		      /*cbfcnp*/dadone,
4211 		      /*tag_action*/MSG_SIMPLE_Q_TAG,
4212 		      block_count,
4213 		      /*data_ptr*/buf,
4214 		      /*dxfer_len*/block_count * ATA_DSM_BLK_SIZE,
4215 		      /*sense_len*/SSD_FULL_SIZE,
4216 		      da_default_timeout * 1000);
4217 	ccb->ccb_h.ccb_state = DA_CCB_DELETE;
4218 	ccb->ccb_h.flags |= CAM_UNLOCKED;
4219 	cam_iosched_submit_trim(softc->cam_iosched);
4220 }
4221 
4222 /*
4223  * We calculate ws_max_blks here based off d_delmaxsize instead
4224  * of using softc->ws_max_blks as it is absolute max for the
4225  * device not the protocol max which may well be lower.
4226  */
4227 static void
4228 da_delete_ws(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
4229 {
4230 	struct da_softc *softc;
4231 	struct bio *bp1;
4232 	uint64_t ws_max_blks;
4233 	uint64_t lba;
4234 	uint64_t count; /* forward compat with WS32 */
4235 
4236 	softc = (struct da_softc *)periph->softc;
4237 	ws_max_blks = softc->disk->d_delmaxsize / softc->params.secsize;
4238 	lba = bp->bio_pblkno;
4239 	count = 0;
4240 	bp1 = bp;
4241 	do {
4242 		if (bp1 != bp)//XXX imp XXX
4243 			bioq_insert_tail(&softc->delete_run_queue, bp1);
4244 		count += bp1->bio_bcount / softc->params.secsize;
4245 		if (count > ws_max_blks) {
4246 			xpt_print(periph->path,
4247 			    "%s issuing short delete %ld > %ld\n",
4248 			    da_delete_method_desc[softc->delete_method],
4249 			    count, ws_max_blks);
4250 			count = omin(count, ws_max_blks);
4251 			break;
4252 		}
4253 		bp1 = cam_iosched_next_trim(softc->cam_iosched);
4254 		if (bp1 == NULL)
4255 			break;
4256 		if (lba + count != bp1->bio_pblkno ||
4257 		    count + bp1->bio_bcount /
4258 		    softc->params.secsize > ws_max_blks) {
4259 			cam_iosched_put_back_trim(softc->cam_iosched, bp1);
4260 			break;
4261 		}
4262 	} while (1);
4263 
4264 	scsi_write_same(&ccb->csio,
4265 			/*retries*/da_retry_count,
4266 			/*cbfcnp*/dadone,
4267 			/*tag_action*/MSG_SIMPLE_Q_TAG,
4268 			/*byte2*/softc->delete_method ==
4269 			    DA_DELETE_ZERO ? 0 : SWS_UNMAP,
4270 			softc->delete_method == DA_DELETE_WS16 ? 16 : 10,
4271 			/*lba*/lba,
4272 			/*block_count*/count,
4273 			/*data_ptr*/ __DECONST(void *, zero_region),
4274 			/*dxfer_len*/ softc->params.secsize,
4275 			/*sense_len*/SSD_FULL_SIZE,
4276 			da_default_timeout * 1000);
4277 	ccb->ccb_h.ccb_state = DA_CCB_DELETE;
4278 	ccb->ccb_h.flags |= CAM_UNLOCKED;
4279 	cam_iosched_submit_trim(softc->cam_iosched);
4280 }
4281 
4282 static int
4283 cmd6workaround(union ccb *ccb)
4284 {
4285 	struct scsi_rw_6 cmd6;
4286 	struct scsi_rw_10 *cmd10;
4287 	struct da_softc *softc;
4288 	u_int8_t *cdb;
4289 	struct bio *bp;
4290 	int frozen;
4291 
4292 	cdb = ccb->csio.cdb_io.cdb_bytes;
4293 	softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
4294 
4295 	if (ccb->ccb_h.ccb_state == DA_CCB_DELETE) {
4296 		da_delete_methods old_method = softc->delete_method;
4297 
4298 		/*
4299 		 * Typically there are two reasons for failure here
4300 		 * 1. Delete method was detected as supported but isn't
4301 		 * 2. Delete failed due to invalid params e.g. too big
4302 		 *
4303 		 * While we will attempt to choose an alternative delete method
4304 		 * this may result in short deletes if the existing delete
4305 		 * requests from geom are big for the new method chosen.
4306 		 *
4307 		 * This method assumes that the error which triggered this
4308 		 * will not retry the io otherwise a panic will occur
4309 		 */
4310 		dadeleteflag(softc, old_method, 0);
4311 		dadeletemethodchoose(softc, DA_DELETE_DISABLE);
4312 		if (softc->delete_method == DA_DELETE_DISABLE)
4313 			xpt_print(ccb->ccb_h.path,
4314 				  "%s failed, disabling BIO_DELETE\n",
4315 				  da_delete_method_desc[old_method]);
4316 		else
4317 			xpt_print(ccb->ccb_h.path,
4318 				  "%s failed, switching to %s BIO_DELETE\n",
4319 				  da_delete_method_desc[old_method],
4320 				  da_delete_method_desc[softc->delete_method]);
4321 
4322 		while ((bp = bioq_takefirst(&softc->delete_run_queue)) != NULL)
4323 			cam_iosched_queue_work(softc->cam_iosched, bp);
4324 		cam_iosched_queue_work(softc->cam_iosched,
4325 		    (struct bio *)ccb->ccb_h.ccb_bp);
4326 		ccb->ccb_h.ccb_bp = NULL;
4327 		return (0);
4328 	}
4329 
4330 	/* Detect unsupported PREVENT ALLOW MEDIUM REMOVAL. */
4331 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) == 0 &&
4332 	    (*cdb == PREVENT_ALLOW) &&
4333 	    (softc->quirks & DA_Q_NO_PREVENT) == 0) {
4334 		if (bootverbose)
4335 			xpt_print(ccb->ccb_h.path,
4336 			    "PREVENT ALLOW MEDIUM REMOVAL not supported.\n");
4337 		softc->quirks |= DA_Q_NO_PREVENT;
4338 		return (0);
4339 	}
4340 
4341 	/* Detect unsupported SYNCHRONIZE CACHE(10). */
4342 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) == 0 &&
4343 	    (*cdb == SYNCHRONIZE_CACHE) &&
4344 	    (softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
4345 		if (bootverbose)
4346 			xpt_print(ccb->ccb_h.path,
4347 			    "SYNCHRONIZE CACHE(10) not supported.\n");
4348 		softc->quirks |= DA_Q_NO_SYNC_CACHE;
4349 		softc->disk->d_flags &= ~DISKFLAG_CANFLUSHCACHE;
4350 		return (0);
4351 	}
4352 
4353 	/* Translation only possible if CDB is an array and cmd is R/W6 */
4354 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
4355 	    (*cdb != READ_6 && *cdb != WRITE_6))
4356 		return 0;
4357 
4358 	xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, "
4359 	    "increasing minimum_cmd_size to 10.\n");
4360 	softc->minimum_cmd_size = 10;
4361 
4362 	bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
4363 	cmd10 = (struct scsi_rw_10 *)cdb;
4364 	cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
4365 	cmd10->byte2 = 0;
4366 	scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
4367 	cmd10->reserved = 0;
4368 	scsi_ulto2b(cmd6.length, cmd10->length);
4369 	cmd10->control = cmd6.control;
4370 	ccb->csio.cdb_len = sizeof(*cmd10);
4371 
4372 	/* Requeue request, unfreezing queue if necessary */
4373 	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
4374 	ccb->ccb_h.status = CAM_REQUEUE_REQ;
4375 	xpt_action(ccb);
4376 	if (frozen) {
4377 		cam_release_devq(ccb->ccb_h.path,
4378 				 /*relsim_flags*/0,
4379 				 /*reduction*/0,
4380 				 /*timeout*/0,
4381 				 /*getcount_only*/0);
4382 	}
4383 	return (ERESTART);
4384 }
4385 
4386 static void
4387 dazonedone(struct cam_periph *periph, union ccb *ccb)
4388 {
4389 	struct da_softc *softc;
4390 	struct bio *bp;
4391 
4392 	softc = periph->softc;
4393 	bp = (struct bio *)ccb->ccb_h.ccb_bp;
4394 
4395 	switch (bp->bio_zone.zone_cmd) {
4396 	case DISK_ZONE_OPEN:
4397 	case DISK_ZONE_CLOSE:
4398 	case DISK_ZONE_FINISH:
4399 	case DISK_ZONE_RWP:
4400 		break;
4401 	case DISK_ZONE_REPORT_ZONES: {
4402 		uint32_t avail_len;
4403 		struct disk_zone_report *rep;
4404 		struct scsi_report_zones_hdr *hdr;
4405 		struct scsi_report_zones_desc *desc;
4406 		struct disk_zone_rep_entry *entry;
4407 		uint32_t hdr_len, num_avail;
4408 		uint32_t num_to_fill, i;
4409 		int ata;
4410 
4411 		rep = &bp->bio_zone.zone_params.report;
4412 		avail_len = ccb->csio.dxfer_len - ccb->csio.resid;
4413 		/*
4414 		 * Note that bio_resid isn't normally used for zone
4415 		 * commands, but it is used by devstat_end_transaction_bio()
4416 		 * to determine how much data was transferred.  Because
4417 		 * the size of the SCSI/ATA data structures is different
4418 		 * than the size of the BIO interface structures, the
4419 		 * amount of data actually transferred from the drive will
4420 		 * be different than the amount of data transferred to
4421 		 * the user.
4422 		 */
4423 		bp->bio_resid = ccb->csio.resid;
4424 		hdr = (struct scsi_report_zones_hdr *)ccb->csio.data_ptr;
4425 		if (avail_len < sizeof(*hdr)) {
4426 			/*
4427 			 * Is there a better error than EIO here?  We asked
4428 			 * for at least the header, and we got less than
4429 			 * that.
4430 			 */
4431 			bp->bio_error = EIO;
4432 			bp->bio_flags |= BIO_ERROR;
4433 			bp->bio_resid = bp->bio_bcount;
4434 			break;
4435 		}
4436 
4437 		if (softc->zone_interface == DA_ZONE_IF_ATA_PASS)
4438 			ata = 1;
4439 		else
4440 			ata = 0;
4441 
4442 		hdr_len = ata ? le32dec(hdr->length) :
4443 				scsi_4btoul(hdr->length);
4444 		if (hdr_len > 0)
4445 			rep->entries_available = hdr_len / sizeof(*desc);
4446 		else
4447 			rep->entries_available = 0;
4448 		/*
4449 		 * NOTE: using the same values for the BIO version of the
4450 		 * same field as the SCSI/ATA values.  This means we could
4451 		 * get some additional values that aren't defined in bio.h
4452 		 * if more values of the same field are defined later.
4453 		 */
4454 		rep->header.same = hdr->byte4 & SRZ_SAME_MASK;
4455 		rep->header.maximum_lba = ata ?  le64dec(hdr->maximum_lba) :
4456 					  scsi_8btou64(hdr->maximum_lba);
4457 		/*
4458 		 * If the drive reports no entries that match the query,
4459 		 * we're done.
4460 		 */
4461 		if (hdr_len == 0) {
4462 			rep->entries_filled = 0;
4463 			break;
4464 		}
4465 
4466 		num_avail = min((avail_len - sizeof(*hdr)) / sizeof(*desc),
4467 				hdr_len / sizeof(*desc));
4468 		/*
4469 		 * If the drive didn't return any data, then we're done.
4470 		 */
4471 		if (num_avail == 0) {
4472 			rep->entries_filled = 0;
4473 			break;
4474 		}
4475 
4476 		num_to_fill = min(num_avail, rep->entries_allocated);
4477 		/*
4478 		 * If the user didn't allocate any entries for us to fill,
4479 		 * we're done.
4480 		 */
4481 		if (num_to_fill == 0) {
4482 			rep->entries_filled = 0;
4483 			break;
4484 		}
4485 
4486 		for (i = 0, desc = &hdr->desc_list[0], entry=&rep->entries[0];
4487 		     i < num_to_fill; i++, desc++, entry++) {
4488 			/*
4489 			 * NOTE: we're mapping the values here directly
4490 			 * from the SCSI/ATA bit definitions to the bio.h
4491 			 * definitions. There is also a warning in
4492 			 * disk_zone.h, but the impact is that if
4493 			 * additional values are added in the SCSI/ATA
4494 			 * specs these will be visible to consumers of
4495 			 * this interface.
4496 			 */
4497 			entry->zone_type = desc->zone_type & SRZ_TYPE_MASK;
4498 			entry->zone_condition =
4499 			    (desc->zone_flags & SRZ_ZONE_COND_MASK) >>
4500 			    SRZ_ZONE_COND_SHIFT;
4501 			entry->zone_flags |= desc->zone_flags &
4502 			    (SRZ_ZONE_NON_SEQ|SRZ_ZONE_RESET);
4503 			entry->zone_length =
4504 			    ata ? le64dec(desc->zone_length) :
4505 				  scsi_8btou64(desc->zone_length);
4506 			entry->zone_start_lba =
4507 			    ata ? le64dec(desc->zone_start_lba) :
4508 				  scsi_8btou64(desc->zone_start_lba);
4509 			entry->write_pointer_lba =
4510 			    ata ? le64dec(desc->write_pointer_lba) :
4511 				  scsi_8btou64(desc->write_pointer_lba);
4512 		}
4513 		rep->entries_filled = num_to_fill;
4514 		break;
4515 	}
4516 	case DISK_ZONE_GET_PARAMS:
4517 	default:
4518 		/*
4519 		 * In theory we should not get a GET_PARAMS bio, since it
4520 		 * should be handled without queueing the command to the
4521 		 * drive.
4522 		 */
4523 		panic("%s: Invalid zone command %d", __func__,
4524 		    bp->bio_zone.zone_cmd);
4525 		break;
4526 	}
4527 
4528 	if (bp->bio_zone.zone_cmd == DISK_ZONE_REPORT_ZONES)
4529 		free(ccb->csio.data_ptr, M_SCSIDA);
4530 }
4531 
4532 static void
4533 dadone(struct cam_periph *periph, union ccb *done_ccb)
4534 {
4535 	struct bio *bp, *bp1;
4536 	struct da_softc *softc;
4537 	struct ccb_scsiio *csio;
4538 	da_ccb_state state;
4539 
4540 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone\n"));
4541 
4542 	softc = (struct da_softc *)periph->softc;
4543 	csio = &done_ccb->csio;
4544 
4545 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4546 	if (csio->bio != NULL)
4547 		biotrack(csio->bio, __func__);
4548 #endif
4549 	state = csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK;
4550 
4551 	cam_periph_lock(periph);
4552 	bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
4553 	if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4554 		int error;
4555 		int sf;
4556 
4557 		if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
4558 			sf = SF_RETRY_UA;
4559 		else
4560 			sf = 0;
4561 
4562 		error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
4563 		if (error == ERESTART) {
4564 			/* A retry was scheduled, so just return. */
4565 			cam_periph_unlock(periph);
4566 			return;
4567 		}
4568 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
4569 		if (error != 0) {
4570 			int queued_error;
4571 
4572 			/*
4573 			 * return all queued I/O with EIO, so that
4574 			 * the client can retry these I/Os in the
4575 			 * proper order should it attempt to recover.
4576 			 */
4577 			queued_error = EIO;
4578 
4579 			if (error == ENXIO
4580 			 && (softc->flags & DA_FLAG_PACK_INVALID)== 0) {
4581 				/*
4582 				 * Catastrophic error.  Mark our pack as
4583 				 * invalid.
4584 				 *
4585 				 * XXX See if this is really a media
4586 				 * XXX change first?
4587 				 */
4588 				xpt_print(periph->path, "Invalidating pack\n");
4589 				softc->flags |= DA_FLAG_PACK_INVALID;
4590 #ifdef CAM_IO_STATS
4591 				softc->invalidations++;
4592 #endif
4593 				queued_error = ENXIO;
4594 			}
4595 			cam_iosched_flush(softc->cam_iosched, NULL,
4596 			   queued_error);
4597 			if (bp != NULL) {
4598 				bp->bio_error = error;
4599 				bp->bio_resid = bp->bio_bcount;
4600 				bp->bio_flags |= BIO_ERROR;
4601 			}
4602 		} else if (bp != NULL) {
4603 			if (state == DA_CCB_DELETE)
4604 				bp->bio_resid = 0;
4605 			else
4606 				bp->bio_resid = csio->resid;
4607 			bp->bio_error = 0;
4608 			if (bp->bio_resid != 0)
4609 				bp->bio_flags |= BIO_ERROR;
4610 		}
4611 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
4612 			cam_release_devq(done_ccb->ccb_h.path,
4613 					 /*relsim_flags*/0,
4614 					 /*reduction*/0,
4615 					 /*timeout*/0,
4616 					 /*getcount_only*/0);
4617 	} else if (bp != NULL) {
4618 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
4619 			panic("REQ_CMP with QFRZN");
4620 		if (bp->bio_cmd == BIO_ZONE)
4621 			dazonedone(periph, done_ccb);
4622 		else if (state == DA_CCB_DELETE)
4623 			bp->bio_resid = 0;
4624 		else
4625 			bp->bio_resid = csio->resid;
4626 		if ((csio->resid > 0) && (bp->bio_cmd != BIO_ZONE))
4627 			bp->bio_flags |= BIO_ERROR;
4628 		if (softc->error_inject != 0) {
4629 			bp->bio_error = softc->error_inject;
4630 			bp->bio_resid = bp->bio_bcount;
4631 			bp->bio_flags |= BIO_ERROR;
4632 			softc->error_inject = 0;
4633 		}
4634 	}
4635 
4636 	if (bp != NULL)
4637 		biotrack(bp, __func__);
4638 	LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
4639 	if (LIST_EMPTY(&softc->pending_ccbs))
4640 		softc->flags |= DA_FLAG_WAS_OTAG;
4641 
4642 	/*
4643 	 * We need to call cam_iosched before we call biodone so that we don't
4644 	 * measure any activity that happens in the completion routine, which in
4645 	 * the case of sendfile can be quite extensive. Release the periph
4646 	 * refcount taken in dastart() for each CCB.
4647 	 */
4648 	cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb);
4649 	xpt_release_ccb(done_ccb);
4650 	KASSERT(softc->refcount >= 1, ("dadone softc %p refcount %d", softc, softc->refcount));
4651 	softc->refcount--;
4652 	if (state == DA_CCB_DELETE) {
4653 		TAILQ_HEAD(, bio) queue;
4654 
4655 		TAILQ_INIT(&queue);
4656 		TAILQ_CONCAT(&queue, &softc->delete_run_queue.queue, bio_queue);
4657 		softc->delete_run_queue.insert_point = NULL;
4658 		/*
4659 		 * Normally, the xpt_release_ccb() above would make sure
4660 		 * that when we have more work to do, that work would
4661 		 * get kicked off. However, we specifically keep
4662 		 * delete_running set to 0 before the call above to
4663 		 * allow other I/O to progress when many BIO_DELETE
4664 		 * requests are pushed down. We set delete_running to 0
4665 		 * and call daschedule again so that we don't stall if
4666 		 * there are no other I/Os pending apart from BIO_DELETEs.
4667 		 */
4668 		cam_iosched_trim_done(softc->cam_iosched);
4669 		daschedule(periph);
4670 		cam_periph_unlock(periph);
4671 		while ((bp1 = TAILQ_FIRST(&queue)) != NULL) {
4672 			TAILQ_REMOVE(&queue, bp1, bio_queue);
4673 			bp1->bio_error = bp->bio_error;
4674 			if (bp->bio_flags & BIO_ERROR) {
4675 				bp1->bio_flags |= BIO_ERROR;
4676 				bp1->bio_resid = bp1->bio_bcount;
4677 			} else
4678 				bp1->bio_resid = 0;
4679 			biodone(bp1);
4680 		}
4681 	} else {
4682 		daschedule(periph);
4683 		cam_periph_unlock(periph);
4684 	}
4685 	if (bp != NULL)
4686 		biodone(bp);
4687 	return;
4688 }
4689 
4690 static void
4691 dadone_probewp(struct cam_periph *periph, union ccb *done_ccb)
4692 {
4693 	struct da_softc *softc;
4694 	struct ccb_scsiio *csio;
4695 	u_int32_t  priority;
4696 
4697 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probewp\n"));
4698 
4699 	softc = (struct da_softc *)periph->softc;
4700 	priority = done_ccb->ccb_h.pinfo.priority;
4701 	csio = &done_ccb->csio;
4702 
4703 	cam_periph_assert(periph, MA_OWNED);
4704 
4705 	KASSERT(softc->state == DA_STATE_PROBE_WP,
4706 	    ("State (%d) not PROBE_WP in dadone_probewp, periph %p ccb %p",
4707 		softc->state, periph, done_ccb));
4708         KASSERT((csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) == DA_CCB_PROBE_WP,
4709 	    ("CCB State (%lu) not PROBE_WP in dadone_probewp, periph %p ccb %p",
4710 		(unsigned long)csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK, periph,
4711 		done_ccb));
4712 
4713 	if (cam_ccb_status(done_ccb) == CAM_REQ_CMP) {
4714 		int len, off;
4715 		uint8_t dev_spec;
4716 
4717 		if (csio->cdb_len > 6) {
4718 			struct scsi_mode_header_10 *mh =
4719 			    (struct scsi_mode_header_10 *)csio->data_ptr;
4720 			len = 2 + scsi_2btoul(mh->data_length);
4721 			off = sizeof(*mh) + scsi_2btoul(mh->blk_desc_len);
4722 			dev_spec = mh->dev_spec;
4723 		} else {
4724 			struct scsi_mode_header_6 *mh =
4725 			    (struct scsi_mode_header_6 *)csio->data_ptr;
4726 			len = 1 + mh->data_length;
4727 			off = sizeof(*mh) + mh->blk_desc_len;
4728 			dev_spec = mh->dev_spec;
4729 		}
4730 		if ((dev_spec & 0x80) != 0)
4731 			softc->disk->d_flags |= DISKFLAG_WRITE_PROTECT;
4732 		else
4733 			softc->disk->d_flags &= ~DISKFLAG_WRITE_PROTECT;
4734 
4735 		/* Next time request only the first of returned mode pages. */
4736 		if (off < len && off < csio->dxfer_len - csio->resid)
4737 			softc->mode_page = csio->data_ptr[off] & SMPH_PC_MASK;
4738 	} else {
4739 		int error;
4740 
4741 		error = daerror(done_ccb, CAM_RETRY_SELTO,
4742 				SF_RETRY_UA|SF_NO_PRINT);
4743 		if (error == ERESTART)
4744 			return;
4745 		else if (error != 0) {
4746 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
4747 				/* Don't wedge this device's queue */
4748 				cam_release_devq(done_ccb->ccb_h.path,
4749 						 /*relsim_flags*/0,
4750 						 /*reduction*/0,
4751 						 /*timeout*/0,
4752 						 /*getcount_only*/0);
4753 			}
4754 
4755 			/* We don't depend on it, so don't try again. */
4756 			softc->mode_page = -1;
4757 		}
4758 	}
4759 
4760 	free(csio->data_ptr, M_SCSIDA);
4761 	if ((softc->flags & DA_FLAG_CAN_RC16) != 0)
4762 		softc->state = DA_STATE_PROBE_RC16;
4763 	else
4764 		softc->state = DA_STATE_PROBE_RC;
4765 	xpt_release_ccb(done_ccb);
4766 	xpt_schedule(periph, priority);
4767 	return;
4768 }
4769 
4770 static void
4771 dadone_proberc(struct cam_periph *periph, union ccb *done_ccb)
4772 {
4773 	struct scsi_read_capacity_data *rdcap;
4774 	struct scsi_read_capacity_data_long *rcaplong;
4775 	struct da_softc *softc;
4776 	struct ccb_scsiio *csio;
4777 	da_ccb_state state;
4778 	char *announce_buf;
4779 	u_int32_t  priority;
4780 	int lbp, n;
4781 
4782 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_proberc\n"));
4783 
4784 	softc = (struct da_softc *)periph->softc;
4785 	priority = done_ccb->ccb_h.pinfo.priority;
4786 	csio = &done_ccb->csio;
4787 	state = csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK;
4788 
4789 	KASSERT(softc->state == DA_STATE_PROBE_RC || softc->state == DA_STATE_PROBE_RC16,
4790 	    ("State (%d) not PROBE_RC* in dadone_proberc, periph %p ccb %p",
4791 		softc->state, periph, done_ccb));
4792 	KASSERT(state == DA_CCB_PROBE_RC || state == DA_CCB_PROBE_RC16,
4793 	    ("CCB State (%lu) not PROBE_RC* in dadone_probewp, periph %p ccb %p",
4794 		(unsigned long)state, periph, done_ccb));
4795 
4796 	lbp = 0;
4797 	rdcap = NULL;
4798 	rcaplong = NULL;
4799 	/* XXX TODO: can this be a malloc? */
4800 	announce_buf = softc->announce_temp;
4801 	bzero(announce_buf, DA_ANNOUNCETMP_SZ);
4802 
4803 	if (state == DA_CCB_PROBE_RC)
4804 		rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
4805 	else
4806 		rcaplong = (struct scsi_read_capacity_data_long *)
4807 			csio->data_ptr;
4808 
4809 	cam_periph_assert(periph, MA_OWNED);
4810 
4811 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
4812 		struct disk_params *dp;
4813 		uint32_t block_size;
4814 		uint64_t maxsector;
4815 		u_int lalba;	/* Lowest aligned LBA. */
4816 
4817 		if (state == DA_CCB_PROBE_RC) {
4818 			block_size = scsi_4btoul(rdcap->length);
4819 			maxsector = scsi_4btoul(rdcap->addr);
4820 			lalba = 0;
4821 
4822 			/*
4823 			 * According to SBC-2, if the standard 10
4824 			 * byte READ CAPACITY command returns 2^32,
4825 			 * we should issue the 16 byte version of
4826 			 * the command, since the device in question
4827 			 * has more sectors than can be represented
4828 			 * with the short version of the command.
4829 			 */
4830 			if (maxsector == 0xffffffff) {
4831 				free(rdcap, M_SCSIDA);
4832 				softc->state = DA_STATE_PROBE_RC16;
4833 				xpt_release_ccb(done_ccb);
4834 				xpt_schedule(periph, priority);
4835 				return;
4836 			}
4837 		} else {
4838 			block_size = scsi_4btoul(rcaplong->length);
4839 			maxsector = scsi_8btou64(rcaplong->addr);
4840 			lalba = scsi_2btoul(rcaplong->lalba_lbp);
4841 		}
4842 
4843 		/*
4844 		 * Because GEOM code just will panic us if we
4845 		 * give them an 'illegal' value we'll avoid that
4846 		 * here.
4847 		 */
4848 		if (block_size == 0) {
4849 			block_size = 512;
4850 			if (maxsector == 0)
4851 				maxsector = -1;
4852 		}
4853 		if (block_size >= maxphys) {
4854 			xpt_print(periph->path,
4855 			    "unsupportable block size %ju\n",
4856 			    (uintmax_t) block_size);
4857 			announce_buf = NULL;
4858 			cam_periph_invalidate(periph);
4859 		} else {
4860 			/*
4861 			 * We pass rcaplong into dasetgeom(),
4862 			 * because it will only use it if it is
4863 			 * non-NULL.
4864 			 */
4865 			dasetgeom(periph, block_size, maxsector,
4866 				  rcaplong, sizeof(*rcaplong));
4867 			lbp = (lalba & SRC16_LBPME_A);
4868 			dp = &softc->params;
4869 			n = snprintf(announce_buf, DA_ANNOUNCETMP_SZ,
4870 			    "%juMB (%ju %u byte sectors",
4871 			    ((uintmax_t)dp->secsize * dp->sectors) /
4872 			     (1024 * 1024),
4873 			    (uintmax_t)dp->sectors, dp->secsize);
4874 			if (softc->p_type != 0) {
4875 				n += snprintf(announce_buf + n,
4876 				    DA_ANNOUNCETMP_SZ - n,
4877 				    ", DIF type %d", softc->p_type);
4878 			}
4879 			snprintf(announce_buf + n, DA_ANNOUNCETMP_SZ - n, ")");
4880 		}
4881 	} else {
4882 		int error;
4883 
4884 		/*
4885 		 * Retry any UNIT ATTENTION type errors.  They
4886 		 * are expected at boot.
4887 		 */
4888 		error = daerror(done_ccb, CAM_RETRY_SELTO,
4889 				SF_RETRY_UA|SF_NO_PRINT);
4890 		if (error == ERESTART) {
4891 			/*
4892 			 * A retry was scheuled, so
4893 			 * just return.
4894 			 */
4895 			return;
4896 		} else if (error != 0) {
4897 			int asc, ascq;
4898 			int sense_key, error_code;
4899 			int have_sense;
4900 			cam_status status;
4901 			struct ccb_getdev cgd;
4902 
4903 			/* Don't wedge this device's queue */
4904 			status = done_ccb->ccb_h.status;
4905 			if ((status & CAM_DEV_QFRZN) != 0)
4906 				cam_release_devq(done_ccb->ccb_h.path,
4907 						 /*relsim_flags*/0,
4908 						 /*reduction*/0,
4909 						 /*timeout*/0,
4910 						 /*getcount_only*/0);
4911 
4912 			memset(&cgd, 0, sizeof(cgd));
4913 			xpt_setup_ccb(&cgd.ccb_h, done_ccb->ccb_h.path,
4914 				      CAM_PRIORITY_NORMAL);
4915 			cgd.ccb_h.func_code = XPT_GDEV_TYPE;
4916 			xpt_action((union ccb *)&cgd);
4917 
4918 			if (scsi_extract_sense_ccb(done_ccb,
4919 			    &error_code, &sense_key, &asc, &ascq))
4920 				have_sense = TRUE;
4921 			else
4922 				have_sense = FALSE;
4923 
4924 			/*
4925 			 * If we tried READ CAPACITY(16) and failed,
4926 			 * fallback to READ CAPACITY(10).
4927 			 */
4928 			if ((state == DA_CCB_PROBE_RC16) &&
4929 			    (softc->flags & DA_FLAG_CAN_RC16) &&
4930 			    (((csio->ccb_h.status & CAM_STATUS_MASK) ==
4931 				CAM_REQ_INVALID) ||
4932 			     ((have_sense) &&
4933 			      (error_code == SSD_CURRENT_ERROR ||
4934 			       error_code == SSD_DESC_CURRENT_ERROR) &&
4935 			      (sense_key == SSD_KEY_ILLEGAL_REQUEST)))) {
4936 				cam_periph_assert(periph, MA_OWNED);
4937 				softc->flags &= ~DA_FLAG_CAN_RC16;
4938 				free(rdcap, M_SCSIDA);
4939 				softc->state = DA_STATE_PROBE_RC;
4940 				xpt_release_ccb(done_ccb);
4941 				xpt_schedule(periph, priority);
4942 				return;
4943 			}
4944 
4945 			/*
4946 			 * Attach to anything that claims to be a
4947 			 * direct access or optical disk device,
4948 			 * as long as it doesn't return a "Logical
4949 			 * unit not supported" (0x25) error.
4950 			 * "Internal Target Failure" (0x44) is also
4951 			 * special and typically means that the
4952 			 * device is a SATA drive behind a SATL
4953 			 * translation that's fallen into a
4954 			 * terminally fatal state.
4955 			 */
4956 			if ((have_sense)
4957 			 && (asc != 0x25) && (asc != 0x44)
4958 			 && (error_code == SSD_CURRENT_ERROR
4959 			  || error_code == SSD_DESC_CURRENT_ERROR)) {
4960 				const char *sense_key_desc;
4961 				const char *asc_desc;
4962 
4963 				dasetgeom(periph, 512, -1, NULL, 0);
4964 				scsi_sense_desc(sense_key, asc, ascq,
4965 						&cgd.inq_data, &sense_key_desc,
4966 						&asc_desc);
4967 				snprintf(announce_buf, DA_ANNOUNCETMP_SZ,
4968 				    "Attempt to query device "
4969 				    "size failed: %s, %s",
4970 				    sense_key_desc, asc_desc);
4971 			} else {
4972 				if (have_sense)
4973 					scsi_sense_print(&done_ccb->csio);
4974 				else {
4975 					xpt_print(periph->path,
4976 					    "got CAM status %#x\n",
4977 					    done_ccb->ccb_h.status);
4978 				}
4979 
4980 				xpt_print(periph->path, "fatal error, "
4981 				    "failed to attach to device\n");
4982 
4983 				announce_buf = NULL;
4984 
4985 				/*
4986 				 * Free up resources.
4987 				 */
4988 				cam_periph_invalidate(periph);
4989 			}
4990 		}
4991 	}
4992 	free(csio->data_ptr, M_SCSIDA);
4993 	if (announce_buf != NULL &&
4994 	    ((softc->flags & DA_FLAG_ANNOUNCED) == 0)) {
4995 		struct sbuf sb;
4996 
4997 		sbuf_new(&sb, softc->announcebuf, DA_ANNOUNCE_SZ,
4998 		    SBUF_FIXEDLEN);
4999 		xpt_announce_periph_sbuf(periph, &sb, announce_buf);
5000 		xpt_announce_quirks_sbuf(periph, &sb, softc->quirks,
5001 		    DA_Q_BIT_STRING);
5002 		sbuf_finish(&sb);
5003 		sbuf_putbuf(&sb);
5004 
5005 		/*
5006 		 * Create our sysctl variables, now that we know
5007 		 * we have successfully attached.
5008 		 */
5009 		/* increase the refcount */
5010 		if (da_periph_acquire(periph, DA_REF_SYSCTL) == 0) {
5011 			taskqueue_enqueue(taskqueue_thread,
5012 					  &softc->sysctl_task);
5013 		} else {
5014 			/* XXX This message is useless! */
5015 			xpt_print(periph->path, "fatal error, "
5016 			    "could not acquire reference count\n");
5017 		}
5018 	}
5019 
5020 	/* We already probed the device. */
5021 	if (softc->flags & DA_FLAG_PROBED) {
5022 		daprobedone(periph, done_ccb);
5023 		return;
5024 	}
5025 
5026 	/* Ensure re-probe doesn't see old delete. */
5027 	softc->delete_available = 0;
5028 	dadeleteflag(softc, DA_DELETE_ZERO, 1);
5029 	if (lbp && (softc->quirks & DA_Q_NO_UNMAP) == 0) {
5030 		/*
5031 		 * Based on older SBC-3 spec revisions
5032 		 * any of the UNMAP methods "may" be
5033 		 * available via LBP given this flag so
5034 		 * we flag all of them as available and
5035 		 * then remove those which further
5036 		 * probes confirm aren't available
5037 		 * later.
5038 		 *
5039 		 * We could also check readcap(16) p_type
5040 		 * flag to exclude one or more invalid
5041 		 * write same (X) types here
5042 		 */
5043 		dadeleteflag(softc, DA_DELETE_WS16, 1);
5044 		dadeleteflag(softc, DA_DELETE_WS10, 1);
5045 		dadeleteflag(softc, DA_DELETE_UNMAP, 1);
5046 
5047 		softc->state = DA_STATE_PROBE_LBP;
5048 		xpt_release_ccb(done_ccb);
5049 		xpt_schedule(periph, priority);
5050 		return;
5051 	}
5052 
5053 	softc->state = DA_STATE_PROBE_BDC;
5054 	xpt_release_ccb(done_ccb);
5055 	xpt_schedule(periph, priority);
5056 	return;
5057 }
5058 
5059 static void
5060 dadone_probelbp(struct cam_periph *periph, union ccb *done_ccb)
5061 {
5062 	struct scsi_vpd_logical_block_prov *lbp;
5063 	struct da_softc *softc;
5064 	struct ccb_scsiio *csio;
5065 	u_int32_t  priority;
5066 
5067 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probelbp\n"));
5068 
5069 	softc = (struct da_softc *)periph->softc;
5070 	priority = done_ccb->ccb_h.pinfo.priority;
5071 	csio = &done_ccb->csio;
5072 	lbp = (struct scsi_vpd_logical_block_prov *)csio->data_ptr;
5073 
5074 	cam_periph_assert(periph, MA_OWNED);
5075 
5076 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5077 		/*
5078 		 * T10/1799-D Revision 31 states at least one of these
5079 		 * must be supported but we don't currently enforce this.
5080 		 */
5081 		dadeleteflag(softc, DA_DELETE_WS16,
5082 		     (lbp->flags & SVPD_LBP_WS16));
5083 		dadeleteflag(softc, DA_DELETE_WS10,
5084 			     (lbp->flags & SVPD_LBP_WS10));
5085 		dadeleteflag(softc, DA_DELETE_UNMAP,
5086 			     (lbp->flags & SVPD_LBP_UNMAP));
5087 	} else {
5088 		int error;
5089 		error = daerror(done_ccb, CAM_RETRY_SELTO,
5090 				SF_RETRY_UA|SF_NO_PRINT);
5091 		if (error == ERESTART)
5092 			return;
5093 		else if (error != 0) {
5094 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5095 				/* Don't wedge this device's queue */
5096 				cam_release_devq(done_ccb->ccb_h.path,
5097 						 /*relsim_flags*/0,
5098 						 /*reduction*/0,
5099 						 /*timeout*/0,
5100 						 /*getcount_only*/0);
5101 			}
5102 
5103 			/*
5104 			 * Failure indicates we don't support any SBC-3
5105 			 * delete methods with UNMAP
5106 			 */
5107 		}
5108 	}
5109 
5110 	free(lbp, M_SCSIDA);
5111 	softc->state = DA_STATE_PROBE_BLK_LIMITS;
5112 	xpt_release_ccb(done_ccb);
5113 	xpt_schedule(periph, priority);
5114 	return;
5115 }
5116 
5117 static void
5118 dadone_probeblklimits(struct cam_periph *periph, union ccb *done_ccb)
5119 {
5120 	struct scsi_vpd_block_limits *block_limits;
5121 	struct da_softc *softc;
5122 	struct ccb_scsiio *csio;
5123 	u_int32_t  priority;
5124 
5125 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probeblklimits\n"));
5126 
5127 	softc = (struct da_softc *)periph->softc;
5128 	priority = done_ccb->ccb_h.pinfo.priority;
5129 	csio = &done_ccb->csio;
5130 	block_limits = (struct scsi_vpd_block_limits *)csio->data_ptr;
5131 
5132 	cam_periph_assert(periph, MA_OWNED);
5133 
5134 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5135 		uint32_t max_txfer_len = scsi_4btoul(
5136 			block_limits->max_txfer_len);
5137 		uint32_t max_unmap_lba_cnt = scsi_4btoul(
5138 			block_limits->max_unmap_lba_cnt);
5139 		uint32_t max_unmap_blk_cnt = scsi_4btoul(
5140 			block_limits->max_unmap_blk_cnt);
5141 		uint32_t unmap_gran = scsi_4btoul(
5142 			block_limits->opt_unmap_grain);
5143 		uint32_t unmap_gran_align = scsi_4btoul(
5144 			block_limits->unmap_grain_align);
5145 		uint64_t ws_max_blks = scsi_8btou64(
5146 			block_limits->max_write_same_length);
5147 
5148 		if (max_txfer_len != 0) {
5149 			softc->disk->d_maxsize = MIN(softc->maxio,
5150 			    (off_t)max_txfer_len * softc->params.secsize);
5151 		}
5152 
5153 		/*
5154 		 * We should already support UNMAP but we check lba
5155 		 * and block count to be sure
5156 		 */
5157 		if (max_unmap_lba_cnt != 0x00L &&
5158 		    max_unmap_blk_cnt != 0x00L) {
5159 			softc->unmap_max_lba = max_unmap_lba_cnt;
5160 			softc->unmap_max_ranges = min(max_unmap_blk_cnt,
5161 				UNMAP_MAX_RANGES);
5162 			if (unmap_gran > 1) {
5163 				softc->unmap_gran = unmap_gran;
5164 				if (unmap_gran_align & 0x80000000) {
5165 					softc->unmap_gran_align =
5166 					    unmap_gran_align & 0x7fffffff;
5167 				}
5168 			}
5169 		} else {
5170 			/*
5171 			 * Unexpected UNMAP limits which means the
5172 			 * device doesn't actually support UNMAP
5173 			 */
5174 			dadeleteflag(softc, DA_DELETE_UNMAP, 0);
5175 		}
5176 
5177 		if (ws_max_blks != 0x00L)
5178 			softc->ws_max_blks = ws_max_blks;
5179 	} else {
5180 		int error;
5181 		error = daerror(done_ccb, CAM_RETRY_SELTO,
5182 				SF_RETRY_UA|SF_NO_PRINT);
5183 		if (error == ERESTART)
5184 			return;
5185 		else if (error != 0) {
5186 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5187 				/* Don't wedge this device's queue */
5188 				cam_release_devq(done_ccb->ccb_h.path,
5189 						 /*relsim_flags*/0,
5190 						 /*reduction*/0,
5191 						 /*timeout*/0,
5192 						 /*getcount_only*/0);
5193 			}
5194 
5195 			/*
5196 			 * Failure here doesn't mean UNMAP is not
5197 			 * supported as this is an optional page.
5198 			 */
5199 			softc->unmap_max_lba = 1;
5200 			softc->unmap_max_ranges = 1;
5201 		}
5202 	}
5203 
5204 	free(block_limits, M_SCSIDA);
5205 	softc->state = DA_STATE_PROBE_BDC;
5206 	xpt_release_ccb(done_ccb);
5207 	xpt_schedule(periph, priority);
5208 	return;
5209 }
5210 
5211 static void
5212 dadone_probebdc(struct cam_periph *periph, union ccb *done_ccb)
5213 {
5214 	struct scsi_vpd_block_device_characteristics *bdc;
5215 	struct da_softc *softc;
5216 	struct ccb_scsiio *csio;
5217 	u_int32_t  priority;
5218 
5219 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probebdc\n"));
5220 
5221 	softc = (struct da_softc *)periph->softc;
5222 	priority = done_ccb->ccb_h.pinfo.priority;
5223 	csio = &done_ccb->csio;
5224 	bdc = (struct scsi_vpd_block_device_characteristics *)csio->data_ptr;
5225 
5226 	cam_periph_assert(periph, MA_OWNED);
5227 
5228 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5229 		uint32_t valid_len;
5230 
5231 		/*
5232 		 * Disable queue sorting for non-rotational media
5233 		 * by default.
5234 		 */
5235 		u_int16_t old_rate = softc->disk->d_rotation_rate;
5236 
5237 		valid_len = csio->dxfer_len - csio->resid;
5238 		if (SBDC_IS_PRESENT(bdc, valid_len,
5239 		    medium_rotation_rate)) {
5240 			softc->disk->d_rotation_rate =
5241 				scsi_2btoul(bdc->medium_rotation_rate);
5242 			if (softc->disk->d_rotation_rate == SVPD_NON_ROTATING) {
5243 				cam_iosched_set_sort_queue(
5244 				    softc->cam_iosched, 0);
5245 				softc->flags &= ~DA_FLAG_ROTATING;
5246 			}
5247 			if (softc->disk->d_rotation_rate != old_rate) {
5248 				disk_attr_changed(softc->disk,
5249 				    "GEOM::rotation_rate", M_NOWAIT);
5250 			}
5251 		}
5252 		if ((SBDC_IS_PRESENT(bdc, valid_len, flags))
5253 		 && (softc->zone_mode == DA_ZONE_NONE)) {
5254 			int ata_proto;
5255 
5256 			if (scsi_vpd_supported_page(periph,
5257 			    SVPD_ATA_INFORMATION))
5258 				ata_proto = 1;
5259 			else
5260 				ata_proto = 0;
5261 
5262 			/*
5263 			 * The Zoned field will only be set for
5264 			 * Drive Managed and Host Aware drives.  If
5265 			 * they are Host Managed, the device type
5266 			 * in the standard INQUIRY data should be
5267 			 * set to T_ZBC_HM (0x14).
5268 			 */
5269 			if ((bdc->flags & SVPD_ZBC_MASK) ==
5270 			     SVPD_HAW_ZBC) {
5271 				softc->zone_mode = DA_ZONE_HOST_AWARE;
5272 				softc->zone_interface = (ata_proto) ?
5273 				   DA_ZONE_IF_ATA_SAT : DA_ZONE_IF_SCSI;
5274 			} else if ((bdc->flags & SVPD_ZBC_MASK) ==
5275 			     SVPD_DM_ZBC) {
5276 				softc->zone_mode =DA_ZONE_DRIVE_MANAGED;
5277 				softc->zone_interface = (ata_proto) ?
5278 				   DA_ZONE_IF_ATA_SAT : DA_ZONE_IF_SCSI;
5279 			} else if ((bdc->flags & SVPD_ZBC_MASK) !=
5280 				  SVPD_ZBC_NR) {
5281 				xpt_print(periph->path, "Unknown zoned "
5282 				    "type %#x",
5283 				    bdc->flags & SVPD_ZBC_MASK);
5284 			}
5285 		}
5286 	} else {
5287 		int error;
5288 		error = daerror(done_ccb, CAM_RETRY_SELTO,
5289 				SF_RETRY_UA|SF_NO_PRINT);
5290 		if (error == ERESTART)
5291 			return;
5292 		else if (error != 0) {
5293 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5294 				/* Don't wedge this device's queue */
5295 				cam_release_devq(done_ccb->ccb_h.path,
5296 						 /*relsim_flags*/0,
5297 						 /*reduction*/0,
5298 						 /*timeout*/0,
5299 						 /*getcount_only*/0);
5300 			}
5301 		}
5302 	}
5303 
5304 	free(bdc, M_SCSIDA);
5305 	softc->state = DA_STATE_PROBE_ATA;
5306 	xpt_release_ccb(done_ccb);
5307 	xpt_schedule(periph, priority);
5308 	return;
5309 }
5310 
5311 static void
5312 dadone_probeata(struct cam_periph *periph, union ccb *done_ccb)
5313 {
5314 	struct ata_params *ata_params;
5315 	struct ccb_scsiio *csio;
5316 	struct da_softc *softc;
5317 	u_int32_t  priority;
5318 	int continue_probe;
5319 	int error;
5320 
5321 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probeata\n"));
5322 
5323 	softc = (struct da_softc *)periph->softc;
5324 	priority = done_ccb->ccb_h.pinfo.priority;
5325 	csio = &done_ccb->csio;
5326 	ata_params = (struct ata_params *)csio->data_ptr;
5327 	continue_probe = 0;
5328 	error = 0;
5329 
5330 	cam_periph_assert(periph, MA_OWNED);
5331 
5332 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5333 		uint16_t old_rate;
5334 
5335 		ata_param_fixup(ata_params);
5336 		if (ata_params->support_dsm & ATA_SUPPORT_DSM_TRIM &&
5337 		    (softc->quirks & DA_Q_NO_UNMAP) == 0) {
5338 			dadeleteflag(softc, DA_DELETE_ATA_TRIM, 1);
5339 			if (ata_params->max_dsm_blocks != 0)
5340 				softc->trim_max_ranges = min(
5341 				  softc->trim_max_ranges,
5342 				  ata_params->max_dsm_blocks *
5343 				  ATA_DSM_BLK_RANGES);
5344 		}
5345 		/*
5346 		 * Disable queue sorting for non-rotational media
5347 		 * by default.
5348 		 */
5349 		old_rate = softc->disk->d_rotation_rate;
5350 		softc->disk->d_rotation_rate = ata_params->media_rotation_rate;
5351 		if (softc->disk->d_rotation_rate == ATA_RATE_NON_ROTATING) {
5352 			cam_iosched_set_sort_queue(softc->cam_iosched, 0);
5353 			softc->flags &= ~DA_FLAG_ROTATING;
5354 		}
5355 		if (softc->disk->d_rotation_rate != old_rate) {
5356 			disk_attr_changed(softc->disk,
5357 			    "GEOM::rotation_rate", M_NOWAIT);
5358 		}
5359 
5360 		cam_periph_assert(periph, MA_OWNED);
5361 		if (ata_params->capabilities1 & ATA_SUPPORT_DMA)
5362 			softc->flags |= DA_FLAG_CAN_ATA_DMA;
5363 
5364 		if (ata_params->support.extension & ATA_SUPPORT_GENLOG)
5365 			softc->flags |= DA_FLAG_CAN_ATA_LOG;
5366 
5367 		/*
5368 		 * At this point, if we have a SATA host aware drive,
5369 		 * we communicate via ATA passthrough unless the
5370 		 * SAT layer supports ZBC -> ZAC translation.  In
5371 		 * that case,
5372 		 *
5373 		 * XXX KDM figure out how to detect a host managed
5374 		 * SATA drive.
5375 		 */
5376 		if (softc->zone_mode == DA_ZONE_NONE) {
5377 			/*
5378 			 * Note that we don't override the zone
5379 			 * mode or interface if it has already been
5380 			 * set.  This is because it has either been
5381 			 * set as a quirk, or when we probed the
5382 			 * SCSI Block Device Characteristics page,
5383 			 * the zoned field was set.  The latter
5384 			 * means that the SAT layer supports ZBC to
5385 			 * ZAC translation, and we would prefer to
5386 			 * use that if it is available.
5387 			 */
5388 			if ((ata_params->support3 &
5389 			    ATA_SUPPORT_ZONE_MASK) ==
5390 			    ATA_SUPPORT_ZONE_HOST_AWARE) {
5391 				softc->zone_mode = DA_ZONE_HOST_AWARE;
5392 				softc->zone_interface =
5393 				    DA_ZONE_IF_ATA_PASS;
5394 			} else if ((ata_params->support3 &
5395 				    ATA_SUPPORT_ZONE_MASK) ==
5396 				    ATA_SUPPORT_ZONE_DEV_MANAGED) {
5397 				softc->zone_mode =DA_ZONE_DRIVE_MANAGED;
5398 				softc->zone_interface = DA_ZONE_IF_ATA_PASS;
5399 			}
5400 		}
5401 
5402 	} else {
5403 		error = daerror(done_ccb, CAM_RETRY_SELTO,
5404 				SF_RETRY_UA|SF_NO_PRINT);
5405 		if (error == ERESTART)
5406 			return;
5407 		else if (error != 0) {
5408 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5409 				/* Don't wedge this device's queue */
5410 				cam_release_devq(done_ccb->ccb_h.path,
5411 						 /*relsim_flags*/0,
5412 						 /*reduction*/0,
5413 						 /*timeout*/0,
5414 						 /*getcount_only*/0);
5415 			}
5416 		}
5417 	}
5418 
5419 	if ((softc->zone_mode == DA_ZONE_HOST_AWARE)
5420 	 || (softc->zone_mode == DA_ZONE_HOST_MANAGED)) {
5421 		/*
5422 		 * If the ATA IDENTIFY failed, we could be talking
5423 		 * to a SCSI drive, although that seems unlikely,
5424 		 * since the drive did report that it supported the
5425 		 * ATA Information VPD page.  If the ATA IDENTIFY
5426 		 * succeeded, and the SAT layer doesn't support
5427 		 * ZBC -> ZAC translation, continue on to get the
5428 		 * directory of ATA logs, and complete the rest of
5429 		 * the ZAC probe.  If the SAT layer does support
5430 		 * ZBC -> ZAC translation, we want to use that,
5431 		 * and we'll probe the SCSI Zoned Block Device
5432 		 * Characteristics VPD page next.
5433 		 */
5434 		if ((error == 0)
5435 		 && (softc->flags & DA_FLAG_CAN_ATA_LOG)
5436 		 && (softc->zone_interface == DA_ZONE_IF_ATA_PASS))
5437 			softc->state = DA_STATE_PROBE_ATA_LOGDIR;
5438 		else
5439 			softc->state = DA_STATE_PROBE_ZONE;
5440 		continue_probe = 1;
5441 	}
5442 	if (continue_probe != 0) {
5443 		xpt_schedule(periph, priority);
5444 		xpt_release_ccb(done_ccb);
5445 		return;
5446 	} else
5447 		daprobedone(periph, done_ccb);
5448 	return;
5449 }
5450 
5451 static void
5452 dadone_probeatalogdir(struct cam_periph *periph, union ccb *done_ccb)
5453 {
5454 	struct da_softc *softc;
5455 	struct ccb_scsiio *csio;
5456 	u_int32_t  priority;
5457 	int error;
5458 
5459 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probeatalogdir\n"));
5460 
5461 	softc = (struct da_softc *)periph->softc;
5462 	priority = done_ccb->ccb_h.pinfo.priority;
5463 	csio = &done_ccb->csio;
5464 
5465 	cam_periph_assert(periph, MA_OWNED);
5466 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5467 		error = 0;
5468 		softc->valid_logdir_len = 0;
5469 		bzero(&softc->ata_logdir, sizeof(softc->ata_logdir));
5470 		softc->valid_logdir_len = csio->dxfer_len - csio->resid;
5471 		if (softc->valid_logdir_len > 0)
5472 			bcopy(csio->data_ptr, &softc->ata_logdir,
5473 			    min(softc->valid_logdir_len,
5474 				sizeof(softc->ata_logdir)));
5475 		/*
5476 		 * Figure out whether the Identify Device log is
5477 		 * supported.  The General Purpose log directory
5478 		 * has a header, and lists the number of pages
5479 		 * available for each GP log identified by the
5480 		 * offset into the list.
5481 		 */
5482 		if ((softc->valid_logdir_len >=
5483 		    ((ATA_IDENTIFY_DATA_LOG + 1) * sizeof(uint16_t)))
5484 		 && (le16dec(softc->ata_logdir.header) ==
5485 		     ATA_GP_LOG_DIR_VERSION)
5486 		 && (le16dec(&softc->ata_logdir.num_pages[
5487 		     (ATA_IDENTIFY_DATA_LOG *
5488 		     sizeof(uint16_t)) - sizeof(uint16_t)]) > 0)){
5489 			softc->flags |= DA_FLAG_CAN_ATA_IDLOG;
5490 		} else {
5491 			softc->flags &= ~DA_FLAG_CAN_ATA_IDLOG;
5492 		}
5493 	} else {
5494 		error = daerror(done_ccb, CAM_RETRY_SELTO,
5495 				SF_RETRY_UA|SF_NO_PRINT);
5496 		if (error == ERESTART)
5497 			return;
5498 		else if (error != 0) {
5499 			/*
5500 			 * If we can't get the ATA log directory,
5501 			 * then ATA logs are effectively not
5502 			 * supported even if the bit is set in the
5503 			 * identify data.
5504 			 */
5505 			softc->flags &= ~(DA_FLAG_CAN_ATA_LOG |
5506 					  DA_FLAG_CAN_ATA_IDLOG);
5507 			if ((done_ccb->ccb_h.status &
5508 			     CAM_DEV_QFRZN) != 0) {
5509 				/* Don't wedge this device's queue */
5510 				cam_release_devq(done_ccb->ccb_h.path,
5511 						 /*relsim_flags*/0,
5512 						 /*reduction*/0,
5513 						 /*timeout*/0,
5514 						 /*getcount_only*/0);
5515 			}
5516 		}
5517 	}
5518 
5519 	free(csio->data_ptr, M_SCSIDA);
5520 
5521 	if ((error == 0)
5522 	 && (softc->flags & DA_FLAG_CAN_ATA_IDLOG)) {
5523 		softc->state = DA_STATE_PROBE_ATA_IDDIR;
5524 		xpt_release_ccb(done_ccb);
5525 		xpt_schedule(periph, priority);
5526 		return;
5527 	}
5528 	daprobedone(periph, done_ccb);
5529 	return;
5530 }
5531 
5532 static void
5533 dadone_probeataiddir(struct cam_periph *periph, union ccb *done_ccb)
5534 {
5535 	struct da_softc *softc;
5536 	struct ccb_scsiio *csio;
5537 	u_int32_t  priority;
5538 	int error;
5539 
5540 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probeataiddir\n"));
5541 
5542 	softc = (struct da_softc *)periph->softc;
5543 	priority = done_ccb->ccb_h.pinfo.priority;
5544 	csio = &done_ccb->csio;
5545 
5546 	cam_periph_assert(periph, MA_OWNED);
5547 
5548 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5549 		off_t entries_offset, max_entries;
5550 		error = 0;
5551 
5552 		softc->valid_iddir_len = 0;
5553 		bzero(&softc->ata_iddir, sizeof(softc->ata_iddir));
5554 		softc->flags &= ~(DA_FLAG_CAN_ATA_SUPCAP |
5555 				  DA_FLAG_CAN_ATA_ZONE);
5556 		softc->valid_iddir_len = csio->dxfer_len - csio->resid;
5557 		if (softc->valid_iddir_len > 0)
5558 			bcopy(csio->data_ptr, &softc->ata_iddir,
5559 			    min(softc->valid_iddir_len,
5560 				sizeof(softc->ata_iddir)));
5561 
5562 		entries_offset =
5563 		    __offsetof(struct ata_identify_log_pages,entries);
5564 		max_entries = softc->valid_iddir_len - entries_offset;
5565 		if ((softc->valid_iddir_len > (entries_offset + 1))
5566 		 && (le64dec(softc->ata_iddir.header) == ATA_IDLOG_REVISION)
5567 		 && (softc->ata_iddir.entry_count > 0)) {
5568 			int num_entries, i;
5569 
5570 			num_entries = softc->ata_iddir.entry_count;
5571 			num_entries = min(num_entries,
5572 			   softc->valid_iddir_len - entries_offset);
5573 			for (i = 0; i < num_entries && i < max_entries; i++) {
5574 				if (softc->ata_iddir.entries[i] ==
5575 				    ATA_IDL_SUP_CAP)
5576 					softc->flags |= DA_FLAG_CAN_ATA_SUPCAP;
5577 				else if (softc->ata_iddir.entries[i] ==
5578 					 ATA_IDL_ZDI)
5579 					softc->flags |= DA_FLAG_CAN_ATA_ZONE;
5580 
5581 				if ((softc->flags & DA_FLAG_CAN_ATA_SUPCAP)
5582 				 && (softc->flags & DA_FLAG_CAN_ATA_ZONE))
5583 					break;
5584 			}
5585 		}
5586 	} else {
5587 		error = daerror(done_ccb, CAM_RETRY_SELTO,
5588 				SF_RETRY_UA|SF_NO_PRINT);
5589 		if (error == ERESTART)
5590 			return;
5591 		else if (error != 0) {
5592 			/*
5593 			 * If we can't get the ATA Identify Data log
5594 			 * directory, then it effectively isn't
5595 			 * supported even if the ATA Log directory
5596 			 * a non-zero number of pages present for
5597 			 * this log.
5598 			 */
5599 			softc->flags &= ~DA_FLAG_CAN_ATA_IDLOG;
5600 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5601 				/* Don't wedge this device's queue */
5602 				cam_release_devq(done_ccb->ccb_h.path,
5603 						 /*relsim_flags*/0,
5604 						 /*reduction*/0,
5605 						 /*timeout*/0,
5606 						 /*getcount_only*/0);
5607 			}
5608 		}
5609 	}
5610 
5611 	free(csio->data_ptr, M_SCSIDA);
5612 
5613 	if ((error == 0) && (softc->flags & DA_FLAG_CAN_ATA_SUPCAP)) {
5614 		softc->state = DA_STATE_PROBE_ATA_SUP;
5615 		xpt_release_ccb(done_ccb);
5616 		xpt_schedule(periph, priority);
5617 		return;
5618 	}
5619 	daprobedone(periph, done_ccb);
5620 	return;
5621 }
5622 
5623 static void
5624 dadone_probeatasup(struct cam_periph *periph, union ccb *done_ccb)
5625 {
5626 	struct da_softc *softc;
5627 	struct ccb_scsiio *csio;
5628 	u_int32_t  priority;
5629 	int error;
5630 
5631 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probeatasup\n"));
5632 
5633 	softc = (struct da_softc *)periph->softc;
5634 	priority = done_ccb->ccb_h.pinfo.priority;
5635 	csio = &done_ccb->csio;
5636 
5637 	cam_periph_assert(periph, MA_OWNED);
5638 
5639 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5640 		uint32_t valid_len;
5641 		size_t needed_size;
5642 		struct ata_identify_log_sup_cap *sup_cap;
5643 		error = 0;
5644 
5645 		sup_cap = (struct ata_identify_log_sup_cap *)csio->data_ptr;
5646 		valid_len = csio->dxfer_len - csio->resid;
5647 		needed_size = __offsetof(struct ata_identify_log_sup_cap,
5648 		    sup_zac_cap) + 1 + sizeof(sup_cap->sup_zac_cap);
5649 		if (valid_len >= needed_size) {
5650 			uint64_t zoned, zac_cap;
5651 
5652 			zoned = le64dec(sup_cap->zoned_cap);
5653 			if (zoned & ATA_ZONED_VALID) {
5654 				/*
5655 				 * This should have already been
5656 				 * set, because this is also in the
5657 				 * ATA identify data.
5658 				 */
5659 				if ((zoned & ATA_ZONED_MASK) ==
5660 				    ATA_SUPPORT_ZONE_HOST_AWARE)
5661 					softc->zone_mode = DA_ZONE_HOST_AWARE;
5662 				else if ((zoned & ATA_ZONED_MASK) ==
5663 				    ATA_SUPPORT_ZONE_DEV_MANAGED)
5664 					softc->zone_mode =
5665 					    DA_ZONE_DRIVE_MANAGED;
5666 			}
5667 
5668 			zac_cap = le64dec(sup_cap->sup_zac_cap);
5669 			if (zac_cap & ATA_SUP_ZAC_CAP_VALID) {
5670 				if (zac_cap & ATA_REPORT_ZONES_SUP)
5671 					softc->zone_flags |=
5672 					    DA_ZONE_FLAG_RZ_SUP;
5673 				if (zac_cap & ATA_ND_OPEN_ZONE_SUP)
5674 					softc->zone_flags |=
5675 					    DA_ZONE_FLAG_OPEN_SUP;
5676 				if (zac_cap & ATA_ND_CLOSE_ZONE_SUP)
5677 					softc->zone_flags |=
5678 					    DA_ZONE_FLAG_CLOSE_SUP;
5679 				if (zac_cap & ATA_ND_FINISH_ZONE_SUP)
5680 					softc->zone_flags |=
5681 					    DA_ZONE_FLAG_FINISH_SUP;
5682 				if (zac_cap & ATA_ND_RWP_SUP)
5683 					softc->zone_flags |=
5684 					    DA_ZONE_FLAG_RWP_SUP;
5685 			} else {
5686 				/*
5687 				 * This field was introduced in
5688 				 * ACS-4, r08 on April 28th, 2015.
5689 				 * If the drive firmware was written
5690 				 * to an earlier spec, it won't have
5691 				 * the field.  So, assume all
5692 				 * commands are supported.
5693 				 */
5694 				softc->zone_flags |= DA_ZONE_FLAG_SUP_MASK;
5695 			}
5696 		}
5697 	} else {
5698 		error = daerror(done_ccb, CAM_RETRY_SELTO,
5699 				SF_RETRY_UA|SF_NO_PRINT);
5700 		if (error == ERESTART)
5701 			return;
5702 		else if (error != 0) {
5703 			/*
5704 			 * If we can't get the ATA Identify Data
5705 			 * Supported Capabilities page, clear the
5706 			 * flag...
5707 			 */
5708 			softc->flags &= ~DA_FLAG_CAN_ATA_SUPCAP;
5709 			/*
5710 			 * And clear zone capabilities.
5711 			 */
5712 			softc->zone_flags &= ~DA_ZONE_FLAG_SUP_MASK;
5713 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5714 				/* Don't wedge this device's queue */
5715 				cam_release_devq(done_ccb->ccb_h.path,
5716 						 /*relsim_flags*/0,
5717 						 /*reduction*/0,
5718 						 /*timeout*/0,
5719 						 /*getcount_only*/0);
5720 			}
5721 		}
5722 	}
5723 
5724 	free(csio->data_ptr, M_SCSIDA);
5725 
5726 	if ((error == 0) && (softc->flags & DA_FLAG_CAN_ATA_ZONE)) {
5727 		softc->state = DA_STATE_PROBE_ATA_ZONE;
5728 		xpt_release_ccb(done_ccb);
5729 		xpt_schedule(periph, priority);
5730 		return;
5731 	}
5732 	daprobedone(periph, done_ccb);
5733 	return;
5734 }
5735 
5736 static void
5737 dadone_probeatazone(struct cam_periph *periph, union ccb *done_ccb)
5738 {
5739 	struct da_softc *softc;
5740 	struct ccb_scsiio *csio;
5741 	int error;
5742 
5743 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probeatazone\n"));
5744 
5745 	softc = (struct da_softc *)periph->softc;
5746 	csio = &done_ccb->csio;
5747 
5748 	cam_periph_assert(periph, MA_OWNED);
5749 
5750 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5751 		struct ata_zoned_info_log *zi_log;
5752 		uint32_t valid_len;
5753 		size_t needed_size;
5754 
5755 		zi_log = (struct ata_zoned_info_log *)csio->data_ptr;
5756 
5757 		valid_len = csio->dxfer_len - csio->resid;
5758 		needed_size = __offsetof(struct ata_zoned_info_log,
5759 		    version_info) + 1 + sizeof(zi_log->version_info);
5760 		if (valid_len >= needed_size) {
5761 			uint64_t tmpvar;
5762 
5763 			tmpvar = le64dec(zi_log->zoned_cap);
5764 			if (tmpvar & ATA_ZDI_CAP_VALID) {
5765 				if (tmpvar & ATA_ZDI_CAP_URSWRZ)
5766 					softc->zone_flags |=
5767 					    DA_ZONE_FLAG_URSWRZ;
5768 				else
5769 					softc->zone_flags &=
5770 					    ~DA_ZONE_FLAG_URSWRZ;
5771 			}
5772 			tmpvar = le64dec(zi_log->optimal_seq_zones);
5773 			if (tmpvar & ATA_ZDI_OPT_SEQ_VALID) {
5774 				softc->zone_flags |= DA_ZONE_FLAG_OPT_SEQ_SET;
5775 				softc->optimal_seq_zones = (tmpvar &
5776 				    ATA_ZDI_OPT_SEQ_MASK);
5777 			} else {
5778 				softc->zone_flags &= ~DA_ZONE_FLAG_OPT_SEQ_SET;
5779 				softc->optimal_seq_zones = 0;
5780 			}
5781 
5782 			tmpvar =le64dec(zi_log->optimal_nonseq_zones);
5783 			if (tmpvar & ATA_ZDI_OPT_NS_VALID) {
5784 				softc->zone_flags |=
5785 				    DA_ZONE_FLAG_OPT_NONSEQ_SET;
5786 				softc->optimal_nonseq_zones =
5787 				    (tmpvar & ATA_ZDI_OPT_NS_MASK);
5788 			} else {
5789 				softc->zone_flags &=
5790 				    ~DA_ZONE_FLAG_OPT_NONSEQ_SET;
5791 				softc->optimal_nonseq_zones = 0;
5792 			}
5793 
5794 			tmpvar = le64dec(zi_log->max_seq_req_zones);
5795 			if (tmpvar & ATA_ZDI_MAX_SEQ_VALID) {
5796 				softc->zone_flags |= DA_ZONE_FLAG_MAX_SEQ_SET;
5797 				softc->max_seq_zones =
5798 				    (tmpvar & ATA_ZDI_MAX_SEQ_MASK);
5799 			} else {
5800 				softc->zone_flags &= ~DA_ZONE_FLAG_MAX_SEQ_SET;
5801 				softc->max_seq_zones = 0;
5802 			}
5803 		}
5804 	} else {
5805 		error = daerror(done_ccb, CAM_RETRY_SELTO,
5806 				SF_RETRY_UA|SF_NO_PRINT);
5807 		if (error == ERESTART)
5808 			return;
5809 		else if (error != 0) {
5810 			softc->flags &= ~DA_FLAG_CAN_ATA_ZONE;
5811 			softc->flags &= ~DA_ZONE_FLAG_SET_MASK;
5812 
5813 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5814 				/* Don't wedge this device's queue */
5815 				cam_release_devq(done_ccb->ccb_h.path,
5816 						 /*relsim_flags*/0,
5817 						 /*reduction*/0,
5818 						 /*timeout*/0,
5819 						 /*getcount_only*/0);
5820 			}
5821 		}
5822 	}
5823 
5824 	free(csio->data_ptr, M_SCSIDA);
5825 
5826 	daprobedone(periph, done_ccb);
5827 	return;
5828 }
5829 
5830 static void
5831 dadone_probezone(struct cam_periph *periph, union ccb *done_ccb)
5832 {
5833 	struct da_softc *softc;
5834 	struct ccb_scsiio *csio;
5835 	int error;
5836 
5837 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_probezone\n"));
5838 
5839 	softc = (struct da_softc *)periph->softc;
5840 	csio = &done_ccb->csio;
5841 
5842 	cam_periph_assert(periph, MA_OWNED);
5843 
5844 	if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5845 		uint32_t valid_len;
5846 		size_t needed_len;
5847 		struct scsi_vpd_zoned_bdc *zoned_bdc;
5848 
5849 		error = 0;
5850 		zoned_bdc = (struct scsi_vpd_zoned_bdc *)csio->data_ptr;
5851 		valid_len = csio->dxfer_len - csio->resid;
5852 		needed_len = __offsetof(struct scsi_vpd_zoned_bdc,
5853 		    max_seq_req_zones) + 1 +
5854 		    sizeof(zoned_bdc->max_seq_req_zones);
5855 		if ((valid_len >= needed_len)
5856 		 && (scsi_2btoul(zoned_bdc->page_length) >= SVPD_ZBDC_PL)) {
5857 			if (zoned_bdc->flags & SVPD_ZBDC_URSWRZ)
5858 				softc->zone_flags |= DA_ZONE_FLAG_URSWRZ;
5859 			else
5860 				softc->zone_flags &= ~DA_ZONE_FLAG_URSWRZ;
5861 			softc->optimal_seq_zones =
5862 			    scsi_4btoul(zoned_bdc->optimal_seq_zones);
5863 			softc->zone_flags |= DA_ZONE_FLAG_OPT_SEQ_SET;
5864 			softc->optimal_nonseq_zones = scsi_4btoul(
5865 			    zoned_bdc->optimal_nonseq_zones);
5866 			softc->zone_flags |= DA_ZONE_FLAG_OPT_NONSEQ_SET;
5867 			softc->max_seq_zones =
5868 			    scsi_4btoul(zoned_bdc->max_seq_req_zones);
5869 			softc->zone_flags |= DA_ZONE_FLAG_MAX_SEQ_SET;
5870 		}
5871 		/*
5872 		 * All of the zone commands are mandatory for SCSI
5873 		 * devices.
5874 		 *
5875 		 * XXX KDM this is valid as of September 2015.
5876 		 * Re-check this assumption once the SAT spec is
5877 		 * updated to support SCSI ZBC to ATA ZAC mapping.
5878 		 * Since ATA allows zone commands to be reported
5879 		 * as supported or not, this may not necessarily
5880 		 * be true for an ATA device behind a SAT (SCSI to
5881 		 * ATA Translation) layer.
5882 		 */
5883 		softc->zone_flags |= DA_ZONE_FLAG_SUP_MASK;
5884 	} else {
5885 		error = daerror(done_ccb, CAM_RETRY_SELTO,
5886 				SF_RETRY_UA|SF_NO_PRINT);
5887 		if (error == ERESTART)
5888 			return;
5889 		else if (error != 0) {
5890 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5891 				/* Don't wedge this device's queue */
5892 				cam_release_devq(done_ccb->ccb_h.path,
5893 						 /*relsim_flags*/0,
5894 						 /*reduction*/0,
5895 						 /*timeout*/0,
5896 						 /*getcount_only*/0);
5897 			}
5898 		}
5899 	}
5900 
5901 	free(csio->data_ptr, M_SCSIDA);
5902 
5903 	daprobedone(periph, done_ccb);
5904 	return;
5905 }
5906 
5907 static void
5908 dadone_tur(struct cam_periph *periph, union ccb *done_ccb)
5909 {
5910 	struct da_softc *softc;
5911 
5912 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone_tur\n"));
5913 
5914 	softc = (struct da_softc *)periph->softc;
5915 
5916 	cam_periph_assert(periph, MA_OWNED);
5917 
5918 	if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5919 		if (daerror(done_ccb, CAM_RETRY_SELTO,
5920 		    SF_RETRY_UA | SF_NO_RECOVERY | SF_NO_PRINT) == ERESTART)
5921 			return;	/* Will complete again, keep reference */
5922 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
5923 			cam_release_devq(done_ccb->ccb_h.path,
5924 					 /*relsim_flags*/0,
5925 					 /*reduction*/0,
5926 					 /*timeout*/0,
5927 					 /*getcount_only*/0);
5928 	}
5929 	softc->flags &= ~DA_FLAG_TUR_PENDING;
5930 	xpt_release_ccb(done_ccb);
5931 	da_periph_release_locked(periph, DA_REF_TUR);
5932 	return;
5933 }
5934 
5935 static void
5936 dareprobe(struct cam_periph *periph)
5937 {
5938 	struct da_softc	  *softc;
5939 	int status __diagused;
5940 
5941 	softc = (struct da_softc *)periph->softc;
5942 
5943 	cam_periph_assert(periph, MA_OWNED);
5944 
5945 	/* Probe in progress; don't interfere. */
5946 	if (softc->state != DA_STATE_NORMAL)
5947 		return;
5948 
5949 	status = da_periph_acquire(periph, DA_REF_REPROBE);
5950 	KASSERT(status == 0, ("dareprobe: cam_periph_acquire failed"));
5951 
5952 	softc->state = DA_STATE_PROBE_WP;
5953 	xpt_schedule(periph, CAM_PRIORITY_DEV);
5954 }
5955 
5956 static int
5957 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
5958 {
5959 	struct da_softc	  *softc;
5960 	struct cam_periph *periph;
5961 	int error, error_code, sense_key, asc, ascq;
5962 
5963 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
5964 	if (ccb->csio.bio != NULL)
5965 		biotrack(ccb->csio.bio, __func__);
5966 #endif
5967 
5968 	periph = xpt_path_periph(ccb->ccb_h.path);
5969 	softc = (struct da_softc *)periph->softc;
5970 
5971 	cam_periph_assert(periph, MA_OWNED);
5972 
5973 	/*
5974 	 * Automatically detect devices that do not support
5975 	 * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
5976 	 */
5977 	error = 0;
5978 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
5979 		error = cmd6workaround(ccb);
5980 	} else if (scsi_extract_sense_ccb(ccb,
5981 	    &error_code, &sense_key, &asc, &ascq)) {
5982 		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
5983 			error = cmd6workaround(ccb);
5984 		/*
5985 		 * If the target replied with CAPACITY DATA HAS CHANGED UA,
5986 		 * query the capacity and notify upper layers.
5987 		 */
5988 		else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
5989 		    asc == 0x2A && ascq == 0x09) {
5990 			xpt_print(periph->path, "Capacity data has changed\n");
5991 			softc->flags &= ~DA_FLAG_PROBED;
5992 			dareprobe(periph);
5993 			sense_flags |= SF_NO_PRINT;
5994 		} else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
5995 		    asc == 0x28 && ascq == 0x00) {
5996 			softc->flags &= ~DA_FLAG_PROBED;
5997 			disk_media_changed(softc->disk, M_NOWAIT);
5998 		} else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
5999 		    asc == 0x3F && ascq == 0x03) {
6000 			xpt_print(periph->path, "INQUIRY data has changed\n");
6001 			softc->flags &= ~DA_FLAG_PROBED;
6002 			dareprobe(periph);
6003 			sense_flags |= SF_NO_PRINT;
6004 		} else if (sense_key == SSD_KEY_NOT_READY &&
6005 		    asc == 0x3a && (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
6006 			softc->flags |= DA_FLAG_PACK_INVALID;
6007 			disk_media_gone(softc->disk, M_NOWAIT);
6008 		}
6009 	}
6010 	if (error == ERESTART)
6011 		return (ERESTART);
6012 
6013 #ifdef CAM_IO_STATS
6014 	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
6015 	case CAM_CMD_TIMEOUT:
6016 		softc->timeouts++;
6017 		break;
6018 	case CAM_REQ_ABORTED:
6019 	case CAM_REQ_CMP_ERR:
6020 	case CAM_REQ_TERMIO:
6021 	case CAM_UNREC_HBA_ERROR:
6022 	case CAM_DATA_RUN_ERR:
6023 	case CAM_SCSI_STATUS_ERROR:
6024 	case CAM_ATA_STATUS_ERROR:
6025 		softc->errors++;
6026 		break;
6027 	default:
6028 		break;
6029 	}
6030 #endif
6031 
6032 	/*
6033 	 * XXX
6034 	 * Until we have a better way of doing pack validation,
6035 	 * don't treat UAs as errors.
6036 	 */
6037 	sense_flags |= SF_RETRY_UA;
6038 
6039 	if (softc->quirks & DA_Q_RETRY_BUSY)
6040 		sense_flags |= SF_RETRY_BUSY;
6041 	return(cam_periph_error(ccb, cam_flags, sense_flags));
6042 }
6043 
6044 static void
6045 damediapoll(void *arg)
6046 {
6047 	struct cam_periph *periph = arg;
6048 	struct da_softc *softc = periph->softc;
6049 
6050 	if (!cam_iosched_has_work_flags(softc->cam_iosched, DA_WORK_TUR) &&
6051 	    (softc->flags & DA_FLAG_TUR_PENDING) == 0 &&
6052 	    softc->state == DA_STATE_NORMAL &&
6053 	    LIST_EMPTY(&softc->pending_ccbs)) {
6054 		if (da_periph_acquire(periph, DA_REF_TUR) == 0) {
6055 			cam_iosched_set_work_flags(softc->cam_iosched, DA_WORK_TUR);
6056 			daschedule(periph);
6057 		}
6058 	}
6059 
6060 	/* Queue us up again */
6061 	if (da_poll_period != 0) {
6062 		callout_schedule_sbt(&softc->mediapoll_c,
6063 		    da_poll_period * SBT_1S, 0, C_PREL(1));
6064 	}
6065 }
6066 
6067 static void
6068 daprevent(struct cam_periph *periph, int action)
6069 {
6070 	struct	da_softc *softc;
6071 	union	ccb *ccb;
6072 	int	error;
6073 
6074 	cam_periph_assert(periph, MA_OWNED);
6075 	softc = (struct da_softc *)periph->softc;
6076 
6077 	if (((action == PR_ALLOW)
6078 	  && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
6079 	 || ((action == PR_PREVENT)
6080 	  && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
6081 		return;
6082 	}
6083 
6084 	ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
6085 
6086 	scsi_prevent(&ccb->csio,
6087 		     /*retries*/1,
6088 		     /*cbcfp*/NULL,
6089 		     MSG_SIMPLE_Q_TAG,
6090 		     action,
6091 		     SSD_FULL_SIZE,
6092 		     5000);
6093 
6094 	error = cam_periph_runccb(ccb, daerror, CAM_RETRY_SELTO,
6095 	    SF_RETRY_UA | SF_NO_PRINT, softc->disk->d_devstat);
6096 
6097 	if (error == 0) {
6098 		if (action == PR_ALLOW)
6099 			softc->flags &= ~DA_FLAG_PACK_LOCKED;
6100 		else
6101 			softc->flags |= DA_FLAG_PACK_LOCKED;
6102 	}
6103 
6104 	xpt_release_ccb(ccb);
6105 }
6106 
6107 static void
6108 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector,
6109 	  struct scsi_read_capacity_data_long *rcaplong, size_t rcap_len)
6110 {
6111 	struct ccb_calc_geometry ccg;
6112 	struct da_softc *softc;
6113 	struct disk_params *dp;
6114 	u_int lbppbe, lalba;
6115 	int error;
6116 
6117 	softc = (struct da_softc *)periph->softc;
6118 
6119 	dp = &softc->params;
6120 	dp->secsize = block_len;
6121 	dp->sectors = maxsector + 1;
6122 	if (rcaplong != NULL) {
6123 		lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
6124 		lalba = scsi_2btoul(rcaplong->lalba_lbp);
6125 		lalba &= SRC16_LALBA_A;
6126 		if (rcaplong->prot & SRC16_PROT_EN)
6127 			softc->p_type = ((rcaplong->prot & SRC16_P_TYPE) >>
6128 			    SRC16_P_TYPE_SHIFT) + 1;
6129 		else
6130 			softc->p_type = 0;
6131 	} else {
6132 		lbppbe = 0;
6133 		lalba = 0;
6134 		softc->p_type = 0;
6135 	}
6136 
6137 	if (lbppbe > 0) {
6138 		dp->stripesize = block_len << lbppbe;
6139 		dp->stripeoffset = (dp->stripesize - block_len * lalba) %
6140 		    dp->stripesize;
6141 	} else if (softc->quirks & DA_Q_4K) {
6142 		dp->stripesize = 4096;
6143 		dp->stripeoffset = 0;
6144 	} else if (softc->unmap_gran != 0) {
6145 		dp->stripesize = block_len * softc->unmap_gran;
6146 		dp->stripeoffset = (dp->stripesize - block_len *
6147 		    softc->unmap_gran_align) % dp->stripesize;
6148 	} else {
6149 		dp->stripesize = 0;
6150 		dp->stripeoffset = 0;
6151 	}
6152 	/*
6153 	 * Have the controller provide us with a geometry
6154 	 * for this disk.  The only time the geometry
6155 	 * matters is when we boot and the controller
6156 	 * is the only one knowledgeable enough to come
6157 	 * up with something that will make this a bootable
6158 	 * device.
6159 	 */
6160 	memset(&ccg, 0, sizeof(ccg));
6161 	xpt_setup_ccb(&ccg.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
6162 	ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
6163 	ccg.block_size = dp->secsize;
6164 	ccg.volume_size = dp->sectors;
6165 	ccg.heads = 0;
6166 	ccg.secs_per_track = 0;
6167 	ccg.cylinders = 0;
6168 	xpt_action((union ccb*)&ccg);
6169 	if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
6170 		/*
6171 		 * We don't know what went wrong here- but just pick
6172 		 * a geometry so we don't have nasty things like divide
6173 		 * by zero.
6174 		 */
6175 		dp->heads = 255;
6176 		dp->secs_per_track = 255;
6177 		dp->cylinders = dp->sectors / (255 * 255);
6178 		if (dp->cylinders == 0) {
6179 			dp->cylinders = 1;
6180 		}
6181 	} else {
6182 		dp->heads = ccg.heads;
6183 		dp->secs_per_track = ccg.secs_per_track;
6184 		dp->cylinders = ccg.cylinders;
6185 	}
6186 
6187 	/*
6188 	 * If the user supplied a read capacity buffer, and if it is
6189 	 * different than the previous buffer, update the data in the EDT.
6190 	 * If it's the same, we don't bother.  This avoids sending an
6191 	 * update every time someone opens this device.
6192 	 */
6193 	if ((rcaplong != NULL)
6194 	 && (bcmp(rcaplong, &softc->rcaplong,
6195 		  min(sizeof(softc->rcaplong), rcap_len)) != 0)) {
6196 		struct ccb_dev_advinfo cdai;
6197 
6198 		memset(&cdai, 0, sizeof(cdai));
6199 		xpt_setup_ccb(&cdai.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
6200 		cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
6201 		cdai.buftype = CDAI_TYPE_RCAPLONG;
6202 		cdai.flags = CDAI_FLAG_STORE;
6203 		cdai.bufsiz = rcap_len;
6204 		cdai.buf = (uint8_t *)rcaplong;
6205 		xpt_action((union ccb *)&cdai);
6206 		if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
6207 			cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
6208 		if (cdai.ccb_h.status != CAM_REQ_CMP) {
6209 			xpt_print(periph->path, "%s: failed to set read "
6210 				  "capacity advinfo\n", __func__);
6211 			/* Use cam_error_print() to decode the status */
6212 			cam_error_print((union ccb *)&cdai, CAM_ESF_CAM_STATUS,
6213 					CAM_EPF_ALL);
6214 		} else {
6215 			bcopy(rcaplong, &softc->rcaplong,
6216 			      min(sizeof(softc->rcaplong), rcap_len));
6217 		}
6218 	}
6219 
6220 	softc->disk->d_sectorsize = softc->params.secsize;
6221 	softc->disk->d_mediasize = softc->params.secsize * (off_t)softc->params.sectors;
6222 	softc->disk->d_stripesize = softc->params.stripesize;
6223 	softc->disk->d_stripeoffset = softc->params.stripeoffset;
6224 	/* XXX: these are not actually "firmware" values, so they may be wrong */
6225 	softc->disk->d_fwsectors = softc->params.secs_per_track;
6226 	softc->disk->d_fwheads = softc->params.heads;
6227 	softc->disk->d_devstat->block_size = softc->params.secsize;
6228 	softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
6229 
6230 	error = disk_resize(softc->disk, M_NOWAIT);
6231 	if (error != 0)
6232 		xpt_print(periph->path, "disk_resize(9) failed, error = %d\n", error);
6233 }
6234 
6235 static void
6236 dasendorderedtag(void *arg)
6237 {
6238 	struct cam_periph *periph = arg;
6239 	struct da_softc *softc = periph->softc;
6240 
6241 	cam_periph_assert(periph, MA_OWNED);
6242 	if (da_send_ordered) {
6243 		if (!LIST_EMPTY(&softc->pending_ccbs)) {
6244 			if ((softc->flags & DA_FLAG_WAS_OTAG) == 0)
6245 				softc->flags |= DA_FLAG_NEED_OTAG;
6246 			softc->flags &= ~DA_FLAG_WAS_OTAG;
6247 		}
6248 	}
6249 
6250 	/* Queue us up again */
6251 	callout_schedule_sbt(&softc->sendordered_c,
6252 	    SBT_1S / DA_ORDEREDTAG_INTERVAL * da_default_timeout, 0,
6253 	    C_PREL(1));
6254 }
6255 
6256 /*
6257  * Step through all DA peripheral drivers, and if the device is still open,
6258  * sync the disk cache to physical media.
6259  */
6260 static void
6261 dashutdown(void * arg, int howto)
6262 {
6263 	struct cam_periph *periph;
6264 	struct da_softc *softc;
6265 	union ccb *ccb;
6266 	int error;
6267 
6268 	if ((howto & RB_NOSYNC) != 0)
6269 		return;
6270 
6271 	CAM_PERIPH_FOREACH(periph, &dadriver) {
6272 		softc = (struct da_softc *)periph->softc;
6273 		if (SCHEDULER_STOPPED()) {
6274 			/* If we paniced with the lock held, do not recurse. */
6275 			if (!cam_periph_owned(periph) &&
6276 			    (softc->flags & DA_FLAG_OPEN)) {
6277 				dadump(softc->disk, NULL, 0, 0);
6278 			}
6279 			continue;
6280 		}
6281 		cam_periph_lock(periph);
6282 
6283 		/*
6284 		 * We only sync the cache if the drive is still open, and
6285 		 * if the drive is capable of it..
6286 		 */
6287 		if (((softc->flags & DA_FLAG_OPEN) == 0)
6288 		 || (softc->quirks & DA_Q_NO_SYNC_CACHE)) {
6289 			cam_periph_unlock(periph);
6290 			continue;
6291 		}
6292 
6293 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
6294 		scsi_synchronize_cache(&ccb->csio,
6295 				       /*retries*/0,
6296 				       /*cbfcnp*/NULL,
6297 				       MSG_SIMPLE_Q_TAG,
6298 				       /*begin_lba*/0, /* whole disk */
6299 				       /*lb_count*/0,
6300 				       SSD_FULL_SIZE,
6301 				       60 * 60 * 1000);
6302 
6303 		error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
6304 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR,
6305 		    softc->disk->d_devstat);
6306 		if (error != 0)
6307 			xpt_print(periph->path, "Synchronize cache failed\n");
6308 		xpt_release_ccb(ccb);
6309 		cam_periph_unlock(periph);
6310 	}
6311 }
6312 
6313 #else /* !_KERNEL */
6314 
6315 /*
6316  * XXX These are only left out of the kernel build to silence warnings.  If,
6317  * for some reason these functions are used in the kernel, the ifdefs should
6318  * be moved so they are included both in the kernel and userland.
6319  */
6320 void
6321 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
6322 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
6323 		 u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
6324 		 u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
6325 		 u_int32_t timeout)
6326 {
6327 	struct scsi_format_unit *scsi_cmd;
6328 
6329 	scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
6330 	scsi_cmd->opcode = FORMAT_UNIT;
6331 	scsi_cmd->byte2 = byte2;
6332 	scsi_ulto2b(ileave, scsi_cmd->interleave);
6333 
6334 	cam_fill_csio(csio,
6335 		      retries,
6336 		      cbfcnp,
6337 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
6338 		      tag_action,
6339 		      data_ptr,
6340 		      dxfer_len,
6341 		      sense_len,
6342 		      sizeof(*scsi_cmd),
6343 		      timeout);
6344 }
6345 
6346 void
6347 scsi_read_defects(struct ccb_scsiio *csio, uint32_t retries,
6348 		  void (*cbfcnp)(struct cam_periph *, union ccb *),
6349 		  uint8_t tag_action, uint8_t list_format,
6350 		  uint32_t addr_desc_index, uint8_t *data_ptr,
6351 		  uint32_t dxfer_len, int minimum_cmd_size,
6352 		  uint8_t sense_len, uint32_t timeout)
6353 {
6354 	uint8_t cdb_len;
6355 
6356 	/*
6357 	 * These conditions allow using the 10 byte command.  Otherwise we
6358 	 * need to use the 12 byte command.
6359 	 */
6360 	if ((minimum_cmd_size <= 10)
6361 	 && (addr_desc_index == 0)
6362 	 && (dxfer_len <= SRDD10_MAX_LENGTH)) {
6363 		struct scsi_read_defect_data_10 *cdb10;
6364 
6365 		cdb10 = (struct scsi_read_defect_data_10 *)
6366 			&csio->cdb_io.cdb_bytes;
6367 
6368 		cdb_len = sizeof(*cdb10);
6369 		bzero(cdb10, cdb_len);
6370                 cdb10->opcode = READ_DEFECT_DATA_10;
6371                 cdb10->format = list_format;
6372                 scsi_ulto2b(dxfer_len, cdb10->alloc_length);
6373 	} else {
6374 		struct scsi_read_defect_data_12 *cdb12;
6375 
6376 		cdb12 = (struct scsi_read_defect_data_12 *)
6377 			&csio->cdb_io.cdb_bytes;
6378 
6379 		cdb_len = sizeof(*cdb12);
6380 		bzero(cdb12, cdb_len);
6381                 cdb12->opcode = READ_DEFECT_DATA_12;
6382                 cdb12->format = list_format;
6383                 scsi_ulto4b(dxfer_len, cdb12->alloc_length);
6384 		scsi_ulto4b(addr_desc_index, cdb12->address_descriptor_index);
6385 	}
6386 
6387 	cam_fill_csio(csio,
6388 		      retries,
6389 		      cbfcnp,
6390 		      /*flags*/ CAM_DIR_IN,
6391 		      tag_action,
6392 		      data_ptr,
6393 		      dxfer_len,
6394 		      sense_len,
6395 		      cdb_len,
6396 		      timeout);
6397 }
6398 
6399 void
6400 scsi_sanitize(struct ccb_scsiio *csio, u_int32_t retries,
6401 	      void (*cbfcnp)(struct cam_periph *, union ccb *),
6402 	      u_int8_t tag_action, u_int8_t byte2, u_int16_t control,
6403 	      u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
6404 	      u_int32_t timeout)
6405 {
6406 	struct scsi_sanitize *scsi_cmd;
6407 
6408 	scsi_cmd = (struct scsi_sanitize *)&csio->cdb_io.cdb_bytes;
6409 	scsi_cmd->opcode = SANITIZE;
6410 	scsi_cmd->byte2 = byte2;
6411 	scsi_cmd->control = control;
6412 	scsi_ulto2b(dxfer_len, scsi_cmd->length);
6413 
6414 	cam_fill_csio(csio,
6415 		      retries,
6416 		      cbfcnp,
6417 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
6418 		      tag_action,
6419 		      data_ptr,
6420 		      dxfer_len,
6421 		      sense_len,
6422 		      sizeof(*scsi_cmd),
6423 		      timeout);
6424 }
6425 
6426 #endif /* _KERNEL */
6427 
6428 void
6429 scsi_zbc_out(struct ccb_scsiio *csio, uint32_t retries,
6430 	     void (*cbfcnp)(struct cam_periph *, union ccb *),
6431 	     uint8_t tag_action, uint8_t service_action, uint64_t zone_id,
6432 	     uint8_t zone_flags, uint8_t *data_ptr, uint32_t dxfer_len,
6433 	     uint8_t sense_len, uint32_t timeout)
6434 {
6435 	struct scsi_zbc_out *scsi_cmd;
6436 
6437 	scsi_cmd = (struct scsi_zbc_out *)&csio->cdb_io.cdb_bytes;
6438 	scsi_cmd->opcode = ZBC_OUT;
6439 	scsi_cmd->service_action = service_action;
6440 	scsi_u64to8b(zone_id, scsi_cmd->zone_id);
6441 	scsi_cmd->zone_flags = zone_flags;
6442 
6443 	cam_fill_csio(csio,
6444 		      retries,
6445 		      cbfcnp,
6446 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
6447 		      tag_action,
6448 		      data_ptr,
6449 		      dxfer_len,
6450 		      sense_len,
6451 		      sizeof(*scsi_cmd),
6452 		      timeout);
6453 }
6454 
6455 void
6456 scsi_zbc_in(struct ccb_scsiio *csio, uint32_t retries,
6457 	    void (*cbfcnp)(struct cam_periph *, union ccb *),
6458 	    uint8_t tag_action, uint8_t service_action, uint64_t zone_start_lba,
6459 	    uint8_t zone_options, uint8_t *data_ptr, uint32_t dxfer_len,
6460 	    uint8_t sense_len, uint32_t timeout)
6461 {
6462 	struct scsi_zbc_in *scsi_cmd;
6463 
6464 	scsi_cmd = (struct scsi_zbc_in *)&csio->cdb_io.cdb_bytes;
6465 	scsi_cmd->opcode = ZBC_IN;
6466 	scsi_cmd->service_action = service_action;
6467 	scsi_ulto4b(dxfer_len, scsi_cmd->length);
6468 	scsi_u64to8b(zone_start_lba, scsi_cmd->zone_start_lba);
6469 	scsi_cmd->zone_options = zone_options;
6470 
6471 	cam_fill_csio(csio,
6472 		      retries,
6473 		      cbfcnp,
6474 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_IN : CAM_DIR_NONE,
6475 		      tag_action,
6476 		      data_ptr,
6477 		      dxfer_len,
6478 		      sense_len,
6479 		      sizeof(*scsi_cmd),
6480 		      timeout);
6481 
6482 }
6483 
6484 int
6485 scsi_ata_zac_mgmt_out(struct ccb_scsiio *csio, uint32_t retries,
6486 		      void (*cbfcnp)(struct cam_periph *, union ccb *),
6487 		      uint8_t tag_action, int use_ncq,
6488 		      uint8_t zm_action, uint64_t zone_id, uint8_t zone_flags,
6489 		      uint8_t *data_ptr, uint32_t dxfer_len,
6490 		      uint8_t *cdb_storage, size_t cdb_storage_len,
6491 		      uint8_t sense_len, uint32_t timeout)
6492 {
6493 	uint8_t command_out, protocol, ata_flags;
6494 	uint16_t features_out;
6495 	uint32_t sectors_out, auxiliary;
6496 	int retval;
6497 
6498 	retval = 0;
6499 
6500 	if (use_ncq == 0) {
6501 		command_out = ATA_ZAC_MANAGEMENT_OUT;
6502 		features_out = (zm_action & 0xf) | (zone_flags << 8);
6503 		ata_flags = AP_FLAG_BYT_BLOK_BLOCKS;
6504 		if (dxfer_len == 0) {
6505 			protocol = AP_PROTO_NON_DATA;
6506 			ata_flags |= AP_FLAG_TLEN_NO_DATA;
6507 			sectors_out = 0;
6508 		} else {
6509 			protocol = AP_PROTO_DMA;
6510 			ata_flags |= AP_FLAG_TLEN_SECT_CNT |
6511 				     AP_FLAG_TDIR_TO_DEV;
6512 			sectors_out = ((dxfer_len >> 9) & 0xffff);
6513 		}
6514 		auxiliary = 0;
6515 	} else {
6516 		ata_flags = AP_FLAG_BYT_BLOK_BLOCKS;
6517 		if (dxfer_len == 0) {
6518 			command_out = ATA_NCQ_NON_DATA;
6519 			features_out = ATA_NCQ_ZAC_MGMT_OUT;
6520 			/*
6521 			 * We're assuming the SCSI to ATA translation layer
6522 			 * will set the NCQ tag number in the tag field.
6523 			 * That isn't clear from the SAT-4 spec (as of rev 05).
6524 			 */
6525 			sectors_out = 0;
6526 			ata_flags |= AP_FLAG_TLEN_NO_DATA;
6527 		} else {
6528 			command_out = ATA_SEND_FPDMA_QUEUED;
6529 			/*
6530 			 * Note that we're defaulting to normal priority,
6531 			 * and assuming that the SCSI to ATA translation
6532 			 * layer will insert the NCQ tag number in the tag
6533 			 * field.  That isn't clear in the SAT-4 spec (as
6534 			 * of rev 05).
6535 			 */
6536 			sectors_out = ATA_SFPDMA_ZAC_MGMT_OUT << 8;
6537 
6538 			ata_flags |= AP_FLAG_TLEN_FEAT |
6539 				     AP_FLAG_TDIR_TO_DEV;
6540 
6541 			/*
6542 			 * For SEND FPDMA QUEUED, the transfer length is
6543 			 * encoded in the FEATURE register, and 0 means
6544 			 * that 65536 512 byte blocks are to be tranferred.
6545 			 * In practice, it seems unlikely that we'll see
6546 			 * a transfer that large, and it may confuse the
6547 			 * the SAT layer, because generally that means that
6548 			 * 0 bytes should be transferred.
6549 			 */
6550 			if (dxfer_len == (65536 * 512)) {
6551 				features_out = 0;
6552 			} else if (dxfer_len <= (65535 * 512)) {
6553 				features_out = ((dxfer_len >> 9) & 0xffff);
6554 			} else {
6555 				/* The transfer is too big. */
6556 				retval = 1;
6557 				goto bailout;
6558 			}
6559 		}
6560 
6561 		auxiliary = (zm_action & 0xf) | (zone_flags << 8);
6562 		protocol = AP_PROTO_FPDMA;
6563 	}
6564 
6565 	protocol |= AP_EXTEND;
6566 
6567 	retval = scsi_ata_pass(csio,
6568 	    retries,
6569 	    cbfcnp,
6570 	    /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
6571 	    tag_action,
6572 	    /*protocol*/ protocol,
6573 	    /*ata_flags*/ ata_flags,
6574 	    /*features*/ features_out,
6575 	    /*sector_count*/ sectors_out,
6576 	    /*lba*/ zone_id,
6577 	    /*command*/ command_out,
6578 	    /*device*/ 0,
6579 	    /*icc*/ 0,
6580 	    /*auxiliary*/ auxiliary,
6581 	    /*control*/ 0,
6582 	    /*data_ptr*/ data_ptr,
6583 	    /*dxfer_len*/ dxfer_len,
6584 	    /*cdb_storage*/ cdb_storage,
6585 	    /*cdb_storage_len*/ cdb_storage_len,
6586 	    /*minimum_cmd_size*/ 0,
6587 	    /*sense_len*/ SSD_FULL_SIZE,
6588 	    /*timeout*/ timeout);
6589 
6590 bailout:
6591 
6592 	return (retval);
6593 }
6594 
6595 int
6596 scsi_ata_zac_mgmt_in(struct ccb_scsiio *csio, uint32_t retries,
6597 		     void (*cbfcnp)(struct cam_periph *, union ccb *),
6598 		     uint8_t tag_action, int use_ncq,
6599 		     uint8_t zm_action, uint64_t zone_id, uint8_t zone_flags,
6600 		     uint8_t *data_ptr, uint32_t dxfer_len,
6601 		     uint8_t *cdb_storage, size_t cdb_storage_len,
6602 		     uint8_t sense_len, uint32_t timeout)
6603 {
6604 	uint8_t command_out, protocol;
6605 	uint16_t features_out, sectors_out;
6606 	uint32_t auxiliary;
6607 	int ata_flags;
6608 	int retval;
6609 
6610 	retval = 0;
6611 	ata_flags = AP_FLAG_TDIR_FROM_DEV | AP_FLAG_BYT_BLOK_BLOCKS;
6612 
6613 	if (use_ncq == 0) {
6614 		command_out = ATA_ZAC_MANAGEMENT_IN;
6615 		/* XXX KDM put a macro here */
6616 		features_out = (zm_action & 0xf) | (zone_flags << 8);
6617 		sectors_out = dxfer_len >> 9; /* XXX KDM macro */
6618 		protocol = AP_PROTO_DMA;
6619 		ata_flags |= AP_FLAG_TLEN_SECT_CNT;
6620 		auxiliary = 0;
6621 	} else {
6622 		ata_flags |= AP_FLAG_TLEN_FEAT;
6623 
6624 		command_out = ATA_RECV_FPDMA_QUEUED;
6625 		sectors_out = ATA_RFPDMA_ZAC_MGMT_IN << 8;
6626 
6627 		/*
6628 		 * For RECEIVE FPDMA QUEUED, the transfer length is
6629 		 * encoded in the FEATURE register, and 0 means
6630 		 * that 65536 512 byte blocks are to be tranferred.
6631 		 * In practice, it seems unlikely that we'll see
6632 		 * a transfer that large, and it may confuse the
6633 		 * the SAT layer, because generally that means that
6634 		 * 0 bytes should be transferred.
6635 		 */
6636 		if (dxfer_len == (65536 * 512)) {
6637 			features_out = 0;
6638 		} else if (dxfer_len <= (65535 * 512)) {
6639 			features_out = ((dxfer_len >> 9) & 0xffff);
6640 		} else {
6641 			/* The transfer is too big. */
6642 			retval = 1;
6643 			goto bailout;
6644 		}
6645 		auxiliary = (zm_action & 0xf) | (zone_flags << 8),
6646 		protocol = AP_PROTO_FPDMA;
6647 	}
6648 
6649 	protocol |= AP_EXTEND;
6650 
6651 	retval = scsi_ata_pass(csio,
6652 	    retries,
6653 	    cbfcnp,
6654 	    /*flags*/ CAM_DIR_IN,
6655 	    tag_action,
6656 	    /*protocol*/ protocol,
6657 	    /*ata_flags*/ ata_flags,
6658 	    /*features*/ features_out,
6659 	    /*sector_count*/ sectors_out,
6660 	    /*lba*/ zone_id,
6661 	    /*command*/ command_out,
6662 	    /*device*/ 0,
6663 	    /*icc*/ 0,
6664 	    /*auxiliary*/ auxiliary,
6665 	    /*control*/ 0,
6666 	    /*data_ptr*/ data_ptr,
6667 	    /*dxfer_len*/ (dxfer_len >> 9) * 512, /* XXX KDM */
6668 	    /*cdb_storage*/ cdb_storage,
6669 	    /*cdb_storage_len*/ cdb_storage_len,
6670 	    /*minimum_cmd_size*/ 0,
6671 	    /*sense_len*/ SSD_FULL_SIZE,
6672 	    /*timeout*/ timeout);
6673 
6674 bailout:
6675 	return (retval);
6676 }
6677