xref: /freebsd/sys/cam/ata/ata_da.c (revision e17f5b1d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer,
12  *    without modification, immediately at the beginning of the file.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include "opt_ada.h"
33 
34 #include <sys/param.h>
35 
36 #ifdef _KERNEL
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/bio.h>
40 #include <sys/sysctl.h>
41 #include <sys/taskqueue.h>
42 #include <sys/lock.h>
43 #include <sys/mutex.h>
44 #include <sys/conf.h>
45 #include <sys/devicestat.h>
46 #include <sys/eventhandler.h>
47 #include <sys/malloc.h>
48 #include <sys/endian.h>
49 #include <sys/cons.h>
50 #include <sys/proc.h>
51 #include <sys/reboot.h>
52 #include <sys/sbuf.h>
53 #include <geom/geom.h>
54 #include <geom/geom_disk.h>
55 #endif /* _KERNEL */
56 
57 #ifndef _KERNEL
58 #include <stdio.h>
59 #include <string.h>
60 #endif /* _KERNEL */
61 
62 #include <cam/cam.h>
63 #include <cam/cam_ccb.h>
64 #include <cam/cam_periph.h>
65 #include <cam/cam_xpt_periph.h>
66 #include <cam/scsi/scsi_all.h>
67 #include <cam/scsi/scsi_da.h>
68 #include <cam/cam_sim.h>
69 #include <cam/cam_iosched.h>
70 
71 #include <cam/ata/ata_all.h>
72 
73 #ifdef _KERNEL
74 
75 #define ATA_MAX_28BIT_LBA               268435455UL
76 
77 extern int iosched_debug;
78 
79 typedef enum {
80 	ADA_STATE_RAHEAD,
81 	ADA_STATE_WCACHE,
82 	ADA_STATE_LOGDIR,
83 	ADA_STATE_IDDIR,
84 	ADA_STATE_SUP_CAP,
85 	ADA_STATE_ZONE,
86 	ADA_STATE_NORMAL
87 } ada_state;
88 
89 typedef enum {
90 	ADA_FLAG_CAN_48BIT	= 0x00000002,
91 	ADA_FLAG_CAN_FLUSHCACHE	= 0x00000004,
92 	ADA_FLAG_CAN_NCQ	= 0x00000008,
93 	ADA_FLAG_CAN_DMA	= 0x00000010,
94 	ADA_FLAG_NEED_OTAG	= 0x00000020,
95 	ADA_FLAG_WAS_OTAG	= 0x00000040,
96 	ADA_FLAG_CAN_TRIM	= 0x00000080,
97 	ADA_FLAG_OPEN		= 0x00000100,
98 	ADA_FLAG_SCTX_INIT	= 0x00000200,
99 	ADA_FLAG_CAN_CFA        = 0x00000400,
100 	ADA_FLAG_CAN_POWERMGT   = 0x00000800,
101 	ADA_FLAG_CAN_DMA48	= 0x00001000,
102 	ADA_FLAG_CAN_LOG	= 0x00002000,
103 	ADA_FLAG_CAN_IDLOG	= 0x00004000,
104 	ADA_FLAG_CAN_SUPCAP	= 0x00008000,
105 	ADA_FLAG_CAN_ZONE	= 0x00010000,
106 	ADA_FLAG_CAN_WCACHE	= 0x00020000,
107 	ADA_FLAG_CAN_RAHEAD	= 0x00040000,
108 	ADA_FLAG_PROBED		= 0x00080000,
109 	ADA_FLAG_ANNOUNCED	= 0x00100000,
110 	ADA_FLAG_DIRTY		= 0x00200000,
111 	ADA_FLAG_CAN_NCQ_TRIM	= 0x00400000,	/* CAN_TRIM also set */
112 	ADA_FLAG_PIM_ATA_EXT	= 0x00800000,
113 	ADA_FLAG_UNMAPPEDIO	= 0x01000000,
114 	ADA_FLAG_ROTATING	= 0x02000000
115 } ada_flags;
116 #define ADA_FLAG_STRING		\
117 	"\020"			\
118 	"\002CAN_48BIT"		\
119 	"\003CAN_FLUSHCACHE"	\
120 	"\004CAN_NCQ"		\
121 	"\005CAN_DMA"		\
122 	"\006NEED_OTAG"		\
123 	"\007WAS_OTAG"		\
124 	"\010CAN_TRIM"		\
125 	"\011OPEN"		\
126 	"\012SCTX_INIT"		\
127 	"\013CAN_CFA"		\
128 	"\014CAN_POWERMGT"	\
129 	"\015CAN_DMA48"		\
130 	"\016CAN_LOG"		\
131 	"\017CAN_IDLOG"		\
132 	"\020CAN_SUPCAP"	\
133 	"\021CAN_ZONE"		\
134 	"\022CAN_WCACHE"	\
135 	"\023CAN_RAHEAD"	\
136 	"\024PROBED"		\
137 	"\025ANNOUNCED"		\
138 	"\026DIRTY"		\
139 	"\027CAN_NCQ_TRIM"	\
140 	"\030PIM_ATA_EXT"	\
141 	"\031UNMAPPEDIO"	\
142 	"\032ROTATING"
143 
144 typedef enum {
145 	ADA_Q_NONE		= 0x00,
146 	ADA_Q_4K		= 0x01,
147 	ADA_Q_NCQ_TRIM_BROKEN	= 0x02,
148 	ADA_Q_LOG_BROKEN	= 0x04,
149 	ADA_Q_SMR_DM		= 0x08,
150 	ADA_Q_NO_TRIM		= 0x10,
151 	ADA_Q_128KB		= 0x20
152 } ada_quirks;
153 
154 #define ADA_Q_BIT_STRING	\
155 	"\020"			\
156 	"\0014K"		\
157 	"\002NCQ_TRIM_BROKEN"	\
158 	"\003LOG_BROKEN"	\
159 	"\004SMR_DM"		\
160 	"\005NO_TRIM"		\
161 	"\006128KB"
162 
163 typedef enum {
164 	ADA_CCB_RAHEAD		= 0x01,
165 	ADA_CCB_WCACHE		= 0x02,
166 	ADA_CCB_BUFFER_IO	= 0x03,
167 	ADA_CCB_DUMP		= 0x05,
168 	ADA_CCB_TRIM		= 0x06,
169 	ADA_CCB_LOGDIR		= 0x07,
170 	ADA_CCB_IDDIR		= 0x08,
171 	ADA_CCB_SUP_CAP		= 0x09,
172 	ADA_CCB_ZONE		= 0x0a,
173 	ADA_CCB_TYPE_MASK	= 0x0F,
174 } ada_ccb_state;
175 
176 typedef enum {
177 	ADA_ZONE_NONE		= 0x00,
178 	ADA_ZONE_DRIVE_MANAGED	= 0x01,
179 	ADA_ZONE_HOST_AWARE	= 0x02,
180 	ADA_ZONE_HOST_MANAGED	= 0x03
181 } ada_zone_mode;
182 
183 typedef enum {
184 	ADA_ZONE_FLAG_RZ_SUP		= 0x0001,
185 	ADA_ZONE_FLAG_OPEN_SUP		= 0x0002,
186 	ADA_ZONE_FLAG_CLOSE_SUP		= 0x0004,
187 	ADA_ZONE_FLAG_FINISH_SUP	= 0x0008,
188 	ADA_ZONE_FLAG_RWP_SUP		= 0x0010,
189 	ADA_ZONE_FLAG_SUP_MASK		= (ADA_ZONE_FLAG_RZ_SUP |
190 					   ADA_ZONE_FLAG_OPEN_SUP |
191 					   ADA_ZONE_FLAG_CLOSE_SUP |
192 					   ADA_ZONE_FLAG_FINISH_SUP |
193 					   ADA_ZONE_FLAG_RWP_SUP),
194 	ADA_ZONE_FLAG_URSWRZ		= 0x0020,
195 	ADA_ZONE_FLAG_OPT_SEQ_SET	= 0x0040,
196 	ADA_ZONE_FLAG_OPT_NONSEQ_SET	= 0x0080,
197 	ADA_ZONE_FLAG_MAX_SEQ_SET	= 0x0100,
198 	ADA_ZONE_FLAG_SET_MASK		= (ADA_ZONE_FLAG_OPT_SEQ_SET |
199 					   ADA_ZONE_FLAG_OPT_NONSEQ_SET |
200 					   ADA_ZONE_FLAG_MAX_SEQ_SET)
201 } ada_zone_flags;
202 
203 static struct ada_zone_desc {
204 	ada_zone_flags value;
205 	const char *desc;
206 } ada_zone_desc_table[] = {
207 	{ADA_ZONE_FLAG_RZ_SUP, "Report Zones" },
208 	{ADA_ZONE_FLAG_OPEN_SUP, "Open" },
209 	{ADA_ZONE_FLAG_CLOSE_SUP, "Close" },
210 	{ADA_ZONE_FLAG_FINISH_SUP, "Finish" },
211 	{ADA_ZONE_FLAG_RWP_SUP, "Reset Write Pointer" },
212 };
213 
214 
215 /* Offsets into our private area for storing information */
216 #define ccb_state	ppriv_field0
217 #define ccb_bp		ppriv_ptr1
218 
219 typedef enum {
220 	ADA_DELETE_NONE,
221 	ADA_DELETE_DISABLE,
222 	ADA_DELETE_CFA_ERASE,
223 	ADA_DELETE_DSM_TRIM,
224 	ADA_DELETE_NCQ_DSM_TRIM,
225 	ADA_DELETE_MIN = ADA_DELETE_CFA_ERASE,
226 	ADA_DELETE_MAX = ADA_DELETE_NCQ_DSM_TRIM,
227 } ada_delete_methods;
228 
229 static const char *ada_delete_method_names[] =
230     { "NONE", "DISABLE", "CFA_ERASE", "DSM_TRIM", "NCQ_DSM_TRIM" };
231 #if 0
232 static const char *ada_delete_method_desc[] =
233     { "NONE", "DISABLED", "CFA Erase", "DSM Trim", "DSM Trim via NCQ" };
234 #endif
235 
236 struct disk_params {
237 	u_int8_t  heads;
238 	u_int8_t  secs_per_track;
239 	u_int32_t cylinders;
240 	u_int32_t secsize;	/* Number of bytes/logical sector */
241 	u_int64_t sectors;	/* Total number sectors */
242 };
243 
244 #define TRIM_MAX_BLOCKS	8
245 #define TRIM_MAX_RANGES	(TRIM_MAX_BLOCKS * ATA_DSM_BLK_RANGES)
246 struct trim_request {
247 	uint8_t		data[TRIM_MAX_RANGES * ATA_DSM_RANGE_SIZE];
248 	TAILQ_HEAD(, bio) bps;
249 };
250 
251 struct ada_softc {
252 	struct   cam_iosched_softc *cam_iosched;
253 	int	 outstanding_cmds;	/* Number of active commands */
254 	int	 refcount;		/* Active xpt_action() calls */
255 	ada_state state;
256 	ada_flags flags;
257 	ada_zone_mode zone_mode;
258 	ada_zone_flags zone_flags;
259 	struct ata_gp_log_dir ata_logdir;
260 	int valid_logdir_len;
261 	struct ata_identify_log_pages ata_iddir;
262 	int valid_iddir_len;
263 	uint64_t optimal_seq_zones;
264 	uint64_t optimal_nonseq_zones;
265 	uint64_t max_seq_zones;
266 	ada_quirks quirks;
267 	ada_delete_methods delete_method;
268 	int	 trim_max_ranges;
269 	int	 read_ahead;
270 	int	 write_cache;
271 #ifdef CAM_TEST_FAILURE
272 	int      force_read_error;
273 	int      force_write_error;
274 	int      periodic_read_error;
275 	int      periodic_read_count;
276 #endif
277 	struct ccb_pathinq	cpi;
278 	struct disk_params	params;
279 	struct disk		*disk;
280 	struct task		sysctl_task;
281 	struct sysctl_ctx_list	sysctl_ctx;
282 	struct sysctl_oid	*sysctl_tree;
283 	struct callout		sendordered_c;
284 	struct trim_request	trim_req;
285 	uint64_t		trim_count;
286 	uint64_t		trim_ranges;
287 	uint64_t		trim_lbas;
288 #ifdef CAM_IO_STATS
289 	struct sysctl_ctx_list	sysctl_stats_ctx;
290 	struct sysctl_oid	*sysctl_stats_tree;
291 	u_int	timeouts;
292 	u_int	errors;
293 	u_int	invalidations;
294 #endif
295 #define ADA_ANNOUNCETMP_SZ 80
296 	char	announce_temp[ADA_ANNOUNCETMP_SZ];
297 #define ADA_ANNOUNCE_SZ 400
298 	char	announce_buffer[ADA_ANNOUNCE_SZ];
299 };
300 
301 struct ada_quirk_entry {
302 	struct scsi_inquiry_pattern inq_pat;
303 	ada_quirks quirks;
304 };
305 
306 static struct ada_quirk_entry ada_quirk_table[] =
307 {
308 	{
309 		/* Sandisk X400 */
310 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SanDisk?SD8SB8U1T00*", "X4162000*" },
311 		/*quirks*/ADA_Q_128KB
312 	},
313 	{
314 		/* Hitachi Advanced Format (4k) drives */
315 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Hitachi H??????????E3*", "*" },
316 		/*quirks*/ADA_Q_4K
317 	},
318 	{
319 		/* Samsung Advanced Format (4k) drives */
320 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD155UI*", "*" },
321 		/*quirks*/ADA_Q_4K
322 	},
323 	{
324 		/* Samsung Advanced Format (4k) drives */
325 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD204UI*", "*" },
326 		/*quirks*/ADA_Q_4K
327 	},
328 	{
329 		/* Seagate Barracuda Green Advanced Format (4k) drives */
330 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DL*", "*" },
331 		/*quirks*/ADA_Q_4K
332 	},
333 	{
334 		/* Seagate Barracuda Advanced Format (4k) drives */
335 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???DM*", "*" },
336 		/*quirks*/ADA_Q_4K
337 	},
338 	{
339 		/* Seagate Barracuda Advanced Format (4k) drives */
340 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DM*", "*" },
341 		/*quirks*/ADA_Q_4K
342 	},
343 	{
344 		/* Seagate Momentus Advanced Format (4k) drives */
345 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500423AS*", "*" },
346 		/*quirks*/ADA_Q_4K
347 	},
348 	{
349 		/* Seagate Momentus Advanced Format (4k) drives */
350 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500424AS*", "*" },
351 		/*quirks*/ADA_Q_4K
352 	},
353 	{
354 		/* Seagate Momentus Advanced Format (4k) drives */
355 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640423AS*", "*" },
356 		/*quirks*/ADA_Q_4K
357 	},
358 	{
359 		/* Seagate Momentus Advanced Format (4k) drives */
360 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640424AS*", "*" },
361 		/*quirks*/ADA_Q_4K
362 	},
363 	{
364 		/* Seagate Momentus Advanced Format (4k) drives */
365 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750420AS*", "*" },
366 		/*quirks*/ADA_Q_4K
367 	},
368 	{
369 		/* Seagate Momentus Advanced Format (4k) drives */
370 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750422AS*", "*" },
371 		/*quirks*/ADA_Q_4K
372 	},
373 	{
374 		/* Seagate Momentus Advanced Format (4k) drives */
375 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750423AS*", "*" },
376 		/*quirks*/ADA_Q_4K
377 	},
378 	{
379 		/* Seagate Momentus Thin Advanced Format (4k) drives */
380 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???LT*", "*" },
381 		/*quirks*/ADA_Q_4K
382 	},
383 	{
384 		/* WDC Caviar Red Advanced Format (4k) drives */
385 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????CX*", "*" },
386 		/*quirks*/ADA_Q_4K
387 	},
388 	{
389 		/* WDC Caviar Green Advanced Format (4k) drives */
390 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RS*", "*" },
391 		/*quirks*/ADA_Q_4K
392 	},
393 	{
394 		/* WDC Caviar Green/Red Advanced Format (4k) drives */
395 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RX*", "*" },
396 		/*quirks*/ADA_Q_4K
397 	},
398 	{
399 		/* WDC Caviar Red Advanced Format (4k) drives */
400 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????CX*", "*" },
401 		/*quirks*/ADA_Q_4K
402 	},
403 	{
404 		/* WDC Caviar Black Advanced Format (4k) drives */
405 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????AZEX*", "*" },
406 		/*quirks*/ADA_Q_4K
407 	},
408 	{
409 		/* WDC Caviar Black Advanced Format (4k) drives */
410 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????FZEX*", "*" },
411 		/*quirks*/ADA_Q_4K
412 	},
413 	{
414 		/* WDC Caviar Green Advanced Format (4k) drives */
415 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RS*", "*" },
416 		/*quirks*/ADA_Q_4K
417 	},
418 	{
419 		/* WDC Caviar Green Advanced Format (4k) drives */
420 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RX*", "*" },
421 		/*quirks*/ADA_Q_4K
422 	},
423 	{
424 		/* WDC Scorpio Black Advanced Format (4k) drives */
425 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PKT*", "*" },
426 		/*quirks*/ADA_Q_4K
427 	},
428 	{
429 		/* WDC Scorpio Black Advanced Format (4k) drives */
430 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PKT*", "*" },
431 		/*quirks*/ADA_Q_4K
432 	},
433 	{
434 		/* WDC Scorpio Blue Advanced Format (4k) drives */
435 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PVT*", "*" },
436 		/*quirks*/ADA_Q_4K
437 	},
438 	{
439 		/* WDC Scorpio Blue Advanced Format (4k) drives */
440 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PVT*", "*" },
441 		/*quirks*/ADA_Q_4K
442 	},
443 	/* SSDs */
444 	{
445 		/*
446 		 * Corsair Force 2 SSDs
447 		 * 4k optimised & trim only works in 4k requests + 4k aligned
448 		 */
449 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair CSSD-F*", "*" },
450 		/*quirks*/ADA_Q_4K
451 	},
452 	{
453 		/*
454 		 * Corsair Force 3 SSDs
455 		 * 4k optimised & trim only works in 4k requests + 4k aligned
456 		 */
457 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force 3*", "*" },
458 		/*quirks*/ADA_Q_4K
459 	},
460 	{
461 		/*
462 		 * Corsair Neutron GTX SSDs
463 		 * 4k optimised & trim only works in 4k requests + 4k aligned
464 		 */
465 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Neutron GTX*", "*" },
466 		/*quirks*/ADA_Q_4K
467 	},
468 	{
469 		/*
470 		 * Corsair Force GT & GS SSDs
471 		 * 4k optimised & trim only works in 4k requests + 4k aligned
472 		 */
473 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force G*", "*" },
474 		/*quirks*/ADA_Q_4K
475 	},
476 	{
477 		/*
478 		 * Crucial M4 SSDs
479 		 * 4k optimised & trim only works in 4k requests + 4k aligned
480 		 */
481 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "M4-CT???M4SSD2*", "*" },
482 		/*quirks*/ADA_Q_4K
483 	},
484 	{
485 		/*
486 		 * Crucial M500 SSDs MU07 firmware
487 		 * NCQ Trim works
488 		 */
489 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "MU07" },
490 		/*quirks*/0
491 	},
492 	{
493 		/*
494 		 * Crucial M500 SSDs all other firmware
495 		 * NCQ Trim doesn't work
496 		 */
497 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "*" },
498 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
499 	},
500 	{
501 		/*
502 		 * Crucial M550 SSDs
503 		 * NCQ Trim doesn't work, but only on MU01 firmware
504 		 */
505 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M550*", "MU01" },
506 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
507 	},
508 	{
509 		/*
510 		 * Crucial MX100 SSDs
511 		 * NCQ Trim doesn't work, but only on MU01 firmware
512 		 */
513 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*MX100*", "MU01" },
514 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
515 	},
516 	{
517 		/*
518 		 * Crucial RealSSD C300 SSDs
519 		 * 4k optimised
520 		 */
521 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "C300-CTFDDAC???MAG*",
522 		"*" }, /*quirks*/ADA_Q_4K
523 	},
524 	{
525 		/*
526 		 * FCCT M500 SSDs
527 		 * NCQ Trim doesn't work
528 		 */
529 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "FCCT*M500*", "*" },
530 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
531 	},
532 	{
533 		/*
534 		 * Intel 320 Series SSDs
535 		 * 4k optimised & trim only works in 4k requests + 4k aligned
536 		 */
537 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSA2CW*", "*" },
538 		/*quirks*/ADA_Q_4K
539 	},
540 	{
541 		/*
542 		 * Intel 330 Series SSDs
543 		 * 4k optimised & trim only works in 4k requests + 4k aligned
544 		 */
545 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2CT*", "*" },
546 		/*quirks*/ADA_Q_4K
547 	},
548 	{
549 		/*
550 		 * Intel 510 Series SSDs
551 		 * 4k optimised & trim only works in 4k requests + 4k aligned
552 		 */
553 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2MH*", "*" },
554 		/*quirks*/ADA_Q_4K
555 	},
556 	{
557 		/*
558 		 * Intel 520 Series SSDs
559 		 * 4k optimised & trim only works in 4k requests + 4k aligned
560 		 */
561 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2BW*", "*" },
562 		/*quirks*/ADA_Q_4K
563 	},
564 	{
565 		/*
566 		 * Intel S3610 Series SSDs
567 		 * 4k optimised & trim only works in 4k requests + 4k aligned
568 		 */
569 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2BX*", "*" },
570 		/*quirks*/ADA_Q_4K
571 	},
572 	{
573 		/*
574 		 * Intel X25-M Series SSDs
575 		 * 4k optimised & trim only works in 4k requests + 4k aligned
576 		 */
577 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSA2M*", "*" },
578 		/*quirks*/ADA_Q_4K
579 	},
580 	{
581 		/*
582 		 * KingDian S200 60GB P0921B
583 		 * Trimming crash the SSD
584 		 */
585 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KingDian S200 *", "*" },
586 		/*quirks*/ADA_Q_NO_TRIM
587 	},
588 	{
589 		/*
590 		 * Kingston E100 Series SSDs
591 		 * 4k optimised & trim only works in 4k requests + 4k aligned
592 		 */
593 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SE100S3*", "*" },
594 		/*quirks*/ADA_Q_4K
595 	},
596 	{
597 		/*
598 		 * Kingston HyperX 3k SSDs
599 		 * 4k optimised & trim only works in 4k requests + 4k aligned
600 		 */
601 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SH103S3*", "*" },
602 		/*quirks*/ADA_Q_4K
603 	},
604 	{
605 		/*
606 		 * Marvell SSDs (entry taken from OpenSolaris)
607 		 * 4k optimised & trim only works in 4k requests + 4k aligned
608 		 */
609 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "MARVELL SD88SA02*", "*" },
610 		/*quirks*/ADA_Q_4K
611 	},
612 	{
613 		/*
614 		 * Micron M500 SSDs firmware MU07
615 		 * NCQ Trim works?
616 		 */
617 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "MU07" },
618 		/*quirks*/0
619 	},
620 	{
621 		/*
622 		 * Micron M500 SSDs all other firmware
623 		 * NCQ Trim doesn't work
624 		 */
625 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "*" },
626 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
627 	},
628 	{
629 		/*
630 		 * Micron M5[15]0 SSDs
631 		 * NCQ Trim doesn't work, but only MU01 firmware
632 		 */
633 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M5[15]0*", "MU01" },
634 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
635 	},
636 	{
637 		/*
638 		 * Micron 5100 SSDs
639 		 * 4k optimised & trim only works in 4k requests + 4k aligned
640 		 */
641 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron 5100 MTFDDAK*", "*" },
642 		/*quirks*/ADA_Q_4K
643 	},
644 	{
645 		/*
646 		 * OCZ Agility 2 SSDs
647 		 * 4k optimised & trim only works in 4k requests + 4k aligned
648 		 */
649 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY2*", "*" },
650 		/*quirks*/ADA_Q_4K
651 	},
652 	{
653 		/*
654 		 * OCZ Agility 3 SSDs
655 		 * 4k optimised & trim only works in 4k requests + 4k aligned
656 		 */
657 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY3*", "*" },
658 		/*quirks*/ADA_Q_4K
659 	},
660 	{
661 		/*
662 		 * OCZ Deneva R Series SSDs
663 		 * 4k optimised & trim only works in 4k requests + 4k aligned
664 		 */
665 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "DENRSTE251M45*", "*" },
666 		/*quirks*/ADA_Q_4K
667 	},
668 	{
669 		/*
670 		 * OCZ Vertex 2 SSDs (inc pro series)
671 		 * 4k optimised & trim only works in 4k requests + 4k aligned
672 		 */
673 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ?VERTEX2*", "*" },
674 		/*quirks*/ADA_Q_4K
675 	},
676 	{
677 		/*
678 		 * OCZ Vertex 3 SSDs
679 		 * 4k optimised & trim only works in 4k requests + 4k aligned
680 		 */
681 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-VERTEX3*", "*" },
682 		/*quirks*/ADA_Q_4K
683 	},
684 	{
685 		/*
686 		 * OCZ Vertex 4 SSDs
687 		 * 4k optimised & trim only works in 4k requests + 4k aligned
688 		 */
689 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-VERTEX4*", "*" },
690 		/*quirks*/ADA_Q_4K
691 	},
692 	{
693 		/*
694 		 * Samsung 750 SSDs
695 		 * 4k optimised, NCQ TRIM seems to work
696 		 */
697 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 750*", "*" },
698 		/*quirks*/ADA_Q_4K
699 	},
700 	{
701 		/*
702 		 * Samsung 830 Series SSDs
703 		 * 4k optimised, NCQ TRIM Broken (normal TRIM is fine)
704 		 */
705 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG SSD 830 Series*", "*" },
706 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
707 	},
708 	{
709 		/*
710 		 * Samsung 840 SSDs
711 		 * 4k optimised, NCQ TRIM Broken (normal TRIM is fine)
712 		 */
713 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 840*", "*" },
714 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
715 	},
716 	{
717 		/*
718 		 * Samsung 845 SSDs
719 		 * 4k optimised, NCQ TRIM Broken (normal TRIM is fine)
720 		 */
721 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 845*", "*" },
722 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
723 	},
724 	{
725 		/*
726 		 * Samsung 850 SSDs
727 		 * 4k optimised, NCQ TRIM broken (normal TRIM fine)
728 		 */
729 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 850*", "*" },
730 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
731 	},
732 	{
733 		/*
734 		 * Samsung SM863 Series SSDs (MZ7KM*)
735 		 * 4k optimised, NCQ believed to be working
736 		 */
737 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7KM*", "*" },
738 		/*quirks*/ADA_Q_4K
739 	},
740 	{
741 		/*
742 		 * Samsung 843T Series SSDs (MZ7WD*)
743 		 * Samsung PM851 Series SSDs (MZ7TE*)
744 		 * Samsung PM853T Series SSDs (MZ7GE*)
745 		 * 4k optimised, NCQ believed to be broken since these are
746 		 * appear to be built with the same controllers as the 840/850.
747 		 */
748 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7*", "*" },
749 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
750 	},
751 	{
752 		/*
753 		 * Same as for SAMSUNG MZ7* but enable the quirks for SSD
754 		 * starting with MZ7* too
755 		 */
756 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "MZ7*", "*" },
757 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
758 	},
759 	{
760 		/*
761 		 * Samsung PM851 Series SSDs Dell OEM
762 		 * device model          "SAMSUNG SSD PM851 mSATA 256GB"
763 		 * 4k optimised, NCQ broken
764 		 */
765 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG SSD PM851*", "*" },
766 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
767 	},
768 	{
769 		/*
770 		 * SuperTalent TeraDrive CT SSDs
771 		 * 4k optimised & trim only works in 4k requests + 4k aligned
772 		 */
773 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "FTM??CT25H*", "*" },
774 		/*quirks*/ADA_Q_4K
775 	},
776 	{
777 		/*
778 		 * XceedIOPS SATA SSDs
779 		 * 4k optimised
780 		 */
781 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SG9XCS2D*", "*" },
782 		/*quirks*/ADA_Q_4K
783 	},
784 	{
785 		/*
786 		 * Samsung drive that doesn't support READ LOG EXT or
787 		 * READ LOG DMA EXT, despite reporting that it does in
788 		 * ATA identify data:
789 		 * SAMSUNG HD200HJ KF100-06
790 		 */
791 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD200*", "*" },
792 		/*quirks*/ADA_Q_LOG_BROKEN
793 	},
794 	{
795 		/*
796 		 * Samsung drive that doesn't support READ LOG EXT or
797 		 * READ LOG DMA EXT, despite reporting that it does in
798 		 * ATA identify data:
799 		 * SAMSUNG HD501LJ CR100-10
800 		 */
801 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD501*", "*" },
802 		/*quirks*/ADA_Q_LOG_BROKEN
803 	},
804 	{
805 		/*
806 		 * Seagate Lamarr 8TB Shingled Magnetic Recording (SMR)
807 		 * Drive Managed SATA hard drive.  This drive doesn't report
808 		 * in firmware that it is a drive managed SMR drive.
809 		 */
810 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST8000AS000[23]*", "*" },
811 		/*quirks*/ADA_Q_SMR_DM
812 	},
813 	{
814 		/* WD Green SSD */
815 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WDS?????G0*", "*" },
816 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
817 	},
818 	{
819 		/* Default */
820 		{
821 		  T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
822 		  /*vendor*/"*", /*product*/"*", /*revision*/"*"
823 		},
824 		/*quirks*/0
825 	},
826 };
827 
828 static	disk_strategy_t	adastrategy;
829 static	dumper_t	adadump;
830 static	periph_init_t	adainit;
831 static	void		adadiskgonecb(struct disk *dp);
832 static	periph_oninv_t	adaoninvalidate;
833 static	periph_dtor_t	adacleanup;
834 static	void		adaasync(void *callback_arg, u_int32_t code,
835 				struct cam_path *path, void *arg);
836 static	int		adabitsysctl(SYSCTL_HANDLER_ARGS);
837 static	int		adaflagssysctl(SYSCTL_HANDLER_ARGS);
838 static	int		adazonesupsysctl(SYSCTL_HANDLER_ARGS);
839 static	void		adasysctlinit(void *context, int pending);
840 static	int		adagetattr(struct bio *bp);
841 static	void		adasetflags(struct ada_softc *softc,
842 				    struct ccb_getdev *cgd);
843 static void		adasetgeom(struct ada_softc *softc,
844 				   struct ccb_getdev *cgd);
845 static	periph_ctor_t	adaregister;
846 static	void		ada_dsmtrim(struct ada_softc *softc, struct bio *bp,
847 				    struct ccb_ataio *ataio);
848 static	void 		ada_cfaerase(struct ada_softc *softc, struct bio *bp,
849 				     struct ccb_ataio *ataio);
850 static	int		ada_zone_bio_to_ata(int disk_zone_cmd);
851 static	int		ada_zone_cmd(struct cam_periph *periph, union ccb *ccb,
852 				     struct bio *bp, int *queue_ccb);
853 static	periph_start_t	adastart;
854 static	void		adaprobedone(struct cam_periph *periph, union ccb *ccb);
855 static	void		adazonedone(struct cam_periph *periph, union ccb *ccb);
856 static	void		adadone(struct cam_periph *periph,
857 			       union ccb *done_ccb);
858 static  int		adaerror(union ccb *ccb, u_int32_t cam_flags,
859 				u_int32_t sense_flags);
860 static callout_func_t	adasendorderedtag;
861 static void		adashutdown(void *arg, int howto);
862 static void		adasuspend(void *arg);
863 static void		adaresume(void *arg);
864 
865 #ifndef ADA_DEFAULT_TIMEOUT
866 #define ADA_DEFAULT_TIMEOUT 30	/* Timeout in seconds */
867 #endif
868 
869 #ifndef	ADA_DEFAULT_RETRY
870 #define	ADA_DEFAULT_RETRY	4
871 #endif
872 
873 #ifndef	ADA_DEFAULT_SEND_ORDERED
874 #define	ADA_DEFAULT_SEND_ORDERED	1
875 #endif
876 
877 #ifndef	ADA_DEFAULT_SPINDOWN_SHUTDOWN
878 #define	ADA_DEFAULT_SPINDOWN_SHUTDOWN	1
879 #endif
880 
881 #ifndef	ADA_DEFAULT_SPINDOWN_SUSPEND
882 #define	ADA_DEFAULT_SPINDOWN_SUSPEND	1
883 #endif
884 
885 #ifndef	ADA_DEFAULT_READ_AHEAD
886 #define	ADA_DEFAULT_READ_AHEAD	1
887 #endif
888 
889 #ifndef	ADA_DEFAULT_WRITE_CACHE
890 #define	ADA_DEFAULT_WRITE_CACHE	1
891 #endif
892 
893 #define	ADA_RA	(softc->read_ahead >= 0 ? \
894 		 softc->read_ahead : ada_read_ahead)
895 #define	ADA_WC	(softc->write_cache >= 0 ? \
896 		 softc->write_cache : ada_write_cache)
897 
898 /*
899  * Most platforms map firmware geometry to actual, but some don't.  If
900  * not overridden, default to nothing.
901  */
902 #ifndef ata_disk_firmware_geom_adjust
903 #define	ata_disk_firmware_geom_adjust(disk)
904 #endif
905 
906 static int ada_retry_count = ADA_DEFAULT_RETRY;
907 static int ada_default_timeout = ADA_DEFAULT_TIMEOUT;
908 static int ada_send_ordered = ADA_DEFAULT_SEND_ORDERED;
909 static int ada_spindown_shutdown = ADA_DEFAULT_SPINDOWN_SHUTDOWN;
910 static int ada_spindown_suspend = ADA_DEFAULT_SPINDOWN_SUSPEND;
911 static int ada_read_ahead = ADA_DEFAULT_READ_AHEAD;
912 static int ada_write_cache = ADA_DEFAULT_WRITE_CACHE;
913 static int ada_enable_biospeedup = 1;
914 
915 static SYSCTL_NODE(_kern_cam, OID_AUTO, ada, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
916     "CAM Direct Access Disk driver");
917 SYSCTL_INT(_kern_cam_ada, OID_AUTO, retry_count, CTLFLAG_RWTUN,
918            &ada_retry_count, 0, "Normal I/O retry count");
919 SYSCTL_INT(_kern_cam_ada, OID_AUTO, default_timeout, CTLFLAG_RWTUN,
920            &ada_default_timeout, 0, "Normal I/O timeout (in seconds)");
921 SYSCTL_INT(_kern_cam_ada, OID_AUTO, send_ordered, CTLFLAG_RWTUN,
922            &ada_send_ordered, 0, "Send Ordered Tags");
923 SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_shutdown, CTLFLAG_RWTUN,
924            &ada_spindown_shutdown, 0, "Spin down upon shutdown");
925 SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_suspend, CTLFLAG_RWTUN,
926            &ada_spindown_suspend, 0, "Spin down upon suspend");
927 SYSCTL_INT(_kern_cam_ada, OID_AUTO, read_ahead, CTLFLAG_RWTUN,
928            &ada_read_ahead, 0, "Enable disk read-ahead");
929 SYSCTL_INT(_kern_cam_ada, OID_AUTO, write_cache, CTLFLAG_RWTUN,
930            &ada_write_cache, 0, "Enable disk write cache");
931 SYSCTL_INT(_kern_cam_ada, OID_AUTO, enable_biospeedup, CTLFLAG_RDTUN,
932 	   &ada_enable_biospeedup, 0, "Enable BIO_SPEEDUP processing");
933 
934 /*
935  * ADA_ORDEREDTAG_INTERVAL determines how often, relative
936  * to the default timeout, we check to see whether an ordered
937  * tagged transaction is appropriate to prevent simple tag
938  * starvation.  Since we'd like to ensure that there is at least
939  * 1/2 of the timeout length left for a starved transaction to
940  * complete after we've sent an ordered tag, we must poll at least
941  * four times in every timeout period.  This takes care of the worst
942  * case where a starved transaction starts during an interval that
943  * meets the requirement "don't send an ordered tag" test so it takes
944  * us two intervals to determine that a tag must be sent.
945  */
946 #ifndef ADA_ORDEREDTAG_INTERVAL
947 #define ADA_ORDEREDTAG_INTERVAL 4
948 #endif
949 
950 static struct periph_driver adadriver =
951 {
952 	adainit, "ada",
953 	TAILQ_HEAD_INITIALIZER(adadriver.units), /* generation */ 0
954 };
955 
956 static int adadeletemethodsysctl(SYSCTL_HANDLER_ARGS);
957 
958 PERIPHDRIVER_DECLARE(ada, adadriver);
959 
960 static MALLOC_DEFINE(M_ATADA, "ata_da", "ata_da buffers");
961 
962 static int
963 adaopen(struct disk *dp)
964 {
965 	struct cam_periph *periph;
966 	struct ada_softc *softc;
967 	int error;
968 
969 	periph = (struct cam_periph *)dp->d_drv1;
970 	if (cam_periph_acquire(periph) != 0) {
971 		return(ENXIO);
972 	}
973 
974 	cam_periph_lock(periph);
975 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
976 		cam_periph_unlock(periph);
977 		cam_periph_release(periph);
978 		return (error);
979 	}
980 
981 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
982 	    ("adaopen\n"));
983 
984 	softc = (struct ada_softc *)periph->softc;
985 	softc->flags |= ADA_FLAG_OPEN;
986 
987 	cam_periph_unhold(periph);
988 	cam_periph_unlock(periph);
989 	return (0);
990 }
991 
992 static int
993 adaclose(struct disk *dp)
994 {
995 	struct	cam_periph *periph;
996 	struct	ada_softc *softc;
997 	union ccb *ccb;
998 	int error;
999 
1000 	periph = (struct cam_periph *)dp->d_drv1;
1001 	softc = (struct ada_softc *)periph->softc;
1002 	cam_periph_lock(periph);
1003 
1004 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1005 	    ("adaclose\n"));
1006 
1007 	/* We only sync the cache if the drive is capable of it. */
1008 	if ((softc->flags & ADA_FLAG_DIRTY) != 0 &&
1009 	    (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) != 0 &&
1010 	    (periph->flags & CAM_PERIPH_INVALID) == 0 &&
1011 	    cam_periph_hold(periph, PRIBIO) == 0) {
1012 
1013 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1014 		cam_fill_ataio(&ccb->ataio,
1015 				    1,
1016 				    NULL,
1017 				    CAM_DIR_NONE,
1018 				    0,
1019 				    NULL,
1020 				    0,
1021 				    ada_default_timeout*1000);
1022 
1023 		if (softc->flags & ADA_FLAG_CAN_48BIT)
1024 			ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
1025 		else
1026 			ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
1027 		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
1028 		    /*sense_flags*/0, softc->disk->d_devstat);
1029 
1030 		if (error != 0)
1031 			xpt_print(periph->path, "Synchronize cache failed\n");
1032 		softc->flags &= ~ADA_FLAG_DIRTY;
1033 		xpt_release_ccb(ccb);
1034 		cam_periph_unhold(periph);
1035 	}
1036 
1037 	softc->flags &= ~ADA_FLAG_OPEN;
1038 
1039 	while (softc->refcount != 0)
1040 		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "adaclose", 1);
1041 	cam_periph_unlock(periph);
1042 	cam_periph_release(periph);
1043 	return (0);
1044 }
1045 
1046 static void
1047 adaschedule(struct cam_periph *periph)
1048 {
1049 	struct ada_softc *softc = (struct ada_softc *)periph->softc;
1050 
1051 	if (softc->state != ADA_STATE_NORMAL)
1052 		return;
1053 
1054 	cam_iosched_schedule(softc->cam_iosched, periph);
1055 }
1056 
1057 /*
1058  * Actually translate the requested transfer into one the physical driver
1059  * can understand.  The transfer is described by a buf and will include
1060  * only one physical transfer.
1061  */
1062 static void
1063 adastrategy(struct bio *bp)
1064 {
1065 	struct cam_periph *periph;
1066 	struct ada_softc *softc;
1067 
1068 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1069 	softc = (struct ada_softc *)periph->softc;
1070 
1071 	cam_periph_lock(periph);
1072 
1073 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastrategy(%p)\n", bp));
1074 
1075 	/*
1076 	 * If the device has been made invalid, error out
1077 	 */
1078 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
1079 		cam_periph_unlock(periph);
1080 		biofinish(bp, NULL, ENXIO);
1081 		return;
1082 	}
1083 
1084 	/*
1085 	 * Zone commands must be ordered, because they can depend on the
1086 	 * effects of previously issued commands, and they may affect
1087 	 * commands after them.
1088 	 */
1089 	if (bp->bio_cmd == BIO_ZONE)
1090 		bp->bio_flags |= BIO_ORDERED;
1091 
1092 	/*
1093 	 * Place it in the queue of disk activities for this disk
1094 	 */
1095 	cam_iosched_queue_work(softc->cam_iosched, bp);
1096 
1097 	/*
1098 	 * Schedule ourselves for performing the work.
1099 	 */
1100 	adaschedule(periph);
1101 	cam_periph_unlock(periph);
1102 
1103 	return;
1104 }
1105 
1106 static int
1107 adadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
1108 {
1109 	struct	    cam_periph *periph;
1110 	struct	    ada_softc *softc;
1111 	u_int	    secsize;
1112 	struct	    ccb_ataio ataio;
1113 	struct	    disk *dp;
1114 	uint64_t    lba;
1115 	uint16_t    count;
1116 	int	    error = 0;
1117 
1118 	dp = arg;
1119 	periph = dp->d_drv1;
1120 	softc = (struct ada_softc *)periph->softc;
1121 	secsize = softc->params.secsize;
1122 	lba = offset / secsize;
1123 	count = length / secsize;
1124 	if ((periph->flags & CAM_PERIPH_INVALID) != 0)
1125 		return (ENXIO);
1126 
1127 	memset(&ataio, 0, sizeof(ataio));
1128 	if (length > 0) {
1129 		xpt_setup_ccb(&ataio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1130 		ataio.ccb_h.ccb_state = ADA_CCB_DUMP;
1131 		cam_fill_ataio(&ataio,
1132 		    0,
1133 		    NULL,
1134 		    CAM_DIR_OUT,
1135 		    0,
1136 		    (u_int8_t *) virtual,
1137 		    length,
1138 		    ada_default_timeout*1000);
1139 		if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
1140 		    (lba + count >= ATA_MAX_28BIT_LBA ||
1141 		    count >= 256)) {
1142 			ata_48bit_cmd(&ataio, ATA_WRITE_DMA48,
1143 			    0, lba, count);
1144 		} else {
1145 			ata_28bit_cmd(&ataio, ATA_WRITE_DMA,
1146 			    0, lba, count);
1147 		}
1148 		error = cam_periph_runccb((union ccb *)&ataio, adaerror,
1149 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1150 		if (error != 0)
1151 			printf("Aborting dump due to I/O error.\n");
1152 
1153 		return (error);
1154 	}
1155 
1156 	if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) {
1157 		xpt_setup_ccb(&ataio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1158 
1159 		/*
1160 		 * Tell the drive to flush its internal cache. if we
1161 		 * can't flush in 5s we have big problems. No need to
1162 		 * wait the default 60s to detect problems.
1163 		 */
1164 		ataio.ccb_h.ccb_state = ADA_CCB_DUMP;
1165 		cam_fill_ataio(&ataio,
1166 				    0,
1167 				    NULL,
1168 				    CAM_DIR_NONE,
1169 				    0,
1170 				    NULL,
1171 				    0,
1172 				    5*1000);
1173 
1174 		if (softc->flags & ADA_FLAG_CAN_48BIT)
1175 			ata_48bit_cmd(&ataio, ATA_FLUSHCACHE48, 0, 0, 0);
1176 		else
1177 			ata_28bit_cmd(&ataio, ATA_FLUSHCACHE, 0, 0, 0);
1178 		error = cam_periph_runccb((union ccb *)&ataio, adaerror,
1179 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1180 		if (error != 0)
1181 			xpt_print(periph->path, "Synchronize cache failed\n");
1182 	}
1183 	return (error);
1184 }
1185 
1186 static void
1187 adainit(void)
1188 {
1189 	cam_status status;
1190 
1191 	/*
1192 	 * Install a global async callback.  This callback will
1193 	 * receive async callbacks like "new device found".
1194 	 */
1195 	status = xpt_register_async(AC_FOUND_DEVICE, adaasync, NULL, NULL);
1196 
1197 	if (status != CAM_REQ_CMP) {
1198 		printf("ada: Failed to attach master async callback "
1199 		       "due to status 0x%x!\n", status);
1200 	} else if (ada_send_ordered) {
1201 
1202 		/* Register our event handlers */
1203 		if ((EVENTHANDLER_REGISTER(power_suspend, adasuspend,
1204 					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
1205 		    printf("adainit: power event registration failed!\n");
1206 		if ((EVENTHANDLER_REGISTER(power_resume, adaresume,
1207 					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
1208 		    printf("adainit: power event registration failed!\n");
1209 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, adashutdown,
1210 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1211 		    printf("adainit: shutdown event registration failed!\n");
1212 	}
1213 }
1214 
1215 /*
1216  * Callback from GEOM, called when it has finished cleaning up its
1217  * resources.
1218  */
1219 static void
1220 adadiskgonecb(struct disk *dp)
1221 {
1222 	struct cam_periph *periph;
1223 
1224 	periph = (struct cam_periph *)dp->d_drv1;
1225 
1226 	cam_periph_release(periph);
1227 }
1228 
1229 static void
1230 adaoninvalidate(struct cam_periph *periph)
1231 {
1232 	struct ada_softc *softc;
1233 
1234 	softc = (struct ada_softc *)periph->softc;
1235 
1236 	/*
1237 	 * De-register any async callbacks.
1238 	 */
1239 	xpt_register_async(0, adaasync, periph, periph->path);
1240 #ifdef CAM_IO_STATS
1241 	softc->invalidations++;
1242 #endif
1243 
1244 	/*
1245 	 * Return all queued I/O with ENXIO.
1246 	 * XXX Handle any transactions queued to the card
1247 	 *     with XPT_ABORT_CCB.
1248 	 */
1249 	cam_iosched_flush(softc->cam_iosched, NULL, ENXIO);
1250 
1251 	disk_gone(softc->disk);
1252 }
1253 
1254 static void
1255 adacleanup(struct cam_periph *periph)
1256 {
1257 	struct ada_softc *softc;
1258 
1259 	softc = (struct ada_softc *)periph->softc;
1260 
1261 	cam_periph_unlock(periph);
1262 
1263 	cam_iosched_fini(softc->cam_iosched);
1264 
1265 	/*
1266 	 * If we can't free the sysctl tree, oh well...
1267 	 */
1268 	if ((softc->flags & ADA_FLAG_SCTX_INIT) != 0) {
1269 #ifdef CAM_IO_STATS
1270 		if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0)
1271 			xpt_print(periph->path,
1272 			    "can't remove sysctl stats context\n");
1273 #endif
1274 		if (sysctl_ctx_free(&softc->sysctl_ctx) != 0)
1275 			xpt_print(periph->path,
1276 			    "can't remove sysctl context\n");
1277 	}
1278 
1279 	disk_destroy(softc->disk);
1280 	callout_drain(&softc->sendordered_c);
1281 	free(softc, M_DEVBUF);
1282 	cam_periph_lock(periph);
1283 }
1284 
1285 static void
1286 adasetdeletemethod(struct ada_softc *softc)
1287 {
1288 
1289 	if (softc->flags & ADA_FLAG_CAN_NCQ_TRIM)
1290 		softc->delete_method = ADA_DELETE_NCQ_DSM_TRIM;
1291 	else if (softc->flags & ADA_FLAG_CAN_TRIM)
1292 		softc->delete_method = ADA_DELETE_DSM_TRIM;
1293 	else if ((softc->flags & ADA_FLAG_CAN_CFA) && !(softc->flags & ADA_FLAG_CAN_48BIT))
1294 		softc->delete_method = ADA_DELETE_CFA_ERASE;
1295 	else
1296 		softc->delete_method = ADA_DELETE_NONE;
1297 }
1298 
1299 static void
1300 adaasync(void *callback_arg, u_int32_t code,
1301 	struct cam_path *path, void *arg)
1302 {
1303 	struct ccb_getdev cgd;
1304 	struct cam_periph *periph;
1305 	struct ada_softc *softc;
1306 
1307 	periph = (struct cam_periph *)callback_arg;
1308 	switch (code) {
1309 	case AC_FOUND_DEVICE:
1310 	{
1311 		struct ccb_getdev *cgd;
1312 		cam_status status;
1313 
1314 		cgd = (struct ccb_getdev *)arg;
1315 		if (cgd == NULL)
1316 			break;
1317 
1318 		if (cgd->protocol != PROTO_ATA)
1319 			break;
1320 
1321 		/*
1322 		 * Allocate a peripheral instance for
1323 		 * this device and start the probe
1324 		 * process.
1325 		 */
1326 		status = cam_periph_alloc(adaregister, adaoninvalidate,
1327 					  adacleanup, adastart,
1328 					  "ada", CAM_PERIPH_BIO,
1329 					  path, adaasync,
1330 					  AC_FOUND_DEVICE, cgd);
1331 
1332 		if (status != CAM_REQ_CMP
1333 		 && status != CAM_REQ_INPROG)
1334 			printf("adaasync: Unable to attach to new device "
1335 				"due to status 0x%x\n", status);
1336 		break;
1337 	}
1338 	case AC_GETDEV_CHANGED:
1339 	{
1340 		softc = (struct ada_softc *)periph->softc;
1341 		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1342 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1343 		xpt_action((union ccb *)&cgd);
1344 
1345 		/*
1346 		 * Update our information based on the new Identify data.
1347 		 */
1348 		adasetflags(softc, &cgd);
1349 		adasetgeom(softc, &cgd);
1350 		disk_resize(softc->disk, M_NOWAIT);
1351 
1352 		cam_periph_async(periph, code, path, arg);
1353 		break;
1354 	}
1355 	case AC_ADVINFO_CHANGED:
1356 	{
1357 		uintptr_t buftype;
1358 
1359 		buftype = (uintptr_t)arg;
1360 		if (buftype == CDAI_TYPE_PHYS_PATH) {
1361 			struct ada_softc *softc;
1362 
1363 			softc = periph->softc;
1364 			disk_attr_changed(softc->disk, "GEOM::physpath",
1365 					  M_NOWAIT);
1366 		}
1367 		break;
1368 	}
1369 	case AC_SENT_BDR:
1370 	case AC_BUS_RESET:
1371 	{
1372 		softc = (struct ada_softc *)periph->softc;
1373 		cam_periph_async(periph, code, path, arg);
1374 		if (softc->state != ADA_STATE_NORMAL)
1375 			break;
1376 		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1377 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1378 		xpt_action((union ccb *)&cgd);
1379 		if (ADA_RA >= 0 && softc->flags & ADA_FLAG_CAN_RAHEAD)
1380 			softc->state = ADA_STATE_RAHEAD;
1381 		else if (ADA_WC >= 0 && softc->flags & ADA_FLAG_CAN_WCACHE)
1382 			softc->state = ADA_STATE_WCACHE;
1383 		else if ((softc->flags & ADA_FLAG_CAN_LOG)
1384 		      && (softc->zone_mode != ADA_ZONE_NONE))
1385 			softc->state = ADA_STATE_LOGDIR;
1386 		else
1387 		    break;
1388 		if (cam_periph_acquire(periph) != 0)
1389 			softc->state = ADA_STATE_NORMAL;
1390 		else
1391 			xpt_schedule(periph, CAM_PRIORITY_DEV);
1392 	}
1393 	default:
1394 		cam_periph_async(periph, code, path, arg);
1395 		break;
1396 	}
1397 }
1398 
1399 static int
1400 adazonemodesysctl(SYSCTL_HANDLER_ARGS)
1401 {
1402 	char tmpbuf[40];
1403 	struct ada_softc *softc;
1404 	int error;
1405 
1406 	softc = (struct ada_softc *)arg1;
1407 
1408 	switch (softc->zone_mode) {
1409 	case ADA_ZONE_DRIVE_MANAGED:
1410 		snprintf(tmpbuf, sizeof(tmpbuf), "Drive Managed");
1411 		break;
1412 	case ADA_ZONE_HOST_AWARE:
1413 		snprintf(tmpbuf, sizeof(tmpbuf), "Host Aware");
1414 		break;
1415 	case ADA_ZONE_HOST_MANAGED:
1416 		snprintf(tmpbuf, sizeof(tmpbuf), "Host Managed");
1417 		break;
1418 	case ADA_ZONE_NONE:
1419 	default:
1420 		snprintf(tmpbuf, sizeof(tmpbuf), "Not Zoned");
1421 		break;
1422 	}
1423 
1424 	error = sysctl_handle_string(oidp, tmpbuf, sizeof(tmpbuf), req);
1425 
1426 	return (error);
1427 }
1428 
1429 static int
1430 adazonesupsysctl(SYSCTL_HANDLER_ARGS)
1431 {
1432 	char tmpbuf[180];
1433 	struct ada_softc *softc;
1434 	struct sbuf sb;
1435 	int error, first;
1436 	unsigned int i;
1437 
1438 	softc = (struct ada_softc *)arg1;
1439 
1440 	error = 0;
1441 	first = 1;
1442 	sbuf_new(&sb, tmpbuf, sizeof(tmpbuf), 0);
1443 
1444 	for (i = 0; i < sizeof(ada_zone_desc_table) /
1445 	     sizeof(ada_zone_desc_table[0]); i++) {
1446 		if (softc->zone_flags & ada_zone_desc_table[i].value) {
1447 			if (first == 0)
1448 				sbuf_printf(&sb, ", ");
1449 			else
1450 				first = 0;
1451 			sbuf_cat(&sb, ada_zone_desc_table[i].desc);
1452 		}
1453 	}
1454 
1455 	if (first == 1)
1456 		sbuf_printf(&sb, "None");
1457 
1458 	sbuf_finish(&sb);
1459 
1460 	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
1461 
1462 	return (error);
1463 }
1464 
1465 
1466 static void
1467 adasysctlinit(void *context, int pending)
1468 {
1469 	struct cam_periph *periph;
1470 	struct ada_softc *softc;
1471 	char tmpstr[32], tmpstr2[16];
1472 
1473 	periph = (struct cam_periph *)context;
1474 
1475 	/* periph was held for us when this task was enqueued */
1476 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
1477 		cam_periph_release(periph);
1478 		return;
1479 	}
1480 
1481 	softc = (struct ada_softc *)periph->softc;
1482 	snprintf(tmpstr, sizeof(tmpstr), "CAM ADA unit %d",periph->unit_number);
1483 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1484 
1485 	sysctl_ctx_init(&softc->sysctl_ctx);
1486 	softc->flags |= ADA_FLAG_SCTX_INIT;
1487 	softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
1488 		SYSCTL_STATIC_CHILDREN(_kern_cam_ada), OID_AUTO, tmpstr2,
1489 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr, "device_index");
1490 	if (softc->sysctl_tree == NULL) {
1491 		printf("adasysctlinit: unable to allocate sysctl tree\n");
1492 		cam_periph_release(periph);
1493 		return;
1494 	}
1495 
1496 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1497 		OID_AUTO, "delete_method",
1498 		CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1499 		softc, 0, adadeletemethodsysctl, "A",
1500 		"BIO_DELETE execution method");
1501 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1502 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1503 		"trim_count", CTLFLAG_RD, &softc->trim_count,
1504 		"Total number of dsm commands sent");
1505 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1506 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1507 		"trim_ranges", CTLFLAG_RD, &softc->trim_ranges,
1508 		"Total number of ranges in dsm commands");
1509 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1510 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1511 		"trim_lbas", CTLFLAG_RD, &softc->trim_lbas,
1512 		"Total lbas in the dsm commands sent");
1513 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1514 		OID_AUTO, "read_ahead", CTLFLAG_RW | CTLFLAG_MPSAFE,
1515 		&softc->read_ahead, 0, "Enable disk read ahead.");
1516 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1517 		OID_AUTO, "write_cache", CTLFLAG_RW | CTLFLAG_MPSAFE,
1518 		&softc->write_cache, 0, "Enable disk write cache.");
1519 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1520 		OID_AUTO, "zone_mode",
1521 		CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
1522 		softc, 0, adazonemodesysctl, "A",
1523 		"Zone Mode");
1524 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1525 		OID_AUTO, "zone_support",
1526 		CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
1527 		softc, 0, adazonesupsysctl, "A",
1528 		"Zone Support");
1529 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1530 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1531 		"optimal_seq_zones", CTLFLAG_RD, &softc->optimal_seq_zones,
1532 		"Optimal Number of Open Sequential Write Preferred Zones");
1533 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1534 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1535 		"optimal_nonseq_zones", CTLFLAG_RD,
1536 		&softc->optimal_nonseq_zones,
1537 		"Optimal Number of Non-Sequentially Written Sequential Write "
1538 		"Preferred Zones");
1539 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1540 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1541 		"max_seq_zones", CTLFLAG_RD, &softc->max_seq_zones,
1542 		"Maximum Number of Open Sequential Write Required Zones");
1543 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1544 	    OID_AUTO, "flags", CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1545 	    softc, 0, adaflagssysctl, "A",
1546 	    "Flags for drive");
1547 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1548 	    OID_AUTO, "unmapped_io", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
1549 	    &softc->flags, (u_int)ADA_FLAG_UNMAPPEDIO, adabitsysctl, "I",
1550 	    "Unmapped I/O support *DEPRECATED* gone in FreeBSD 14");
1551 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1552 	    OID_AUTO, "rotating", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
1553 	    &softc->flags, (u_int)ADA_FLAG_ROTATING, adabitsysctl, "I",
1554 	    "Rotating media *DEPRECATED* gone in FreeBSD 14");
1555 
1556 #ifdef CAM_TEST_FAILURE
1557 	/*
1558 	 * Add a 'door bell' sysctl which allows one to set it from userland
1559 	 * and cause something bad to happen.  For the moment, we only allow
1560 	 * whacking the next read or write.
1561 	 */
1562 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1563 		OID_AUTO, "force_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1564 		&softc->force_read_error, 0,
1565 		"Force a read error for the next N reads.");
1566 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1567 		OID_AUTO, "force_write_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1568 		&softc->force_write_error, 0,
1569 		"Force a write error for the next N writes.");
1570 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1571 		OID_AUTO, "periodic_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1572 		&softc->periodic_read_error, 0,
1573 		"Force a read error every N reads (don't set too low).");
1574 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1575 		OID_AUTO, "invalidate", CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
1576 		periph, 0, cam_periph_invalidate_sysctl, "I",
1577 		"Write 1 to invalidate the drive immediately");
1578 #endif
1579 
1580 #ifdef CAM_IO_STATS
1581 	softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx,
1582 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats",
1583 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "Statistics");
1584 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
1585 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
1586 		OID_AUTO, "timeouts", CTLFLAG_RD | CTLFLAG_MPSAFE,
1587 		&softc->timeouts, 0,
1588 		"Device timeouts reported by the SIM");
1589 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
1590 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
1591 		OID_AUTO, "errors", CTLFLAG_RD | CTLFLAG_MPSAFE,
1592 		&softc->errors, 0,
1593 		"Transport errors reported by the SIM.");
1594 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
1595 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
1596 		OID_AUTO, "pack_invalidations", CTLFLAG_RD | CTLFLAG_MPSAFE,
1597 		&softc->invalidations, 0,
1598 		"Device pack invalidations.");
1599 #endif
1600 
1601 	cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx,
1602 	    softc->sysctl_tree);
1603 
1604 	cam_periph_release(periph);
1605 }
1606 
1607 static int
1608 adagetattr(struct bio *bp)
1609 {
1610 	int ret;
1611 	struct cam_periph *periph;
1612 
1613 	if (g_handleattr_int(bp, "GEOM::canspeedup", ada_enable_biospeedup))
1614 		return (EJUSTRETURN);
1615 
1616 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1617 	cam_periph_lock(periph);
1618 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1619 	    periph->path);
1620 	cam_periph_unlock(periph);
1621 	if (ret == 0)
1622 		bp->bio_completed = bp->bio_length;
1623 	return ret;
1624 }
1625 
1626 static int
1627 adadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
1628 {
1629 	char buf[16];
1630 	const char *p;
1631 	struct ada_softc *softc;
1632 	int i, error, value, methods;
1633 
1634 	softc = (struct ada_softc *)arg1;
1635 
1636 	value = softc->delete_method;
1637 	if (value < 0 || value > ADA_DELETE_MAX)
1638 		p = "UNKNOWN";
1639 	else
1640 		p = ada_delete_method_names[value];
1641 	strncpy(buf, p, sizeof(buf));
1642 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1643 	if (error != 0 || req->newptr == NULL)
1644 		return (error);
1645 	methods = 1 << ADA_DELETE_DISABLE;
1646 	if ((softc->flags & ADA_FLAG_CAN_CFA) &&
1647 	    !(softc->flags & ADA_FLAG_CAN_48BIT))
1648 		methods |= 1 << ADA_DELETE_CFA_ERASE;
1649 	if (softc->flags & ADA_FLAG_CAN_TRIM)
1650 		methods |= 1 << ADA_DELETE_DSM_TRIM;
1651 	if (softc->flags & ADA_FLAG_CAN_NCQ_TRIM)
1652 		methods |= 1 << ADA_DELETE_NCQ_DSM_TRIM;
1653 	for (i = 0; i <= ADA_DELETE_MAX; i++) {
1654 		if (!(methods & (1 << i)) ||
1655 		    strcmp(buf, ada_delete_method_names[i]) != 0)
1656 			continue;
1657 		softc->delete_method = i;
1658 		return (0);
1659 	}
1660 	return (EINVAL);
1661 }
1662 
1663 static int
1664 adabitsysctl(SYSCTL_HANDLER_ARGS)
1665 {
1666 	u_int *flags = arg1;
1667 	u_int test = arg2;
1668 	int tmpout, error;
1669 
1670 	tmpout = !!(*flags & test);
1671 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1672 	if (error || !req->newptr)
1673 		return (error);
1674 
1675 	return (EPERM);
1676 }
1677 
1678 static int
1679 adaflagssysctl(SYSCTL_HANDLER_ARGS)
1680 {
1681 	struct sbuf sbuf;
1682 	struct ada_softc *softc = arg1;
1683 	int error;
1684 
1685 	sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
1686 	if (softc->flags != 0)
1687 		sbuf_printf(&sbuf, "0x%b", (unsigned)softc->flags, ADA_FLAG_STRING);
1688 	else
1689 		sbuf_printf(&sbuf, "0");
1690 	error = sbuf_finish(&sbuf);
1691 	sbuf_delete(&sbuf);
1692 
1693 	return (error);
1694 }
1695 
1696 static void
1697 adasetflags(struct ada_softc *softc, struct ccb_getdev *cgd)
1698 {
1699 	if ((cgd->ident_data.capabilities1 & ATA_SUPPORT_DMA) &&
1700 	    (cgd->inq_flags & SID_DMA))
1701 		softc->flags |= ADA_FLAG_CAN_DMA;
1702 	else
1703 		softc->flags &= ~ADA_FLAG_CAN_DMA;
1704 
1705 	if (cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) {
1706 		softc->flags |= ADA_FLAG_CAN_48BIT;
1707 		if (cgd->inq_flags & SID_DMA48)
1708 			softc->flags |= ADA_FLAG_CAN_DMA48;
1709 		else
1710 			softc->flags &= ~ADA_FLAG_CAN_DMA48;
1711 	} else
1712 		softc->flags &= ~(ADA_FLAG_CAN_48BIT | ADA_FLAG_CAN_DMA48);
1713 
1714 	if (cgd->ident_data.support.command2 & ATA_SUPPORT_FLUSHCACHE)
1715 		softc->flags |= ADA_FLAG_CAN_FLUSHCACHE;
1716 	else
1717 		softc->flags &= ~ADA_FLAG_CAN_FLUSHCACHE;
1718 
1719 	if (cgd->ident_data.support.command1 & ATA_SUPPORT_POWERMGT)
1720 		softc->flags |= ADA_FLAG_CAN_POWERMGT;
1721 	else
1722 		softc->flags &= ~ADA_FLAG_CAN_POWERMGT;
1723 
1724 	if ((cgd->ident_data.satacapabilities & ATA_SUPPORT_NCQ) &&
1725 	    (cgd->inq_flags & SID_DMA) && (cgd->inq_flags & SID_CmdQue))
1726 		softc->flags |= ADA_FLAG_CAN_NCQ;
1727 	else
1728 		softc->flags &= ~ADA_FLAG_CAN_NCQ;
1729 
1730 	if ((cgd->ident_data.support_dsm & ATA_SUPPORT_DSM_TRIM) &&
1731 	    (cgd->inq_flags & SID_DMA) &&
1732 	    (softc->quirks & ADA_Q_NO_TRIM) == 0) {
1733 		softc->flags |= ADA_FLAG_CAN_TRIM;
1734 		softc->trim_max_ranges = TRIM_MAX_RANGES;
1735 		if (cgd->ident_data.max_dsm_blocks != 0) {
1736 			softc->trim_max_ranges =
1737 			    min(cgd->ident_data.max_dsm_blocks *
1738 				ATA_DSM_BLK_RANGES, softc->trim_max_ranges);
1739 		}
1740 		/*
1741 		 * If we can do RCVSND_FPDMA_QUEUED commands, we may be able
1742 		 * to do NCQ trims, if we support trims at all. We also need
1743 		 * support from the SIM to do things properly. Perhaps we
1744 		 * should look at log 13 dword 0 bit 0 and dword 1 bit 0 are
1745 		 * set too...
1746 		 */
1747 		if ((softc->quirks & ADA_Q_NCQ_TRIM_BROKEN) == 0 &&
1748 		    (softc->flags & ADA_FLAG_PIM_ATA_EXT) != 0 &&
1749 		    (cgd->ident_data.satacapabilities2 &
1750 		     ATA_SUPPORT_RCVSND_FPDMA_QUEUED) != 0 &&
1751 		    (softc->flags & ADA_FLAG_CAN_TRIM) != 0)
1752 			softc->flags |= ADA_FLAG_CAN_NCQ_TRIM;
1753 		else
1754 			softc->flags &= ~ADA_FLAG_CAN_NCQ_TRIM;
1755 	} else
1756 		softc->flags &= ~(ADA_FLAG_CAN_TRIM | ADA_FLAG_CAN_NCQ_TRIM);
1757 
1758 	if (cgd->ident_data.support.command2 & ATA_SUPPORT_CFA)
1759 		softc->flags |= ADA_FLAG_CAN_CFA;
1760 	else
1761 		softc->flags &= ~ADA_FLAG_CAN_CFA;
1762 
1763 	/*
1764 	 * Now that we've set the appropriate flags, setup the delete
1765 	 * method.
1766 	 */
1767 	adasetdeletemethod(softc);
1768 
1769 	if ((cgd->ident_data.support.extension & ATA_SUPPORT_GENLOG)
1770 	 && ((softc->quirks & ADA_Q_LOG_BROKEN) == 0))
1771 		softc->flags |= ADA_FLAG_CAN_LOG;
1772 	else
1773 		softc->flags &= ~ADA_FLAG_CAN_LOG;
1774 
1775 	if ((cgd->ident_data.support3 & ATA_SUPPORT_ZONE_MASK) ==
1776 	     ATA_SUPPORT_ZONE_HOST_AWARE)
1777 		softc->zone_mode = ADA_ZONE_HOST_AWARE;
1778 	else if (((cgd->ident_data.support3 & ATA_SUPPORT_ZONE_MASK) ==
1779 		   ATA_SUPPORT_ZONE_DEV_MANAGED)
1780 	      || (softc->quirks & ADA_Q_SMR_DM))
1781 		softc->zone_mode = ADA_ZONE_DRIVE_MANAGED;
1782 	else
1783 		softc->zone_mode = ADA_ZONE_NONE;
1784 
1785 	if (cgd->ident_data.support.command1 & ATA_SUPPORT_LOOKAHEAD)
1786 		softc->flags |= ADA_FLAG_CAN_RAHEAD;
1787 	else
1788 		softc->flags &= ~ADA_FLAG_CAN_RAHEAD;
1789 
1790 	if (cgd->ident_data.support.command1 & ATA_SUPPORT_WRITECACHE)
1791 		softc->flags |= ADA_FLAG_CAN_WCACHE;
1792 	else
1793 		softc->flags &= ~ADA_FLAG_CAN_WCACHE;
1794 }
1795 
1796 static cam_status
1797 adaregister(struct cam_periph *periph, void *arg)
1798 {
1799 	struct ada_softc *softc;
1800 	struct ccb_getdev *cgd;
1801 	struct disk_params *dp;
1802 	struct sbuf sb;
1803 	char   *announce_buf;
1804 	caddr_t match;
1805 	int quirks;
1806 
1807 	cgd = (struct ccb_getdev *)arg;
1808 	if (cgd == NULL) {
1809 		printf("adaregister: no getdev CCB, can't register device\n");
1810 		return(CAM_REQ_CMP_ERR);
1811 	}
1812 
1813 	softc = (struct ada_softc *)malloc(sizeof(*softc), M_DEVBUF,
1814 	    M_NOWAIT|M_ZERO);
1815 
1816 	if (softc == NULL) {
1817 		printf("adaregister: Unable to probe new device. "
1818 		    "Unable to allocate softc\n");
1819 		return(CAM_REQ_CMP_ERR);
1820 	}
1821 
1822 	announce_buf = softc->announce_temp;
1823 	bzero(announce_buf, ADA_ANNOUNCETMP_SZ);
1824 
1825 	if (cam_iosched_init(&softc->cam_iosched, periph) != 0) {
1826 		printf("adaregister: Unable to probe new device. "
1827 		       "Unable to allocate iosched memory\n");
1828 		free(softc, M_DEVBUF);
1829 		return(CAM_REQ_CMP_ERR);
1830 	}
1831 
1832 	periph->softc = softc;
1833 	xpt_path_inq(&softc->cpi, periph->path);
1834 
1835 	/*
1836 	 * See if this device has any quirks.
1837 	 */
1838 	match = cam_quirkmatch((caddr_t)&cgd->ident_data,
1839 			       (caddr_t)ada_quirk_table,
1840 			       nitems(ada_quirk_table),
1841 			       sizeof(*ada_quirk_table), ata_identify_match);
1842 	if (match != NULL)
1843 		softc->quirks = ((struct ada_quirk_entry *)match)->quirks;
1844 	else
1845 		softc->quirks = ADA_Q_NONE;
1846 
1847 	TASK_INIT(&softc->sysctl_task, 0, adasysctlinit, periph);
1848 
1849 	/*
1850 	 * Register this media as a disk
1851 	 */
1852 	(void)cam_periph_hold(periph, PRIBIO);
1853 	cam_periph_unlock(periph);
1854 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1855 	    "kern.cam.ada.%d.quirks", periph->unit_number);
1856 	quirks = softc->quirks;
1857 	TUNABLE_INT_FETCH(announce_buf, &quirks);
1858 	softc->quirks = quirks;
1859 	softc->read_ahead = -1;
1860 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1861 	    "kern.cam.ada.%d.read_ahead", periph->unit_number);
1862 	TUNABLE_INT_FETCH(announce_buf, &softc->read_ahead);
1863 	softc->write_cache = -1;
1864 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1865 	    "kern.cam.ada.%d.write_cache", periph->unit_number);
1866 	TUNABLE_INT_FETCH(announce_buf, &softc->write_cache);
1867 
1868 	/*
1869 	 * Set support flags based on the Identify data and quirks.
1870 	 */
1871 	adasetflags(softc, cgd);
1872 	if (softc->cpi.hba_misc & PIM_ATA_EXT)
1873 		softc->flags |= ADA_FLAG_PIM_ATA_EXT;
1874 
1875 	/* Disable queue sorting for non-rotational media by default. */
1876 	if (cgd->ident_data.media_rotation_rate == ATA_RATE_NON_ROTATING) {
1877 		softc->flags &= ~ADA_FLAG_ROTATING;
1878 	} else {
1879 		softc->flags |= ADA_FLAG_ROTATING;
1880 	}
1881 	cam_iosched_set_sort_queue(softc->cam_iosched,
1882 	    (softc->flags & ADA_FLAG_ROTATING) ? -1 : 0);
1883 	softc->disk = disk_alloc();
1884 	adasetgeom(softc, cgd);
1885 	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
1886 			  periph->unit_number, softc->params.secsize,
1887 			  DEVSTAT_ALL_SUPPORTED,
1888 			  DEVSTAT_TYPE_DIRECT |
1889 			  XPORT_DEVSTAT_TYPE(softc->cpi.transport),
1890 			  DEVSTAT_PRIORITY_DISK);
1891 	softc->disk->d_open = adaopen;
1892 	softc->disk->d_close = adaclose;
1893 	softc->disk->d_strategy = adastrategy;
1894 	softc->disk->d_getattr = adagetattr;
1895 	softc->disk->d_dump = adadump;
1896 	softc->disk->d_gone = adadiskgonecb;
1897 	softc->disk->d_name = "ada";
1898 	softc->disk->d_drv1 = periph;
1899 	softc->disk->d_unit = periph->unit_number;
1900 
1901 	/*
1902 	 * Acquire a reference to the periph before we register with GEOM.
1903 	 * We'll release this reference once GEOM calls us back (via
1904 	 * adadiskgonecb()) telling us that our provider has been freed.
1905 	 */
1906 	if (cam_periph_acquire(periph) != 0) {
1907 		xpt_print(periph->path, "%s: lost periph during "
1908 			  "registration!\n", __func__);
1909 		cam_periph_lock(periph);
1910 		return (CAM_REQ_CMP_ERR);
1911 	}
1912 	disk_create(softc->disk, DISK_VERSION);
1913 	cam_periph_lock(periph);
1914 
1915 	dp = &softc->params;
1916 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1917 	    "%juMB (%ju %u byte sectors)",
1918 	    ((uintmax_t)dp->secsize * dp->sectors) / (1024 * 1024),
1919 	    (uintmax_t)dp->sectors, dp->secsize);
1920 
1921 	sbuf_new(&sb, softc->announce_buffer, ADA_ANNOUNCE_SZ, SBUF_FIXEDLEN);
1922 	xpt_announce_periph_sbuf(periph, &sb, announce_buf);
1923 	xpt_announce_quirks_sbuf(periph, &sb, softc->quirks, ADA_Q_BIT_STRING);
1924 	sbuf_finish(&sb);
1925 	sbuf_putbuf(&sb);
1926 
1927 	/*
1928 	 * Create our sysctl variables, now that we know
1929 	 * we have successfully attached.
1930 	 */
1931 	if (cam_periph_acquire(periph) == 0)
1932 		taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
1933 
1934 	/*
1935 	 * Add async callbacks for bus reset and
1936 	 * bus device reset calls.  I don't bother
1937 	 * checking if this fails as, in most cases,
1938 	 * the system will function just fine without
1939 	 * them and the only alternative would be to
1940 	 * not attach the device on failure.
1941 	 */
1942 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
1943 	    AC_GETDEV_CHANGED | AC_ADVINFO_CHANGED,
1944 	    adaasync, periph, periph->path);
1945 
1946 	/*
1947 	 * Schedule a periodic event to occasionally send an
1948 	 * ordered tag to a device.
1949 	 */
1950 	callout_init_mtx(&softc->sendordered_c, cam_periph_mtx(periph), 0);
1951 	callout_reset(&softc->sendordered_c,
1952 	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
1953 	    adasendorderedtag, softc);
1954 
1955 	if (ADA_RA >= 0 && softc->flags & ADA_FLAG_CAN_RAHEAD) {
1956 		softc->state = ADA_STATE_RAHEAD;
1957 	} else if (ADA_WC >= 0 && softc->flags & ADA_FLAG_CAN_WCACHE) {
1958 		softc->state = ADA_STATE_WCACHE;
1959 	} else if ((softc->flags & ADA_FLAG_CAN_LOG)
1960 		&& (softc->zone_mode != ADA_ZONE_NONE)) {
1961 		softc->state = ADA_STATE_LOGDIR;
1962 	} else {
1963 		/*
1964 		 * Nothing to probe, so we can just transition to the
1965 		 * normal state.
1966 		 */
1967 		adaprobedone(periph, NULL);
1968 		return(CAM_REQ_CMP);
1969 	}
1970 
1971 	xpt_schedule(periph, CAM_PRIORITY_DEV);
1972 
1973 	return(CAM_REQ_CMP);
1974 }
1975 
1976 static int
1977 ada_dsmtrim_req_create(struct ada_softc *softc, struct bio *bp, struct trim_request *req)
1978 {
1979 	uint64_t lastlba = (uint64_t)-1, lbas = 0;
1980 	int c, lastcount = 0, off, ranges = 0;
1981 
1982 	bzero(req, sizeof(*req));
1983 	TAILQ_INIT(&req->bps);
1984 	do {
1985 		uint64_t lba = bp->bio_pblkno;
1986 		int count = bp->bio_bcount / softc->params.secsize;
1987 
1988 		/* Try to extend the previous range. */
1989 		if (lba == lastlba) {
1990 			c = min(count, ATA_DSM_RANGE_MAX - lastcount);
1991 			lastcount += c;
1992 			off = (ranges - 1) * ATA_DSM_RANGE_SIZE;
1993 			req->data[off + 6] = lastcount & 0xff;
1994 			req->data[off + 7] =
1995 				(lastcount >> 8) & 0xff;
1996 			count -= c;
1997 			lba += c;
1998 			lbas += c;
1999 		}
2000 
2001 		while (count > 0) {
2002 			c = min(count, ATA_DSM_RANGE_MAX);
2003 			off = ranges * ATA_DSM_RANGE_SIZE;
2004 			req->data[off + 0] = lba & 0xff;
2005 			req->data[off + 1] = (lba >> 8) & 0xff;
2006 			req->data[off + 2] = (lba >> 16) & 0xff;
2007 			req->data[off + 3] = (lba >> 24) & 0xff;
2008 			req->data[off + 4] = (lba >> 32) & 0xff;
2009 			req->data[off + 5] = (lba >> 40) & 0xff;
2010 			req->data[off + 6] = c & 0xff;
2011 			req->data[off + 7] = (c >> 8) & 0xff;
2012 			lba += c;
2013 			lbas += c;
2014 			count -= c;
2015 			lastcount = c;
2016 			ranges++;
2017 			/*
2018 			 * Its the caller's responsibility to ensure the
2019 			 * request will fit so we don't need to check for
2020 			 * overrun here
2021 			 */
2022 		}
2023 		lastlba = lba;
2024 		TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);
2025 
2026 		bp = cam_iosched_next_trim(softc->cam_iosched);
2027 		if (bp == NULL)
2028 			break;
2029 		if (bp->bio_bcount / softc->params.secsize >
2030 		    (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX) {
2031 			cam_iosched_put_back_trim(softc->cam_iosched, bp);
2032 			break;
2033 		}
2034 	} while (1);
2035 	softc->trim_count++;
2036 	softc->trim_ranges += ranges;
2037 	softc->trim_lbas += lbas;
2038 
2039 	return (ranges);
2040 }
2041 
2042 static void
2043 ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
2044 {
2045 	struct trim_request *req = &softc->trim_req;
2046 	int ranges;
2047 
2048 	ranges = ada_dsmtrim_req_create(softc, bp, req);
2049 	cam_fill_ataio(ataio,
2050 	    ada_retry_count,
2051 	    adadone,
2052 	    CAM_DIR_OUT,
2053 	    0,
2054 	    req->data,
2055 	    howmany(ranges, ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
2056 	    ada_default_timeout * 1000);
2057 	ata_48bit_cmd(ataio, ATA_DATA_SET_MANAGEMENT,
2058 	    ATA_DSM_TRIM, 0, howmany(ranges, ATA_DSM_BLK_RANGES));
2059 }
2060 
2061 static void
2062 ada_ncq_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
2063 {
2064 	struct trim_request *req = &softc->trim_req;
2065 	int ranges;
2066 
2067 	ranges = ada_dsmtrim_req_create(softc, bp, req);
2068 	cam_fill_ataio(ataio,
2069 	    ada_retry_count,
2070 	    adadone,
2071 	    CAM_DIR_OUT,
2072 	    0,
2073 	    req->data,
2074 	    howmany(ranges, ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
2075 	    ada_default_timeout * 1000);
2076 	ata_ncq_cmd(ataio,
2077 	    ATA_SEND_FPDMA_QUEUED,
2078 	    0,
2079 	    howmany(ranges, ATA_DSM_BLK_RANGES));
2080 	ataio->cmd.sector_count_exp = ATA_SFPDMA_DSM;
2081 	ataio->ata_flags |= ATA_FLAG_AUX;
2082 	ataio->aux = 1;
2083 }
2084 
2085 static void
2086 ada_cfaerase(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
2087 {
2088 	struct trim_request *req = &softc->trim_req;
2089 	uint64_t lba = bp->bio_pblkno;
2090 	uint16_t count = bp->bio_bcount / softc->params.secsize;
2091 
2092 	bzero(req, sizeof(*req));
2093 	TAILQ_INIT(&req->bps);
2094 	TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);
2095 
2096 	cam_fill_ataio(ataio,
2097 	    ada_retry_count,
2098 	    adadone,
2099 	    CAM_DIR_NONE,
2100 	    0,
2101 	    NULL,
2102 	    0,
2103 	    ada_default_timeout*1000);
2104 
2105 	if (count >= 256)
2106 		count = 0;
2107 	ata_28bit_cmd(ataio, ATA_CFA_ERASE, 0, lba, count);
2108 }
2109 
2110 static int
2111 ada_zone_bio_to_ata(int disk_zone_cmd)
2112 {
2113 	switch (disk_zone_cmd) {
2114 	case DISK_ZONE_OPEN:
2115 		return ATA_ZM_OPEN_ZONE;
2116 	case DISK_ZONE_CLOSE:
2117 		return ATA_ZM_CLOSE_ZONE;
2118 	case DISK_ZONE_FINISH:
2119 		return ATA_ZM_FINISH_ZONE;
2120 	case DISK_ZONE_RWP:
2121 		return ATA_ZM_RWP;
2122 	}
2123 
2124 	return -1;
2125 }
2126 
2127 static int
2128 ada_zone_cmd(struct cam_periph *periph, union ccb *ccb, struct bio *bp,
2129 	     int *queue_ccb)
2130 {
2131 	struct ada_softc *softc;
2132 	int error;
2133 
2134 	error = 0;
2135 
2136 	if (bp->bio_cmd != BIO_ZONE) {
2137 		error = EINVAL;
2138 		goto bailout;
2139 	}
2140 
2141 	softc = periph->softc;
2142 
2143 	switch (bp->bio_zone.zone_cmd) {
2144 	case DISK_ZONE_OPEN:
2145 	case DISK_ZONE_CLOSE:
2146 	case DISK_ZONE_FINISH:
2147 	case DISK_ZONE_RWP: {
2148 		int zone_flags;
2149 		int zone_sa;
2150 		uint64_t lba;
2151 
2152 		zone_sa = ada_zone_bio_to_ata(bp->bio_zone.zone_cmd);
2153 		if (zone_sa == -1) {
2154 			xpt_print(periph->path, "Cannot translate zone "
2155 			    "cmd %#x to ATA\n", bp->bio_zone.zone_cmd);
2156 			error = EINVAL;
2157 			goto bailout;
2158 		}
2159 
2160 		zone_flags = 0;
2161 		lba = bp->bio_zone.zone_params.rwp.id;
2162 
2163 		if (bp->bio_zone.zone_params.rwp.flags &
2164 		    DISK_ZONE_RWP_FLAG_ALL)
2165 			zone_flags |= ZBC_OUT_ALL;
2166 
2167 		ata_zac_mgmt_out(&ccb->ataio,
2168 				 /*retries*/ ada_retry_count,
2169 				 /*cbfcnp*/ adadone,
2170 				 /*use_ncq*/ (softc->flags &
2171 					      ADA_FLAG_PIM_ATA_EXT) ? 1 : 0,
2172 				 /*zm_action*/ zone_sa,
2173 				 /*zone_id*/ lba,
2174 				 /*zone_flags*/ zone_flags,
2175 				 /*sector_count*/ 0,
2176 				 /*data_ptr*/ NULL,
2177 				 /*dxfer_len*/ 0,
2178 				 /*timeout*/ ada_default_timeout * 1000);
2179 		*queue_ccb = 1;
2180 
2181 		break;
2182 	}
2183 	case DISK_ZONE_REPORT_ZONES: {
2184 		uint8_t *rz_ptr;
2185 		uint32_t num_entries, alloc_size;
2186 		struct disk_zone_report *rep;
2187 
2188 		rep = &bp->bio_zone.zone_params.report;
2189 
2190 		num_entries = rep->entries_allocated;
2191 		if (num_entries == 0) {
2192 			xpt_print(periph->path, "No entries allocated for "
2193 			    "Report Zones request\n");
2194 			error = EINVAL;
2195 			goto bailout;
2196 		}
2197 		alloc_size = sizeof(struct scsi_report_zones_hdr) +
2198 		    (sizeof(struct scsi_report_zones_desc) * num_entries);
2199 		alloc_size = min(alloc_size, softc->disk->d_maxsize);
2200 		rz_ptr = malloc(alloc_size, M_ATADA, M_NOWAIT | M_ZERO);
2201 		if (rz_ptr == NULL) {
2202 			xpt_print(periph->path, "Unable to allocate memory "
2203 			   "for Report Zones request\n");
2204 			error = ENOMEM;
2205 			goto bailout;
2206 		}
2207 
2208 		ata_zac_mgmt_in(&ccb->ataio,
2209 				/*retries*/ ada_retry_count,
2210 				/*cbcfnp*/ adadone,
2211 				/*use_ncq*/ (softc->flags &
2212 					     ADA_FLAG_PIM_ATA_EXT) ? 1 : 0,
2213 				/*zm_action*/ ATA_ZM_REPORT_ZONES,
2214 				/*zone_id*/ rep->starting_id,
2215 				/*zone_flags*/ rep->rep_options,
2216 				/*data_ptr*/ rz_ptr,
2217 				/*dxfer_len*/ alloc_size,
2218 				/*timeout*/ ada_default_timeout * 1000);
2219 
2220 		/*
2221 		 * For BIO_ZONE, this isn't normally needed.  However, it
2222 		 * is used by devstat_end_transaction_bio() to determine
2223 		 * how much data was transferred.
2224 		 */
2225 		/*
2226 		 * XXX KDM we have a problem.  But I'm not sure how to fix
2227 		 * it.  devstat uses bio_bcount - bio_resid to calculate
2228 		 * the amount of data transferred.   The GEOM disk code
2229 		 * uses bio_length - bio_resid to calculate the amount of
2230 		 * data in bio_completed.  We have different structure
2231 		 * sizes above and below the ada(4) driver.  So, if we
2232 		 * use the sizes above, the amount transferred won't be
2233 		 * quite accurate for devstat.  If we use different sizes
2234 		 * for bio_bcount and bio_length (above and below
2235 		 * respectively), then the residual needs to match one or
2236 		 * the other.  Everything is calculated after the bio
2237 		 * leaves the driver, so changing the values around isn't
2238 		 * really an option.  For now, just set the count to the
2239 		 * passed in length.  This means that the calculations
2240 		 * above (e.g. bio_completed) will be correct, but the
2241 		 * amount of data reported to devstat will be slightly
2242 		 * under or overstated.
2243 		 */
2244 		bp->bio_bcount = bp->bio_length;
2245 
2246 		*queue_ccb = 1;
2247 
2248 		break;
2249 	}
2250 	case DISK_ZONE_GET_PARAMS: {
2251 		struct disk_zone_disk_params *params;
2252 
2253 		params = &bp->bio_zone.zone_params.disk_params;
2254 		bzero(params, sizeof(*params));
2255 
2256 		switch (softc->zone_mode) {
2257 		case ADA_ZONE_DRIVE_MANAGED:
2258 			params->zone_mode = DISK_ZONE_MODE_DRIVE_MANAGED;
2259 			break;
2260 		case ADA_ZONE_HOST_AWARE:
2261 			params->zone_mode = DISK_ZONE_MODE_HOST_AWARE;
2262 			break;
2263 		case ADA_ZONE_HOST_MANAGED:
2264 			params->zone_mode = DISK_ZONE_MODE_HOST_MANAGED;
2265 			break;
2266 		default:
2267 		case ADA_ZONE_NONE:
2268 			params->zone_mode = DISK_ZONE_MODE_NONE;
2269 			break;
2270 		}
2271 
2272 		if (softc->zone_flags & ADA_ZONE_FLAG_URSWRZ)
2273 			params->flags |= DISK_ZONE_DISK_URSWRZ;
2274 
2275 		if (softc->zone_flags & ADA_ZONE_FLAG_OPT_SEQ_SET) {
2276 			params->optimal_seq_zones = softc->optimal_seq_zones;
2277 			params->flags |= DISK_ZONE_OPT_SEQ_SET;
2278 		}
2279 
2280 		if (softc->zone_flags & ADA_ZONE_FLAG_OPT_NONSEQ_SET) {
2281 			params->optimal_nonseq_zones =
2282 			    softc->optimal_nonseq_zones;
2283 			params->flags |= DISK_ZONE_OPT_NONSEQ_SET;
2284 		}
2285 
2286 		if (softc->zone_flags & ADA_ZONE_FLAG_MAX_SEQ_SET) {
2287 			params->max_seq_zones = softc->max_seq_zones;
2288 			params->flags |= DISK_ZONE_MAX_SEQ_SET;
2289 		}
2290 		if (softc->zone_flags & ADA_ZONE_FLAG_RZ_SUP)
2291 			params->flags |= DISK_ZONE_RZ_SUP;
2292 
2293 		if (softc->zone_flags & ADA_ZONE_FLAG_OPEN_SUP)
2294 			params->flags |= DISK_ZONE_OPEN_SUP;
2295 
2296 		if (softc->zone_flags & ADA_ZONE_FLAG_CLOSE_SUP)
2297 			params->flags |= DISK_ZONE_CLOSE_SUP;
2298 
2299 		if (softc->zone_flags & ADA_ZONE_FLAG_FINISH_SUP)
2300 			params->flags |= DISK_ZONE_FINISH_SUP;
2301 
2302 		if (softc->zone_flags & ADA_ZONE_FLAG_RWP_SUP)
2303 			params->flags |= DISK_ZONE_RWP_SUP;
2304 		break;
2305 	}
2306 	default:
2307 		break;
2308 	}
2309 bailout:
2310 	return (error);
2311 }
2312 
2313 static void
2314 adastart(struct cam_periph *periph, union ccb *start_ccb)
2315 {
2316 	struct ada_softc *softc = (struct ada_softc *)periph->softc;
2317 	struct ccb_ataio *ataio = &start_ccb->ataio;
2318 
2319 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastart\n"));
2320 
2321 	switch (softc->state) {
2322 	case ADA_STATE_NORMAL:
2323 	{
2324 		struct bio *bp;
2325 		u_int8_t tag_code;
2326 
2327 		bp = cam_iosched_next_bio(softc->cam_iosched);
2328 		if (bp == NULL) {
2329 			xpt_release_ccb(start_ccb);
2330 			break;
2331 		}
2332 
2333 		if ((bp->bio_flags & BIO_ORDERED) != 0 ||
2334 		    (bp->bio_cmd != BIO_DELETE && (softc->flags & ADA_FLAG_NEED_OTAG) != 0)) {
2335 			softc->flags &= ~ADA_FLAG_NEED_OTAG;
2336 			softc->flags |= ADA_FLAG_WAS_OTAG;
2337 			tag_code = 0;
2338 		} else {
2339 			tag_code = 1;
2340 		}
2341 		switch (bp->bio_cmd) {
2342 		case BIO_WRITE:
2343 		case BIO_READ:
2344 		{
2345 			uint64_t lba = bp->bio_pblkno;
2346 			uint16_t count = bp->bio_bcount / softc->params.secsize;
2347 			void *data_ptr;
2348 			int rw_op;
2349 
2350 			if (bp->bio_cmd == BIO_WRITE) {
2351 				softc->flags |= ADA_FLAG_DIRTY;
2352 				rw_op = CAM_DIR_OUT;
2353 			} else {
2354 				rw_op = CAM_DIR_IN;
2355 			}
2356 
2357 			data_ptr = bp->bio_data;
2358 			if ((bp->bio_flags & (BIO_UNMAPPED|BIO_VLIST)) != 0) {
2359 				rw_op |= CAM_DATA_BIO;
2360 				data_ptr = bp;
2361 			}
2362 
2363 #ifdef CAM_TEST_FAILURE
2364 			int fail = 0;
2365 
2366 			/*
2367 			 * Support the failure ioctls.  If the command is a
2368 			 * read, and there are pending forced read errors, or
2369 			 * if a write and pending write errors, then fail this
2370 			 * operation with EIO.  This is useful for testing
2371 			 * purposes.  Also, support having every Nth read fail.
2372 			 *
2373 			 * This is a rather blunt tool.
2374 			 */
2375 			if (bp->bio_cmd == BIO_READ) {
2376 				if (softc->force_read_error) {
2377 					softc->force_read_error--;
2378 					fail = 1;
2379 				}
2380 				if (softc->periodic_read_error > 0) {
2381 					if (++softc->periodic_read_count >=
2382 					    softc->periodic_read_error) {
2383 						softc->periodic_read_count = 0;
2384 						fail = 1;
2385 					}
2386 				}
2387 			} else {
2388 				if (softc->force_write_error) {
2389 					softc->force_write_error--;
2390 					fail = 1;
2391 				}
2392 			}
2393 			if (fail) {
2394 				biofinish(bp, NULL, EIO);
2395 				xpt_release_ccb(start_ccb);
2396 				adaschedule(periph);
2397 				return;
2398 			}
2399 #endif
2400 			KASSERT((bp->bio_flags & BIO_UNMAPPED) == 0 ||
2401 			    round_page(bp->bio_bcount + bp->bio_ma_offset) /
2402 			    PAGE_SIZE == bp->bio_ma_n,
2403 			    ("Short bio %p", bp));
2404 			cam_fill_ataio(ataio,
2405 			    ada_retry_count,
2406 			    adadone,
2407 			    rw_op,
2408 			    0,
2409 			    data_ptr,
2410 			    bp->bio_bcount,
2411 			    ada_default_timeout*1000);
2412 
2413 			if ((softc->flags & ADA_FLAG_CAN_NCQ) && tag_code) {
2414 				if (bp->bio_cmd == BIO_READ) {
2415 					ata_ncq_cmd(ataio, ATA_READ_FPDMA_QUEUED,
2416 					    lba, count);
2417 				} else {
2418 					ata_ncq_cmd(ataio, ATA_WRITE_FPDMA_QUEUED,
2419 					    lba, count);
2420 				}
2421 			} else if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
2422 			    (lba + count >= ATA_MAX_28BIT_LBA ||
2423 			    count > 256)) {
2424 				if (softc->flags & ADA_FLAG_CAN_DMA48) {
2425 					if (bp->bio_cmd == BIO_READ) {
2426 						ata_48bit_cmd(ataio, ATA_READ_DMA48,
2427 						    0, lba, count);
2428 					} else {
2429 						ata_48bit_cmd(ataio, ATA_WRITE_DMA48,
2430 						    0, lba, count);
2431 					}
2432 				} else {
2433 					if (bp->bio_cmd == BIO_READ) {
2434 						ata_48bit_cmd(ataio, ATA_READ_MUL48,
2435 						    0, lba, count);
2436 					} else {
2437 						ata_48bit_cmd(ataio, ATA_WRITE_MUL48,
2438 						    0, lba, count);
2439 					}
2440 				}
2441 			} else {
2442 				if (count == 256)
2443 					count = 0;
2444 				if (softc->flags & ADA_FLAG_CAN_DMA) {
2445 					if (bp->bio_cmd == BIO_READ) {
2446 						ata_28bit_cmd(ataio, ATA_READ_DMA,
2447 						    0, lba, count);
2448 					} else {
2449 						ata_28bit_cmd(ataio, ATA_WRITE_DMA,
2450 						    0, lba, count);
2451 					}
2452 				} else {
2453 					if (bp->bio_cmd == BIO_READ) {
2454 						ata_28bit_cmd(ataio, ATA_READ_MUL,
2455 						    0, lba, count);
2456 					} else {
2457 						ata_28bit_cmd(ataio, ATA_WRITE_MUL,
2458 						    0, lba, count);
2459 					}
2460 				}
2461 			}
2462 			break;
2463 		}
2464 		case BIO_DELETE:
2465 			switch (softc->delete_method) {
2466 			case ADA_DELETE_NCQ_DSM_TRIM:
2467 				ada_ncq_dsmtrim(softc, bp, ataio);
2468 				break;
2469 			case ADA_DELETE_DSM_TRIM:
2470 				ada_dsmtrim(softc, bp, ataio);
2471 				break;
2472 			case ADA_DELETE_CFA_ERASE:
2473 				ada_cfaerase(softc, bp, ataio);
2474 				break;
2475 			default:
2476 				biofinish(bp, NULL, EOPNOTSUPP);
2477 				xpt_release_ccb(start_ccb);
2478 				adaschedule(periph);
2479 				return;
2480 			}
2481 			start_ccb->ccb_h.ccb_state = ADA_CCB_TRIM;
2482 			start_ccb->ccb_h.flags |= CAM_UNLOCKED;
2483 			cam_iosched_submit_trim(softc->cam_iosched);
2484 			goto out;
2485 		case BIO_FLUSH:
2486 			cam_fill_ataio(ataio,
2487 			    1,
2488 			    adadone,
2489 			    CAM_DIR_NONE,
2490 			    0,
2491 			    NULL,
2492 			    0,
2493 			    ada_default_timeout*1000);
2494 
2495 			if (softc->flags & ADA_FLAG_CAN_48BIT)
2496 				ata_48bit_cmd(ataio, ATA_FLUSHCACHE48, 0, 0, 0);
2497 			else
2498 				ata_28bit_cmd(ataio, ATA_FLUSHCACHE, 0, 0, 0);
2499 			break;
2500 		case BIO_ZONE: {
2501 			int error, queue_ccb;
2502 
2503 			queue_ccb = 0;
2504 
2505 			error = ada_zone_cmd(periph, start_ccb, bp, &queue_ccb);
2506 			if ((error != 0)
2507 			 || (queue_ccb == 0)) {
2508 				biofinish(bp, NULL, error);
2509 				xpt_release_ccb(start_ccb);
2510 				return;
2511 			}
2512 			break;
2513 		}
2514 		default:
2515 			biofinish(bp, NULL, EOPNOTSUPP);
2516 			xpt_release_ccb(start_ccb);
2517 			return;
2518 		}
2519 		start_ccb->ccb_h.ccb_state = ADA_CCB_BUFFER_IO;
2520 		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
2521 out:
2522 		start_ccb->ccb_h.ccb_bp = bp;
2523 		softc->outstanding_cmds++;
2524 		softc->refcount++;
2525 		cam_periph_unlock(periph);
2526 		xpt_action(start_ccb);
2527 		cam_periph_lock(periph);
2528 
2529 		/* May have more work to do, so ensure we stay scheduled */
2530 		adaschedule(periph);
2531 		break;
2532 	}
2533 	case ADA_STATE_RAHEAD:
2534 	case ADA_STATE_WCACHE:
2535 	{
2536 		cam_fill_ataio(ataio,
2537 		    1,
2538 		    adadone,
2539 		    CAM_DIR_NONE,
2540 		    0,
2541 		    NULL,
2542 		    0,
2543 		    ada_default_timeout*1000);
2544 
2545 		if (softc->state == ADA_STATE_RAHEAD) {
2546 			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_RA ?
2547 			    ATA_SF_ENAB_RCACHE : ATA_SF_DIS_RCACHE, 0, 0);
2548 			start_ccb->ccb_h.ccb_state = ADA_CCB_RAHEAD;
2549 		} else {
2550 			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_WC ?
2551 			    ATA_SF_ENAB_WCACHE : ATA_SF_DIS_WCACHE, 0, 0);
2552 			start_ccb->ccb_h.ccb_state = ADA_CCB_WCACHE;
2553 		}
2554 		start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2555 		xpt_action(start_ccb);
2556 		break;
2557 	}
2558 	case ADA_STATE_LOGDIR:
2559 	{
2560 		struct ata_gp_log_dir *log_dir;
2561 
2562 		if ((softc->flags & ADA_FLAG_CAN_LOG) == 0) {
2563 			adaprobedone(periph, start_ccb);
2564 			break;
2565 		}
2566 
2567 		log_dir = malloc(sizeof(*log_dir), M_ATADA, M_NOWAIT|M_ZERO);
2568 		if (log_dir == NULL) {
2569 			xpt_print(periph->path, "Couldn't malloc log_dir "
2570 			    "data\n");
2571 			softc->state = ADA_STATE_NORMAL;
2572 			xpt_release_ccb(start_ccb);
2573 			break;
2574 		}
2575 
2576 
2577 		ata_read_log(ataio,
2578 		    /*retries*/1,
2579 		    /*cbfcnp*/adadone,
2580 		    /*log_address*/ ATA_LOG_DIRECTORY,
2581 		    /*page_number*/ 0,
2582 		    /*block_count*/ 1,
2583 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2584 				 CAM_ATAIO_DMA : 0,
2585 		    /*data_ptr*/ (uint8_t *)log_dir,
2586 		    /*dxfer_len*/sizeof(*log_dir),
2587 		    /*timeout*/ada_default_timeout*1000);
2588 
2589 		start_ccb->ccb_h.ccb_state = ADA_CCB_LOGDIR;
2590 		xpt_action(start_ccb);
2591 		break;
2592 	}
2593 	case ADA_STATE_IDDIR:
2594 	{
2595 		struct ata_identify_log_pages *id_dir;
2596 
2597 		id_dir = malloc(sizeof(*id_dir), M_ATADA, M_NOWAIT | M_ZERO);
2598 		if (id_dir == NULL) {
2599 			xpt_print(periph->path, "Couldn't malloc id_dir "
2600 			    "data\n");
2601 			adaprobedone(periph, start_ccb);
2602 			break;
2603 		}
2604 
2605 		ata_read_log(ataio,
2606 		    /*retries*/1,
2607 		    /*cbfcnp*/adadone,
2608 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
2609 		    /*page_number*/ ATA_IDL_PAGE_LIST,
2610 		    /*block_count*/ 1,
2611 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2612 				 CAM_ATAIO_DMA : 0,
2613 		    /*data_ptr*/ (uint8_t *)id_dir,
2614 		    /*dxfer_len*/ sizeof(*id_dir),
2615 		    /*timeout*/ada_default_timeout*1000);
2616 
2617 		start_ccb->ccb_h.ccb_state = ADA_CCB_IDDIR;
2618 		xpt_action(start_ccb);
2619 		break;
2620 	}
2621 	case ADA_STATE_SUP_CAP:
2622 	{
2623 		struct ata_identify_log_sup_cap *sup_cap;
2624 
2625 		sup_cap = malloc(sizeof(*sup_cap), M_ATADA, M_NOWAIT|M_ZERO);
2626 		if (sup_cap == NULL) {
2627 			xpt_print(periph->path, "Couldn't malloc sup_cap "
2628 			    "data\n");
2629 			adaprobedone(periph, start_ccb);
2630 			break;
2631 		}
2632 
2633 		ata_read_log(ataio,
2634 		    /*retries*/1,
2635 		    /*cbfcnp*/adadone,
2636 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
2637 		    /*page_number*/ ATA_IDL_SUP_CAP,
2638 		    /*block_count*/ 1,
2639 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2640 				 CAM_ATAIO_DMA : 0,
2641 		    /*data_ptr*/ (uint8_t *)sup_cap,
2642 		    /*dxfer_len*/ sizeof(*sup_cap),
2643 		    /*timeout*/ada_default_timeout*1000);
2644 
2645 		start_ccb->ccb_h.ccb_state = ADA_CCB_SUP_CAP;
2646 		xpt_action(start_ccb);
2647 		break;
2648 	}
2649 	case ADA_STATE_ZONE:
2650 	{
2651 		struct ata_zoned_info_log *ata_zone;
2652 
2653 		ata_zone = malloc(sizeof(*ata_zone), M_ATADA, M_NOWAIT|M_ZERO);
2654 		if (ata_zone == NULL) {
2655 			xpt_print(periph->path, "Couldn't malloc ata_zone "
2656 			    "data\n");
2657 			adaprobedone(periph, start_ccb);
2658 			break;
2659 		}
2660 
2661 		ata_read_log(ataio,
2662 		    /*retries*/1,
2663 		    /*cbfcnp*/adadone,
2664 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
2665 		    /*page_number*/ ATA_IDL_ZDI,
2666 		    /*block_count*/ 1,
2667 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2668 				 CAM_ATAIO_DMA : 0,
2669 		    /*data_ptr*/ (uint8_t *)ata_zone,
2670 		    /*dxfer_len*/ sizeof(*ata_zone),
2671 		    /*timeout*/ada_default_timeout*1000);
2672 
2673 		start_ccb->ccb_h.ccb_state = ADA_CCB_ZONE;
2674 		xpt_action(start_ccb);
2675 		break;
2676 	}
2677 	}
2678 }
2679 
2680 static void
2681 adaprobedone(struct cam_periph *periph, union ccb *ccb)
2682 {
2683 	struct ada_softc *softc;
2684 
2685 	softc = (struct ada_softc *)periph->softc;
2686 
2687 	if (ccb != NULL)
2688 		xpt_release_ccb(ccb);
2689 
2690 	softc->state = ADA_STATE_NORMAL;
2691 	softc->flags |= ADA_FLAG_PROBED;
2692 	adaschedule(periph);
2693 	if ((softc->flags & ADA_FLAG_ANNOUNCED) == 0) {
2694 		softc->flags |= ADA_FLAG_ANNOUNCED;
2695 		cam_periph_unhold(periph);
2696 	} else {
2697 		cam_periph_release_locked(periph);
2698 	}
2699 }
2700 
2701 static void
2702 adazonedone(struct cam_periph *periph, union ccb *ccb)
2703 {
2704 	struct bio *bp;
2705 
2706 	bp = (struct bio *)ccb->ccb_h.ccb_bp;
2707 
2708 	switch (bp->bio_zone.zone_cmd) {
2709 	case DISK_ZONE_OPEN:
2710 	case DISK_ZONE_CLOSE:
2711 	case DISK_ZONE_FINISH:
2712 	case DISK_ZONE_RWP:
2713 		break;
2714 	case DISK_ZONE_REPORT_ZONES: {
2715 		uint32_t avail_len;
2716 		struct disk_zone_report *rep;
2717 		struct scsi_report_zones_hdr *hdr;
2718 		struct scsi_report_zones_desc *desc;
2719 		struct disk_zone_rep_entry *entry;
2720 		uint32_t hdr_len, num_avail;
2721 		uint32_t num_to_fill, i;
2722 
2723 		rep = &bp->bio_zone.zone_params.report;
2724 		avail_len = ccb->ataio.dxfer_len - ccb->ataio.resid;
2725 		/*
2726 		 * Note that bio_resid isn't normally used for zone
2727 		 * commands, but it is used by devstat_end_transaction_bio()
2728 		 * to determine how much data was transferred.  Because
2729 		 * the size of the SCSI/ATA data structures is different
2730 		 * than the size of the BIO interface structures, the
2731 		 * amount of data actually transferred from the drive will
2732 		 * be different than the amount of data transferred to
2733 		 * the user.
2734 		 */
2735 		hdr = (struct scsi_report_zones_hdr *)ccb->ataio.data_ptr;
2736 		if (avail_len < sizeof(*hdr)) {
2737 			/*
2738 			 * Is there a better error than EIO here?  We asked
2739 			 * for at least the header, and we got less than
2740 			 * that.
2741 			 */
2742 			bp->bio_error = EIO;
2743 			bp->bio_flags |= BIO_ERROR;
2744 			bp->bio_resid = bp->bio_bcount;
2745 			break;
2746 		}
2747 
2748 		hdr_len = le32dec(hdr->length);
2749 		if (hdr_len > 0)
2750 			rep->entries_available = hdr_len / sizeof(*desc);
2751 		else
2752 			rep->entries_available = 0;
2753 		/*
2754 		 * NOTE: using the same values for the BIO version of the
2755 		 * same field as the SCSI/ATA values.  This means we could
2756 		 * get some additional values that aren't defined in bio.h
2757 		 * if more values of the same field are defined later.
2758 		 */
2759 		rep->header.same = hdr->byte4 & SRZ_SAME_MASK;
2760 		rep->header.maximum_lba = le64dec(hdr->maximum_lba);
2761 		/*
2762 		 * If the drive reports no entries that match the query,
2763 		 * we're done.
2764 		 */
2765 		if (hdr_len == 0) {
2766 			rep->entries_filled = 0;
2767 			bp->bio_resid = bp->bio_bcount;
2768 			break;
2769 		}
2770 
2771 		num_avail = min((avail_len - sizeof(*hdr)) / sizeof(*desc),
2772 				hdr_len / sizeof(*desc));
2773 		/*
2774 		 * If the drive didn't return any data, then we're done.
2775 		 */
2776 		if (num_avail == 0) {
2777 			rep->entries_filled = 0;
2778 			bp->bio_resid = bp->bio_bcount;
2779 			break;
2780 		}
2781 
2782 		num_to_fill = min(num_avail, rep->entries_allocated);
2783 		/*
2784 		 * If the user didn't allocate any entries for us to fill,
2785 		 * we're done.
2786 		 */
2787 		if (num_to_fill == 0) {
2788 			rep->entries_filled = 0;
2789 			bp->bio_resid = bp->bio_bcount;
2790 			break;
2791 		}
2792 
2793 		for (i = 0, desc = &hdr->desc_list[0], entry=&rep->entries[0];
2794 		     i < num_to_fill; i++, desc++, entry++) {
2795 			/*
2796 			 * NOTE: we're mapping the values here directly
2797 			 * from the SCSI/ATA bit definitions to the bio.h
2798 			 * definitions.  There is also a warning in
2799 			 * disk_zone.h, but the impact is that if
2800 			 * additional values are added in the SCSI/ATA
2801 			 * specs these will be visible to consumers of
2802 			 * this interface.
2803 			 */
2804 			entry->zone_type = desc->zone_type & SRZ_TYPE_MASK;
2805 			entry->zone_condition =
2806 			    (desc->zone_flags & SRZ_ZONE_COND_MASK) >>
2807 			    SRZ_ZONE_COND_SHIFT;
2808 			entry->zone_flags |= desc->zone_flags &
2809 			    (SRZ_ZONE_NON_SEQ|SRZ_ZONE_RESET);
2810 			entry->zone_length = le64dec(desc->zone_length);
2811 			entry->zone_start_lba = le64dec(desc->zone_start_lba);
2812 			entry->write_pointer_lba =
2813 			    le64dec(desc->write_pointer_lba);
2814 		}
2815 		rep->entries_filled = num_to_fill;
2816 		/*
2817 		 * Note that this residual is accurate from the user's
2818 		 * standpoint, but the amount transferred isn't accurate
2819 		 * from the standpoint of what actually came back from the
2820 		 * drive.
2821 		 */
2822 		bp->bio_resid = bp->bio_bcount - (num_to_fill * sizeof(*entry));
2823 		break;
2824 	}
2825 	case DISK_ZONE_GET_PARAMS:
2826 	default:
2827 		/*
2828 		 * In theory we should not get a GET_PARAMS bio, since it
2829 		 * should be handled without queueing the command to the
2830 		 * drive.
2831 		 */
2832 		panic("%s: Invalid zone command %d", __func__,
2833 		    bp->bio_zone.zone_cmd);
2834 		break;
2835 	}
2836 
2837 	if (bp->bio_zone.zone_cmd == DISK_ZONE_REPORT_ZONES)
2838 		free(ccb->ataio.data_ptr, M_ATADA);
2839 }
2840 
2841 
2842 static void
2843 adadone(struct cam_periph *periph, union ccb *done_ccb)
2844 {
2845 	struct ada_softc *softc;
2846 	struct ccb_ataio *ataio;
2847 	struct cam_path *path;
2848 	uint32_t priority;
2849 	int state;
2850 
2851 	softc = (struct ada_softc *)periph->softc;
2852 	ataio = &done_ccb->ataio;
2853 	path = done_ccb->ccb_h.path;
2854 	priority = done_ccb->ccb_h.pinfo.priority;
2855 
2856 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("adadone\n"));
2857 
2858 	state = ataio->ccb_h.ccb_state & ADA_CCB_TYPE_MASK;
2859 	switch (state) {
2860 	case ADA_CCB_BUFFER_IO:
2861 	case ADA_CCB_TRIM:
2862 	{
2863 		struct bio *bp;
2864 		int error;
2865 
2866 		cam_periph_lock(periph);
2867 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2868 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2869 			error = adaerror(done_ccb, 0, 0);
2870 			if (error == ERESTART) {
2871 				/* A retry was scheduled, so just return. */
2872 				cam_periph_unlock(periph);
2873 				return;
2874 			}
2875 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2876 				cam_release_devq(path,
2877 						 /*relsim_flags*/0,
2878 						 /*reduction*/0,
2879 						 /*timeout*/0,
2880 						 /*getcount_only*/0);
2881 			/*
2882 			 * If we get an error on an NCQ DSM TRIM, fall back
2883 			 * to a non-NCQ DSM TRIM forever. Please note that if
2884 			 * CAN_NCQ_TRIM is set, CAN_TRIM is necessarily set too.
2885 			 * However, for this one trim, we treat it as advisory
2886 			 * and return success up the stack.
2887 			 */
2888 			if (state == ADA_CCB_TRIM &&
2889 			    error != 0 &&
2890 			    (softc->flags & ADA_FLAG_CAN_NCQ_TRIM) != 0) {
2891 				softc->flags &= ~ADA_FLAG_CAN_NCQ_TRIM;
2892 				error = 0;
2893 				adasetdeletemethod(softc);
2894 			}
2895 		} else {
2896 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2897 				panic("REQ_CMP with QFRZN");
2898 
2899 			error = 0;
2900 		}
2901 		bp->bio_error = error;
2902 		if (error != 0) {
2903 			bp->bio_resid = bp->bio_bcount;
2904 			bp->bio_flags |= BIO_ERROR;
2905 		} else {
2906 			if (bp->bio_cmd == BIO_ZONE)
2907 				adazonedone(periph, done_ccb);
2908 			else if (state == ADA_CCB_TRIM)
2909 				bp->bio_resid = 0;
2910 			else
2911 				bp->bio_resid = ataio->resid;
2912 
2913 			if ((bp->bio_resid > 0)
2914 			 && (bp->bio_cmd != BIO_ZONE))
2915 				bp->bio_flags |= BIO_ERROR;
2916 		}
2917 		softc->outstanding_cmds--;
2918 		if (softc->outstanding_cmds == 0)
2919 			softc->flags |= ADA_FLAG_WAS_OTAG;
2920 
2921 		/*
2922 		 * We need to call cam_iosched before we call biodone so that we
2923 		 * don't measure any activity that happens in the completion
2924 		 * routine, which in the case of sendfile can be quite
2925 		 * extensive.  Release the periph refcount taken in adastart()
2926 		 * for each CCB.
2927 		 */
2928 		cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb);
2929 		xpt_release_ccb(done_ccb);
2930 		KASSERT(softc->refcount >= 1, ("adadone softc %p refcount %d", softc, softc->refcount));
2931 		softc->refcount--;
2932 		if (state == ADA_CCB_TRIM) {
2933 			TAILQ_HEAD(, bio) queue;
2934 			struct bio *bp1;
2935 
2936 			TAILQ_INIT(&queue);
2937 			TAILQ_CONCAT(&queue, &softc->trim_req.bps, bio_queue);
2938 			/*
2939 			 * Normally, the xpt_release_ccb() above would make sure
2940 			 * that when we have more work to do, that work would
2941 			 * get kicked off. However, we specifically keep
2942 			 * trim_running set to 0 before the call above to allow
2943 			 * other I/O to progress when many BIO_DELETE requests
2944 			 * are pushed down. We set trim_running to 0 and call
2945 			 * daschedule again so that we don't stall if there are
2946 			 * no other I/Os pending apart from BIO_DELETEs.
2947 			 */
2948 			cam_iosched_trim_done(softc->cam_iosched);
2949 			adaschedule(periph);
2950 			cam_periph_unlock(periph);
2951 			while ((bp1 = TAILQ_FIRST(&queue)) != NULL) {
2952 				TAILQ_REMOVE(&queue, bp1, bio_queue);
2953 				bp1->bio_error = error;
2954 				if (error != 0) {
2955 					bp1->bio_flags |= BIO_ERROR;
2956 					bp1->bio_resid = bp1->bio_bcount;
2957 				} else
2958 					bp1->bio_resid = 0;
2959 				biodone(bp1);
2960 			}
2961 		} else {
2962 			adaschedule(periph);
2963 			cam_periph_unlock(periph);
2964 			biodone(bp);
2965 		}
2966 		return;
2967 	}
2968 	case ADA_CCB_RAHEAD:
2969 	{
2970 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2971 			if (adaerror(done_ccb, 0, 0) == ERESTART) {
2972 				/* Drop freeze taken due to CAM_DEV_QFREEZE */
2973 				cam_release_devq(path, 0, 0, 0, FALSE);
2974 				return;
2975 			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
2976 				cam_release_devq(path,
2977 				    /*relsim_flags*/0,
2978 				    /*reduction*/0,
2979 				    /*timeout*/0,
2980 				    /*getcount_only*/0);
2981 			}
2982 		}
2983 
2984 		/*
2985 		 * Since our peripheral may be invalidated by an error
2986 		 * above or an external event, we must release our CCB
2987 		 * before releasing the reference on the peripheral.
2988 		 * The peripheral will only go away once the last reference
2989 		 * is removed, and we need it around for the CCB release
2990 		 * operation.
2991 		 */
2992 
2993 		xpt_release_ccb(done_ccb);
2994 		softc->state = ADA_STATE_WCACHE;
2995 		xpt_schedule(periph, priority);
2996 		/* Drop freeze taken due to CAM_DEV_QFREEZE */
2997 		cam_release_devq(path, 0, 0, 0, FALSE);
2998 		return;
2999 	}
3000 	case ADA_CCB_WCACHE:
3001 	{
3002 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3003 			if (adaerror(done_ccb, 0, 0) == ERESTART) {
3004 				/* Drop freeze taken due to CAM_DEV_QFREEZE */
3005 				cam_release_devq(path, 0, 0, 0, FALSE);
3006 				return;
3007 			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3008 				cam_release_devq(path,
3009 				    /*relsim_flags*/0,
3010 				    /*reduction*/0,
3011 				    /*timeout*/0,
3012 				    /*getcount_only*/0);
3013 			}
3014 		}
3015 
3016 		/* Drop freeze taken due to CAM_DEV_QFREEZE */
3017 		cam_release_devq(path, 0, 0, 0, FALSE);
3018 
3019 		if ((softc->flags & ADA_FLAG_CAN_LOG)
3020 		 && (softc->zone_mode != ADA_ZONE_NONE)) {
3021 			xpt_release_ccb(done_ccb);
3022 			softc->state = ADA_STATE_LOGDIR;
3023 			xpt_schedule(periph, priority);
3024 		} else {
3025 			adaprobedone(periph, done_ccb);
3026 		}
3027 		return;
3028 	}
3029 	case ADA_CCB_LOGDIR:
3030 	{
3031 		int error;
3032 
3033 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3034 			error = 0;
3035 			softc->valid_logdir_len = 0;
3036 			bzero(&softc->ata_logdir, sizeof(softc->ata_logdir));
3037 			softc->valid_logdir_len =
3038 				ataio->dxfer_len - ataio->resid;
3039 			if (softc->valid_logdir_len > 0)
3040 				bcopy(ataio->data_ptr, &softc->ata_logdir,
3041 				    min(softc->valid_logdir_len,
3042 					sizeof(softc->ata_logdir)));
3043 			/*
3044 			 * Figure out whether the Identify Device log is
3045 			 * supported.  The General Purpose log directory
3046 			 * has a header, and lists the number of pages
3047 			 * available for each GP log identified by the
3048 			 * offset into the list.
3049 			 */
3050 			if ((softc->valid_logdir_len >=
3051 			    ((ATA_IDENTIFY_DATA_LOG + 1) * sizeof(uint16_t)))
3052 			 && (le16dec(softc->ata_logdir.header) ==
3053 			     ATA_GP_LOG_DIR_VERSION)
3054 			 && (le16dec(&softc->ata_logdir.num_pages[
3055 			     (ATA_IDENTIFY_DATA_LOG *
3056 			     sizeof(uint16_t)) - sizeof(uint16_t)]) > 0)){
3057 				softc->flags |= ADA_FLAG_CAN_IDLOG;
3058 			} else {
3059 				softc->flags &= ~ADA_FLAG_CAN_IDLOG;
3060 			}
3061 		} else {
3062 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3063 					 SF_RETRY_UA|SF_NO_PRINT);
3064 			if (error == ERESTART)
3065 				return;
3066 			else if (error != 0) {
3067 				/*
3068 				 * If we can't get the ATA log directory,
3069 				 * then ATA logs are effectively not
3070 				 * supported even if the bit is set in the
3071 				 * identify data.
3072 				 */
3073 				softc->flags &= ~(ADA_FLAG_CAN_LOG |
3074 						  ADA_FLAG_CAN_IDLOG);
3075 				if ((done_ccb->ccb_h.status &
3076 				     CAM_DEV_QFRZN) != 0) {
3077 					/* Don't wedge this device's queue */
3078 					cam_release_devq(done_ccb->ccb_h.path,
3079 							 /*relsim_flags*/0,
3080 							 /*reduction*/0,
3081 							 /*timeout*/0,
3082 							 /*getcount_only*/0);
3083 				}
3084 			}
3085 
3086 
3087 		}
3088 
3089 		free(ataio->data_ptr, M_ATADA);
3090 
3091 		if ((error == 0)
3092 		 && (softc->flags & ADA_FLAG_CAN_IDLOG)) {
3093 			softc->state = ADA_STATE_IDDIR;
3094 			xpt_release_ccb(done_ccb);
3095 			xpt_schedule(periph, priority);
3096 		} else
3097 			adaprobedone(periph, done_ccb);
3098 
3099 		return;
3100 	}
3101 	case ADA_CCB_IDDIR: {
3102 		int error;
3103 
3104 		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3105 			off_t entries_offset, max_entries;
3106 			error = 0;
3107 
3108 			softc->valid_iddir_len = 0;
3109 			bzero(&softc->ata_iddir, sizeof(softc->ata_iddir));
3110 			softc->flags &= ~(ADA_FLAG_CAN_SUPCAP |
3111 					  ADA_FLAG_CAN_ZONE);
3112 			softc->valid_iddir_len =
3113 				ataio->dxfer_len - ataio->resid;
3114 			if (softc->valid_iddir_len > 0)
3115 				bcopy(ataio->data_ptr, &softc->ata_iddir,
3116 				    min(softc->valid_iddir_len,
3117 					sizeof(softc->ata_iddir)));
3118 
3119 			entries_offset =
3120 			    __offsetof(struct ata_identify_log_pages,entries);
3121 			max_entries = softc->valid_iddir_len - entries_offset;
3122 			if ((softc->valid_iddir_len > (entries_offset + 1))
3123 			 && (le64dec(softc->ata_iddir.header) ==
3124 			     ATA_IDLOG_REVISION)
3125 			 && (softc->ata_iddir.entry_count > 0)) {
3126 				int num_entries, i;
3127 
3128 				num_entries = softc->ata_iddir.entry_count;
3129 				num_entries = min(num_entries,
3130 				   softc->valid_iddir_len - entries_offset);
3131 				for (i = 0; i < num_entries &&
3132 				     i < max_entries; i++) {
3133 					if (softc->ata_iddir.entries[i] ==
3134 					    ATA_IDL_SUP_CAP)
3135 						softc->flags |=
3136 						    ADA_FLAG_CAN_SUPCAP;
3137 					else if (softc->ata_iddir.entries[i]==
3138 						 ATA_IDL_ZDI)
3139 						softc->flags |=
3140 						    ADA_FLAG_CAN_ZONE;
3141 
3142 					if ((softc->flags &
3143 					     ADA_FLAG_CAN_SUPCAP)
3144 					 && (softc->flags &
3145 					     ADA_FLAG_CAN_ZONE))
3146 						break;
3147 				}
3148 			}
3149 		} else {
3150 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3151 					 SF_RETRY_UA|SF_NO_PRINT);
3152 			if (error == ERESTART)
3153 				return;
3154 			else if (error != 0) {
3155 				/*
3156 				 * If we can't get the ATA Identify Data log
3157 				 * directory, then it effectively isn't
3158 				 * supported even if the ATA Log directory
3159 				 * a non-zero number of pages present for
3160 				 * this log.
3161 				 */
3162 				softc->flags &= ~ADA_FLAG_CAN_IDLOG;
3163 				if ((done_ccb->ccb_h.status &
3164 				     CAM_DEV_QFRZN) != 0) {
3165 					/* Don't wedge this device's queue */
3166 					cam_release_devq(done_ccb->ccb_h.path,
3167 							 /*relsim_flags*/0,
3168 							 /*reduction*/0,
3169 							 /*timeout*/0,
3170 							 /*getcount_only*/0);
3171 				}
3172 			}
3173 		}
3174 
3175 		free(ataio->data_ptr, M_ATADA);
3176 
3177 		if ((error == 0)
3178 		 && (softc->flags & ADA_FLAG_CAN_SUPCAP)) {
3179 			softc->state = ADA_STATE_SUP_CAP;
3180 			xpt_release_ccb(done_ccb);
3181 			xpt_schedule(periph, priority);
3182 		} else
3183 			adaprobedone(periph, done_ccb);
3184 		return;
3185 	}
3186 	case ADA_CCB_SUP_CAP: {
3187 		int error;
3188 
3189 		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3190 			uint32_t valid_len;
3191 			size_t needed_size;
3192 			struct ata_identify_log_sup_cap *sup_cap;
3193 			error = 0;
3194 
3195 			sup_cap = (struct ata_identify_log_sup_cap *)
3196 			    ataio->data_ptr;
3197 			valid_len = ataio->dxfer_len - ataio->resid;
3198 			needed_size =
3199 			    __offsetof(struct ata_identify_log_sup_cap,
3200 			    sup_zac_cap) + 1 + sizeof(sup_cap->sup_zac_cap);
3201 			if (valid_len >= needed_size) {
3202 				uint64_t zoned, zac_cap;
3203 
3204 				zoned = le64dec(sup_cap->zoned_cap);
3205 				if (zoned & ATA_ZONED_VALID) {
3206 					/*
3207 					 * This should have already been
3208 					 * set, because this is also in the
3209 					 * ATA identify data.
3210 					 */
3211 					if ((zoned & ATA_ZONED_MASK) ==
3212 					    ATA_SUPPORT_ZONE_HOST_AWARE)
3213 						softc->zone_mode =
3214 						    ADA_ZONE_HOST_AWARE;
3215 					else if ((zoned & ATA_ZONED_MASK) ==
3216 					    ATA_SUPPORT_ZONE_DEV_MANAGED)
3217 						softc->zone_mode =
3218 						    ADA_ZONE_DRIVE_MANAGED;
3219 				}
3220 
3221 				zac_cap = le64dec(sup_cap->sup_zac_cap);
3222 				if (zac_cap & ATA_SUP_ZAC_CAP_VALID) {
3223 					if (zac_cap & ATA_REPORT_ZONES_SUP)
3224 						softc->zone_flags |=
3225 						    ADA_ZONE_FLAG_RZ_SUP;
3226 					if (zac_cap & ATA_ND_OPEN_ZONE_SUP)
3227 						softc->zone_flags |=
3228 						    ADA_ZONE_FLAG_OPEN_SUP;
3229 					if (zac_cap & ATA_ND_CLOSE_ZONE_SUP)
3230 						softc->zone_flags |=
3231 						    ADA_ZONE_FLAG_CLOSE_SUP;
3232 					if (zac_cap & ATA_ND_FINISH_ZONE_SUP)
3233 						softc->zone_flags |=
3234 						    ADA_ZONE_FLAG_FINISH_SUP;
3235 					if (zac_cap & ATA_ND_RWP_SUP)
3236 						softc->zone_flags |=
3237 						    ADA_ZONE_FLAG_RWP_SUP;
3238 				} else {
3239 					/*
3240 					 * This field was introduced in
3241 					 * ACS-4, r08 on April 28th, 2015.
3242 					 * If the drive firmware was written
3243 					 * to an earlier spec, it won't have
3244 					 * the field.  So, assume all
3245 					 * commands are supported.
3246 					 */
3247 					softc->zone_flags |=
3248 					    ADA_ZONE_FLAG_SUP_MASK;
3249 				}
3250 			}
3251 		} else {
3252 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3253 					 SF_RETRY_UA|SF_NO_PRINT);
3254 			if (error == ERESTART)
3255 				return;
3256 			else if (error != 0) {
3257 				/*
3258 				 * If we can't get the ATA Identify Data
3259 				 * Supported Capabilities page, clear the
3260 				 * flag...
3261 				 */
3262 				softc->flags &= ~ADA_FLAG_CAN_SUPCAP;
3263 				/*
3264 				 * And clear zone capabilities.
3265 				 */
3266 				softc->zone_flags &= ~ADA_ZONE_FLAG_SUP_MASK;
3267 				if ((done_ccb->ccb_h.status &
3268 				     CAM_DEV_QFRZN) != 0) {
3269 					/* Don't wedge this device's queue */
3270 					cam_release_devq(done_ccb->ccb_h.path,
3271 							 /*relsim_flags*/0,
3272 							 /*reduction*/0,
3273 							 /*timeout*/0,
3274 							 /*getcount_only*/0);
3275 				}
3276 			}
3277 		}
3278 
3279 		free(ataio->data_ptr, M_ATADA);
3280 
3281 		if ((error == 0)
3282 		 && (softc->flags & ADA_FLAG_CAN_ZONE)) {
3283 			softc->state = ADA_STATE_ZONE;
3284 			xpt_release_ccb(done_ccb);
3285 			xpt_schedule(periph, priority);
3286 		} else
3287 			adaprobedone(periph, done_ccb);
3288 		return;
3289 	}
3290 	case ADA_CCB_ZONE: {
3291 		int error;
3292 
3293 		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3294 			struct ata_zoned_info_log *zi_log;
3295 			uint32_t valid_len;
3296 			size_t needed_size;
3297 
3298 			zi_log = (struct ata_zoned_info_log *)ataio->data_ptr;
3299 
3300 			valid_len = ataio->dxfer_len - ataio->resid;
3301 			needed_size = __offsetof(struct ata_zoned_info_log,
3302 			    version_info) + 1 + sizeof(zi_log->version_info);
3303 			if (valid_len >= needed_size) {
3304 				uint64_t tmpvar;
3305 
3306 				tmpvar = le64dec(zi_log->zoned_cap);
3307 				if (tmpvar & ATA_ZDI_CAP_VALID) {
3308 					if (tmpvar & ATA_ZDI_CAP_URSWRZ)
3309 						softc->zone_flags |=
3310 						    ADA_ZONE_FLAG_URSWRZ;
3311 					else
3312 						softc->zone_flags &=
3313 						    ~ADA_ZONE_FLAG_URSWRZ;
3314 				}
3315 				tmpvar = le64dec(zi_log->optimal_seq_zones);
3316 				if (tmpvar & ATA_ZDI_OPT_SEQ_VALID) {
3317 					softc->zone_flags |=
3318 					    ADA_ZONE_FLAG_OPT_SEQ_SET;
3319 					softc->optimal_seq_zones = (tmpvar &
3320 					    ATA_ZDI_OPT_SEQ_MASK);
3321 				} else {
3322 					softc->zone_flags &=
3323 					    ~ADA_ZONE_FLAG_OPT_SEQ_SET;
3324 					softc->optimal_seq_zones = 0;
3325 				}
3326 
3327 				tmpvar =le64dec(zi_log->optimal_nonseq_zones);
3328 				if (tmpvar & ATA_ZDI_OPT_NS_VALID) {
3329 					softc->zone_flags |=
3330 					    ADA_ZONE_FLAG_OPT_NONSEQ_SET;
3331 					softc->optimal_nonseq_zones =
3332 					    (tmpvar & ATA_ZDI_OPT_NS_MASK);
3333 				} else {
3334 					softc->zone_flags &=
3335 					    ~ADA_ZONE_FLAG_OPT_NONSEQ_SET;
3336 					softc->optimal_nonseq_zones = 0;
3337 				}
3338 
3339 				tmpvar = le64dec(zi_log->max_seq_req_zones);
3340 				if (tmpvar & ATA_ZDI_MAX_SEQ_VALID) {
3341 					softc->zone_flags |=
3342 					    ADA_ZONE_FLAG_MAX_SEQ_SET;
3343 					softc->max_seq_zones =
3344 					    (tmpvar & ATA_ZDI_MAX_SEQ_MASK);
3345 				} else {
3346 					softc->zone_flags &=
3347 					    ~ADA_ZONE_FLAG_MAX_SEQ_SET;
3348 					softc->max_seq_zones = 0;
3349 				}
3350 			}
3351 		} else {
3352 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3353 					 SF_RETRY_UA|SF_NO_PRINT);
3354 			if (error == ERESTART)
3355 				return;
3356 			else if (error != 0) {
3357 				softc->flags &= ~ADA_FLAG_CAN_ZONE;
3358 				softc->flags &= ~ADA_ZONE_FLAG_SET_MASK;
3359 
3360 				if ((done_ccb->ccb_h.status &
3361 				     CAM_DEV_QFRZN) != 0) {
3362 					/* Don't wedge this device's queue */
3363 					cam_release_devq(done_ccb->ccb_h.path,
3364 							 /*relsim_flags*/0,
3365 							 /*reduction*/0,
3366 							 /*timeout*/0,
3367 							 /*getcount_only*/0);
3368 				}
3369 			}
3370 		}
3371 		free(ataio->data_ptr, M_ATADA);
3372 
3373 		adaprobedone(periph, done_ccb);
3374 		return;
3375 	}
3376 	case ADA_CCB_DUMP:
3377 		/* No-op.  We're polling */
3378 		return;
3379 	default:
3380 		break;
3381 	}
3382 	xpt_release_ccb(done_ccb);
3383 }
3384 
3385 static int
3386 adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3387 {
3388 #ifdef CAM_IO_STATS
3389 	struct ada_softc *softc;
3390 	struct cam_periph *periph;
3391 
3392 	periph = xpt_path_periph(ccb->ccb_h.path);
3393 	softc = (struct ada_softc *)periph->softc;
3394 
3395 	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
3396 	case CAM_CMD_TIMEOUT:
3397 		softc->timeouts++;
3398 		break;
3399 	case CAM_REQ_ABORTED:
3400 	case CAM_REQ_CMP_ERR:
3401 	case CAM_REQ_TERMIO:
3402 	case CAM_UNREC_HBA_ERROR:
3403 	case CAM_DATA_RUN_ERR:
3404 	case CAM_ATA_STATUS_ERROR:
3405 		softc->errors++;
3406 		break;
3407 	default:
3408 		break;
3409 	}
3410 #endif
3411 
3412 	return(cam_periph_error(ccb, cam_flags, sense_flags));
3413 }
3414 
3415 static void
3416 adasetgeom(struct ada_softc *softc, struct ccb_getdev *cgd)
3417 {
3418 	struct disk_params *dp = &softc->params;
3419 	u_int64_t lbasize48;
3420 	u_int32_t lbasize;
3421 	u_int maxio, d_flags;
3422 
3423 	dp->secsize = ata_logical_sector_size(&cgd->ident_data);
3424 	if ((cgd->ident_data.atavalid & ATA_FLAG_54_58) &&
3425 	    cgd->ident_data.current_heads != 0 &&
3426 	    cgd->ident_data.current_sectors != 0) {
3427 		dp->heads = cgd->ident_data.current_heads;
3428 		dp->secs_per_track = cgd->ident_data.current_sectors;
3429 		dp->cylinders = cgd->ident_data.cylinders;
3430 		dp->sectors = (u_int32_t)cgd->ident_data.current_size_1 |
3431 			  ((u_int32_t)cgd->ident_data.current_size_2 << 16);
3432 	} else {
3433 		dp->heads = cgd->ident_data.heads;
3434 		dp->secs_per_track = cgd->ident_data.sectors;
3435 		dp->cylinders = cgd->ident_data.cylinders;
3436 		dp->sectors = cgd->ident_data.cylinders *
3437 			      (u_int32_t)(dp->heads * dp->secs_per_track);
3438 	}
3439 	lbasize = (u_int32_t)cgd->ident_data.lba_size_1 |
3440 		  ((u_int32_t)cgd->ident_data.lba_size_2 << 16);
3441 
3442 	/* use the 28bit LBA size if valid or bigger than the CHS mapping */
3443 	if (cgd->ident_data.cylinders == 16383 || dp->sectors < lbasize)
3444 		dp->sectors = lbasize;
3445 
3446 	/* use the 48bit LBA size if valid */
3447 	lbasize48 = ((u_int64_t)cgd->ident_data.lba_size48_1) |
3448 		    ((u_int64_t)cgd->ident_data.lba_size48_2 << 16) |
3449 		    ((u_int64_t)cgd->ident_data.lba_size48_3 << 32) |
3450 		    ((u_int64_t)cgd->ident_data.lba_size48_4 << 48);
3451 	if ((cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) &&
3452 	    lbasize48 > ATA_MAX_28BIT_LBA)
3453 		dp->sectors = lbasize48;
3454 
3455 	maxio = softc->cpi.maxio;		/* Honor max I/O size of SIM */
3456 	if (maxio == 0)
3457 		maxio = DFLTPHYS;	/* traditional default */
3458 	else if (maxio > MAXPHYS)
3459 		maxio = MAXPHYS;	/* for safety */
3460 	if (softc->flags & ADA_FLAG_CAN_48BIT)
3461 		maxio = min(maxio, 65536 * softc->params.secsize);
3462 	else					/* 28bit ATA command limit */
3463 		maxio = min(maxio, 256 * softc->params.secsize);
3464 	if (softc->quirks & ADA_Q_128KB)
3465 		maxio = min(maxio, 128 * 1024);
3466 	softc->disk->d_maxsize = maxio;
3467 	d_flags = DISKFLAG_DIRECT_COMPLETION | DISKFLAG_CANZONE;
3468 	if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE)
3469 		d_flags |= DISKFLAG_CANFLUSHCACHE;
3470 	if (softc->flags & ADA_FLAG_CAN_TRIM) {
3471 		d_flags |= DISKFLAG_CANDELETE;
3472 		softc->disk->d_delmaxsize = softc->params.secsize *
3473 		    ATA_DSM_RANGE_MAX * softc->trim_max_ranges;
3474 	} else if ((softc->flags & ADA_FLAG_CAN_CFA) &&
3475 	    !(softc->flags & ADA_FLAG_CAN_48BIT)) {
3476 		d_flags |= DISKFLAG_CANDELETE;
3477 		softc->disk->d_delmaxsize = 256 * softc->params.secsize;
3478 	} else
3479 		softc->disk->d_delmaxsize = maxio;
3480 	if ((softc->cpi.hba_misc & PIM_UNMAPPED) != 0) {
3481 		d_flags |= DISKFLAG_UNMAPPED_BIO;
3482 		softc->flags |= ADA_FLAG_UNMAPPEDIO;
3483 	}
3484 	softc->disk->d_flags = d_flags;
3485 	strlcpy(softc->disk->d_descr, cgd->ident_data.model,
3486 	    MIN(sizeof(softc->disk->d_descr), sizeof(cgd->ident_data.model)));
3487 	strlcpy(softc->disk->d_ident, cgd->ident_data.serial,
3488 	    MIN(sizeof(softc->disk->d_ident), sizeof(cgd->ident_data.serial)));
3489 
3490 	softc->disk->d_sectorsize = softc->params.secsize;
3491 	softc->disk->d_mediasize = (off_t)softc->params.sectors *
3492 	    softc->params.secsize;
3493 	if (ata_physical_sector_size(&cgd->ident_data) !=
3494 	    softc->params.secsize) {
3495 		softc->disk->d_stripesize =
3496 		    ata_physical_sector_size(&cgd->ident_data);
3497 		softc->disk->d_stripeoffset = (softc->disk->d_stripesize -
3498 		    ata_logical_sector_offset(&cgd->ident_data)) %
3499 		    softc->disk->d_stripesize;
3500 	} else if (softc->quirks & ADA_Q_4K) {
3501 		softc->disk->d_stripesize = 4096;
3502 		softc->disk->d_stripeoffset = 0;
3503 	}
3504 	softc->disk->d_fwsectors = softc->params.secs_per_track;
3505 	softc->disk->d_fwheads = softc->params.heads;
3506 	ata_disk_firmware_geom_adjust(softc->disk);
3507 	softc->disk->d_rotation_rate = cgd->ident_data.media_rotation_rate;
3508 	snprintf(softc->disk->d_attachment, sizeof(softc->disk->d_attachment),
3509 	    "%s%d", softc->cpi.dev_name, softc->cpi.unit_number);
3510 }
3511 
3512 static void
3513 adasendorderedtag(void *arg)
3514 {
3515 	struct ada_softc *softc = arg;
3516 
3517 	if (ada_send_ordered) {
3518 		if (softc->outstanding_cmds > 0) {
3519 			if ((softc->flags & ADA_FLAG_WAS_OTAG) == 0)
3520 				softc->flags |= ADA_FLAG_NEED_OTAG;
3521 			softc->flags &= ~ADA_FLAG_WAS_OTAG;
3522 		}
3523 	}
3524 	/* Queue us up again */
3525 	callout_reset(&softc->sendordered_c,
3526 	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
3527 	    adasendorderedtag, softc);
3528 }
3529 
3530 /*
3531  * Step through all ADA peripheral drivers, and if the device is still open,
3532  * sync the disk cache to physical media.
3533  */
3534 static void
3535 adaflush(void)
3536 {
3537 	struct cam_periph *periph;
3538 	struct ada_softc *softc;
3539 	union ccb *ccb;
3540 	int error;
3541 
3542 	CAM_PERIPH_FOREACH(periph, &adadriver) {
3543 		softc = (struct ada_softc *)periph->softc;
3544 		if (SCHEDULER_STOPPED()) {
3545 			/* If we paniced with the lock held, do not recurse. */
3546 			if (!cam_periph_owned(periph) &&
3547 			    (softc->flags & ADA_FLAG_OPEN)) {
3548 				adadump(softc->disk, NULL, 0, 0, 0);
3549 			}
3550 			continue;
3551 		}
3552 		cam_periph_lock(periph);
3553 		/*
3554 		 * We only sync the cache if the drive is still open, and
3555 		 * if the drive is capable of it..
3556 		 */
3557 		if (((softc->flags & ADA_FLAG_OPEN) == 0) ||
3558 		    (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) == 0) {
3559 			cam_periph_unlock(periph);
3560 			continue;
3561 		}
3562 
3563 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3564 		cam_fill_ataio(&ccb->ataio,
3565 				    0,
3566 				    NULL,
3567 				    CAM_DIR_NONE,
3568 				    0,
3569 				    NULL,
3570 				    0,
3571 				    ada_default_timeout*1000);
3572 		if (softc->flags & ADA_FLAG_CAN_48BIT)
3573 			ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
3574 		else
3575 			ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
3576 
3577 		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
3578 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
3579 		    softc->disk->d_devstat);
3580 		if (error != 0)
3581 			xpt_print(periph->path, "Synchronize cache failed\n");
3582 		xpt_release_ccb(ccb);
3583 		cam_periph_unlock(periph);
3584 	}
3585 }
3586 
3587 static void
3588 adaspindown(uint8_t cmd, int flags)
3589 {
3590 	struct cam_periph *periph;
3591 	struct ada_softc *softc;
3592 	struct ccb_ataio local_ccb;
3593 	int error;
3594 
3595 	CAM_PERIPH_FOREACH(periph, &adadriver) {
3596 		/* If we paniced with lock held - not recurse here. */
3597 		if (cam_periph_owned(periph))
3598 			continue;
3599 		cam_periph_lock(periph);
3600 		softc = (struct ada_softc *)periph->softc;
3601 		/*
3602 		 * We only spin-down the drive if it is capable of it..
3603 		 */
3604 		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
3605 			cam_periph_unlock(periph);
3606 			continue;
3607 		}
3608 
3609 		if (bootverbose)
3610 			xpt_print(periph->path, "spin-down\n");
3611 
3612 		memset(&local_ccb, 0, sizeof(local_ccb));
3613 		xpt_setup_ccb(&local_ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3614 		local_ccb.ccb_h.ccb_state = ADA_CCB_DUMP;
3615 
3616 		cam_fill_ataio(&local_ccb,
3617 				    0,
3618 				    NULL,
3619 				    CAM_DIR_NONE | flags,
3620 				    0,
3621 				    NULL,
3622 				    0,
3623 				    ada_default_timeout*1000);
3624 		ata_28bit_cmd(&local_ccb, cmd, 0, 0, 0);
3625 		error = cam_periph_runccb((union ccb *)&local_ccb, adaerror,
3626 		    /*cam_flags*/0, /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
3627 		    softc->disk->d_devstat);
3628 		if (error != 0)
3629 			xpt_print(periph->path, "Spin-down disk failed\n");
3630 		cam_periph_unlock(periph);
3631 	}
3632 }
3633 
3634 static void
3635 adashutdown(void *arg, int howto)
3636 {
3637 	int how;
3638 
3639 	adaflush();
3640 
3641 	/*
3642 	 * STANDBY IMMEDIATE saves any volatile data to the drive. It also spins
3643 	 * down hard drives. IDLE IMMEDIATE also saves the volatile data without
3644 	 * a spindown. We send the former when we expect to lose power soon. For
3645 	 * a warm boot, we send the latter to avoid a thundering herd of spinups
3646 	 * just after the kernel loads while probing. We have to do something to
3647 	 * flush the data because the BIOS in many systems resets the HBA
3648 	 * causing a COMINIT/COMRESET negotiation, which some drives interpret
3649 	 * as license to toss the volatile data, and others count as unclean
3650 	 * shutdown when in the Active PM state in SMART attributes.
3651 	 *
3652 	 * adaspindown will ensure that we don't send this to a drive that
3653 	 * doesn't support it.
3654 	 */
3655 	if (ada_spindown_shutdown != 0) {
3656 		how = (howto & (RB_HALT | RB_POWEROFF | RB_POWERCYCLE)) ?
3657 		    ATA_STANDBY_IMMEDIATE : ATA_IDLE_IMMEDIATE;
3658 		adaspindown(how, 0);
3659 	}
3660 }
3661 
3662 static void
3663 adasuspend(void *arg)
3664 {
3665 
3666 	adaflush();
3667 	/*
3668 	 * SLEEP also fushes any volatile data, like STANDBY IMEDIATE,
3669 	 * so we don't need to send it as well.
3670 	 */
3671 	if (ada_spindown_suspend != 0)
3672 		adaspindown(ATA_SLEEP, CAM_DEV_QFREEZE);
3673 }
3674 
3675 static void
3676 adaresume(void *arg)
3677 {
3678 	struct cam_periph *periph;
3679 	struct ada_softc *softc;
3680 
3681 	if (ada_spindown_suspend == 0)
3682 		return;
3683 
3684 	CAM_PERIPH_FOREACH(periph, &adadriver) {
3685 		cam_periph_lock(periph);
3686 		softc = (struct ada_softc *)periph->softc;
3687 		/*
3688 		 * We only spin-down the drive if it is capable of it..
3689 		 */
3690 		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
3691 			cam_periph_unlock(periph);
3692 			continue;
3693 		}
3694 
3695 		if (bootverbose)
3696 			xpt_print(periph->path, "resume\n");
3697 
3698 		/*
3699 		 * Drop freeze taken due to CAM_DEV_QFREEZE flag set on
3700 		 * sleep request.
3701 		 */
3702 		cam_release_devq(periph->path,
3703 			 /*relsim_flags*/0,
3704 			 /*openings*/0,
3705 			 /*timeout*/0,
3706 			 /*getcount_only*/0);
3707 
3708 		cam_periph_unlock(periph);
3709 	}
3710 }
3711 
3712 #endif /* _KERNEL */
3713