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