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