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