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