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