xref: /freebsd/sys/cam/ata/ata_da.c (revision c7d9dfe810d250db7ce58b4f27fe901dd9715901)
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	int		adazonesupsysctl(SYSCTL_HANDLER_ARGS);
840 static	void		adasysctlinit(void *context, int pending);
841 static	int		adagetattr(struct bio *bp);
842 static	void		adasetflags(struct ada_softc *softc,
843 				    struct ccb_getdev *cgd);
844 static void		adasetgeom(struct ada_softc *softc,
845 				   struct ccb_getdev *cgd);
846 static	periph_ctor_t	adaregister;
847 static	void		ada_dsmtrim(struct ada_softc *softc, struct bio *bp,
848 				    struct ccb_ataio *ataio);
849 static	void 		ada_cfaerase(struct ada_softc *softc, struct bio *bp,
850 				     struct ccb_ataio *ataio);
851 static	int		ada_zone_bio_to_ata(int disk_zone_cmd);
852 static	int		ada_zone_cmd(struct cam_periph *periph, union ccb *ccb,
853 				     struct bio *bp, int *queue_ccb);
854 static	periph_start_t	adastart;
855 static	void		adaprobedone(struct cam_periph *periph, union ccb *ccb);
856 static	void		adazonedone(struct cam_periph *periph, union ccb *ccb);
857 static	void		adadone(struct cam_periph *periph,
858 			       union ccb *done_ccb);
859 static  int		adaerror(union ccb *ccb, u_int32_t cam_flags,
860 				u_int32_t sense_flags);
861 static callout_func_t	adasendorderedtag;
862 static void		adashutdown(void *arg, int howto);
863 static void		adasuspend(void *arg);
864 static void		adaresume(void *arg);
865 
866 #ifndef ADA_DEFAULT_TIMEOUT
867 #define ADA_DEFAULT_TIMEOUT 30	/* Timeout in seconds */
868 #endif
869 
870 #ifndef	ADA_DEFAULT_RETRY
871 #define	ADA_DEFAULT_RETRY	4
872 #endif
873 
874 #ifndef	ADA_DEFAULT_SEND_ORDERED
875 #define	ADA_DEFAULT_SEND_ORDERED	1
876 #endif
877 
878 #ifndef	ADA_DEFAULT_SPINDOWN_SHUTDOWN
879 #define	ADA_DEFAULT_SPINDOWN_SHUTDOWN	1
880 #endif
881 
882 #ifndef	ADA_DEFAULT_SPINDOWN_SUSPEND
883 #define	ADA_DEFAULT_SPINDOWN_SUSPEND	1
884 #endif
885 
886 #ifndef	ADA_DEFAULT_READ_AHEAD
887 #define	ADA_DEFAULT_READ_AHEAD	1
888 #endif
889 
890 #ifndef	ADA_DEFAULT_WRITE_CACHE
891 #define	ADA_DEFAULT_WRITE_CACHE	1
892 #endif
893 
894 #define	ADA_RA	(softc->read_ahead >= 0 ? \
895 		 softc->read_ahead : ada_read_ahead)
896 #define	ADA_WC	(softc->write_cache >= 0 ? \
897 		 softc->write_cache : ada_write_cache)
898 
899 /*
900  * Most platforms map firmware geometry to actual, but some don't.  If
901  * not overridden, default to nothing.
902  */
903 #ifndef ata_disk_firmware_geom_adjust
904 #define	ata_disk_firmware_geom_adjust(disk)
905 #endif
906 
907 static int ada_retry_count = ADA_DEFAULT_RETRY;
908 static int ada_default_timeout = ADA_DEFAULT_TIMEOUT;
909 static int ada_send_ordered = ADA_DEFAULT_SEND_ORDERED;
910 static int ada_spindown_shutdown = ADA_DEFAULT_SPINDOWN_SHUTDOWN;
911 static int ada_spindown_suspend = ADA_DEFAULT_SPINDOWN_SUSPEND;
912 static int ada_read_ahead = ADA_DEFAULT_READ_AHEAD;
913 static int ada_write_cache = ADA_DEFAULT_WRITE_CACHE;
914 static int ada_enable_biospeedup = 1;
915 
916 static SYSCTL_NODE(_kern_cam, OID_AUTO, ada, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
917     "CAM Direct Access Disk driver");
918 SYSCTL_INT(_kern_cam_ada, OID_AUTO, retry_count, CTLFLAG_RWTUN,
919            &ada_retry_count, 0, "Normal I/O retry count");
920 SYSCTL_INT(_kern_cam_ada, OID_AUTO, default_timeout, CTLFLAG_RWTUN,
921            &ada_default_timeout, 0, "Normal I/O timeout (in seconds)");
922 SYSCTL_INT(_kern_cam_ada, OID_AUTO, send_ordered, CTLFLAG_RWTUN,
923            &ada_send_ordered, 0, "Send Ordered Tags");
924 SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_shutdown, CTLFLAG_RWTUN,
925            &ada_spindown_shutdown, 0, "Spin down upon shutdown");
926 SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_suspend, CTLFLAG_RWTUN,
927            &ada_spindown_suspend, 0, "Spin down upon suspend");
928 SYSCTL_INT(_kern_cam_ada, OID_AUTO, read_ahead, CTLFLAG_RWTUN,
929            &ada_read_ahead, 0, "Enable disk read-ahead");
930 SYSCTL_INT(_kern_cam_ada, OID_AUTO, write_cache, CTLFLAG_RWTUN,
931            &ada_write_cache, 0, "Enable disk write cache");
932 SYSCTL_INT(_kern_cam_ada, OID_AUTO, enable_biospeedup, CTLFLAG_RDTUN,
933 	   &ada_enable_biospeedup, 0, "Enable BIO_SPEEDUP processing");
934 
935 /*
936  * ADA_ORDEREDTAG_INTERVAL determines how often, relative
937  * to the default timeout, we check to see whether an ordered
938  * tagged transaction is appropriate to prevent simple tag
939  * starvation.  Since we'd like to ensure that there is at least
940  * 1/2 of the timeout length left for a starved transaction to
941  * complete after we've sent an ordered tag, we must poll at least
942  * four times in every timeout period.  This takes care of the worst
943  * case where a starved transaction starts during an interval that
944  * meets the requirement "don't send an ordered tag" test so it takes
945  * us two intervals to determine that a tag must be sent.
946  */
947 #ifndef ADA_ORDEREDTAG_INTERVAL
948 #define ADA_ORDEREDTAG_INTERVAL 4
949 #endif
950 
951 static struct periph_driver adadriver =
952 {
953 	adainit, "ada",
954 	TAILQ_HEAD_INITIALIZER(adadriver.units), /* generation */ 0
955 };
956 
957 static int adadeletemethodsysctl(SYSCTL_HANDLER_ARGS);
958 
959 PERIPHDRIVER_DECLARE(ada, adadriver);
960 
961 static MALLOC_DEFINE(M_ATADA, "ata_da", "ata_da buffers");
962 
963 static int
964 adaopen(struct disk *dp)
965 {
966 	struct cam_periph *periph;
967 	struct ada_softc *softc;
968 	int error;
969 
970 	periph = (struct cam_periph *)dp->d_drv1;
971 	if (cam_periph_acquire(periph) != 0) {
972 		return(ENXIO);
973 	}
974 
975 	cam_periph_lock(periph);
976 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
977 		cam_periph_unlock(periph);
978 		cam_periph_release(periph);
979 		return (error);
980 	}
981 
982 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
983 	    ("adaopen\n"));
984 
985 	softc = (struct ada_softc *)periph->softc;
986 	softc->flags |= ADA_FLAG_OPEN;
987 
988 	cam_periph_unhold(periph);
989 	cam_periph_unlock(periph);
990 	return (0);
991 }
992 
993 static int
994 adaclose(struct disk *dp)
995 {
996 	struct	cam_periph *periph;
997 	struct	ada_softc *softc;
998 	union ccb *ccb;
999 	int error;
1000 
1001 	periph = (struct cam_periph *)dp->d_drv1;
1002 	softc = (struct ada_softc *)periph->softc;
1003 	cam_periph_lock(periph);
1004 
1005 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1006 	    ("adaclose\n"));
1007 
1008 	/* We only sync the cache if the drive is capable of it. */
1009 	if ((softc->flags & ADA_FLAG_DIRTY) != 0 &&
1010 	    (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) != 0 &&
1011 	    (periph->flags & CAM_PERIPH_INVALID) == 0 &&
1012 	    cam_periph_hold(periph, PRIBIO) == 0) {
1013 
1014 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1015 		cam_fill_ataio(&ccb->ataio,
1016 				    1,
1017 				    NULL,
1018 				    CAM_DIR_NONE,
1019 				    0,
1020 				    NULL,
1021 				    0,
1022 				    ada_default_timeout*1000);
1023 
1024 		if (softc->flags & ADA_FLAG_CAN_48BIT)
1025 			ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
1026 		else
1027 			ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
1028 		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
1029 		    /*sense_flags*/0, softc->disk->d_devstat);
1030 
1031 		if (error != 0)
1032 			xpt_print(periph->path, "Synchronize cache failed\n");
1033 		softc->flags &= ~ADA_FLAG_DIRTY;
1034 		xpt_release_ccb(ccb);
1035 		cam_periph_unhold(periph);
1036 	}
1037 
1038 	softc->flags &= ~ADA_FLAG_OPEN;
1039 
1040 	while (softc->refcount != 0)
1041 		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "adaclose", 1);
1042 	cam_periph_unlock(periph);
1043 	cam_periph_release(periph);
1044 	return (0);
1045 }
1046 
1047 static void
1048 adaschedule(struct cam_periph *periph)
1049 {
1050 	struct ada_softc *softc = (struct ada_softc *)periph->softc;
1051 
1052 	if (softc->state != ADA_STATE_NORMAL)
1053 		return;
1054 
1055 	cam_iosched_schedule(softc->cam_iosched, periph);
1056 }
1057 
1058 /*
1059  * Actually translate the requested transfer into one the physical driver
1060  * can understand.  The transfer is described by a buf and will include
1061  * only one physical transfer.
1062  */
1063 static void
1064 adastrategy(struct bio *bp)
1065 {
1066 	struct cam_periph *periph;
1067 	struct ada_softc *softc;
1068 
1069 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1070 	softc = (struct ada_softc *)periph->softc;
1071 
1072 	cam_periph_lock(periph);
1073 
1074 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastrategy(%p)\n", bp));
1075 
1076 	/*
1077 	 * If the device has been made invalid, error out
1078 	 */
1079 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
1080 		cam_periph_unlock(periph);
1081 		biofinish(bp, NULL, ENXIO);
1082 		return;
1083 	}
1084 
1085 	/*
1086 	 * Zone commands must be ordered, because they can depend on the
1087 	 * effects of previously issued commands, and they may affect
1088 	 * commands after them.
1089 	 */
1090 	if (bp->bio_cmd == BIO_ZONE)
1091 		bp->bio_flags |= BIO_ORDERED;
1092 
1093 	/*
1094 	 * Place it in the queue of disk activities for this disk
1095 	 */
1096 	cam_iosched_queue_work(softc->cam_iosched, bp);
1097 
1098 	/*
1099 	 * Schedule ourselves for performing the work.
1100 	 */
1101 	adaschedule(periph);
1102 	cam_periph_unlock(periph);
1103 
1104 	return;
1105 }
1106 
1107 static int
1108 adadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
1109 {
1110 	struct	    cam_periph *periph;
1111 	struct	    ada_softc *softc;
1112 	u_int	    secsize;
1113 	struct	    ccb_ataio ataio;
1114 	struct	    disk *dp;
1115 	uint64_t    lba;
1116 	uint16_t    count;
1117 	int	    error = 0;
1118 
1119 	dp = arg;
1120 	periph = dp->d_drv1;
1121 	softc = (struct ada_softc *)periph->softc;
1122 	secsize = softc->params.secsize;
1123 	lba = offset / secsize;
1124 	count = length / secsize;
1125 	if ((periph->flags & CAM_PERIPH_INVALID) != 0)
1126 		return (ENXIO);
1127 
1128 	memset(&ataio, 0, sizeof(ataio));
1129 	if (length > 0) {
1130 		xpt_setup_ccb(&ataio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1131 		ataio.ccb_h.ccb_state = ADA_CCB_DUMP;
1132 		cam_fill_ataio(&ataio,
1133 		    0,
1134 		    NULL,
1135 		    CAM_DIR_OUT,
1136 		    0,
1137 		    (u_int8_t *) virtual,
1138 		    length,
1139 		    ada_default_timeout*1000);
1140 		if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
1141 		    (lba + count >= ATA_MAX_28BIT_LBA ||
1142 		    count >= 256)) {
1143 			ata_48bit_cmd(&ataio, ATA_WRITE_DMA48,
1144 			    0, lba, count);
1145 		} else {
1146 			ata_28bit_cmd(&ataio, ATA_WRITE_DMA,
1147 			    0, lba, count);
1148 		}
1149 		error = cam_periph_runccb((union ccb *)&ataio, adaerror,
1150 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1151 		if (error != 0)
1152 			printf("Aborting dump due to I/O error.\n");
1153 
1154 		return (error);
1155 	}
1156 
1157 	if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) {
1158 		xpt_setup_ccb(&ataio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1159 
1160 		/*
1161 		 * Tell the drive to flush its internal cache. if we
1162 		 * can't flush in 5s we have big problems. No need to
1163 		 * wait the default 60s to detect problems.
1164 		 */
1165 		ataio.ccb_h.ccb_state = ADA_CCB_DUMP;
1166 		cam_fill_ataio(&ataio,
1167 				    0,
1168 				    NULL,
1169 				    CAM_DIR_NONE,
1170 				    0,
1171 				    NULL,
1172 				    0,
1173 				    5*1000);
1174 
1175 		if (softc->flags & ADA_FLAG_CAN_48BIT)
1176 			ata_48bit_cmd(&ataio, ATA_FLUSHCACHE48, 0, 0, 0);
1177 		else
1178 			ata_28bit_cmd(&ataio, ATA_FLUSHCACHE, 0, 0, 0);
1179 		error = cam_periph_runccb((union ccb *)&ataio, adaerror,
1180 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1181 		if (error != 0)
1182 			xpt_print(periph->path, "Synchronize cache failed\n");
1183 	}
1184 	return (error);
1185 }
1186 
1187 static void
1188 adainit(void)
1189 {
1190 	cam_status status;
1191 
1192 	/*
1193 	 * Install a global async callback.  This callback will
1194 	 * receive async callbacks like "new device found".
1195 	 */
1196 	status = xpt_register_async(AC_FOUND_DEVICE, adaasync, NULL, NULL);
1197 
1198 	if (status != CAM_REQ_CMP) {
1199 		printf("ada: Failed to attach master async callback "
1200 		       "due to status 0x%x!\n", status);
1201 	} else if (ada_send_ordered) {
1202 
1203 		/* Register our event handlers */
1204 		if ((EVENTHANDLER_REGISTER(power_suspend, adasuspend,
1205 					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
1206 		    printf("adainit: power event registration failed!\n");
1207 		if ((EVENTHANDLER_REGISTER(power_resume, adaresume,
1208 					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
1209 		    printf("adainit: power event registration failed!\n");
1210 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, adashutdown,
1211 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1212 		    printf("adainit: shutdown event registration failed!\n");
1213 	}
1214 }
1215 
1216 /*
1217  * Callback from GEOM, called when it has finished cleaning up its
1218  * resources.
1219  */
1220 static void
1221 adadiskgonecb(struct disk *dp)
1222 {
1223 	struct cam_periph *periph;
1224 
1225 	periph = (struct cam_periph *)dp->d_drv1;
1226 
1227 	cam_periph_release(periph);
1228 }
1229 
1230 static void
1231 adaoninvalidate(struct cam_periph *periph)
1232 {
1233 	struct ada_softc *softc;
1234 
1235 	softc = (struct ada_softc *)periph->softc;
1236 
1237 	/*
1238 	 * De-register any async callbacks.
1239 	 */
1240 	xpt_register_async(0, adaasync, periph, periph->path);
1241 #ifdef CAM_IO_STATS
1242 	softc->invalidations++;
1243 #endif
1244 
1245 	/*
1246 	 * Return all queued I/O with ENXIO.
1247 	 * XXX Handle any transactions queued to the card
1248 	 *     with XPT_ABORT_CCB.
1249 	 */
1250 	cam_iosched_flush(softc->cam_iosched, NULL, ENXIO);
1251 
1252 	disk_gone(softc->disk);
1253 }
1254 
1255 static void
1256 adacleanup(struct cam_periph *periph)
1257 {
1258 	struct ada_softc *softc;
1259 
1260 	softc = (struct ada_softc *)periph->softc;
1261 
1262 	cam_periph_unlock(periph);
1263 
1264 	cam_iosched_fini(softc->cam_iosched);
1265 
1266 	/*
1267 	 * If we can't free the sysctl tree, oh well...
1268 	 */
1269 	if ((softc->flags & ADA_FLAG_SCTX_INIT) != 0) {
1270 #ifdef CAM_IO_STATS
1271 		if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0)
1272 			xpt_print(periph->path,
1273 			    "can't remove sysctl stats context\n");
1274 #endif
1275 		if (sysctl_ctx_free(&softc->sysctl_ctx) != 0)
1276 			xpt_print(periph->path,
1277 			    "can't remove sysctl context\n");
1278 	}
1279 
1280 	disk_destroy(softc->disk);
1281 	callout_drain(&softc->sendordered_c);
1282 	free(softc, M_DEVBUF);
1283 	cam_periph_lock(periph);
1284 }
1285 
1286 static void
1287 adasetdeletemethod(struct ada_softc *softc)
1288 {
1289 
1290 	if (softc->flags & ADA_FLAG_CAN_NCQ_TRIM)
1291 		softc->delete_method = ADA_DELETE_NCQ_DSM_TRIM;
1292 	else if (softc->flags & ADA_FLAG_CAN_TRIM)
1293 		softc->delete_method = ADA_DELETE_DSM_TRIM;
1294 	else if ((softc->flags & ADA_FLAG_CAN_CFA) && !(softc->flags & ADA_FLAG_CAN_48BIT))
1295 		softc->delete_method = ADA_DELETE_CFA_ERASE;
1296 	else
1297 		softc->delete_method = ADA_DELETE_NONE;
1298 }
1299 
1300 static void
1301 adaasync(void *callback_arg, u_int32_t code,
1302 	struct cam_path *path, void *arg)
1303 {
1304 	struct ccb_getdev cgd;
1305 	struct cam_periph *periph;
1306 	struct ada_softc *softc;
1307 
1308 	periph = (struct cam_periph *)callback_arg;
1309 	switch (code) {
1310 	case AC_FOUND_DEVICE:
1311 	{
1312 		struct ccb_getdev *cgd;
1313 		cam_status status;
1314 
1315 		cgd = (struct ccb_getdev *)arg;
1316 		if (cgd == NULL)
1317 			break;
1318 
1319 		if (cgd->protocol != PROTO_ATA)
1320 			break;
1321 
1322 		/*
1323 		 * Allocate a peripheral instance for
1324 		 * this device and start the probe
1325 		 * process.
1326 		 */
1327 		status = cam_periph_alloc(adaregister, adaoninvalidate,
1328 					  adacleanup, adastart,
1329 					  "ada", CAM_PERIPH_BIO,
1330 					  path, adaasync,
1331 					  AC_FOUND_DEVICE, cgd);
1332 
1333 		if (status != CAM_REQ_CMP
1334 		 && status != CAM_REQ_INPROG)
1335 			printf("adaasync: Unable to attach to new device "
1336 				"due to status 0x%x\n", status);
1337 		break;
1338 	}
1339 	case AC_GETDEV_CHANGED:
1340 	{
1341 		softc = (struct ada_softc *)periph->softc;
1342 		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1343 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1344 		xpt_action((union ccb *)&cgd);
1345 
1346 		/*
1347 		 * Update our information based on the new Identify data.
1348 		 */
1349 		adasetflags(softc, &cgd);
1350 		adasetgeom(softc, &cgd);
1351 		disk_resize(softc->disk, M_NOWAIT);
1352 
1353 		cam_periph_async(periph, code, path, arg);
1354 		break;
1355 	}
1356 	case AC_ADVINFO_CHANGED:
1357 	{
1358 		uintptr_t buftype;
1359 
1360 		buftype = (uintptr_t)arg;
1361 		if (buftype == CDAI_TYPE_PHYS_PATH) {
1362 			struct ada_softc *softc;
1363 
1364 			softc = periph->softc;
1365 			disk_attr_changed(softc->disk, "GEOM::physpath",
1366 					  M_NOWAIT);
1367 		}
1368 		break;
1369 	}
1370 	case AC_SENT_BDR:
1371 	case AC_BUS_RESET:
1372 	{
1373 		softc = (struct ada_softc *)periph->softc;
1374 		cam_periph_async(periph, code, path, arg);
1375 		if (softc->state != ADA_STATE_NORMAL)
1376 			break;
1377 		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1378 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1379 		xpt_action((union ccb *)&cgd);
1380 		if (ADA_RA >= 0 && softc->flags & ADA_FLAG_CAN_RAHEAD)
1381 			softc->state = ADA_STATE_RAHEAD;
1382 		else if (ADA_WC >= 0 && softc->flags & ADA_FLAG_CAN_WCACHE)
1383 			softc->state = ADA_STATE_WCACHE;
1384 		else if ((softc->flags & ADA_FLAG_CAN_LOG)
1385 		      && (softc->zone_mode != ADA_ZONE_NONE))
1386 			softc->state = ADA_STATE_LOGDIR;
1387 		else
1388 		    break;
1389 		if (cam_periph_acquire(periph) != 0)
1390 			softc->state = ADA_STATE_NORMAL;
1391 		else
1392 			xpt_schedule(periph, CAM_PRIORITY_DEV);
1393 	}
1394 	default:
1395 		cam_periph_async(periph, code, path, arg);
1396 		break;
1397 	}
1398 }
1399 
1400 static int
1401 adazonemodesysctl(SYSCTL_HANDLER_ARGS)
1402 {
1403 	char tmpbuf[40];
1404 	struct ada_softc *softc;
1405 	int error;
1406 
1407 	softc = (struct ada_softc *)arg1;
1408 
1409 	switch (softc->zone_mode) {
1410 	case ADA_ZONE_DRIVE_MANAGED:
1411 		snprintf(tmpbuf, sizeof(tmpbuf), "Drive Managed");
1412 		break;
1413 	case ADA_ZONE_HOST_AWARE:
1414 		snprintf(tmpbuf, sizeof(tmpbuf), "Host Aware");
1415 		break;
1416 	case ADA_ZONE_HOST_MANAGED:
1417 		snprintf(tmpbuf, sizeof(tmpbuf), "Host Managed");
1418 		break;
1419 	case ADA_ZONE_NONE:
1420 	default:
1421 		snprintf(tmpbuf, sizeof(tmpbuf), "Not Zoned");
1422 		break;
1423 	}
1424 
1425 	error = sysctl_handle_string(oidp, tmpbuf, sizeof(tmpbuf), req);
1426 
1427 	return (error);
1428 }
1429 
1430 static int
1431 adazonesupsysctl(SYSCTL_HANDLER_ARGS)
1432 {
1433 	char tmpbuf[180];
1434 	struct ada_softc *softc;
1435 	struct sbuf sb;
1436 	int error, first;
1437 	unsigned int i;
1438 
1439 	softc = (struct ada_softc *)arg1;
1440 
1441 	error = 0;
1442 	first = 1;
1443 	sbuf_new(&sb, tmpbuf, sizeof(tmpbuf), 0);
1444 
1445 	for (i = 0; i < sizeof(ada_zone_desc_table) /
1446 	     sizeof(ada_zone_desc_table[0]); i++) {
1447 		if (softc->zone_flags & ada_zone_desc_table[i].value) {
1448 			if (first == 0)
1449 				sbuf_printf(&sb, ", ");
1450 			else
1451 				first = 0;
1452 			sbuf_cat(&sb, ada_zone_desc_table[i].desc);
1453 		}
1454 	}
1455 
1456 	if (first == 1)
1457 		sbuf_printf(&sb, "None");
1458 
1459 	sbuf_finish(&sb);
1460 
1461 	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
1462 
1463 	return (error);
1464 }
1465 
1466 
1467 static void
1468 adasysctlinit(void *context, int pending)
1469 {
1470 	struct cam_periph *periph;
1471 	struct ada_softc *softc;
1472 	char tmpstr[32], tmpstr2[16];
1473 
1474 	periph = (struct cam_periph *)context;
1475 
1476 	/* periph was held for us when this task was enqueued */
1477 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
1478 		cam_periph_release(periph);
1479 		return;
1480 	}
1481 
1482 	softc = (struct ada_softc *)periph->softc;
1483 	snprintf(tmpstr, sizeof(tmpstr), "CAM ADA unit %d",periph->unit_number);
1484 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1485 
1486 	sysctl_ctx_init(&softc->sysctl_ctx);
1487 	softc->flags |= ADA_FLAG_SCTX_INIT;
1488 	softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
1489 		SYSCTL_STATIC_CHILDREN(_kern_cam_ada), OID_AUTO, tmpstr2,
1490 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr, "device_index");
1491 	if (softc->sysctl_tree == NULL) {
1492 		printf("adasysctlinit: unable to allocate sysctl tree\n");
1493 		cam_periph_release(periph);
1494 		return;
1495 	}
1496 
1497 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1498 		OID_AUTO, "delete_method",
1499 		CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1500 		softc, 0, adadeletemethodsysctl, "A",
1501 		"BIO_DELETE execution method");
1502 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1503 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1504 		"trim_count", CTLFLAG_RD, &softc->trim_count,
1505 		"Total number of dsm commands sent");
1506 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1507 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1508 		"trim_ranges", CTLFLAG_RD, &softc->trim_ranges,
1509 		"Total number of ranges in dsm commands");
1510 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1511 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1512 		"trim_lbas", CTLFLAG_RD, &softc->trim_lbas,
1513 		"Total lbas in the dsm commands sent");
1514 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1515 		OID_AUTO, "read_ahead", CTLFLAG_RW | CTLFLAG_MPSAFE,
1516 		&softc->read_ahead, 0, "Enable disk read ahead.");
1517 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1518 		OID_AUTO, "write_cache", CTLFLAG_RW | CTLFLAG_MPSAFE,
1519 		&softc->write_cache, 0, "Enable disk write cache.");
1520 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1521 		OID_AUTO, "zone_mode",
1522 		CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
1523 		softc, 0, adazonemodesysctl, "A",
1524 		"Zone Mode");
1525 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1526 		OID_AUTO, "zone_support",
1527 		CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
1528 		softc, 0, adazonesupsysctl, "A",
1529 		"Zone Support");
1530 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1531 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1532 		"optimal_seq_zones", CTLFLAG_RD, &softc->optimal_seq_zones,
1533 		"Optimal Number of Open Sequential Write Preferred Zones");
1534 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1535 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1536 		"optimal_nonseq_zones", CTLFLAG_RD,
1537 		&softc->optimal_nonseq_zones,
1538 		"Optimal Number of Non-Sequentially Written Sequential Write "
1539 		"Preferred Zones");
1540 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1541 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1542 		"max_seq_zones", CTLFLAG_RD, &softc->max_seq_zones,
1543 		"Maximum Number of Open Sequential Write Required Zones");
1544 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1545 	    OID_AUTO, "flags", CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1546 	    softc, 0, adaflagssysctl, "A",
1547 	    "Flags for drive");
1548 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1549 	    OID_AUTO, "unmapped_io", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
1550 	    &softc->flags, (u_int)ADA_FLAG_UNMAPPEDIO, adabitsysctl, "I",
1551 	    "Unmapped I/O support *DEPRECATED* gone in FreeBSD 14");
1552 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1553 	    OID_AUTO, "rotating", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
1554 	    &softc->flags, (u_int)ADA_FLAG_ROTATING, adabitsysctl, "I",
1555 	    "Rotating media *DEPRECATED* gone in FreeBSD 14");
1556 
1557 #ifdef CAM_TEST_FAILURE
1558 	/*
1559 	 * Add a 'door bell' sysctl which allows one to set it from userland
1560 	 * and cause something bad to happen.  For the moment, we only allow
1561 	 * whacking the next read or write.
1562 	 */
1563 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1564 		OID_AUTO, "force_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1565 		&softc->force_read_error, 0,
1566 		"Force a read error for the next N reads.");
1567 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1568 		OID_AUTO, "force_write_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1569 		&softc->force_write_error, 0,
1570 		"Force a write error for the next N writes.");
1571 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1572 		OID_AUTO, "periodic_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1573 		&softc->periodic_read_error, 0,
1574 		"Force a read error every N reads (don't set too low).");
1575 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1576 		OID_AUTO, "invalidate", CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
1577 		periph, 0, cam_periph_invalidate_sysctl, "I",
1578 		"Write 1 to invalidate the drive immediately");
1579 #endif
1580 
1581 #ifdef CAM_IO_STATS
1582 	softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx,
1583 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats",
1584 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "Statistics");
1585 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
1586 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
1587 		OID_AUTO, "timeouts", CTLFLAG_RD | CTLFLAG_MPSAFE,
1588 		&softc->timeouts, 0,
1589 		"Device timeouts reported by the SIM");
1590 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
1591 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
1592 		OID_AUTO, "errors", CTLFLAG_RD | CTLFLAG_MPSAFE,
1593 		&softc->errors, 0,
1594 		"Transport errors reported by the SIM.");
1595 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
1596 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
1597 		OID_AUTO, "pack_invalidations", CTLFLAG_RD | CTLFLAG_MPSAFE,
1598 		&softc->invalidations, 0,
1599 		"Device pack invalidations.");
1600 #endif
1601 
1602 	cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx,
1603 	    softc->sysctl_tree);
1604 
1605 	cam_periph_release(periph);
1606 }
1607 
1608 static int
1609 adagetattr(struct bio *bp)
1610 {
1611 	int ret;
1612 	struct cam_periph *periph;
1613 
1614 	if (g_handleattr_int(bp, "GEOM::canspeedup", ada_enable_biospeedup))
1615 		return (EJUSTRETURN);
1616 
1617 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1618 	cam_periph_lock(periph);
1619 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1620 	    periph->path);
1621 	cam_periph_unlock(periph);
1622 	if (ret == 0)
1623 		bp->bio_completed = bp->bio_length;
1624 	return ret;
1625 }
1626 
1627 static int
1628 adadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
1629 {
1630 	char buf[16];
1631 	const char *p;
1632 	struct ada_softc *softc;
1633 	int i, error, value, methods;
1634 
1635 	softc = (struct ada_softc *)arg1;
1636 
1637 	value = softc->delete_method;
1638 	if (value < 0 || value > ADA_DELETE_MAX)
1639 		p = "UNKNOWN";
1640 	else
1641 		p = ada_delete_method_names[value];
1642 	strncpy(buf, p, sizeof(buf));
1643 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1644 	if (error != 0 || req->newptr == NULL)
1645 		return (error);
1646 	methods = 1 << ADA_DELETE_DISABLE;
1647 	if ((softc->flags & ADA_FLAG_CAN_CFA) &&
1648 	    !(softc->flags & ADA_FLAG_CAN_48BIT))
1649 		methods |= 1 << ADA_DELETE_CFA_ERASE;
1650 	if (softc->flags & ADA_FLAG_CAN_TRIM)
1651 		methods |= 1 << ADA_DELETE_DSM_TRIM;
1652 	if (softc->flags & ADA_FLAG_CAN_NCQ_TRIM)
1653 		methods |= 1 << ADA_DELETE_NCQ_DSM_TRIM;
1654 	for (i = 0; i <= ADA_DELETE_MAX; i++) {
1655 		if (!(methods & (1 << i)) ||
1656 		    strcmp(buf, ada_delete_method_names[i]) != 0)
1657 			continue;
1658 		softc->delete_method = i;
1659 		return (0);
1660 	}
1661 	return (EINVAL);
1662 }
1663 
1664 static int
1665 adabitsysctl(SYSCTL_HANDLER_ARGS)
1666 {
1667 	u_int *flags = arg1;
1668 	u_int test = arg2;
1669 	int tmpout, error;
1670 
1671 	tmpout = !!(*flags & test);
1672 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1673 	if (error || !req->newptr)
1674 		return (error);
1675 
1676 	return (EPERM);
1677 }
1678 
1679 static int
1680 adaflagssysctl(SYSCTL_HANDLER_ARGS)
1681 {
1682 	struct sbuf sbuf;
1683 	struct ada_softc *softc = arg1;
1684 	int error;
1685 
1686 	sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
1687 	if (softc->flags != 0)
1688 		sbuf_printf(&sbuf, "0x%b", (unsigned)softc->flags, ADA_FLAG_STRING);
1689 	else
1690 		sbuf_printf(&sbuf, "0");
1691 	error = sbuf_finish(&sbuf);
1692 	sbuf_delete(&sbuf);
1693 
1694 	return (error);
1695 }
1696 
1697 static void
1698 adasetflags(struct ada_softc *softc, struct ccb_getdev *cgd)
1699 {
1700 	if ((cgd->ident_data.capabilities1 & ATA_SUPPORT_DMA) &&
1701 	    (cgd->inq_flags & SID_DMA))
1702 		softc->flags |= ADA_FLAG_CAN_DMA;
1703 	else
1704 		softc->flags &= ~ADA_FLAG_CAN_DMA;
1705 
1706 	if (cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) {
1707 		softc->flags |= ADA_FLAG_CAN_48BIT;
1708 		if (cgd->inq_flags & SID_DMA48)
1709 			softc->flags |= ADA_FLAG_CAN_DMA48;
1710 		else
1711 			softc->flags &= ~ADA_FLAG_CAN_DMA48;
1712 	} else
1713 		softc->flags &= ~(ADA_FLAG_CAN_48BIT | ADA_FLAG_CAN_DMA48);
1714 
1715 	if (cgd->ident_data.support.command2 & ATA_SUPPORT_FLUSHCACHE)
1716 		softc->flags |= ADA_FLAG_CAN_FLUSHCACHE;
1717 	else
1718 		softc->flags &= ~ADA_FLAG_CAN_FLUSHCACHE;
1719 
1720 	if (cgd->ident_data.support.command1 & ATA_SUPPORT_POWERMGT)
1721 		softc->flags |= ADA_FLAG_CAN_POWERMGT;
1722 	else
1723 		softc->flags &= ~ADA_FLAG_CAN_POWERMGT;
1724 
1725 	if ((cgd->ident_data.satacapabilities & ATA_SUPPORT_NCQ) &&
1726 	    (cgd->inq_flags & SID_DMA) && (cgd->inq_flags & SID_CmdQue))
1727 		softc->flags |= ADA_FLAG_CAN_NCQ;
1728 	else
1729 		softc->flags &= ~ADA_FLAG_CAN_NCQ;
1730 
1731 	if ((cgd->ident_data.support_dsm & ATA_SUPPORT_DSM_TRIM) &&
1732 	    (cgd->inq_flags & SID_DMA) &&
1733 	    (softc->quirks & ADA_Q_NO_TRIM) == 0) {
1734 		softc->flags |= ADA_FLAG_CAN_TRIM;
1735 		softc->trim_max_ranges = TRIM_MAX_RANGES;
1736 		if (cgd->ident_data.max_dsm_blocks != 0) {
1737 			softc->trim_max_ranges =
1738 			    min(cgd->ident_data.max_dsm_blocks *
1739 				ATA_DSM_BLK_RANGES, softc->trim_max_ranges);
1740 		}
1741 		/*
1742 		 * If we can do RCVSND_FPDMA_QUEUED commands, we may be able
1743 		 * to do NCQ trims, if we support trims at all. We also need
1744 		 * support from the SIM to do things properly. Perhaps we
1745 		 * should look at log 13 dword 0 bit 0 and dword 1 bit 0 are
1746 		 * set too...
1747 		 */
1748 		if ((softc->quirks & ADA_Q_NCQ_TRIM_BROKEN) == 0 &&
1749 		    (softc->flags & ADA_FLAG_PIM_ATA_EXT) != 0 &&
1750 		    (cgd->ident_data.satacapabilities2 &
1751 		     ATA_SUPPORT_RCVSND_FPDMA_QUEUED) != 0 &&
1752 		    (softc->flags & ADA_FLAG_CAN_TRIM) != 0)
1753 			softc->flags |= ADA_FLAG_CAN_NCQ_TRIM;
1754 		else
1755 			softc->flags &= ~ADA_FLAG_CAN_NCQ_TRIM;
1756 	} else
1757 		softc->flags &= ~(ADA_FLAG_CAN_TRIM | ADA_FLAG_CAN_NCQ_TRIM);
1758 
1759 	if (cgd->ident_data.support.command2 & ATA_SUPPORT_CFA)
1760 		softc->flags |= ADA_FLAG_CAN_CFA;
1761 	else
1762 		softc->flags &= ~ADA_FLAG_CAN_CFA;
1763 
1764 	/*
1765 	 * Now that we've set the appropriate flags, setup the delete
1766 	 * method.
1767 	 */
1768 	adasetdeletemethod(softc);
1769 
1770 	if ((cgd->ident_data.support.extension & ATA_SUPPORT_GENLOG)
1771 	 && ((softc->quirks & ADA_Q_LOG_BROKEN) == 0))
1772 		softc->flags |= ADA_FLAG_CAN_LOG;
1773 	else
1774 		softc->flags &= ~ADA_FLAG_CAN_LOG;
1775 
1776 	if ((cgd->ident_data.support3 & ATA_SUPPORT_ZONE_MASK) ==
1777 	     ATA_SUPPORT_ZONE_HOST_AWARE)
1778 		softc->zone_mode = ADA_ZONE_HOST_AWARE;
1779 	else if (((cgd->ident_data.support3 & ATA_SUPPORT_ZONE_MASK) ==
1780 		   ATA_SUPPORT_ZONE_DEV_MANAGED)
1781 	      || (softc->quirks & ADA_Q_SMR_DM))
1782 		softc->zone_mode = ADA_ZONE_DRIVE_MANAGED;
1783 	else
1784 		softc->zone_mode = ADA_ZONE_NONE;
1785 
1786 	if (cgd->ident_data.support.command1 & ATA_SUPPORT_LOOKAHEAD)
1787 		softc->flags |= ADA_FLAG_CAN_RAHEAD;
1788 	else
1789 		softc->flags &= ~ADA_FLAG_CAN_RAHEAD;
1790 
1791 	if (cgd->ident_data.support.command1 & ATA_SUPPORT_WRITECACHE)
1792 		softc->flags |= ADA_FLAG_CAN_WCACHE;
1793 	else
1794 		softc->flags &= ~ADA_FLAG_CAN_WCACHE;
1795 }
1796 
1797 static cam_status
1798 adaregister(struct cam_periph *periph, void *arg)
1799 {
1800 	struct ada_softc *softc;
1801 	struct ccb_getdev *cgd;
1802 	struct disk_params *dp;
1803 	struct sbuf sb;
1804 	char   *announce_buf;
1805 	caddr_t match;
1806 	int quirks;
1807 
1808 	cgd = (struct ccb_getdev *)arg;
1809 	if (cgd == NULL) {
1810 		printf("adaregister: no getdev CCB, can't register device\n");
1811 		return(CAM_REQ_CMP_ERR);
1812 	}
1813 
1814 	softc = (struct ada_softc *)malloc(sizeof(*softc), M_DEVBUF,
1815 	    M_NOWAIT|M_ZERO);
1816 
1817 	if (softc == NULL) {
1818 		printf("adaregister: Unable to probe new device. "
1819 		    "Unable to allocate softc\n");
1820 		return(CAM_REQ_CMP_ERR);
1821 	}
1822 
1823 	announce_buf = softc->announce_temp;
1824 	bzero(announce_buf, ADA_ANNOUNCETMP_SZ);
1825 
1826 	if (cam_iosched_init(&softc->cam_iosched, periph) != 0) {
1827 		printf("adaregister: Unable to probe new device. "
1828 		       "Unable to allocate iosched memory\n");
1829 		free(softc, M_DEVBUF);
1830 		return(CAM_REQ_CMP_ERR);
1831 	}
1832 
1833 	periph->softc = softc;
1834 	xpt_path_inq(&softc->cpi, periph->path);
1835 
1836 	/*
1837 	 * See if this device has any quirks.
1838 	 */
1839 	match = cam_quirkmatch((caddr_t)&cgd->ident_data,
1840 			       (caddr_t)ada_quirk_table,
1841 			       nitems(ada_quirk_table),
1842 			       sizeof(*ada_quirk_table), ata_identify_match);
1843 	if (match != NULL)
1844 		softc->quirks = ((struct ada_quirk_entry *)match)->quirks;
1845 	else
1846 		softc->quirks = ADA_Q_NONE;
1847 
1848 	TASK_INIT(&softc->sysctl_task, 0, adasysctlinit, periph);
1849 
1850 	/*
1851 	 * Register this media as a disk
1852 	 */
1853 	(void)cam_periph_hold(periph, PRIBIO);
1854 	cam_periph_unlock(periph);
1855 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1856 	    "kern.cam.ada.%d.quirks", periph->unit_number);
1857 	quirks = softc->quirks;
1858 	TUNABLE_INT_FETCH(announce_buf, &quirks);
1859 	softc->quirks = quirks;
1860 	softc->read_ahead = -1;
1861 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1862 	    "kern.cam.ada.%d.read_ahead", periph->unit_number);
1863 	TUNABLE_INT_FETCH(announce_buf, &softc->read_ahead);
1864 	softc->write_cache = -1;
1865 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1866 	    "kern.cam.ada.%d.write_cache", periph->unit_number);
1867 	TUNABLE_INT_FETCH(announce_buf, &softc->write_cache);
1868 
1869 	/*
1870 	 * Set support flags based on the Identify data and quirks.
1871 	 */
1872 	adasetflags(softc, cgd);
1873 	if (softc->cpi.hba_misc & PIM_ATA_EXT)
1874 		softc->flags |= ADA_FLAG_PIM_ATA_EXT;
1875 
1876 	/* Disable queue sorting for non-rotational media by default. */
1877 	if (cgd->ident_data.media_rotation_rate == ATA_RATE_NON_ROTATING) {
1878 		softc->flags &= ~ADA_FLAG_ROTATING;
1879 	} else {
1880 		softc->flags |= ADA_FLAG_ROTATING;
1881 	}
1882 	cam_iosched_set_sort_queue(softc->cam_iosched,
1883 	    (softc->flags & ADA_FLAG_ROTATING) ? -1 : 0);
1884 	softc->disk = disk_alloc();
1885 	adasetgeom(softc, cgd);
1886 	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
1887 			  periph->unit_number, softc->params.secsize,
1888 			  DEVSTAT_ALL_SUPPORTED,
1889 			  DEVSTAT_TYPE_DIRECT |
1890 			  XPORT_DEVSTAT_TYPE(softc->cpi.transport),
1891 			  DEVSTAT_PRIORITY_DISK);
1892 	softc->disk->d_open = adaopen;
1893 	softc->disk->d_close = adaclose;
1894 	softc->disk->d_strategy = adastrategy;
1895 	softc->disk->d_getattr = adagetattr;
1896 	softc->disk->d_dump = adadump;
1897 	softc->disk->d_gone = adadiskgonecb;
1898 	softc->disk->d_name = "ada";
1899 	softc->disk->d_drv1 = periph;
1900 	softc->disk->d_unit = periph->unit_number;
1901 
1902 	/*
1903 	 * Acquire a reference to the periph before we register with GEOM.
1904 	 * We'll release this reference once GEOM calls us back (via
1905 	 * adadiskgonecb()) telling us that our provider has been freed.
1906 	 */
1907 	if (cam_periph_acquire(periph) != 0) {
1908 		xpt_print(periph->path, "%s: lost periph during "
1909 			  "registration!\n", __func__);
1910 		cam_periph_lock(periph);
1911 		return (CAM_REQ_CMP_ERR);
1912 	}
1913 	disk_create(softc->disk, DISK_VERSION);
1914 	cam_periph_lock(periph);
1915 
1916 	dp = &softc->params;
1917 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1918 	    "%juMB (%ju %u byte sectors)",
1919 	    ((uintmax_t)dp->secsize * dp->sectors) / (1024 * 1024),
1920 	    (uintmax_t)dp->sectors, dp->secsize);
1921 
1922 	sbuf_new(&sb, softc->announce_buffer, ADA_ANNOUNCE_SZ, SBUF_FIXEDLEN);
1923 	xpt_announce_periph_sbuf(periph, &sb, announce_buf);
1924 	xpt_announce_quirks_sbuf(periph, &sb, softc->quirks, ADA_Q_BIT_STRING);
1925 	sbuf_finish(&sb);
1926 	sbuf_putbuf(&sb);
1927 
1928 	/*
1929 	 * Create our sysctl variables, now that we know
1930 	 * we have successfully attached.
1931 	 */
1932 	if (cam_periph_acquire(periph) == 0)
1933 		taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
1934 
1935 	/*
1936 	 * Add async callbacks for bus reset and
1937 	 * bus device reset calls.  I don't bother
1938 	 * checking if this fails as, in most cases,
1939 	 * the system will function just fine without
1940 	 * them and the only alternative would be to
1941 	 * not attach the device on failure.
1942 	 */
1943 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
1944 	    AC_GETDEV_CHANGED | AC_ADVINFO_CHANGED,
1945 	    adaasync, periph, periph->path);
1946 
1947 	/*
1948 	 * Schedule a periodic event to occasionally send an
1949 	 * ordered tag to a device.
1950 	 */
1951 	callout_init_mtx(&softc->sendordered_c, cam_periph_mtx(periph), 0);
1952 	callout_reset(&softc->sendordered_c,
1953 	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
1954 	    adasendorderedtag, softc);
1955 
1956 	if (ADA_RA >= 0 && softc->flags & ADA_FLAG_CAN_RAHEAD) {
1957 		softc->state = ADA_STATE_RAHEAD;
1958 	} else if (ADA_WC >= 0 && softc->flags & ADA_FLAG_CAN_WCACHE) {
1959 		softc->state = ADA_STATE_WCACHE;
1960 	} else if ((softc->flags & ADA_FLAG_CAN_LOG)
1961 		&& (softc->zone_mode != ADA_ZONE_NONE)) {
1962 		softc->state = ADA_STATE_LOGDIR;
1963 	} else {
1964 		/*
1965 		 * Nothing to probe, so we can just transition to the
1966 		 * normal state.
1967 		 */
1968 		adaprobedone(periph, NULL);
1969 		return(CAM_REQ_CMP);
1970 	}
1971 
1972 	xpt_schedule(periph, CAM_PRIORITY_DEV);
1973 
1974 	return(CAM_REQ_CMP);
1975 }
1976 
1977 static int
1978 ada_dsmtrim_req_create(struct ada_softc *softc, struct bio *bp, struct trim_request *req)
1979 {
1980 	uint64_t lastlba = (uint64_t)-1, lbas = 0;
1981 	int c, lastcount = 0, off, ranges = 0;
1982 
1983 	bzero(req, sizeof(*req));
1984 	TAILQ_INIT(&req->bps);
1985 	do {
1986 		uint64_t lba = bp->bio_pblkno;
1987 		int count = bp->bio_bcount / softc->params.secsize;
1988 
1989 		/* Try to extend the previous range. */
1990 		if (lba == lastlba) {
1991 			c = min(count, ATA_DSM_RANGE_MAX - lastcount);
1992 			lastcount += c;
1993 			off = (ranges - 1) * ATA_DSM_RANGE_SIZE;
1994 			req->data[off + 6] = lastcount & 0xff;
1995 			req->data[off + 7] =
1996 				(lastcount >> 8) & 0xff;
1997 			count -= c;
1998 			lba += c;
1999 			lbas += c;
2000 		}
2001 
2002 		while (count > 0) {
2003 			c = min(count, ATA_DSM_RANGE_MAX);
2004 			off = ranges * ATA_DSM_RANGE_SIZE;
2005 			req->data[off + 0] = lba & 0xff;
2006 			req->data[off + 1] = (lba >> 8) & 0xff;
2007 			req->data[off + 2] = (lba >> 16) & 0xff;
2008 			req->data[off + 3] = (lba >> 24) & 0xff;
2009 			req->data[off + 4] = (lba >> 32) & 0xff;
2010 			req->data[off + 5] = (lba >> 40) & 0xff;
2011 			req->data[off + 6] = c & 0xff;
2012 			req->data[off + 7] = (c >> 8) & 0xff;
2013 			lba += c;
2014 			lbas += c;
2015 			count -= c;
2016 			lastcount = c;
2017 			ranges++;
2018 			/*
2019 			 * Its the caller's responsibility to ensure the
2020 			 * request will fit so we don't need to check for
2021 			 * overrun here
2022 			 */
2023 		}
2024 		lastlba = lba;
2025 		TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);
2026 
2027 		bp = cam_iosched_next_trim(softc->cam_iosched);
2028 		if (bp == NULL)
2029 			break;
2030 		if (bp->bio_bcount / softc->params.secsize >
2031 		    (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX) {
2032 			cam_iosched_put_back_trim(softc->cam_iosched, bp);
2033 			break;
2034 		}
2035 	} while (1);
2036 	softc->trim_count++;
2037 	softc->trim_ranges += ranges;
2038 	softc->trim_lbas += lbas;
2039 
2040 	return (ranges);
2041 }
2042 
2043 static void
2044 ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
2045 {
2046 	struct trim_request *req = &softc->trim_req;
2047 	int ranges;
2048 
2049 	ranges = ada_dsmtrim_req_create(softc, bp, req);
2050 	cam_fill_ataio(ataio,
2051 	    ada_retry_count,
2052 	    adadone,
2053 	    CAM_DIR_OUT,
2054 	    0,
2055 	    req->data,
2056 	    howmany(ranges, ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
2057 	    ada_default_timeout * 1000);
2058 	ata_48bit_cmd(ataio, ATA_DATA_SET_MANAGEMENT,
2059 	    ATA_DSM_TRIM, 0, howmany(ranges, ATA_DSM_BLK_RANGES));
2060 }
2061 
2062 static void
2063 ada_ncq_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
2064 {
2065 	struct trim_request *req = &softc->trim_req;
2066 	int ranges;
2067 
2068 	ranges = ada_dsmtrim_req_create(softc, bp, req);
2069 	cam_fill_ataio(ataio,
2070 	    ada_retry_count,
2071 	    adadone,
2072 	    CAM_DIR_OUT,
2073 	    0,
2074 	    req->data,
2075 	    howmany(ranges, ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
2076 	    ada_default_timeout * 1000);
2077 	ata_ncq_cmd(ataio,
2078 	    ATA_SEND_FPDMA_QUEUED,
2079 	    0,
2080 	    howmany(ranges, ATA_DSM_BLK_RANGES));
2081 	ataio->cmd.sector_count_exp = ATA_SFPDMA_DSM;
2082 	ataio->ata_flags |= ATA_FLAG_AUX;
2083 	ataio->aux = 1;
2084 }
2085 
2086 static void
2087 ada_cfaerase(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
2088 {
2089 	struct trim_request *req = &softc->trim_req;
2090 	uint64_t lba = bp->bio_pblkno;
2091 	uint16_t count = bp->bio_bcount / softc->params.secsize;
2092 
2093 	bzero(req, sizeof(*req));
2094 	TAILQ_INIT(&req->bps);
2095 	TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);
2096 
2097 	cam_fill_ataio(ataio,
2098 	    ada_retry_count,
2099 	    adadone,
2100 	    CAM_DIR_NONE,
2101 	    0,
2102 	    NULL,
2103 	    0,
2104 	    ada_default_timeout*1000);
2105 
2106 	if (count >= 256)
2107 		count = 0;
2108 	ata_28bit_cmd(ataio, ATA_CFA_ERASE, 0, lba, count);
2109 }
2110 
2111 static int
2112 ada_zone_bio_to_ata(int disk_zone_cmd)
2113 {
2114 	switch (disk_zone_cmd) {
2115 	case DISK_ZONE_OPEN:
2116 		return ATA_ZM_OPEN_ZONE;
2117 	case DISK_ZONE_CLOSE:
2118 		return ATA_ZM_CLOSE_ZONE;
2119 	case DISK_ZONE_FINISH:
2120 		return ATA_ZM_FINISH_ZONE;
2121 	case DISK_ZONE_RWP:
2122 		return ATA_ZM_RWP;
2123 	}
2124 
2125 	return -1;
2126 }
2127 
2128 static int
2129 ada_zone_cmd(struct cam_periph *periph, union ccb *ccb, struct bio *bp,
2130 	     int *queue_ccb)
2131 {
2132 	struct ada_softc *softc;
2133 	int error;
2134 
2135 	error = 0;
2136 
2137 	if (bp->bio_cmd != BIO_ZONE) {
2138 		error = EINVAL;
2139 		goto bailout;
2140 	}
2141 
2142 	softc = periph->softc;
2143 
2144 	switch (bp->bio_zone.zone_cmd) {
2145 	case DISK_ZONE_OPEN:
2146 	case DISK_ZONE_CLOSE:
2147 	case DISK_ZONE_FINISH:
2148 	case DISK_ZONE_RWP: {
2149 		int zone_flags;
2150 		int zone_sa;
2151 		uint64_t lba;
2152 
2153 		zone_sa = ada_zone_bio_to_ata(bp->bio_zone.zone_cmd);
2154 		if (zone_sa == -1) {
2155 			xpt_print(periph->path, "Cannot translate zone "
2156 			    "cmd %#x to ATA\n", bp->bio_zone.zone_cmd);
2157 			error = EINVAL;
2158 			goto bailout;
2159 		}
2160 
2161 		zone_flags = 0;
2162 		lba = bp->bio_zone.zone_params.rwp.id;
2163 
2164 		if (bp->bio_zone.zone_params.rwp.flags &
2165 		    DISK_ZONE_RWP_FLAG_ALL)
2166 			zone_flags |= ZBC_OUT_ALL;
2167 
2168 		ata_zac_mgmt_out(&ccb->ataio,
2169 				 /*retries*/ ada_retry_count,
2170 				 /*cbfcnp*/ adadone,
2171 				 /*use_ncq*/ (softc->flags &
2172 					      ADA_FLAG_PIM_ATA_EXT) ? 1 : 0,
2173 				 /*zm_action*/ zone_sa,
2174 				 /*zone_id*/ lba,
2175 				 /*zone_flags*/ zone_flags,
2176 				 /*sector_count*/ 0,
2177 				 /*data_ptr*/ NULL,
2178 				 /*dxfer_len*/ 0,
2179 				 /*timeout*/ ada_default_timeout * 1000);
2180 		*queue_ccb = 1;
2181 
2182 		break;
2183 	}
2184 	case DISK_ZONE_REPORT_ZONES: {
2185 		uint8_t *rz_ptr;
2186 		uint32_t num_entries, alloc_size;
2187 		struct disk_zone_report *rep;
2188 
2189 		rep = &bp->bio_zone.zone_params.report;
2190 
2191 		num_entries = rep->entries_allocated;
2192 		if (num_entries == 0) {
2193 			xpt_print(periph->path, "No entries allocated for "
2194 			    "Report Zones request\n");
2195 			error = EINVAL;
2196 			goto bailout;
2197 		}
2198 		alloc_size = sizeof(struct scsi_report_zones_hdr) +
2199 		    (sizeof(struct scsi_report_zones_desc) * num_entries);
2200 		alloc_size = min(alloc_size, softc->disk->d_maxsize);
2201 		rz_ptr = malloc(alloc_size, M_ATADA, M_NOWAIT | M_ZERO);
2202 		if (rz_ptr == NULL) {
2203 			xpt_print(periph->path, "Unable to allocate memory "
2204 			   "for Report Zones request\n");
2205 			error = ENOMEM;
2206 			goto bailout;
2207 		}
2208 
2209 		ata_zac_mgmt_in(&ccb->ataio,
2210 				/*retries*/ ada_retry_count,
2211 				/*cbcfnp*/ adadone,
2212 				/*use_ncq*/ (softc->flags &
2213 					     ADA_FLAG_PIM_ATA_EXT) ? 1 : 0,
2214 				/*zm_action*/ ATA_ZM_REPORT_ZONES,
2215 				/*zone_id*/ rep->starting_id,
2216 				/*zone_flags*/ rep->rep_options,
2217 				/*data_ptr*/ rz_ptr,
2218 				/*dxfer_len*/ alloc_size,
2219 				/*timeout*/ ada_default_timeout * 1000);
2220 
2221 		/*
2222 		 * For BIO_ZONE, this isn't normally needed.  However, it
2223 		 * is used by devstat_end_transaction_bio() to determine
2224 		 * how much data was transferred.
2225 		 */
2226 		/*
2227 		 * XXX KDM we have a problem.  But I'm not sure how to fix
2228 		 * it.  devstat uses bio_bcount - bio_resid to calculate
2229 		 * the amount of data transferred.   The GEOM disk code
2230 		 * uses bio_length - bio_resid to calculate the amount of
2231 		 * data in bio_completed.  We have different structure
2232 		 * sizes above and below the ada(4) driver.  So, if we
2233 		 * use the sizes above, the amount transferred won't be
2234 		 * quite accurate for devstat.  If we use different sizes
2235 		 * for bio_bcount and bio_length (above and below
2236 		 * respectively), then the residual needs to match one or
2237 		 * the other.  Everything is calculated after the bio
2238 		 * leaves the driver, so changing the values around isn't
2239 		 * really an option.  For now, just set the count to the
2240 		 * passed in length.  This means that the calculations
2241 		 * above (e.g. bio_completed) will be correct, but the
2242 		 * amount of data reported to devstat will be slightly
2243 		 * under or overstated.
2244 		 */
2245 		bp->bio_bcount = bp->bio_length;
2246 
2247 		*queue_ccb = 1;
2248 
2249 		break;
2250 	}
2251 	case DISK_ZONE_GET_PARAMS: {
2252 		struct disk_zone_disk_params *params;
2253 
2254 		params = &bp->bio_zone.zone_params.disk_params;
2255 		bzero(params, sizeof(*params));
2256 
2257 		switch (softc->zone_mode) {
2258 		case ADA_ZONE_DRIVE_MANAGED:
2259 			params->zone_mode = DISK_ZONE_MODE_DRIVE_MANAGED;
2260 			break;
2261 		case ADA_ZONE_HOST_AWARE:
2262 			params->zone_mode = DISK_ZONE_MODE_HOST_AWARE;
2263 			break;
2264 		case ADA_ZONE_HOST_MANAGED:
2265 			params->zone_mode = DISK_ZONE_MODE_HOST_MANAGED;
2266 			break;
2267 		default:
2268 		case ADA_ZONE_NONE:
2269 			params->zone_mode = DISK_ZONE_MODE_NONE;
2270 			break;
2271 		}
2272 
2273 		if (softc->zone_flags & ADA_ZONE_FLAG_URSWRZ)
2274 			params->flags |= DISK_ZONE_DISK_URSWRZ;
2275 
2276 		if (softc->zone_flags & ADA_ZONE_FLAG_OPT_SEQ_SET) {
2277 			params->optimal_seq_zones = softc->optimal_seq_zones;
2278 			params->flags |= DISK_ZONE_OPT_SEQ_SET;
2279 		}
2280 
2281 		if (softc->zone_flags & ADA_ZONE_FLAG_OPT_NONSEQ_SET) {
2282 			params->optimal_nonseq_zones =
2283 			    softc->optimal_nonseq_zones;
2284 			params->flags |= DISK_ZONE_OPT_NONSEQ_SET;
2285 		}
2286 
2287 		if (softc->zone_flags & ADA_ZONE_FLAG_MAX_SEQ_SET) {
2288 			params->max_seq_zones = softc->max_seq_zones;
2289 			params->flags |= DISK_ZONE_MAX_SEQ_SET;
2290 		}
2291 		if (softc->zone_flags & ADA_ZONE_FLAG_RZ_SUP)
2292 			params->flags |= DISK_ZONE_RZ_SUP;
2293 
2294 		if (softc->zone_flags & ADA_ZONE_FLAG_OPEN_SUP)
2295 			params->flags |= DISK_ZONE_OPEN_SUP;
2296 
2297 		if (softc->zone_flags & ADA_ZONE_FLAG_CLOSE_SUP)
2298 			params->flags |= DISK_ZONE_CLOSE_SUP;
2299 
2300 		if (softc->zone_flags & ADA_ZONE_FLAG_FINISH_SUP)
2301 			params->flags |= DISK_ZONE_FINISH_SUP;
2302 
2303 		if (softc->zone_flags & ADA_ZONE_FLAG_RWP_SUP)
2304 			params->flags |= DISK_ZONE_RWP_SUP;
2305 		break;
2306 	}
2307 	default:
2308 		break;
2309 	}
2310 bailout:
2311 	return (error);
2312 }
2313 
2314 static void
2315 adastart(struct cam_periph *periph, union ccb *start_ccb)
2316 {
2317 	struct ada_softc *softc = (struct ada_softc *)periph->softc;
2318 	struct ccb_ataio *ataio = &start_ccb->ataio;
2319 
2320 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastart\n"));
2321 
2322 	switch (softc->state) {
2323 	case ADA_STATE_NORMAL:
2324 	{
2325 		struct bio *bp;
2326 		u_int8_t tag_code;
2327 
2328 		bp = cam_iosched_next_bio(softc->cam_iosched);
2329 		if (bp == NULL) {
2330 			xpt_release_ccb(start_ccb);
2331 			break;
2332 		}
2333 
2334 		if ((bp->bio_flags & BIO_ORDERED) != 0 ||
2335 		    (bp->bio_cmd != BIO_DELETE && (softc->flags & ADA_FLAG_NEED_OTAG) != 0)) {
2336 			softc->flags &= ~ADA_FLAG_NEED_OTAG;
2337 			softc->flags |= ADA_FLAG_WAS_OTAG;
2338 			tag_code = 0;
2339 		} else {
2340 			tag_code = 1;
2341 		}
2342 		switch (bp->bio_cmd) {
2343 		case BIO_WRITE:
2344 		case BIO_READ:
2345 		{
2346 			uint64_t lba = bp->bio_pblkno;
2347 			uint16_t count = bp->bio_bcount / softc->params.secsize;
2348 			void *data_ptr;
2349 			int rw_op;
2350 
2351 			if (bp->bio_cmd == BIO_WRITE) {
2352 				softc->flags |= ADA_FLAG_DIRTY;
2353 				rw_op = CAM_DIR_OUT;
2354 			} else {
2355 				rw_op = CAM_DIR_IN;
2356 			}
2357 
2358 			data_ptr = bp->bio_data;
2359 			if ((bp->bio_flags & (BIO_UNMAPPED|BIO_VLIST)) != 0) {
2360 				rw_op |= CAM_DATA_BIO;
2361 				data_ptr = bp;
2362 			}
2363 
2364 #ifdef CAM_TEST_FAILURE
2365 			int fail = 0;
2366 
2367 			/*
2368 			 * Support the failure ioctls.  If the command is a
2369 			 * read, and there are pending forced read errors, or
2370 			 * if a write and pending write errors, then fail this
2371 			 * operation with EIO.  This is useful for testing
2372 			 * purposes.  Also, support having every Nth read fail.
2373 			 *
2374 			 * This is a rather blunt tool.
2375 			 */
2376 			if (bp->bio_cmd == BIO_READ) {
2377 				if (softc->force_read_error) {
2378 					softc->force_read_error--;
2379 					fail = 1;
2380 				}
2381 				if (softc->periodic_read_error > 0) {
2382 					if (++softc->periodic_read_count >=
2383 					    softc->periodic_read_error) {
2384 						softc->periodic_read_count = 0;
2385 						fail = 1;
2386 					}
2387 				}
2388 			} else {
2389 				if (softc->force_write_error) {
2390 					softc->force_write_error--;
2391 					fail = 1;
2392 				}
2393 			}
2394 			if (fail) {
2395 				biofinish(bp, NULL, EIO);
2396 				xpt_release_ccb(start_ccb);
2397 				adaschedule(periph);
2398 				return;
2399 			}
2400 #endif
2401 			KASSERT((bp->bio_flags & BIO_UNMAPPED) == 0 ||
2402 			    round_page(bp->bio_bcount + bp->bio_ma_offset) /
2403 			    PAGE_SIZE == bp->bio_ma_n,
2404 			    ("Short bio %p", bp));
2405 			cam_fill_ataio(ataio,
2406 			    ada_retry_count,
2407 			    adadone,
2408 			    rw_op,
2409 			    0,
2410 			    data_ptr,
2411 			    bp->bio_bcount,
2412 			    ada_default_timeout*1000);
2413 
2414 			if ((softc->flags & ADA_FLAG_CAN_NCQ) && tag_code) {
2415 				if (bp->bio_cmd == BIO_READ) {
2416 					ata_ncq_cmd(ataio, ATA_READ_FPDMA_QUEUED,
2417 					    lba, count);
2418 				} else {
2419 					ata_ncq_cmd(ataio, ATA_WRITE_FPDMA_QUEUED,
2420 					    lba, count);
2421 				}
2422 			} else if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
2423 			    (lba + count >= ATA_MAX_28BIT_LBA ||
2424 			    count > 256)) {
2425 				if (softc->flags & ADA_FLAG_CAN_DMA48) {
2426 					if (bp->bio_cmd == BIO_READ) {
2427 						ata_48bit_cmd(ataio, ATA_READ_DMA48,
2428 						    0, lba, count);
2429 					} else {
2430 						ata_48bit_cmd(ataio, ATA_WRITE_DMA48,
2431 						    0, lba, count);
2432 					}
2433 				} else {
2434 					if (bp->bio_cmd == BIO_READ) {
2435 						ata_48bit_cmd(ataio, ATA_READ_MUL48,
2436 						    0, lba, count);
2437 					} else {
2438 						ata_48bit_cmd(ataio, ATA_WRITE_MUL48,
2439 						    0, lba, count);
2440 					}
2441 				}
2442 			} else {
2443 				if (count == 256)
2444 					count = 0;
2445 				if (softc->flags & ADA_FLAG_CAN_DMA) {
2446 					if (bp->bio_cmd == BIO_READ) {
2447 						ata_28bit_cmd(ataio, ATA_READ_DMA,
2448 						    0, lba, count);
2449 					} else {
2450 						ata_28bit_cmd(ataio, ATA_WRITE_DMA,
2451 						    0, lba, count);
2452 					}
2453 				} else {
2454 					if (bp->bio_cmd == BIO_READ) {
2455 						ata_28bit_cmd(ataio, ATA_READ_MUL,
2456 						    0, lba, count);
2457 					} else {
2458 						ata_28bit_cmd(ataio, ATA_WRITE_MUL,
2459 						    0, lba, count);
2460 					}
2461 				}
2462 			}
2463 			break;
2464 		}
2465 		case BIO_DELETE:
2466 			switch (softc->delete_method) {
2467 			case ADA_DELETE_NCQ_DSM_TRIM:
2468 				ada_ncq_dsmtrim(softc, bp, ataio);
2469 				break;
2470 			case ADA_DELETE_DSM_TRIM:
2471 				ada_dsmtrim(softc, bp, ataio);
2472 				break;
2473 			case ADA_DELETE_CFA_ERASE:
2474 				ada_cfaerase(softc, bp, ataio);
2475 				break;
2476 			default:
2477 				biofinish(bp, NULL, EOPNOTSUPP);
2478 				xpt_release_ccb(start_ccb);
2479 				adaschedule(periph);
2480 				return;
2481 			}
2482 			start_ccb->ccb_h.ccb_state = ADA_CCB_TRIM;
2483 			start_ccb->ccb_h.flags |= CAM_UNLOCKED;
2484 			cam_iosched_submit_trim(softc->cam_iosched);
2485 			goto out;
2486 		case BIO_FLUSH:
2487 			cam_fill_ataio(ataio,
2488 			    1,
2489 			    adadone,
2490 			    CAM_DIR_NONE,
2491 			    0,
2492 			    NULL,
2493 			    0,
2494 			    ada_default_timeout*1000);
2495 
2496 			if (softc->flags & ADA_FLAG_CAN_48BIT)
2497 				ata_48bit_cmd(ataio, ATA_FLUSHCACHE48, 0, 0, 0);
2498 			else
2499 				ata_28bit_cmd(ataio, ATA_FLUSHCACHE, 0, 0, 0);
2500 			break;
2501 		case BIO_ZONE: {
2502 			int error, queue_ccb;
2503 
2504 			queue_ccb = 0;
2505 
2506 			error = ada_zone_cmd(periph, start_ccb, bp, &queue_ccb);
2507 			if ((error != 0)
2508 			 || (queue_ccb == 0)) {
2509 				biofinish(bp, NULL, error);
2510 				xpt_release_ccb(start_ccb);
2511 				return;
2512 			}
2513 			break;
2514 		}
2515 		default:
2516 			biofinish(bp, NULL, EOPNOTSUPP);
2517 			xpt_release_ccb(start_ccb);
2518 			return;
2519 		}
2520 		start_ccb->ccb_h.ccb_state = ADA_CCB_BUFFER_IO;
2521 		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
2522 out:
2523 		start_ccb->ccb_h.ccb_bp = bp;
2524 		softc->outstanding_cmds++;
2525 		softc->refcount++;
2526 		cam_periph_unlock(periph);
2527 		xpt_action(start_ccb);
2528 		cam_periph_lock(periph);
2529 
2530 		/* May have more work to do, so ensure we stay scheduled */
2531 		adaschedule(periph);
2532 		break;
2533 	}
2534 	case ADA_STATE_RAHEAD:
2535 	case ADA_STATE_WCACHE:
2536 	{
2537 		cam_fill_ataio(ataio,
2538 		    1,
2539 		    adadone,
2540 		    CAM_DIR_NONE,
2541 		    0,
2542 		    NULL,
2543 		    0,
2544 		    ada_default_timeout*1000);
2545 
2546 		if (softc->state == ADA_STATE_RAHEAD) {
2547 			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_RA ?
2548 			    ATA_SF_ENAB_RCACHE : ATA_SF_DIS_RCACHE, 0, 0);
2549 			start_ccb->ccb_h.ccb_state = ADA_CCB_RAHEAD;
2550 		} else {
2551 			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_WC ?
2552 			    ATA_SF_ENAB_WCACHE : ATA_SF_DIS_WCACHE, 0, 0);
2553 			start_ccb->ccb_h.ccb_state = ADA_CCB_WCACHE;
2554 		}
2555 		start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2556 		xpt_action(start_ccb);
2557 		break;
2558 	}
2559 	case ADA_STATE_LOGDIR:
2560 	{
2561 		struct ata_gp_log_dir *log_dir;
2562 
2563 		if ((softc->flags & ADA_FLAG_CAN_LOG) == 0) {
2564 			adaprobedone(periph, start_ccb);
2565 			break;
2566 		}
2567 
2568 		log_dir = malloc(sizeof(*log_dir), M_ATADA, M_NOWAIT|M_ZERO);
2569 		if (log_dir == NULL) {
2570 			xpt_print(periph->path, "Couldn't malloc log_dir "
2571 			    "data\n");
2572 			softc->state = ADA_STATE_NORMAL;
2573 			xpt_release_ccb(start_ccb);
2574 			break;
2575 		}
2576 
2577 
2578 		ata_read_log(ataio,
2579 		    /*retries*/1,
2580 		    /*cbfcnp*/adadone,
2581 		    /*log_address*/ ATA_LOG_DIRECTORY,
2582 		    /*page_number*/ 0,
2583 		    /*block_count*/ 1,
2584 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2585 				 CAM_ATAIO_DMA : 0,
2586 		    /*data_ptr*/ (uint8_t *)log_dir,
2587 		    /*dxfer_len*/sizeof(*log_dir),
2588 		    /*timeout*/ada_default_timeout*1000);
2589 
2590 		start_ccb->ccb_h.ccb_state = ADA_CCB_LOGDIR;
2591 		xpt_action(start_ccb);
2592 		break;
2593 	}
2594 	case ADA_STATE_IDDIR:
2595 	{
2596 		struct ata_identify_log_pages *id_dir;
2597 
2598 		id_dir = malloc(sizeof(*id_dir), M_ATADA, M_NOWAIT | M_ZERO);
2599 		if (id_dir == NULL) {
2600 			xpt_print(periph->path, "Couldn't malloc id_dir "
2601 			    "data\n");
2602 			adaprobedone(periph, start_ccb);
2603 			break;
2604 		}
2605 
2606 		ata_read_log(ataio,
2607 		    /*retries*/1,
2608 		    /*cbfcnp*/adadone,
2609 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
2610 		    /*page_number*/ ATA_IDL_PAGE_LIST,
2611 		    /*block_count*/ 1,
2612 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2613 				 CAM_ATAIO_DMA : 0,
2614 		    /*data_ptr*/ (uint8_t *)id_dir,
2615 		    /*dxfer_len*/ sizeof(*id_dir),
2616 		    /*timeout*/ada_default_timeout*1000);
2617 
2618 		start_ccb->ccb_h.ccb_state = ADA_CCB_IDDIR;
2619 		xpt_action(start_ccb);
2620 		break;
2621 	}
2622 	case ADA_STATE_SUP_CAP:
2623 	{
2624 		struct ata_identify_log_sup_cap *sup_cap;
2625 
2626 		sup_cap = malloc(sizeof(*sup_cap), M_ATADA, M_NOWAIT|M_ZERO);
2627 		if (sup_cap == NULL) {
2628 			xpt_print(periph->path, "Couldn't malloc sup_cap "
2629 			    "data\n");
2630 			adaprobedone(periph, start_ccb);
2631 			break;
2632 		}
2633 
2634 		ata_read_log(ataio,
2635 		    /*retries*/1,
2636 		    /*cbfcnp*/adadone,
2637 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
2638 		    /*page_number*/ ATA_IDL_SUP_CAP,
2639 		    /*block_count*/ 1,
2640 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2641 				 CAM_ATAIO_DMA : 0,
2642 		    /*data_ptr*/ (uint8_t *)sup_cap,
2643 		    /*dxfer_len*/ sizeof(*sup_cap),
2644 		    /*timeout*/ada_default_timeout*1000);
2645 
2646 		start_ccb->ccb_h.ccb_state = ADA_CCB_SUP_CAP;
2647 		xpt_action(start_ccb);
2648 		break;
2649 	}
2650 	case ADA_STATE_ZONE:
2651 	{
2652 		struct ata_zoned_info_log *ata_zone;
2653 
2654 		ata_zone = malloc(sizeof(*ata_zone), M_ATADA, M_NOWAIT|M_ZERO);
2655 		if (ata_zone == NULL) {
2656 			xpt_print(periph->path, "Couldn't malloc ata_zone "
2657 			    "data\n");
2658 			adaprobedone(periph, start_ccb);
2659 			break;
2660 		}
2661 
2662 		ata_read_log(ataio,
2663 		    /*retries*/1,
2664 		    /*cbfcnp*/adadone,
2665 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
2666 		    /*page_number*/ ATA_IDL_ZDI,
2667 		    /*block_count*/ 1,
2668 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2669 				 CAM_ATAIO_DMA : 0,
2670 		    /*data_ptr*/ (uint8_t *)ata_zone,
2671 		    /*dxfer_len*/ sizeof(*ata_zone),
2672 		    /*timeout*/ada_default_timeout*1000);
2673 
2674 		start_ccb->ccb_h.ccb_state = ADA_CCB_ZONE;
2675 		xpt_action(start_ccb);
2676 		break;
2677 	}
2678 	}
2679 }
2680 
2681 static void
2682 adaprobedone(struct cam_periph *periph, union ccb *ccb)
2683 {
2684 	struct ada_softc *softc;
2685 
2686 	softc = (struct ada_softc *)periph->softc;
2687 
2688 	if (ccb != NULL)
2689 		xpt_release_ccb(ccb);
2690 
2691 	softc->state = ADA_STATE_NORMAL;
2692 	softc->flags |= ADA_FLAG_PROBED;
2693 	adaschedule(periph);
2694 	if ((softc->flags & ADA_FLAG_ANNOUNCED) == 0) {
2695 		softc->flags |= ADA_FLAG_ANNOUNCED;
2696 		cam_periph_unhold(periph);
2697 	} else {
2698 		cam_periph_release_locked(periph);
2699 	}
2700 }
2701 
2702 static void
2703 adazonedone(struct cam_periph *periph, union ccb *ccb)
2704 {
2705 	struct bio *bp;
2706 
2707 	bp = (struct bio *)ccb->ccb_h.ccb_bp;
2708 
2709 	switch (bp->bio_zone.zone_cmd) {
2710 	case DISK_ZONE_OPEN:
2711 	case DISK_ZONE_CLOSE:
2712 	case DISK_ZONE_FINISH:
2713 	case DISK_ZONE_RWP:
2714 		break;
2715 	case DISK_ZONE_REPORT_ZONES: {
2716 		uint32_t avail_len;
2717 		struct disk_zone_report *rep;
2718 		struct scsi_report_zones_hdr *hdr;
2719 		struct scsi_report_zones_desc *desc;
2720 		struct disk_zone_rep_entry *entry;
2721 		uint32_t hdr_len, num_avail;
2722 		uint32_t num_to_fill, i;
2723 
2724 		rep = &bp->bio_zone.zone_params.report;
2725 		avail_len = ccb->ataio.dxfer_len - ccb->ataio.resid;
2726 		/*
2727 		 * Note that bio_resid isn't normally used for zone
2728 		 * commands, but it is used by devstat_end_transaction_bio()
2729 		 * to determine how much data was transferred.  Because
2730 		 * the size of the SCSI/ATA data structures is different
2731 		 * than the size of the BIO interface structures, the
2732 		 * amount of data actually transferred from the drive will
2733 		 * be different than the amount of data transferred to
2734 		 * the user.
2735 		 */
2736 		hdr = (struct scsi_report_zones_hdr *)ccb->ataio.data_ptr;
2737 		if (avail_len < sizeof(*hdr)) {
2738 			/*
2739 			 * Is there a better error than EIO here?  We asked
2740 			 * for at least the header, and we got less than
2741 			 * that.
2742 			 */
2743 			bp->bio_error = EIO;
2744 			bp->bio_flags |= BIO_ERROR;
2745 			bp->bio_resid = bp->bio_bcount;
2746 			break;
2747 		}
2748 
2749 		hdr_len = le32dec(hdr->length);
2750 		if (hdr_len > 0)
2751 			rep->entries_available = hdr_len / sizeof(*desc);
2752 		else
2753 			rep->entries_available = 0;
2754 		/*
2755 		 * NOTE: using the same values for the BIO version of the
2756 		 * same field as the SCSI/ATA values.  This means we could
2757 		 * get some additional values that aren't defined in bio.h
2758 		 * if more values of the same field are defined later.
2759 		 */
2760 		rep->header.same = hdr->byte4 & SRZ_SAME_MASK;
2761 		rep->header.maximum_lba = le64dec(hdr->maximum_lba);
2762 		/*
2763 		 * If the drive reports no entries that match the query,
2764 		 * we're done.
2765 		 */
2766 		if (hdr_len == 0) {
2767 			rep->entries_filled = 0;
2768 			bp->bio_resid = bp->bio_bcount;
2769 			break;
2770 		}
2771 
2772 		num_avail = min((avail_len - sizeof(*hdr)) / sizeof(*desc),
2773 				hdr_len / sizeof(*desc));
2774 		/*
2775 		 * If the drive didn't return any data, then we're done.
2776 		 */
2777 		if (num_avail == 0) {
2778 			rep->entries_filled = 0;
2779 			bp->bio_resid = bp->bio_bcount;
2780 			break;
2781 		}
2782 
2783 		num_to_fill = min(num_avail, rep->entries_allocated);
2784 		/*
2785 		 * If the user didn't allocate any entries for us to fill,
2786 		 * we're done.
2787 		 */
2788 		if (num_to_fill == 0) {
2789 			rep->entries_filled = 0;
2790 			bp->bio_resid = bp->bio_bcount;
2791 			break;
2792 		}
2793 
2794 		for (i = 0, desc = &hdr->desc_list[0], entry=&rep->entries[0];
2795 		     i < num_to_fill; i++, desc++, entry++) {
2796 			/*
2797 			 * NOTE: we're mapping the values here directly
2798 			 * from the SCSI/ATA bit definitions to the bio.h
2799 			 * definitions.  There is also a warning in
2800 			 * disk_zone.h, but the impact is that if
2801 			 * additional values are added in the SCSI/ATA
2802 			 * specs these will be visible to consumers of
2803 			 * this interface.
2804 			 */
2805 			entry->zone_type = desc->zone_type & SRZ_TYPE_MASK;
2806 			entry->zone_condition =
2807 			    (desc->zone_flags & SRZ_ZONE_COND_MASK) >>
2808 			    SRZ_ZONE_COND_SHIFT;
2809 			entry->zone_flags |= desc->zone_flags &
2810 			    (SRZ_ZONE_NON_SEQ|SRZ_ZONE_RESET);
2811 			entry->zone_length = le64dec(desc->zone_length);
2812 			entry->zone_start_lba = le64dec(desc->zone_start_lba);
2813 			entry->write_pointer_lba =
2814 			    le64dec(desc->write_pointer_lba);
2815 		}
2816 		rep->entries_filled = num_to_fill;
2817 		/*
2818 		 * Note that this residual is accurate from the user's
2819 		 * standpoint, but the amount transferred isn't accurate
2820 		 * from the standpoint of what actually came back from the
2821 		 * drive.
2822 		 */
2823 		bp->bio_resid = bp->bio_bcount - (num_to_fill * sizeof(*entry));
2824 		break;
2825 	}
2826 	case DISK_ZONE_GET_PARAMS:
2827 	default:
2828 		/*
2829 		 * In theory we should not get a GET_PARAMS bio, since it
2830 		 * should be handled without queueing the command to the
2831 		 * drive.
2832 		 */
2833 		panic("%s: Invalid zone command %d", __func__,
2834 		    bp->bio_zone.zone_cmd);
2835 		break;
2836 	}
2837 
2838 	if (bp->bio_zone.zone_cmd == DISK_ZONE_REPORT_ZONES)
2839 		free(ccb->ataio.data_ptr, M_ATADA);
2840 }
2841 
2842 
2843 static void
2844 adadone(struct cam_periph *periph, union ccb *done_ccb)
2845 {
2846 	struct ada_softc *softc;
2847 	struct ccb_ataio *ataio;
2848 	struct cam_path *path;
2849 	uint32_t priority;
2850 	int state;
2851 
2852 	softc = (struct ada_softc *)periph->softc;
2853 	ataio = &done_ccb->ataio;
2854 	path = done_ccb->ccb_h.path;
2855 	priority = done_ccb->ccb_h.pinfo.priority;
2856 
2857 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("adadone\n"));
2858 
2859 	state = ataio->ccb_h.ccb_state & ADA_CCB_TYPE_MASK;
2860 	switch (state) {
2861 	case ADA_CCB_BUFFER_IO:
2862 	case ADA_CCB_TRIM:
2863 	{
2864 		struct bio *bp;
2865 		int error;
2866 
2867 		cam_periph_lock(periph);
2868 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2869 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2870 			error = adaerror(done_ccb, 0, 0);
2871 			if (error == ERESTART) {
2872 				/* A retry was scheduled, so just return. */
2873 				cam_periph_unlock(periph);
2874 				return;
2875 			}
2876 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2877 				cam_release_devq(path,
2878 						 /*relsim_flags*/0,
2879 						 /*reduction*/0,
2880 						 /*timeout*/0,
2881 						 /*getcount_only*/0);
2882 			/*
2883 			 * If we get an error on an NCQ DSM TRIM, fall back
2884 			 * to a non-NCQ DSM TRIM forever. Please note that if
2885 			 * CAN_NCQ_TRIM is set, CAN_TRIM is necessarily set too.
2886 			 * However, for this one trim, we treat it as advisory
2887 			 * and return success up the stack.
2888 			 */
2889 			if (state == ADA_CCB_TRIM &&
2890 			    error != 0 &&
2891 			    (softc->flags & ADA_FLAG_CAN_NCQ_TRIM) != 0) {
2892 				softc->flags &= ~ADA_FLAG_CAN_NCQ_TRIM;
2893 				error = 0;
2894 				adasetdeletemethod(softc);
2895 			}
2896 		} else {
2897 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2898 				panic("REQ_CMP with QFRZN");
2899 
2900 			error = 0;
2901 		}
2902 		bp->bio_error = error;
2903 		if (error != 0) {
2904 			bp->bio_resid = bp->bio_bcount;
2905 			bp->bio_flags |= BIO_ERROR;
2906 		} else {
2907 			if (bp->bio_cmd == BIO_ZONE)
2908 				adazonedone(periph, done_ccb);
2909 			else if (state == ADA_CCB_TRIM)
2910 				bp->bio_resid = 0;
2911 			else
2912 				bp->bio_resid = ataio->resid;
2913 
2914 			if ((bp->bio_resid > 0)
2915 			 && (bp->bio_cmd != BIO_ZONE))
2916 				bp->bio_flags |= BIO_ERROR;
2917 		}
2918 		softc->outstanding_cmds--;
2919 		if (softc->outstanding_cmds == 0)
2920 			softc->flags |= ADA_FLAG_WAS_OTAG;
2921 
2922 		/*
2923 		 * We need to call cam_iosched before we call biodone so that we
2924 		 * don't measure any activity that happens in the completion
2925 		 * routine, which in the case of sendfile can be quite
2926 		 * extensive.  Release the periph refcount taken in adastart()
2927 		 * for each CCB.
2928 		 */
2929 		cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb);
2930 		xpt_release_ccb(done_ccb);
2931 		KASSERT(softc->refcount >= 1, ("adadone softc %p refcount %d", softc, softc->refcount));
2932 		softc->refcount--;
2933 		if (state == ADA_CCB_TRIM) {
2934 			TAILQ_HEAD(, bio) queue;
2935 			struct bio *bp1;
2936 
2937 			TAILQ_INIT(&queue);
2938 			TAILQ_CONCAT(&queue, &softc->trim_req.bps, bio_queue);
2939 			/*
2940 			 * Normally, the xpt_release_ccb() above would make sure
2941 			 * that when we have more work to do, that work would
2942 			 * get kicked off. However, we specifically keep
2943 			 * trim_running set to 0 before the call above to allow
2944 			 * other I/O to progress when many BIO_DELETE requests
2945 			 * are pushed down. We set trim_running to 0 and call
2946 			 * daschedule again so that we don't stall if there are
2947 			 * no other I/Os pending apart from BIO_DELETEs.
2948 			 */
2949 			cam_iosched_trim_done(softc->cam_iosched);
2950 			adaschedule(periph);
2951 			cam_periph_unlock(periph);
2952 			while ((bp1 = TAILQ_FIRST(&queue)) != NULL) {
2953 				TAILQ_REMOVE(&queue, bp1, bio_queue);
2954 				bp1->bio_error = error;
2955 				if (error != 0) {
2956 					bp1->bio_flags |= BIO_ERROR;
2957 					bp1->bio_resid = bp1->bio_bcount;
2958 				} else
2959 					bp1->bio_resid = 0;
2960 				biodone(bp1);
2961 			}
2962 		} else {
2963 			adaschedule(periph);
2964 			cam_periph_unlock(periph);
2965 			biodone(bp);
2966 		}
2967 		return;
2968 	}
2969 	case ADA_CCB_RAHEAD:
2970 	{
2971 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2972 			if (adaerror(done_ccb, 0, 0) == ERESTART) {
2973 				/* Drop freeze taken due to CAM_DEV_QFREEZE */
2974 				cam_release_devq(path, 0, 0, 0, FALSE);
2975 				return;
2976 			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
2977 				cam_release_devq(path,
2978 				    /*relsim_flags*/0,
2979 				    /*reduction*/0,
2980 				    /*timeout*/0,
2981 				    /*getcount_only*/0);
2982 			}
2983 		}
2984 
2985 		/*
2986 		 * Since our peripheral may be invalidated by an error
2987 		 * above or an external event, we must release our CCB
2988 		 * before releasing the reference on the peripheral.
2989 		 * The peripheral will only go away once the last reference
2990 		 * is removed, and we need it around for the CCB release
2991 		 * operation.
2992 		 */
2993 
2994 		xpt_release_ccb(done_ccb);
2995 		softc->state = ADA_STATE_WCACHE;
2996 		xpt_schedule(periph, priority);
2997 		/* Drop freeze taken due to CAM_DEV_QFREEZE */
2998 		cam_release_devq(path, 0, 0, 0, FALSE);
2999 		return;
3000 	}
3001 	case ADA_CCB_WCACHE:
3002 	{
3003 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3004 			if (adaerror(done_ccb, 0, 0) == ERESTART) {
3005 				/* Drop freeze taken due to CAM_DEV_QFREEZE */
3006 				cam_release_devq(path, 0, 0, 0, FALSE);
3007 				return;
3008 			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3009 				cam_release_devq(path,
3010 				    /*relsim_flags*/0,
3011 				    /*reduction*/0,
3012 				    /*timeout*/0,
3013 				    /*getcount_only*/0);
3014 			}
3015 		}
3016 
3017 		/* Drop freeze taken due to CAM_DEV_QFREEZE */
3018 		cam_release_devq(path, 0, 0, 0, FALSE);
3019 
3020 		if ((softc->flags & ADA_FLAG_CAN_LOG)
3021 		 && (softc->zone_mode != ADA_ZONE_NONE)) {
3022 			xpt_release_ccb(done_ccb);
3023 			softc->state = ADA_STATE_LOGDIR;
3024 			xpt_schedule(periph, priority);
3025 		} else {
3026 			adaprobedone(periph, done_ccb);
3027 		}
3028 		return;
3029 	}
3030 	case ADA_CCB_LOGDIR:
3031 	{
3032 		int error;
3033 
3034 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3035 			error = 0;
3036 			softc->valid_logdir_len = 0;
3037 			bzero(&softc->ata_logdir, sizeof(softc->ata_logdir));
3038 			softc->valid_logdir_len =
3039 				ataio->dxfer_len - ataio->resid;
3040 			if (softc->valid_logdir_len > 0)
3041 				bcopy(ataio->data_ptr, &softc->ata_logdir,
3042 				    min(softc->valid_logdir_len,
3043 					sizeof(softc->ata_logdir)));
3044 			/*
3045 			 * Figure out whether the Identify Device log is
3046 			 * supported.  The General Purpose log directory
3047 			 * has a header, and lists the number of pages
3048 			 * available for each GP log identified by the
3049 			 * offset into the list.
3050 			 */
3051 			if ((softc->valid_logdir_len >=
3052 			    ((ATA_IDENTIFY_DATA_LOG + 1) * sizeof(uint16_t)))
3053 			 && (le16dec(softc->ata_logdir.header) ==
3054 			     ATA_GP_LOG_DIR_VERSION)
3055 			 && (le16dec(&softc->ata_logdir.num_pages[
3056 			     (ATA_IDENTIFY_DATA_LOG *
3057 			     sizeof(uint16_t)) - sizeof(uint16_t)]) > 0)){
3058 				softc->flags |= ADA_FLAG_CAN_IDLOG;
3059 			} else {
3060 				softc->flags &= ~ADA_FLAG_CAN_IDLOG;
3061 			}
3062 		} else {
3063 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3064 					 SF_RETRY_UA|SF_NO_PRINT);
3065 			if (error == ERESTART)
3066 				return;
3067 			else if (error != 0) {
3068 				/*
3069 				 * If we can't get the ATA log directory,
3070 				 * then ATA logs are effectively not
3071 				 * supported even if the bit is set in the
3072 				 * identify data.
3073 				 */
3074 				softc->flags &= ~(ADA_FLAG_CAN_LOG |
3075 						  ADA_FLAG_CAN_IDLOG);
3076 				if ((done_ccb->ccb_h.status &
3077 				     CAM_DEV_QFRZN) != 0) {
3078 					/* Don't wedge this device's queue */
3079 					cam_release_devq(done_ccb->ccb_h.path,
3080 							 /*relsim_flags*/0,
3081 							 /*reduction*/0,
3082 							 /*timeout*/0,
3083 							 /*getcount_only*/0);
3084 				}
3085 			}
3086 
3087 
3088 		}
3089 
3090 		free(ataio->data_ptr, M_ATADA);
3091 
3092 		if ((error == 0)
3093 		 && (softc->flags & ADA_FLAG_CAN_IDLOG)) {
3094 			softc->state = ADA_STATE_IDDIR;
3095 			xpt_release_ccb(done_ccb);
3096 			xpt_schedule(periph, priority);
3097 		} else
3098 			adaprobedone(periph, done_ccb);
3099 
3100 		return;
3101 	}
3102 	case ADA_CCB_IDDIR: {
3103 		int error;
3104 
3105 		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3106 			off_t entries_offset, max_entries;
3107 			error = 0;
3108 
3109 			softc->valid_iddir_len = 0;
3110 			bzero(&softc->ata_iddir, sizeof(softc->ata_iddir));
3111 			softc->flags &= ~(ADA_FLAG_CAN_SUPCAP |
3112 					  ADA_FLAG_CAN_ZONE);
3113 			softc->valid_iddir_len =
3114 				ataio->dxfer_len - ataio->resid;
3115 			if (softc->valid_iddir_len > 0)
3116 				bcopy(ataio->data_ptr, &softc->ata_iddir,
3117 				    min(softc->valid_iddir_len,
3118 					sizeof(softc->ata_iddir)));
3119 
3120 			entries_offset =
3121 			    __offsetof(struct ata_identify_log_pages,entries);
3122 			max_entries = softc->valid_iddir_len - entries_offset;
3123 			if ((softc->valid_iddir_len > (entries_offset + 1))
3124 			 && (le64dec(softc->ata_iddir.header) ==
3125 			     ATA_IDLOG_REVISION)
3126 			 && (softc->ata_iddir.entry_count > 0)) {
3127 				int num_entries, i;
3128 
3129 				num_entries = softc->ata_iddir.entry_count;
3130 				num_entries = min(num_entries,
3131 				   softc->valid_iddir_len - entries_offset);
3132 				for (i = 0; i < num_entries &&
3133 				     i < max_entries; i++) {
3134 					if (softc->ata_iddir.entries[i] ==
3135 					    ATA_IDL_SUP_CAP)
3136 						softc->flags |=
3137 						    ADA_FLAG_CAN_SUPCAP;
3138 					else if (softc->ata_iddir.entries[i]==
3139 						 ATA_IDL_ZDI)
3140 						softc->flags |=
3141 						    ADA_FLAG_CAN_ZONE;
3142 
3143 					if ((softc->flags &
3144 					     ADA_FLAG_CAN_SUPCAP)
3145 					 && (softc->flags &
3146 					     ADA_FLAG_CAN_ZONE))
3147 						break;
3148 				}
3149 			}
3150 		} else {
3151 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3152 					 SF_RETRY_UA|SF_NO_PRINT);
3153 			if (error == ERESTART)
3154 				return;
3155 			else if (error != 0) {
3156 				/*
3157 				 * If we can't get the ATA Identify Data log
3158 				 * directory, then it effectively isn't
3159 				 * supported even if the ATA Log directory
3160 				 * a non-zero number of pages present for
3161 				 * this log.
3162 				 */
3163 				softc->flags &= ~ADA_FLAG_CAN_IDLOG;
3164 				if ((done_ccb->ccb_h.status &
3165 				     CAM_DEV_QFRZN) != 0) {
3166 					/* Don't wedge this device's queue */
3167 					cam_release_devq(done_ccb->ccb_h.path,
3168 							 /*relsim_flags*/0,
3169 							 /*reduction*/0,
3170 							 /*timeout*/0,
3171 							 /*getcount_only*/0);
3172 				}
3173 			}
3174 		}
3175 
3176 		free(ataio->data_ptr, M_ATADA);
3177 
3178 		if ((error == 0)
3179 		 && (softc->flags & ADA_FLAG_CAN_SUPCAP)) {
3180 			softc->state = ADA_STATE_SUP_CAP;
3181 			xpt_release_ccb(done_ccb);
3182 			xpt_schedule(periph, priority);
3183 		} else
3184 			adaprobedone(periph, done_ccb);
3185 		return;
3186 	}
3187 	case ADA_CCB_SUP_CAP: {
3188 		int error;
3189 
3190 		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3191 			uint32_t valid_len;
3192 			size_t needed_size;
3193 			struct ata_identify_log_sup_cap *sup_cap;
3194 			error = 0;
3195 
3196 			sup_cap = (struct ata_identify_log_sup_cap *)
3197 			    ataio->data_ptr;
3198 			valid_len = ataio->dxfer_len - ataio->resid;
3199 			needed_size =
3200 			    __offsetof(struct ata_identify_log_sup_cap,
3201 			    sup_zac_cap) + 1 + sizeof(sup_cap->sup_zac_cap);
3202 			if (valid_len >= needed_size) {
3203 				uint64_t zoned, zac_cap;
3204 
3205 				zoned = le64dec(sup_cap->zoned_cap);
3206 				if (zoned & ATA_ZONED_VALID) {
3207 					/*
3208 					 * This should have already been
3209 					 * set, because this is also in the
3210 					 * ATA identify data.
3211 					 */
3212 					if ((zoned & ATA_ZONED_MASK) ==
3213 					    ATA_SUPPORT_ZONE_HOST_AWARE)
3214 						softc->zone_mode =
3215 						    ADA_ZONE_HOST_AWARE;
3216 					else if ((zoned & ATA_ZONED_MASK) ==
3217 					    ATA_SUPPORT_ZONE_DEV_MANAGED)
3218 						softc->zone_mode =
3219 						    ADA_ZONE_DRIVE_MANAGED;
3220 				}
3221 
3222 				zac_cap = le64dec(sup_cap->sup_zac_cap);
3223 				if (zac_cap & ATA_SUP_ZAC_CAP_VALID) {
3224 					if (zac_cap & ATA_REPORT_ZONES_SUP)
3225 						softc->zone_flags |=
3226 						    ADA_ZONE_FLAG_RZ_SUP;
3227 					if (zac_cap & ATA_ND_OPEN_ZONE_SUP)
3228 						softc->zone_flags |=
3229 						    ADA_ZONE_FLAG_OPEN_SUP;
3230 					if (zac_cap & ATA_ND_CLOSE_ZONE_SUP)
3231 						softc->zone_flags |=
3232 						    ADA_ZONE_FLAG_CLOSE_SUP;
3233 					if (zac_cap & ATA_ND_FINISH_ZONE_SUP)
3234 						softc->zone_flags |=
3235 						    ADA_ZONE_FLAG_FINISH_SUP;
3236 					if (zac_cap & ATA_ND_RWP_SUP)
3237 						softc->zone_flags |=
3238 						    ADA_ZONE_FLAG_RWP_SUP;
3239 				} else {
3240 					/*
3241 					 * This field was introduced in
3242 					 * ACS-4, r08 on April 28th, 2015.
3243 					 * If the drive firmware was written
3244 					 * to an earlier spec, it won't have
3245 					 * the field.  So, assume all
3246 					 * commands are supported.
3247 					 */
3248 					softc->zone_flags |=
3249 					    ADA_ZONE_FLAG_SUP_MASK;
3250 				}
3251 			}
3252 		} else {
3253 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3254 					 SF_RETRY_UA|SF_NO_PRINT);
3255 			if (error == ERESTART)
3256 				return;
3257 			else if (error != 0) {
3258 				/*
3259 				 * If we can't get the ATA Identify Data
3260 				 * Supported Capabilities page, clear the
3261 				 * flag...
3262 				 */
3263 				softc->flags &= ~ADA_FLAG_CAN_SUPCAP;
3264 				/*
3265 				 * And clear zone capabilities.
3266 				 */
3267 				softc->zone_flags &= ~ADA_ZONE_FLAG_SUP_MASK;
3268 				if ((done_ccb->ccb_h.status &
3269 				     CAM_DEV_QFRZN) != 0) {
3270 					/* Don't wedge this device's queue */
3271 					cam_release_devq(done_ccb->ccb_h.path,
3272 							 /*relsim_flags*/0,
3273 							 /*reduction*/0,
3274 							 /*timeout*/0,
3275 							 /*getcount_only*/0);
3276 				}
3277 			}
3278 		}
3279 
3280 		free(ataio->data_ptr, M_ATADA);
3281 
3282 		if ((error == 0)
3283 		 && (softc->flags & ADA_FLAG_CAN_ZONE)) {
3284 			softc->state = ADA_STATE_ZONE;
3285 			xpt_release_ccb(done_ccb);
3286 			xpt_schedule(periph, priority);
3287 		} else
3288 			adaprobedone(periph, done_ccb);
3289 		return;
3290 	}
3291 	case ADA_CCB_ZONE: {
3292 		int error;
3293 
3294 		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3295 			struct ata_zoned_info_log *zi_log;
3296 			uint32_t valid_len;
3297 			size_t needed_size;
3298 
3299 			zi_log = (struct ata_zoned_info_log *)ataio->data_ptr;
3300 
3301 			valid_len = ataio->dxfer_len - ataio->resid;
3302 			needed_size = __offsetof(struct ata_zoned_info_log,
3303 			    version_info) + 1 + sizeof(zi_log->version_info);
3304 			if (valid_len >= needed_size) {
3305 				uint64_t tmpvar;
3306 
3307 				tmpvar = le64dec(zi_log->zoned_cap);
3308 				if (tmpvar & ATA_ZDI_CAP_VALID) {
3309 					if (tmpvar & ATA_ZDI_CAP_URSWRZ)
3310 						softc->zone_flags |=
3311 						    ADA_ZONE_FLAG_URSWRZ;
3312 					else
3313 						softc->zone_flags &=
3314 						    ~ADA_ZONE_FLAG_URSWRZ;
3315 				}
3316 				tmpvar = le64dec(zi_log->optimal_seq_zones);
3317 				if (tmpvar & ATA_ZDI_OPT_SEQ_VALID) {
3318 					softc->zone_flags |=
3319 					    ADA_ZONE_FLAG_OPT_SEQ_SET;
3320 					softc->optimal_seq_zones = (tmpvar &
3321 					    ATA_ZDI_OPT_SEQ_MASK);
3322 				} else {
3323 					softc->zone_flags &=
3324 					    ~ADA_ZONE_FLAG_OPT_SEQ_SET;
3325 					softc->optimal_seq_zones = 0;
3326 				}
3327 
3328 				tmpvar =le64dec(zi_log->optimal_nonseq_zones);
3329 				if (tmpvar & ATA_ZDI_OPT_NS_VALID) {
3330 					softc->zone_flags |=
3331 					    ADA_ZONE_FLAG_OPT_NONSEQ_SET;
3332 					softc->optimal_nonseq_zones =
3333 					    (tmpvar & ATA_ZDI_OPT_NS_MASK);
3334 				} else {
3335 					softc->zone_flags &=
3336 					    ~ADA_ZONE_FLAG_OPT_NONSEQ_SET;
3337 					softc->optimal_nonseq_zones = 0;
3338 				}
3339 
3340 				tmpvar = le64dec(zi_log->max_seq_req_zones);
3341 				if (tmpvar & ATA_ZDI_MAX_SEQ_VALID) {
3342 					softc->zone_flags |=
3343 					    ADA_ZONE_FLAG_MAX_SEQ_SET;
3344 					softc->max_seq_zones =
3345 					    (tmpvar & ATA_ZDI_MAX_SEQ_MASK);
3346 				} else {
3347 					softc->zone_flags &=
3348 					    ~ADA_ZONE_FLAG_MAX_SEQ_SET;
3349 					softc->max_seq_zones = 0;
3350 				}
3351 			}
3352 		} else {
3353 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3354 					 SF_RETRY_UA|SF_NO_PRINT);
3355 			if (error == ERESTART)
3356 				return;
3357 			else if (error != 0) {
3358 				softc->flags &= ~ADA_FLAG_CAN_ZONE;
3359 				softc->flags &= ~ADA_ZONE_FLAG_SET_MASK;
3360 
3361 				if ((done_ccb->ccb_h.status &
3362 				     CAM_DEV_QFRZN) != 0) {
3363 					/* Don't wedge this device's queue */
3364 					cam_release_devq(done_ccb->ccb_h.path,
3365 							 /*relsim_flags*/0,
3366 							 /*reduction*/0,
3367 							 /*timeout*/0,
3368 							 /*getcount_only*/0);
3369 				}
3370 			}
3371 		}
3372 		free(ataio->data_ptr, M_ATADA);
3373 
3374 		adaprobedone(periph, done_ccb);
3375 		return;
3376 	}
3377 	case ADA_CCB_DUMP:
3378 		/* No-op.  We're polling */
3379 		return;
3380 	default:
3381 		break;
3382 	}
3383 	xpt_release_ccb(done_ccb);
3384 }
3385 
3386 static int
3387 adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3388 {
3389 #ifdef CAM_IO_STATS
3390 	struct ada_softc *softc;
3391 	struct cam_periph *periph;
3392 
3393 	periph = xpt_path_periph(ccb->ccb_h.path);
3394 	softc = (struct ada_softc *)periph->softc;
3395 
3396 	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
3397 	case CAM_CMD_TIMEOUT:
3398 		softc->timeouts++;
3399 		break;
3400 	case CAM_REQ_ABORTED:
3401 	case CAM_REQ_CMP_ERR:
3402 	case CAM_REQ_TERMIO:
3403 	case CAM_UNREC_HBA_ERROR:
3404 	case CAM_DATA_RUN_ERR:
3405 	case CAM_ATA_STATUS_ERROR:
3406 		softc->errors++;
3407 		break;
3408 	default:
3409 		break;
3410 	}
3411 #endif
3412 
3413 	return(cam_periph_error(ccb, cam_flags, sense_flags));
3414 }
3415 
3416 static void
3417 adasetgeom(struct ada_softc *softc, struct ccb_getdev *cgd)
3418 {
3419 	struct disk_params *dp = &softc->params;
3420 	u_int64_t lbasize48;
3421 	u_int32_t lbasize;
3422 	u_int maxio, d_flags;
3423 
3424 	dp->secsize = ata_logical_sector_size(&cgd->ident_data);
3425 	if ((cgd->ident_data.atavalid & ATA_FLAG_54_58) &&
3426 	    cgd->ident_data.current_heads != 0 &&
3427 	    cgd->ident_data.current_sectors != 0) {
3428 		dp->heads = cgd->ident_data.current_heads;
3429 		dp->secs_per_track = cgd->ident_data.current_sectors;
3430 		dp->cylinders = cgd->ident_data.cylinders;
3431 		dp->sectors = (u_int32_t)cgd->ident_data.current_size_1 |
3432 			  ((u_int32_t)cgd->ident_data.current_size_2 << 16);
3433 	} else {
3434 		dp->heads = cgd->ident_data.heads;
3435 		dp->secs_per_track = cgd->ident_data.sectors;
3436 		dp->cylinders = cgd->ident_data.cylinders;
3437 		dp->sectors = cgd->ident_data.cylinders *
3438 			      (u_int32_t)(dp->heads * dp->secs_per_track);
3439 	}
3440 	lbasize = (u_int32_t)cgd->ident_data.lba_size_1 |
3441 		  ((u_int32_t)cgd->ident_data.lba_size_2 << 16);
3442 
3443 	/* use the 28bit LBA size if valid or bigger than the CHS mapping */
3444 	if (cgd->ident_data.cylinders == 16383 || dp->sectors < lbasize)
3445 		dp->sectors = lbasize;
3446 
3447 	/* use the 48bit LBA size if valid */
3448 	lbasize48 = ((u_int64_t)cgd->ident_data.lba_size48_1) |
3449 		    ((u_int64_t)cgd->ident_data.lba_size48_2 << 16) |
3450 		    ((u_int64_t)cgd->ident_data.lba_size48_3 << 32) |
3451 		    ((u_int64_t)cgd->ident_data.lba_size48_4 << 48);
3452 	if ((cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) &&
3453 	    lbasize48 > ATA_MAX_28BIT_LBA)
3454 		dp->sectors = lbasize48;
3455 
3456 	maxio = softc->cpi.maxio;		/* Honor max I/O size of SIM */
3457 	if (maxio == 0)
3458 		maxio = DFLTPHYS;	/* traditional default */
3459 	else if (maxio > MAXPHYS)
3460 		maxio = MAXPHYS;	/* for safety */
3461 	if (softc->flags & ADA_FLAG_CAN_48BIT)
3462 		maxio = min(maxio, 65536 * softc->params.secsize);
3463 	else					/* 28bit ATA command limit */
3464 		maxio = min(maxio, 256 * softc->params.secsize);
3465 	if (softc->quirks & ADA_Q_128KB)
3466 		maxio = min(maxio, 128 * 1024);
3467 	softc->disk->d_maxsize = maxio;
3468 	d_flags = DISKFLAG_DIRECT_COMPLETION | DISKFLAG_CANZONE;
3469 	if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE)
3470 		d_flags |= DISKFLAG_CANFLUSHCACHE;
3471 	if (softc->flags & ADA_FLAG_CAN_TRIM) {
3472 		d_flags |= DISKFLAG_CANDELETE;
3473 		softc->disk->d_delmaxsize = softc->params.secsize *
3474 		    ATA_DSM_RANGE_MAX * softc->trim_max_ranges;
3475 	} else if ((softc->flags & ADA_FLAG_CAN_CFA) &&
3476 	    !(softc->flags & ADA_FLAG_CAN_48BIT)) {
3477 		d_flags |= DISKFLAG_CANDELETE;
3478 		softc->disk->d_delmaxsize = 256 * softc->params.secsize;
3479 	} else
3480 		softc->disk->d_delmaxsize = maxio;
3481 	if ((softc->cpi.hba_misc & PIM_UNMAPPED) != 0) {
3482 		d_flags |= DISKFLAG_UNMAPPED_BIO;
3483 		softc->flags |= ADA_FLAG_UNMAPPEDIO;
3484 	}
3485 	softc->disk->d_flags = d_flags;
3486 	strlcpy(softc->disk->d_descr, cgd->ident_data.model,
3487 	    MIN(sizeof(softc->disk->d_descr), sizeof(cgd->ident_data.model)));
3488 	strlcpy(softc->disk->d_ident, cgd->ident_data.serial,
3489 	    MIN(sizeof(softc->disk->d_ident), sizeof(cgd->ident_data.serial)));
3490 
3491 	softc->disk->d_sectorsize = softc->params.secsize;
3492 	softc->disk->d_mediasize = (off_t)softc->params.sectors *
3493 	    softc->params.secsize;
3494 	if (ata_physical_sector_size(&cgd->ident_data) !=
3495 	    softc->params.secsize) {
3496 		softc->disk->d_stripesize =
3497 		    ata_physical_sector_size(&cgd->ident_data);
3498 		softc->disk->d_stripeoffset = (softc->disk->d_stripesize -
3499 		    ata_logical_sector_offset(&cgd->ident_data)) %
3500 		    softc->disk->d_stripesize;
3501 	} else if (softc->quirks & ADA_Q_4K) {
3502 		softc->disk->d_stripesize = 4096;
3503 		softc->disk->d_stripeoffset = 0;
3504 	}
3505 	softc->disk->d_fwsectors = softc->params.secs_per_track;
3506 	softc->disk->d_fwheads = softc->params.heads;
3507 	ata_disk_firmware_geom_adjust(softc->disk);
3508 	softc->disk->d_rotation_rate = cgd->ident_data.media_rotation_rate;
3509 	snprintf(softc->disk->d_attachment, sizeof(softc->disk->d_attachment),
3510 	    "%s%d", softc->cpi.dev_name, softc->cpi.unit_number);
3511 }
3512 
3513 static void
3514 adasendorderedtag(void *arg)
3515 {
3516 	struct ada_softc *softc = arg;
3517 
3518 	if (ada_send_ordered) {
3519 		if (softc->outstanding_cmds > 0) {
3520 			if ((softc->flags & ADA_FLAG_WAS_OTAG) == 0)
3521 				softc->flags |= ADA_FLAG_NEED_OTAG;
3522 			softc->flags &= ~ADA_FLAG_WAS_OTAG;
3523 		}
3524 	}
3525 	/* Queue us up again */
3526 	callout_reset(&softc->sendordered_c,
3527 	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
3528 	    adasendorderedtag, softc);
3529 }
3530 
3531 /*
3532  * Step through all ADA peripheral drivers, and if the device is still open,
3533  * sync the disk cache to physical media.
3534  */
3535 static void
3536 adaflush(void)
3537 {
3538 	struct cam_periph *periph;
3539 	struct ada_softc *softc;
3540 	union ccb *ccb;
3541 	int error;
3542 
3543 	CAM_PERIPH_FOREACH(periph, &adadriver) {
3544 		softc = (struct ada_softc *)periph->softc;
3545 		if (SCHEDULER_STOPPED()) {
3546 			/* If we paniced with the lock held, do not recurse. */
3547 			if (!cam_periph_owned(periph) &&
3548 			    (softc->flags & ADA_FLAG_OPEN)) {
3549 				adadump(softc->disk, NULL, 0, 0, 0);
3550 			}
3551 			continue;
3552 		}
3553 		cam_periph_lock(periph);
3554 		/*
3555 		 * We only sync the cache if the drive is still open, and
3556 		 * if the drive is capable of it..
3557 		 */
3558 		if (((softc->flags & ADA_FLAG_OPEN) == 0) ||
3559 		    (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) == 0) {
3560 			cam_periph_unlock(periph);
3561 			continue;
3562 		}
3563 
3564 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3565 		cam_fill_ataio(&ccb->ataio,
3566 				    0,
3567 				    NULL,
3568 				    CAM_DIR_NONE,
3569 				    0,
3570 				    NULL,
3571 				    0,
3572 				    ada_default_timeout*1000);
3573 		if (softc->flags & ADA_FLAG_CAN_48BIT)
3574 			ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
3575 		else
3576 			ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
3577 
3578 		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
3579 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
3580 		    softc->disk->d_devstat);
3581 		if (error != 0)
3582 			xpt_print(periph->path, "Synchronize cache failed\n");
3583 		xpt_release_ccb(ccb);
3584 		cam_periph_unlock(periph);
3585 	}
3586 }
3587 
3588 static void
3589 adaspindown(uint8_t cmd, int flags)
3590 {
3591 	struct cam_periph *periph;
3592 	struct ada_softc *softc;
3593 	struct ccb_ataio local_ccb;
3594 	int error;
3595 
3596 	CAM_PERIPH_FOREACH(periph, &adadriver) {
3597 		/* If we paniced with lock held - not recurse here. */
3598 		if (cam_periph_owned(periph))
3599 			continue;
3600 		cam_periph_lock(periph);
3601 		softc = (struct ada_softc *)periph->softc;
3602 		/*
3603 		 * We only spin-down the drive if it is capable of it..
3604 		 */
3605 		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
3606 			cam_periph_unlock(periph);
3607 			continue;
3608 		}
3609 
3610 		if (bootverbose)
3611 			xpt_print(periph->path, "spin-down\n");
3612 
3613 		memset(&local_ccb, 0, sizeof(local_ccb));
3614 		xpt_setup_ccb(&local_ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3615 		local_ccb.ccb_h.ccb_state = ADA_CCB_DUMP;
3616 
3617 		cam_fill_ataio(&local_ccb,
3618 				    0,
3619 				    NULL,
3620 				    CAM_DIR_NONE | flags,
3621 				    0,
3622 				    NULL,
3623 				    0,
3624 				    ada_default_timeout*1000);
3625 		ata_28bit_cmd(&local_ccb, cmd, 0, 0, 0);
3626 		error = cam_periph_runccb((union ccb *)&local_ccb, adaerror,
3627 		    /*cam_flags*/0, /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
3628 		    softc->disk->d_devstat);
3629 		if (error != 0)
3630 			xpt_print(periph->path, "Spin-down disk failed\n");
3631 		cam_periph_unlock(periph);
3632 	}
3633 }
3634 
3635 static void
3636 adashutdown(void *arg, int howto)
3637 {
3638 	int how;
3639 
3640 	adaflush();
3641 
3642 	/*
3643 	 * STANDBY IMMEDIATE saves any volatile data to the drive. It also spins
3644 	 * down hard drives. IDLE IMMEDIATE also saves the volatile data without
3645 	 * a spindown. We send the former when we expect to lose power soon. For
3646 	 * a warm boot, we send the latter to avoid a thundering herd of spinups
3647 	 * just after the kernel loads while probing. We have to do something to
3648 	 * flush the data because the BIOS in many systems resets the HBA
3649 	 * causing a COMINIT/COMRESET negotiation, which some drives interpret
3650 	 * as license to toss the volatile data, and others count as unclean
3651 	 * shutdown when in the Active PM state in SMART attributes.
3652 	 *
3653 	 * adaspindown will ensure that we don't send this to a drive that
3654 	 * doesn't support it.
3655 	 */
3656 	if (ada_spindown_shutdown != 0) {
3657 		how = (howto & (RB_HALT | RB_POWEROFF | RB_POWERCYCLE)) ?
3658 		    ATA_STANDBY_IMMEDIATE : ATA_IDLE_IMMEDIATE;
3659 		adaspindown(how, 0);
3660 	}
3661 }
3662 
3663 static void
3664 adasuspend(void *arg)
3665 {
3666 
3667 	adaflush();
3668 	/*
3669 	 * SLEEP also fushes any volatile data, like STANDBY IMEDIATE,
3670 	 * so we don't need to send it as well.
3671 	 */
3672 	if (ada_spindown_suspend != 0)
3673 		adaspindown(ATA_SLEEP, CAM_DEV_QFREEZE);
3674 }
3675 
3676 static void
3677 adaresume(void *arg)
3678 {
3679 	struct cam_periph *periph;
3680 	struct ada_softc *softc;
3681 
3682 	if (ada_spindown_suspend == 0)
3683 		return;
3684 
3685 	CAM_PERIPH_FOREACH(periph, &adadriver) {
3686 		cam_periph_lock(periph);
3687 		softc = (struct ada_softc *)periph->softc;
3688 		/*
3689 		 * We only spin-down the drive if it is capable of it..
3690 		 */
3691 		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
3692 			cam_periph_unlock(periph);
3693 			continue;
3694 		}
3695 
3696 		if (bootverbose)
3697 			xpt_print(periph->path, "resume\n");
3698 
3699 		/*
3700 		 * Drop freeze taken due to CAM_DEV_QFREEZE flag set on
3701 		 * sleep request.
3702 		 */
3703 		cam_release_devq(periph->path,
3704 			 /*relsim_flags*/0,
3705 			 /*openings*/0,
3706 			 /*timeout*/0,
3707 			 /*getcount_only*/0);
3708 
3709 		cam_periph_unlock(periph);
3710 	}
3711 }
3712 
3713 #endif /* _KERNEL */
3714