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