xref: /freebsd/sys/cam/ata/ata_da.c (revision f56f82e0)
1 /*-
2  * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_ada.h"
31 
32 #include <sys/param.h>
33 
34 #ifdef _KERNEL
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/bio.h>
38 #include <sys/sysctl.h>
39 #include <sys/taskqueue.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/conf.h>
43 #include <sys/devicestat.h>
44 #include <sys/eventhandler.h>
45 #include <sys/malloc.h>
46 #include <sys/endian.h>
47 #include <sys/cons.h>
48 #include <sys/proc.h>
49 #include <sys/reboot.h>
50 #include <sys/sbuf.h>
51 #include <geom/geom_disk.h>
52 #endif /* _KERNEL */
53 
54 #ifndef _KERNEL
55 #include <stdio.h>
56 #include <string.h>
57 #endif /* _KERNEL */
58 
59 #include <cam/cam.h>
60 #include <cam/cam_ccb.h>
61 #include <cam/cam_periph.h>
62 #include <cam/cam_xpt_periph.h>
63 #include <cam/scsi/scsi_all.h>
64 #include <cam/scsi/scsi_da.h>
65 #include <cam/cam_sim.h>
66 #include <cam/cam_iosched.h>
67 
68 #include <cam/ata/ata_all.h>
69 
70 #include <machine/md_var.h>	/* geometry translation */
71 
72 #ifdef _KERNEL
73 
74 #define ATA_MAX_28BIT_LBA               268435455UL
75 
76 extern int iosched_debug;
77 
78 typedef enum {
79 	ADA_STATE_RAHEAD,
80 	ADA_STATE_WCACHE,
81 	ADA_STATE_LOGDIR,
82 	ADA_STATE_IDDIR,
83 	ADA_STATE_SUP_CAP,
84 	ADA_STATE_ZONE,
85 	ADA_STATE_NORMAL
86 } ada_state;
87 
88 typedef enum {
89 	ADA_FLAG_CAN_48BIT	= 0x00000002,
90 	ADA_FLAG_CAN_FLUSHCACHE	= 0x00000004,
91 	ADA_FLAG_CAN_NCQ	= 0x00000008,
92 	ADA_FLAG_CAN_DMA	= 0x00000010,
93 	ADA_FLAG_NEED_OTAG	= 0x00000020,
94 	ADA_FLAG_WAS_OTAG	= 0x00000040,
95 	ADA_FLAG_CAN_TRIM	= 0x00000080,
96 	ADA_FLAG_OPEN		= 0x00000100,
97 	ADA_FLAG_SCTX_INIT	= 0x00000200,
98 	ADA_FLAG_CAN_CFA        = 0x00000400,
99 	ADA_FLAG_CAN_POWERMGT   = 0x00000800,
100 	ADA_FLAG_CAN_DMA48	= 0x00001000,
101 	ADA_FLAG_CAN_LOG	= 0x00002000,
102 	ADA_FLAG_CAN_IDLOG	= 0x00004000,
103 	ADA_FLAG_CAN_SUPCAP	= 0x00008000,
104 	ADA_FLAG_CAN_ZONE	= 0x00010000,
105 	ADA_FLAG_CAN_WCACHE	= 0x00020000,
106 	ADA_FLAG_CAN_RAHEAD	= 0x00040000,
107 	ADA_FLAG_PROBED		= 0x00080000,
108 	ADA_FLAG_ANNOUNCED	= 0x00100000,
109 	ADA_FLAG_DIRTY		= 0x00200000,
110 	ADA_FLAG_CAN_NCQ_TRIM	= 0x00400000,	/* CAN_TRIM also set */
111 	ADA_FLAG_PIM_ATA_EXT	= 0x00800000
112 } ada_flags;
113 
114 typedef enum {
115 	ADA_Q_NONE		= 0x00,
116 	ADA_Q_4K		= 0x01,
117 	ADA_Q_NCQ_TRIM_BROKEN	= 0x02,
118 	ADA_Q_LOG_BROKEN	= 0x04,
119 	ADA_Q_SMR_DM		= 0x08
120 } ada_quirks;
121 
122 #define ADA_Q_BIT_STRING	\
123 	"\020"			\
124 	"\0014K"		\
125 	"\002NCQ_TRIM_BROKEN"	\
126 	"\003LOG_BROKEN"	\
127 	"\004SMR_DM"
128 
129 typedef enum {
130 	ADA_CCB_RAHEAD		= 0x01,
131 	ADA_CCB_WCACHE		= 0x02,
132 	ADA_CCB_BUFFER_IO	= 0x03,
133 	ADA_CCB_DUMP		= 0x05,
134 	ADA_CCB_TRIM		= 0x06,
135 	ADA_CCB_LOGDIR		= 0x07,
136 	ADA_CCB_IDDIR		= 0x08,
137 	ADA_CCB_SUP_CAP		= 0x09,
138 	ADA_CCB_ZONE		= 0x0a,
139 	ADA_CCB_TYPE_MASK	= 0x0F,
140 } ada_ccb_state;
141 
142 typedef enum {
143 	ADA_ZONE_NONE		= 0x00,
144 	ADA_ZONE_DRIVE_MANAGED	= 0x01,
145 	ADA_ZONE_HOST_AWARE	= 0x02,
146 	ADA_ZONE_HOST_MANAGED	= 0x03
147 } ada_zone_mode;
148 
149 typedef enum {
150 	ADA_ZONE_FLAG_RZ_SUP		= 0x0001,
151 	ADA_ZONE_FLAG_OPEN_SUP		= 0x0002,
152 	ADA_ZONE_FLAG_CLOSE_SUP		= 0x0004,
153 	ADA_ZONE_FLAG_FINISH_SUP	= 0x0008,
154 	ADA_ZONE_FLAG_RWP_SUP		= 0x0010,
155 	ADA_ZONE_FLAG_SUP_MASK		= (ADA_ZONE_FLAG_RZ_SUP |
156 					   ADA_ZONE_FLAG_OPEN_SUP |
157 					   ADA_ZONE_FLAG_CLOSE_SUP |
158 					   ADA_ZONE_FLAG_FINISH_SUP |
159 					   ADA_ZONE_FLAG_RWP_SUP),
160 	ADA_ZONE_FLAG_URSWRZ		= 0x0020,
161 	ADA_ZONE_FLAG_OPT_SEQ_SET	= 0x0040,
162 	ADA_ZONE_FLAG_OPT_NONSEQ_SET	= 0x0080,
163 	ADA_ZONE_FLAG_MAX_SEQ_SET	= 0x0100,
164 	ADA_ZONE_FLAG_SET_MASK		= (ADA_ZONE_FLAG_OPT_SEQ_SET |
165 					   ADA_ZONE_FLAG_OPT_NONSEQ_SET |
166 					   ADA_ZONE_FLAG_MAX_SEQ_SET)
167 } ada_zone_flags;
168 
169 static struct ada_zone_desc {
170 	ada_zone_flags value;
171 	const char *desc;
172 } ada_zone_desc_table[] = {
173 	{ADA_ZONE_FLAG_RZ_SUP, "Report Zones" },
174 	{ADA_ZONE_FLAG_OPEN_SUP, "Open" },
175 	{ADA_ZONE_FLAG_CLOSE_SUP, "Close" },
176 	{ADA_ZONE_FLAG_FINISH_SUP, "Finish" },
177 	{ADA_ZONE_FLAG_RWP_SUP, "Reset Write Pointer" },
178 };
179 
180 
181 /* Offsets into our private area for storing information */
182 #define ccb_state	ppriv_field0
183 #define ccb_bp		ppriv_ptr1
184 
185 typedef enum {
186 	ADA_DELETE_NONE,
187 	ADA_DELETE_DISABLE,
188 	ADA_DELETE_CFA_ERASE,
189 	ADA_DELETE_DSM_TRIM,
190 	ADA_DELETE_NCQ_DSM_TRIM,
191 	ADA_DELETE_MIN = ADA_DELETE_CFA_ERASE,
192 	ADA_DELETE_MAX = ADA_DELETE_NCQ_DSM_TRIM,
193 } ada_delete_methods;
194 
195 static const char *ada_delete_method_names[] =
196     { "NONE", "DISABLE", "CFA_ERASE", "DSM_TRIM", "NCQ_DSM_TRIM" };
197 #if 0
198 static const char *ada_delete_method_desc[] =
199     { "NONE", "DISABLED", "CFA Erase", "DSM Trim", "DSM Trim via NCQ" };
200 #endif
201 
202 struct disk_params {
203 	u_int8_t  heads;
204 	u_int8_t  secs_per_track;
205 	u_int32_t cylinders;
206 	u_int32_t secsize;	/* Number of bytes/logical sector */
207 	u_int64_t sectors;	/* Total number sectors */
208 };
209 
210 #define TRIM_MAX_BLOCKS	8
211 #define TRIM_MAX_RANGES	(TRIM_MAX_BLOCKS * ATA_DSM_BLK_RANGES)
212 struct trim_request {
213 	uint8_t		data[TRIM_MAX_RANGES * ATA_DSM_RANGE_SIZE];
214 	TAILQ_HEAD(, bio) bps;
215 };
216 
217 struct ada_softc {
218 	struct   cam_iosched_softc *cam_iosched;
219 	int	 outstanding_cmds;	/* Number of active commands */
220 	int	 refcount;		/* Active xpt_action() calls */
221 	ada_state state;
222 	ada_flags flags;
223 	ada_zone_mode zone_mode;
224 	ada_zone_flags zone_flags;
225 	struct ata_gp_log_dir ata_logdir;
226 	int valid_logdir_len;
227 	struct ata_identify_log_pages ata_iddir;
228 	int valid_iddir_len;
229 	uint64_t optimal_seq_zones;
230 	uint64_t optimal_nonseq_zones;
231 	uint64_t max_seq_zones;
232 	ada_quirks quirks;
233 	ada_delete_methods delete_method;
234 	int	 trim_max_ranges;
235 	int	 read_ahead;
236 	int	 write_cache;
237 	int	 unmappedio;
238 	int	 rotating;
239 #ifdef ADA_TEST_FAILURE
240 	int      force_read_error;
241 	int      force_write_error;
242 	int      periodic_read_error;
243 	int      periodic_read_count;
244 #endif
245 	struct	 disk_params params;
246 	struct	 disk *disk;
247 	struct task		sysctl_task;
248 	struct sysctl_ctx_list	sysctl_ctx;
249 	struct sysctl_oid	*sysctl_tree;
250 	struct callout		sendordered_c;
251 	struct trim_request	trim_req;
252 #ifdef CAM_IO_STATS
253 	struct sysctl_ctx_list	sysctl_stats_ctx;
254 	struct sysctl_oid	*sysctl_stats_tree;
255 	u_int	timeouts;
256 	u_int	errors;
257 	u_int	invalidations;
258 #endif
259 #define ADA_ANNOUNCETMP_SZ 80
260 	char	announce_temp[ADA_ANNOUNCETMP_SZ];
261 #define ADA_ANNOUNCE_SZ 400
262 	char	announce_buffer[ADA_ANNOUNCE_SZ];
263 };
264 
265 struct ada_quirk_entry {
266 	struct scsi_inquiry_pattern inq_pat;
267 	ada_quirks quirks;
268 };
269 
270 static struct ada_quirk_entry ada_quirk_table[] =
271 {
272 	{
273 		/* Hitachi Advanced Format (4k) drives */
274 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Hitachi H??????????E3*", "*" },
275 		/*quirks*/ADA_Q_4K
276 	},
277 	{
278 		/* Samsung Advanced Format (4k) drives */
279 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD155UI*", "*" },
280 		/*quirks*/ADA_Q_4K
281 	},
282 	{
283 		/* Samsung Advanced Format (4k) drives */
284 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD204UI*", "*" },
285 		/*quirks*/ADA_Q_4K
286 	},
287 	{
288 		/* Seagate Barracuda Green Advanced Format (4k) drives */
289 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DL*", "*" },
290 		/*quirks*/ADA_Q_4K
291 	},
292 	{
293 		/* Seagate Barracuda Advanced Format (4k) drives */
294 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???DM*", "*" },
295 		/*quirks*/ADA_Q_4K
296 	},
297 	{
298 		/* Seagate Barracuda Advanced Format (4k) drives */
299 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DM*", "*" },
300 		/*quirks*/ADA_Q_4K
301 	},
302 	{
303 		/* Seagate Momentus Advanced Format (4k) drives */
304 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500423AS*", "*" },
305 		/*quirks*/ADA_Q_4K
306 	},
307 	{
308 		/* Seagate Momentus Advanced Format (4k) drives */
309 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500424AS*", "*" },
310 		/*quirks*/ADA_Q_4K
311 	},
312 	{
313 		/* Seagate Momentus Advanced Format (4k) drives */
314 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640423AS*", "*" },
315 		/*quirks*/ADA_Q_4K
316 	},
317 	{
318 		/* Seagate Momentus Advanced Format (4k) drives */
319 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640424AS*", "*" },
320 		/*quirks*/ADA_Q_4K
321 	},
322 	{
323 		/* Seagate Momentus Advanced Format (4k) drives */
324 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750420AS*", "*" },
325 		/*quirks*/ADA_Q_4K
326 	},
327 	{
328 		/* Seagate Momentus Advanced Format (4k) drives */
329 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750422AS*", "*" },
330 		/*quirks*/ADA_Q_4K
331 	},
332 	{
333 		/* Seagate Momentus Advanced Format (4k) drives */
334 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750423AS*", "*" },
335 		/*quirks*/ADA_Q_4K
336 	},
337 	{
338 		/* Seagate Momentus Thin Advanced Format (4k) drives */
339 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???LT*", "*" },
340 		/*quirks*/ADA_Q_4K
341 	},
342 	{
343 		/* WDC Caviar Red Advanced Format (4k) drives */
344 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????CX*", "*" },
345 		/*quirks*/ADA_Q_4K
346 	},
347 	{
348 		/* WDC Caviar Green Advanced Format (4k) drives */
349 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RS*", "*" },
350 		/*quirks*/ADA_Q_4K
351 	},
352 	{
353 		/* WDC Caviar Green/Red Advanced Format (4k) drives */
354 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RX*", "*" },
355 		/*quirks*/ADA_Q_4K
356 	},
357 	{
358 		/* WDC Caviar Red Advanced Format (4k) drives */
359 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????CX*", "*" },
360 		/*quirks*/ADA_Q_4K
361 	},
362 	{
363 		/* WDC Caviar Black Advanced Format (4k) drives */
364 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????EX*", "*" },
365 		/*quirks*/ADA_Q_4K
366 	},
367 	{
368 		/* WDC Caviar Green Advanced Format (4k) drives */
369 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RS*", "*" },
370 		/*quirks*/ADA_Q_4K
371 	},
372 	{
373 		/* WDC Caviar Green Advanced Format (4k) drives */
374 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RX*", "*" },
375 		/*quirks*/ADA_Q_4K
376 	},
377 	{
378 		/* WDC Scorpio Black Advanced Format (4k) drives */
379 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PKT*", "*" },
380 		/*quirks*/ADA_Q_4K
381 	},
382 	{
383 		/* WDC Scorpio Black Advanced Format (4k) drives */
384 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PKT*", "*" },
385 		/*quirks*/ADA_Q_4K
386 	},
387 	{
388 		/* WDC Scorpio Blue Advanced Format (4k) drives */
389 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PVT*", "*" },
390 		/*quirks*/ADA_Q_4K
391 	},
392 	{
393 		/* WDC Scorpio Blue Advanced Format (4k) drives */
394 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PVT*", "*" },
395 		/*quirks*/ADA_Q_4K
396 	},
397 	/* SSDs */
398 	{
399 		/*
400 		 * Corsair Force 2 SSDs
401 		 * 4k optimised & trim only works in 4k requests + 4k aligned
402 		 */
403 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair CSSD-F*", "*" },
404 		/*quirks*/ADA_Q_4K
405 	},
406 	{
407 		/*
408 		 * Corsair Force 3 SSDs
409 		 * 4k optimised & trim only works in 4k requests + 4k aligned
410 		 */
411 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force 3*", "*" },
412 		/*quirks*/ADA_Q_4K
413 	},
414 	{
415 		/*
416 		 * Corsair Neutron GTX SSDs
417 		 * 4k optimised & trim only works in 4k requests + 4k aligned
418 		 */
419 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Neutron GTX*", "*" },
420 		/*quirks*/ADA_Q_4K
421 	},
422 	{
423 		/*
424 		 * Corsair Force GT & GS SSDs
425 		 * 4k optimised & trim only works in 4k requests + 4k aligned
426 		 */
427 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force G*", "*" },
428 		/*quirks*/ADA_Q_4K
429 	},
430 	{
431 		/*
432 		 * Crucial M4 SSDs
433 		 * 4k optimised & trim only works in 4k requests + 4k aligned
434 		 */
435 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "M4-CT???M4SSD2*", "*" },
436 		/*quirks*/ADA_Q_4K
437 	},
438 	{
439 		/*
440 		 * Crucial M500 SSDs MU07 firmware
441 		 * NCQ Trim works
442 		 */
443 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "MU07" },
444 		/*quirks*/0
445 	},
446 	{
447 		/*
448 		 * Crucial M500 SSDs all other firmware
449 		 * NCQ Trim doesn't work
450 		 */
451 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "*" },
452 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
453 	},
454 	{
455 		/*
456 		 * Crucial M550 SSDs
457 		 * NCQ Trim doesn't work, but only on MU01 firmware
458 		 */
459 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M550*", "MU01" },
460 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
461 	},
462 	{
463 		/*
464 		 * Crucial MX100 SSDs
465 		 * NCQ Trim doesn't work, but only on MU01 firmware
466 		 */
467 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*MX100*", "MU01" },
468 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
469 	},
470 	{
471 		/*
472 		 * Crucial RealSSD C300 SSDs
473 		 * 4k optimised
474 		 */
475 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "C300-CTFDDAC???MAG*",
476 		"*" }, /*quirks*/ADA_Q_4K
477 	},
478 	{
479 		/*
480 		 * FCCT M500 SSDs
481 		 * NCQ Trim doesn't work
482 		 */
483 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "FCCT*M500*", "*" },
484 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
485 	},
486 	{
487 		/*
488 		 * Intel 320 Series SSDs
489 		 * 4k optimised & trim only works in 4k requests + 4k aligned
490 		 */
491 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSA2CW*", "*" },
492 		/*quirks*/ADA_Q_4K
493 	},
494 	{
495 		/*
496 		 * Intel 330 Series SSDs
497 		 * 4k optimised & trim only works in 4k requests + 4k aligned
498 		 */
499 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2CT*", "*" },
500 		/*quirks*/ADA_Q_4K
501 	},
502 	{
503 		/*
504 		 * Intel 510 Series SSDs
505 		 * 4k optimised & trim only works in 4k requests + 4k aligned
506 		 */
507 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2MH*", "*" },
508 		/*quirks*/ADA_Q_4K
509 	},
510 	{
511 		/*
512 		 * Intel 520 Series SSDs
513 		 * 4k optimised & trim only works in 4k requests + 4k aligned
514 		 */
515 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2BW*", "*" },
516 		/*quirks*/ADA_Q_4K
517 	},
518 	{
519 		/*
520 		 * Intel S3610 Series SSDs
521 		 * 4k optimised & trim only works in 4k requests + 4k aligned
522 		 */
523 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2BX*", "*" },
524 		/*quirks*/ADA_Q_4K
525 	},
526 	{
527 		/*
528 		 * Intel X25-M Series SSDs
529 		 * 4k optimised & trim only works in 4k requests + 4k aligned
530 		 */
531 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSA2M*", "*" },
532 		/*quirks*/ADA_Q_4K
533 	},
534 	{
535 		/*
536 		 * Kingston E100 Series SSDs
537 		 * 4k optimised & trim only works in 4k requests + 4k aligned
538 		 */
539 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SE100S3*", "*" },
540 		/*quirks*/ADA_Q_4K
541 	},
542 	{
543 		/*
544 		 * Kingston HyperX 3k SSDs
545 		 * 4k optimised & trim only works in 4k requests + 4k aligned
546 		 */
547 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SH103S3*", "*" },
548 		/*quirks*/ADA_Q_4K
549 	},
550 	{
551 		/*
552 		 * Marvell SSDs (entry taken from OpenSolaris)
553 		 * 4k optimised & trim only works in 4k requests + 4k aligned
554 		 */
555 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "MARVELL SD88SA02*", "*" },
556 		/*quirks*/ADA_Q_4K
557 	},
558 	{
559 		/*
560 		 * Micron M500 SSDs firmware MU07
561 		 * NCQ Trim works?
562 		 */
563 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "MU07" },
564 		/*quirks*/0
565 	},
566 	{
567 		/*
568 		 * Micron M500 SSDs all other firmware
569 		 * NCQ Trim doesn't work
570 		 */
571 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "*" },
572 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
573 	},
574 	{
575 		/*
576 		 * Micron M5[15]0 SSDs
577 		 * NCQ Trim doesn't work, but only MU01 firmware
578 		 */
579 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M5[15]0*", "MU01" },
580 		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
581 	},
582 	{
583 		/*
584 		 * Micron 5100 SSDs
585 		 * 4k optimised & trim only works in 4k requests + 4k aligned
586 		 */
587 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron 5100 MTFDDAK*", "*" },
588 		/*quirks*/ADA_Q_4K
589 	},
590 	{
591 		/*
592 		 * OCZ Agility 2 SSDs
593 		 * 4k optimised & trim only works in 4k requests + 4k aligned
594 		 */
595 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY2*", "*" },
596 		/*quirks*/ADA_Q_4K
597 	},
598 	{
599 		/*
600 		 * OCZ Agility 3 SSDs
601 		 * 4k optimised & trim only works in 4k requests + 4k aligned
602 		 */
603 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY3*", "*" },
604 		/*quirks*/ADA_Q_4K
605 	},
606 	{
607 		/*
608 		 * OCZ Deneva R Series SSDs
609 		 * 4k optimised & trim only works in 4k requests + 4k aligned
610 		 */
611 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "DENRSTE251M45*", "*" },
612 		/*quirks*/ADA_Q_4K
613 	},
614 	{
615 		/*
616 		 * OCZ Vertex 2 SSDs (inc pro series)
617 		 * 4k optimised & trim only works in 4k requests + 4k aligned
618 		 */
619 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ?VERTEX2*", "*" },
620 		/*quirks*/ADA_Q_4K
621 	},
622 	{
623 		/*
624 		 * OCZ Vertex 3 SSDs
625 		 * 4k optimised & trim only works in 4k requests + 4k aligned
626 		 */
627 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-VERTEX3*", "*" },
628 		/*quirks*/ADA_Q_4K
629 	},
630 	{
631 		/*
632 		 * OCZ Vertex 4 SSDs
633 		 * 4k optimised & trim only works in 4k requests + 4k aligned
634 		 */
635 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-VERTEX4*", "*" },
636 		/*quirks*/ADA_Q_4K
637 	},
638 	{
639 		/*
640 		 * Samsung 830 Series SSDs
641 		 * 4k optimised, NCQ TRIM Broken (normal TRIM is fine)
642 		 */
643 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG SSD 830 Series*", "*" },
644 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
645 	},
646 	{
647 		/*
648 		 * Samsung 840 SSDs
649 		 * 4k optimised, NCQ TRIM Broken (normal TRIM is fine)
650 		 */
651 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 840*", "*" },
652 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
653 	},
654 	{
655 		/*
656 		 * Samsung 850 SSDs
657 		 * 4k optimised, NCQ TRIM broken (normal TRIM fine)
658 		 */
659 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 850*", "*" },
660 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
661 	},
662 	{
663 		/*
664 		 * Samsung SM863 Series SSDs (MZ7KM*)
665 		 * 4k optimised, NCQ believed to be working
666 		 */
667 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7KM*", "*" },
668 		/*quirks*/ADA_Q_4K
669 	},
670 	{
671 		/*
672 		 * Samsung 843T Series SSDs (MZ7WD*)
673 		 * Samsung PM851 Series SSDs (MZ7TE*)
674 		 * Samsung PM853T Series SSDs (MZ7GE*)
675 		 * 4k optimised, NCQ believed to be broken since these are
676 		 * appear to be built with the same controllers as the 840/850.
677 		 */
678 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7*", "*" },
679 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
680 	},
681 	{
682 		/*
683 		 * Samsung PM851 Series SSDs Dell OEM
684 		 * device model          "SAMSUNG SSD PM851 mSATA 256GB"
685 		 * 4k optimised, NCQ broken
686 		 */
687 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG SSD PM851*", "*" },
688 		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
689 	},
690 	{
691 		/*
692 		 * SuperTalent TeraDrive CT SSDs
693 		 * 4k optimised & trim only works in 4k requests + 4k aligned
694 		 */
695 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "FTM??CT25H*", "*" },
696 		/*quirks*/ADA_Q_4K
697 	},
698 	{
699 		/*
700 		 * XceedIOPS SATA SSDs
701 		 * 4k optimised
702 		 */
703 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SG9XCS2D*", "*" },
704 		/*quirks*/ADA_Q_4K
705 	},
706 	{
707 		/*
708 		 * Samsung drive that doesn't support READ LOG EXT or
709 		 * READ LOG DMA EXT, despite reporting that it does in
710 		 * ATA identify data:
711 		 * SAMSUNG HD200HJ KF100-06
712 		 */
713 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD200*", "*" },
714 		/*quirks*/ADA_Q_LOG_BROKEN
715 	},
716 	{
717 		/*
718 		 * Samsung drive that doesn't support READ LOG EXT or
719 		 * READ LOG DMA EXT, despite reporting that it does in
720 		 * ATA identify data:
721 		 * SAMSUNG HD501LJ CR100-10
722 		 */
723 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD501*", "*" },
724 		/*quirks*/ADA_Q_LOG_BROKEN
725 	},
726 	{
727 		/*
728 		 * Seagate Lamarr 8TB Shingled Magnetic Recording (SMR)
729 		 * Drive Managed SATA hard drive.  This drive doesn't report
730 		 * in firmware that it is a drive managed SMR drive.
731 		 */
732 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST8000AS0002*", "*" },
733 		/*quirks*/ADA_Q_SMR_DM
734 	},
735 	{
736 		/* Default */
737 		{
738 		  T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
739 		  /*vendor*/"*", /*product*/"*", /*revision*/"*"
740 		},
741 		/*quirks*/0
742 	},
743 };
744 
745 static	disk_strategy_t	adastrategy;
746 static	dumper_t	adadump;
747 static	periph_init_t	adainit;
748 static	void		adadiskgonecb(struct disk *dp);
749 static	periph_oninv_t	adaoninvalidate;
750 static	periph_dtor_t	adacleanup;
751 static	void		adaasync(void *callback_arg, u_int32_t code,
752 				struct cam_path *path, void *arg);
753 static	int		adazonemodesysctl(SYSCTL_HANDLER_ARGS);
754 static	int		adazonesupsysctl(SYSCTL_HANDLER_ARGS);
755 static	void		adasysctlinit(void *context, int pending);
756 static	int		adagetattr(struct bio *bp);
757 static	void		adasetflags(struct ada_softc *softc,
758 				    struct ccb_getdev *cgd);
759 static	periph_ctor_t	adaregister;
760 static	void		ada_dsmtrim(struct ada_softc *softc, struct bio *bp,
761 				    struct ccb_ataio *ataio);
762 static	void 		ada_cfaerase(struct ada_softc *softc, struct bio *bp,
763 				     struct ccb_ataio *ataio);
764 static	int		ada_zone_bio_to_ata(int disk_zone_cmd);
765 static	int		ada_zone_cmd(struct cam_periph *periph, union ccb *ccb,
766 				     struct bio *bp, int *queue_ccb);
767 static	periph_start_t	adastart;
768 static	void		adaprobedone(struct cam_periph *periph, union ccb *ccb);
769 static	void		adazonedone(struct cam_periph *periph, union ccb *ccb);
770 static	void		adadone(struct cam_periph *periph,
771 			       union ccb *done_ccb);
772 static  int		adaerror(union ccb *ccb, u_int32_t cam_flags,
773 				u_int32_t sense_flags);
774 static void		adagetparams(struct cam_periph *periph,
775 				struct ccb_getdev *cgd);
776 static timeout_t	adasendorderedtag;
777 static void		adashutdown(void *arg, int howto);
778 static void		adasuspend(void *arg);
779 static void		adaresume(void *arg);
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 	struct disk_params *dp;
1667 	struct sbuf sb;
1668 	char   *announce_buf;
1669 	caddr_t match;
1670 	u_int maxio;
1671 	int quirks;
1672 
1673 	cgd = (struct ccb_getdev *)arg;
1674 	if (cgd == NULL) {
1675 		printf("adaregister: no getdev CCB, can't register device\n");
1676 		return(CAM_REQ_CMP_ERR);
1677 	}
1678 
1679 	softc = (struct ada_softc *)malloc(sizeof(*softc), M_DEVBUF,
1680 	    M_NOWAIT|M_ZERO);
1681 
1682 	if (softc == NULL) {
1683 		printf("adaregister: Unable to probe new device. "
1684 		    "Unable to allocate softc\n");
1685 		return(CAM_REQ_CMP_ERR);
1686 	}
1687 
1688 	announce_buf = softc->announce_temp;
1689 	bzero(announce_buf, ADA_ANNOUNCETMP_SZ);
1690 
1691 	if (cam_iosched_init(&softc->cam_iosched, periph) != 0) {
1692 		printf("adaregister: Unable to probe new device. "
1693 		       "Unable to allocate iosched memory\n");
1694 		free(softc, M_DEVBUF);
1695 		return(CAM_REQ_CMP_ERR);
1696 	}
1697 
1698 	periph->softc = softc;
1699 
1700 	/*
1701 	 * See if this device has any quirks.
1702 	 */
1703 	match = cam_quirkmatch((caddr_t)&cgd->ident_data,
1704 			       (caddr_t)ada_quirk_table,
1705 			       nitems(ada_quirk_table),
1706 			       sizeof(*ada_quirk_table), ata_identify_match);
1707 	if (match != NULL)
1708 		softc->quirks = ((struct ada_quirk_entry *)match)->quirks;
1709 	else
1710 		softc->quirks = ADA_Q_NONE;
1711 
1712 	bzero(&cpi, sizeof(cpi));
1713 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NONE);
1714 	cpi.ccb_h.func_code = XPT_PATH_INQ;
1715 	xpt_action((union ccb *)&cpi);
1716 
1717 	TASK_INIT(&softc->sysctl_task, 0, adasysctlinit, periph);
1718 
1719 	/*
1720 	 * Register this media as a disk
1721 	 */
1722 	(void)cam_periph_hold(periph, PRIBIO);
1723 	cam_periph_unlock(periph);
1724 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1725 	    "kern.cam.ada.%d.quirks", periph->unit_number);
1726 	quirks = softc->quirks;
1727 	TUNABLE_INT_FETCH(announce_buf, &quirks);
1728 	softc->quirks = quirks;
1729 	softc->read_ahead = -1;
1730 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1731 	    "kern.cam.ada.%d.read_ahead", periph->unit_number);
1732 	TUNABLE_INT_FETCH(announce_buf, &softc->read_ahead);
1733 	softc->write_cache = -1;
1734 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1735 	    "kern.cam.ada.%d.write_cache", periph->unit_number);
1736 	TUNABLE_INT_FETCH(announce_buf, &softc->write_cache);
1737 
1738 	/*
1739 	 * Set support flags based on the Identify data and quirks.
1740 	 */
1741 	adasetflags(softc, cgd);
1742 
1743 	/* Disable queue sorting for non-rotational media by default. */
1744 	if (cgd->ident_data.media_rotation_rate == ATA_RATE_NON_ROTATING) {
1745 		softc->rotating = 0;
1746 	} else {
1747 		softc->rotating = 1;
1748 	}
1749 	cam_iosched_set_sort_queue(softc->cam_iosched,  softc->rotating ? -1 : 0);
1750 	adagetparams(periph, cgd);
1751 	softc->disk = disk_alloc();
1752 	softc->disk->d_rotation_rate = cgd->ident_data.media_rotation_rate;
1753 	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
1754 			  periph->unit_number, softc->params.secsize,
1755 			  DEVSTAT_ALL_SUPPORTED,
1756 			  DEVSTAT_TYPE_DIRECT |
1757 			  XPORT_DEVSTAT_TYPE(cpi.transport),
1758 			  DEVSTAT_PRIORITY_DISK);
1759 	softc->disk->d_open = adaopen;
1760 	softc->disk->d_close = adaclose;
1761 	softc->disk->d_strategy = adastrategy;
1762 	softc->disk->d_getattr = adagetattr;
1763 	softc->disk->d_dump = adadump;
1764 	softc->disk->d_gone = adadiskgonecb;
1765 	softc->disk->d_name = "ada";
1766 	softc->disk->d_drv1 = periph;
1767 	maxio = cpi.maxio;		/* Honor max I/O size of SIM */
1768 	if (maxio == 0)
1769 		maxio = DFLTPHYS;	/* traditional default */
1770 	else if (maxio > MAXPHYS)
1771 		maxio = MAXPHYS;	/* for safety */
1772 	if (softc->flags & ADA_FLAG_CAN_48BIT)
1773 		maxio = min(maxio, 65536 * softc->params.secsize);
1774 	else					/* 28bit ATA command limit */
1775 		maxio = min(maxio, 256 * softc->params.secsize);
1776 	softc->disk->d_maxsize = maxio;
1777 	softc->disk->d_unit = periph->unit_number;
1778 	softc->disk->d_flags = DISKFLAG_DIRECT_COMPLETION | DISKFLAG_CANZONE;
1779 	if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE)
1780 		softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
1781 	if (softc->flags & ADA_FLAG_CAN_TRIM) {
1782 		softc->disk->d_flags |= DISKFLAG_CANDELETE;
1783 		softc->disk->d_delmaxsize = softc->params.secsize *
1784 					    ATA_DSM_RANGE_MAX *
1785 					    softc->trim_max_ranges;
1786 	} else if ((softc->flags & ADA_FLAG_CAN_CFA) &&
1787 	    !(softc->flags & ADA_FLAG_CAN_48BIT)) {
1788 		softc->disk->d_flags |= DISKFLAG_CANDELETE;
1789 		softc->disk->d_delmaxsize = 256 * softc->params.secsize;
1790 	} else
1791 		softc->disk->d_delmaxsize = maxio;
1792 	if ((cpi.hba_misc & PIM_UNMAPPED) != 0) {
1793 		softc->disk->d_flags |= DISKFLAG_UNMAPPED_BIO;
1794 		softc->unmappedio = 1;
1795 	}
1796 	if (cpi.hba_misc & PIM_ATA_EXT)
1797 		softc->flags |= ADA_FLAG_PIM_ATA_EXT;
1798 	strlcpy(softc->disk->d_descr, cgd->ident_data.model,
1799 	    MIN(sizeof(softc->disk->d_descr), sizeof(cgd->ident_data.model)));
1800 	strlcpy(softc->disk->d_ident, cgd->ident_data.serial,
1801 	    MIN(sizeof(softc->disk->d_ident), sizeof(cgd->ident_data.serial)));
1802 	softc->disk->d_hba_vendor = cpi.hba_vendor;
1803 	softc->disk->d_hba_device = cpi.hba_device;
1804 	softc->disk->d_hba_subvendor = cpi.hba_subvendor;
1805 	softc->disk->d_hba_subdevice = cpi.hba_subdevice;
1806 
1807 	softc->disk->d_sectorsize = softc->params.secsize;
1808 	softc->disk->d_mediasize = (off_t)softc->params.sectors *
1809 	    softc->params.secsize;
1810 	if (ata_physical_sector_size(&cgd->ident_data) !=
1811 	    softc->params.secsize) {
1812 		softc->disk->d_stripesize =
1813 		    ata_physical_sector_size(&cgd->ident_data);
1814 		softc->disk->d_stripeoffset = (softc->disk->d_stripesize -
1815 		    ata_logical_sector_offset(&cgd->ident_data)) %
1816 		    softc->disk->d_stripesize;
1817 	} else if (softc->quirks & ADA_Q_4K) {
1818 		softc->disk->d_stripesize = 4096;
1819 		softc->disk->d_stripeoffset = 0;
1820 	}
1821 	softc->disk->d_fwsectors = softc->params.secs_per_track;
1822 	softc->disk->d_fwheads = softc->params.heads;
1823 	ata_disk_firmware_geom_adjust(softc->disk);
1824 
1825 	/*
1826 	 * Acquire a reference to the periph before we register with GEOM.
1827 	 * We'll release this reference once GEOM calls us back (via
1828 	 * adadiskgonecb()) telling us that our provider has been freed.
1829 	 */
1830 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
1831 		xpt_print(periph->path, "%s: lost periph during "
1832 			  "registration!\n", __func__);
1833 		cam_periph_lock(periph);
1834 		return (CAM_REQ_CMP_ERR);
1835 	}
1836 	disk_create(softc->disk, DISK_VERSION);
1837 	cam_periph_lock(periph);
1838 
1839 	dp = &softc->params;
1840 	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
1841 	    "%juMB (%ju %u byte sectors)",
1842 	    ((uintmax_t)dp->secsize * dp->sectors) / (1024 * 1024),
1843 	    (uintmax_t)dp->sectors, dp->secsize);
1844 
1845 	sbuf_new(&sb, softc->announce_buffer, ADA_ANNOUNCE_SZ, SBUF_FIXEDLEN);
1846 	xpt_announce_periph_sbuf(periph, &sb, announce_buf);
1847 	xpt_announce_quirks_sbuf(periph, &sb, softc->quirks, ADA_Q_BIT_STRING);
1848 	sbuf_finish(&sb);
1849 	sbuf_putbuf(&sb);
1850 
1851 	/*
1852 	 * Create our sysctl variables, now that we know
1853 	 * we have successfully attached.
1854 	 */
1855 	if (cam_periph_acquire(periph) == CAM_REQ_CMP)
1856 		taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
1857 
1858 	/*
1859 	 * Add async callbacks for bus reset and
1860 	 * bus device reset calls.  I don't bother
1861 	 * checking if this fails as, in most cases,
1862 	 * the system will function just fine without
1863 	 * them and the only alternative would be to
1864 	 * not attach the device on failure.
1865 	 */
1866 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
1867 	    AC_GETDEV_CHANGED | AC_ADVINFO_CHANGED,
1868 	    adaasync, periph, periph->path);
1869 
1870 	/*
1871 	 * Schedule a periodic event to occasionally send an
1872 	 * ordered tag to a device.
1873 	 */
1874 	callout_init_mtx(&softc->sendordered_c, cam_periph_mtx(periph), 0);
1875 	callout_reset(&softc->sendordered_c,
1876 	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
1877 	    adasendorderedtag, softc);
1878 
1879 	if (ADA_RA >= 0 && softc->flags & ADA_FLAG_CAN_RAHEAD) {
1880 		softc->state = ADA_STATE_RAHEAD;
1881 	} else if (ADA_WC >= 0 && softc->flags & ADA_FLAG_CAN_WCACHE) {
1882 		softc->state = ADA_STATE_WCACHE;
1883 	} else if ((softc->flags & ADA_FLAG_CAN_LOG)
1884 		&& (softc->zone_mode != ADA_ZONE_NONE)) {
1885 		softc->state = ADA_STATE_LOGDIR;
1886 	} else {
1887 		/*
1888 		 * Nothing to probe, so we can just transition to the
1889 		 * normal state.
1890 		 */
1891 		adaprobedone(periph, NULL);
1892 		return(CAM_REQ_CMP);
1893 	}
1894 
1895 	xpt_schedule(periph, CAM_PRIORITY_DEV);
1896 
1897 	return(CAM_REQ_CMP);
1898 }
1899 
1900 static int
1901 ada_dsmtrim_req_create(struct ada_softc *softc, struct bio *bp, struct trim_request *req)
1902 {
1903 	uint64_t lastlba = (uint64_t)-1;
1904 	int c, lastcount = 0, off, ranges = 0;
1905 
1906 	bzero(req, sizeof(*req));
1907 	TAILQ_INIT(&req->bps);
1908 	do {
1909 		uint64_t lba = bp->bio_pblkno;
1910 		int count = bp->bio_bcount / softc->params.secsize;
1911 
1912 		/* Try to extend the previous range. */
1913 		if (lba == lastlba) {
1914 			c = min(count, ATA_DSM_RANGE_MAX - lastcount);
1915 			lastcount += c;
1916 			off = (ranges - 1) * ATA_DSM_RANGE_SIZE;
1917 			req->data[off + 6] = lastcount & 0xff;
1918 			req->data[off + 7] =
1919 				(lastcount >> 8) & 0xff;
1920 			count -= c;
1921 			lba += c;
1922 		}
1923 
1924 		while (count > 0) {
1925 			c = min(count, ATA_DSM_RANGE_MAX);
1926 			off = ranges * ATA_DSM_RANGE_SIZE;
1927 			req->data[off + 0] = lba & 0xff;
1928 			req->data[off + 1] = (lba >> 8) & 0xff;
1929 			req->data[off + 2] = (lba >> 16) & 0xff;
1930 			req->data[off + 3] = (lba >> 24) & 0xff;
1931 			req->data[off + 4] = (lba >> 32) & 0xff;
1932 			req->data[off + 5] = (lba >> 40) & 0xff;
1933 			req->data[off + 6] = c & 0xff;
1934 			req->data[off + 7] = (c >> 8) & 0xff;
1935 			lba += c;
1936 			count -= c;
1937 			lastcount = c;
1938 			ranges++;
1939 			/*
1940 			 * Its the caller's responsibility to ensure the
1941 			 * request will fit so we don't need to check for
1942 			 * overrun here
1943 			 */
1944 		}
1945 		lastlba = lba;
1946 		TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);
1947 
1948 		bp = cam_iosched_next_trim(softc->cam_iosched);
1949 		if (bp == NULL)
1950 			break;
1951 		if (bp->bio_bcount / softc->params.secsize >
1952 		    (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX) {
1953 			cam_iosched_put_back_trim(softc->cam_iosched, bp);
1954 			break;
1955 		}
1956 	} while (1);
1957 
1958 	return (ranges);
1959 }
1960 
1961 static void
1962 ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
1963 {
1964 	struct trim_request *req = &softc->trim_req;
1965 	int ranges;
1966 
1967 	ranges = ada_dsmtrim_req_create(softc, bp, req);
1968 	cam_fill_ataio(ataio,
1969 	    ada_retry_count,
1970 	    adadone,
1971 	    CAM_DIR_OUT,
1972 	    0,
1973 	    req->data,
1974 	    howmany(ranges, ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
1975 	    ada_default_timeout * 1000);
1976 	ata_48bit_cmd(ataio, ATA_DATA_SET_MANAGEMENT,
1977 	    ATA_DSM_TRIM, 0, howmany(ranges, ATA_DSM_BLK_RANGES));
1978 }
1979 
1980 static void
1981 ada_ncq_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
1982 {
1983 	struct trim_request *req = &softc->trim_req;
1984 	int ranges;
1985 
1986 	ranges = ada_dsmtrim_req_create(softc, bp, req);
1987 	cam_fill_ataio(ataio,
1988 	    ada_retry_count,
1989 	    adadone,
1990 	    CAM_DIR_OUT,
1991 	    0,
1992 	    req->data,
1993 	    howmany(ranges, ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
1994 	    ada_default_timeout * 1000);
1995 	ata_ncq_cmd(ataio,
1996 	    ATA_SEND_FPDMA_QUEUED,
1997 	    0,
1998 	    howmany(ranges, ATA_DSM_BLK_RANGES));
1999 	ataio->cmd.sector_count_exp = ATA_SFPDMA_DSM;
2000 	ataio->ata_flags |= ATA_FLAG_AUX;
2001 	ataio->aux = 1;
2002 }
2003 
2004 static void
2005 ada_cfaerase(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
2006 {
2007 	struct trim_request *req = &softc->trim_req;
2008 	uint64_t lba = bp->bio_pblkno;
2009 	uint16_t count = bp->bio_bcount / softc->params.secsize;
2010 
2011 	bzero(req, sizeof(*req));
2012 	TAILQ_INIT(&req->bps);
2013 	TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);
2014 
2015 	cam_fill_ataio(ataio,
2016 	    ada_retry_count,
2017 	    adadone,
2018 	    CAM_DIR_NONE,
2019 	    0,
2020 	    NULL,
2021 	    0,
2022 	    ada_default_timeout*1000);
2023 
2024 	if (count >= 256)
2025 		count = 0;
2026 	ata_28bit_cmd(ataio, ATA_CFA_ERASE, 0, lba, count);
2027 }
2028 
2029 static int
2030 ada_zone_bio_to_ata(int disk_zone_cmd)
2031 {
2032 	switch (disk_zone_cmd) {
2033 	case DISK_ZONE_OPEN:
2034 		return ATA_ZM_OPEN_ZONE;
2035 	case DISK_ZONE_CLOSE:
2036 		return ATA_ZM_CLOSE_ZONE;
2037 	case DISK_ZONE_FINISH:
2038 		return ATA_ZM_FINISH_ZONE;
2039 	case DISK_ZONE_RWP:
2040 		return ATA_ZM_RWP;
2041 	}
2042 
2043 	return -1;
2044 }
2045 
2046 static int
2047 ada_zone_cmd(struct cam_periph *periph, union ccb *ccb, struct bio *bp,
2048 	     int *queue_ccb)
2049 {
2050 	struct ada_softc *softc;
2051 	int error;
2052 
2053 	error = 0;
2054 
2055 	if (bp->bio_cmd != BIO_ZONE) {
2056 		error = EINVAL;
2057 		goto bailout;
2058 	}
2059 
2060 	softc = periph->softc;
2061 
2062 	switch (bp->bio_zone.zone_cmd) {
2063 	case DISK_ZONE_OPEN:
2064 	case DISK_ZONE_CLOSE:
2065 	case DISK_ZONE_FINISH:
2066 	case DISK_ZONE_RWP: {
2067 		int zone_flags;
2068 		int zone_sa;
2069 		uint64_t lba;
2070 
2071 		zone_sa = ada_zone_bio_to_ata(bp->bio_zone.zone_cmd);
2072 		if (zone_sa == -1) {
2073 			xpt_print(periph->path, "Cannot translate zone "
2074 			    "cmd %#x to ATA\n", bp->bio_zone.zone_cmd);
2075 			error = EINVAL;
2076 			goto bailout;
2077 		}
2078 
2079 		zone_flags = 0;
2080 		lba = bp->bio_zone.zone_params.rwp.id;
2081 
2082 		if (bp->bio_zone.zone_params.rwp.flags &
2083 		    DISK_ZONE_RWP_FLAG_ALL)
2084 			zone_flags |= ZBC_OUT_ALL;
2085 
2086 		ata_zac_mgmt_out(&ccb->ataio,
2087 				 /*retries*/ ada_retry_count,
2088 				 /*cbfcnp*/ adadone,
2089 				 /*use_ncq*/ (softc->flags &
2090 					      ADA_FLAG_PIM_ATA_EXT) ? 1 : 0,
2091 				 /*zm_action*/ zone_sa,
2092 				 /*zone_id*/ lba,
2093 				 /*zone_flags*/ zone_flags,
2094 				 /*sector_count*/ 0,
2095 				 /*data_ptr*/ NULL,
2096 				 /*dxfer_len*/ 0,
2097 				 /*timeout*/ ada_default_timeout * 1000);
2098 		*queue_ccb = 1;
2099 
2100 		break;
2101 	}
2102 	case DISK_ZONE_REPORT_ZONES: {
2103 		uint8_t *rz_ptr;
2104 		uint32_t num_entries, alloc_size;
2105 		struct disk_zone_report *rep;
2106 
2107 		rep = &bp->bio_zone.zone_params.report;
2108 
2109 		num_entries = rep->entries_allocated;
2110 		if (num_entries == 0) {
2111 			xpt_print(periph->path, "No entries allocated for "
2112 			    "Report Zones request\n");
2113 			error = EINVAL;
2114 			goto bailout;
2115 		}
2116 		alloc_size = sizeof(struct scsi_report_zones_hdr) +
2117 		    (sizeof(struct scsi_report_zones_desc) * num_entries);
2118 		alloc_size = min(alloc_size, softc->disk->d_maxsize);
2119 		rz_ptr = malloc(alloc_size, M_ATADA, M_NOWAIT | M_ZERO);
2120 		if (rz_ptr == NULL) {
2121 			xpt_print(periph->path, "Unable to allocate memory "
2122 			   "for Report Zones request\n");
2123 			error = ENOMEM;
2124 			goto bailout;
2125 		}
2126 
2127 		ata_zac_mgmt_in(&ccb->ataio,
2128 				/*retries*/ ada_retry_count,
2129 				/*cbcfnp*/ adadone,
2130 				/*use_ncq*/ (softc->flags &
2131 					     ADA_FLAG_PIM_ATA_EXT) ? 1 : 0,
2132 				/*zm_action*/ ATA_ZM_REPORT_ZONES,
2133 				/*zone_id*/ rep->starting_id,
2134 				/*zone_flags*/ rep->rep_options,
2135 				/*data_ptr*/ rz_ptr,
2136 				/*dxfer_len*/ alloc_size,
2137 				/*timeout*/ ada_default_timeout * 1000);
2138 
2139 		/*
2140 		 * For BIO_ZONE, this isn't normally needed.  However, it
2141 		 * is used by devstat_end_transaction_bio() to determine
2142 		 * how much data was transferred.
2143 		 */
2144 		/*
2145 		 * XXX KDM we have a problem.  But I'm not sure how to fix
2146 		 * it.  devstat uses bio_bcount - bio_resid to calculate
2147 		 * the amount of data transferred.   The GEOM disk code
2148 		 * uses bio_length - bio_resid to calculate the amount of
2149 		 * data in bio_completed.  We have different structure
2150 		 * sizes above and below the ada(4) driver.  So, if we
2151 		 * use the sizes above, the amount transferred won't be
2152 		 * quite accurate for devstat.  If we use different sizes
2153 		 * for bio_bcount and bio_length (above and below
2154 		 * respectively), then the residual needs to match one or
2155 		 * the other.  Everything is calculated after the bio
2156 		 * leaves the driver, so changing the values around isn't
2157 		 * really an option.  For now, just set the count to the
2158 		 * passed in length.  This means that the calculations
2159 		 * above (e.g. bio_completed) will be correct, but the
2160 		 * amount of data reported to devstat will be slightly
2161 		 * under or overstated.
2162 		 */
2163 		bp->bio_bcount = bp->bio_length;
2164 
2165 		*queue_ccb = 1;
2166 
2167 		break;
2168 	}
2169 	case DISK_ZONE_GET_PARAMS: {
2170 		struct disk_zone_disk_params *params;
2171 
2172 		params = &bp->bio_zone.zone_params.disk_params;
2173 		bzero(params, sizeof(*params));
2174 
2175 		switch (softc->zone_mode) {
2176 		case ADA_ZONE_DRIVE_MANAGED:
2177 			params->zone_mode = DISK_ZONE_MODE_DRIVE_MANAGED;
2178 			break;
2179 		case ADA_ZONE_HOST_AWARE:
2180 			params->zone_mode = DISK_ZONE_MODE_HOST_AWARE;
2181 			break;
2182 		case ADA_ZONE_HOST_MANAGED:
2183 			params->zone_mode = DISK_ZONE_MODE_HOST_MANAGED;
2184 			break;
2185 		default:
2186 		case ADA_ZONE_NONE:
2187 			params->zone_mode = DISK_ZONE_MODE_NONE;
2188 			break;
2189 		}
2190 
2191 		if (softc->zone_flags & ADA_ZONE_FLAG_URSWRZ)
2192 			params->flags |= DISK_ZONE_DISK_URSWRZ;
2193 
2194 		if (softc->zone_flags & ADA_ZONE_FLAG_OPT_SEQ_SET) {
2195 			params->optimal_seq_zones = softc->optimal_seq_zones;
2196 			params->flags |= DISK_ZONE_OPT_SEQ_SET;
2197 		}
2198 
2199 		if (softc->zone_flags & ADA_ZONE_FLAG_OPT_NONSEQ_SET) {
2200 			params->optimal_nonseq_zones =
2201 			    softc->optimal_nonseq_zones;
2202 			params->flags |= DISK_ZONE_OPT_NONSEQ_SET;
2203 		}
2204 
2205 		if (softc->zone_flags & ADA_ZONE_FLAG_MAX_SEQ_SET) {
2206 			params->max_seq_zones = softc->max_seq_zones;
2207 			params->flags |= DISK_ZONE_MAX_SEQ_SET;
2208 		}
2209 		if (softc->zone_flags & ADA_ZONE_FLAG_RZ_SUP)
2210 			params->flags |= DISK_ZONE_RZ_SUP;
2211 
2212 		if (softc->zone_flags & ADA_ZONE_FLAG_OPEN_SUP)
2213 			params->flags |= DISK_ZONE_OPEN_SUP;
2214 
2215 		if (softc->zone_flags & ADA_ZONE_FLAG_CLOSE_SUP)
2216 			params->flags |= DISK_ZONE_CLOSE_SUP;
2217 
2218 		if (softc->zone_flags & ADA_ZONE_FLAG_FINISH_SUP)
2219 			params->flags |= DISK_ZONE_FINISH_SUP;
2220 
2221 		if (softc->zone_flags & ADA_ZONE_FLAG_RWP_SUP)
2222 			params->flags |= DISK_ZONE_RWP_SUP;
2223 		break;
2224 	}
2225 	default:
2226 		break;
2227 	}
2228 bailout:
2229 	return (error);
2230 }
2231 
2232 static void
2233 adastart(struct cam_periph *periph, union ccb *start_ccb)
2234 {
2235 	struct ada_softc *softc = (struct ada_softc *)periph->softc;
2236 	struct ccb_ataio *ataio = &start_ccb->ataio;
2237 
2238 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastart\n"));
2239 
2240 	switch (softc->state) {
2241 	case ADA_STATE_NORMAL:
2242 	{
2243 		struct bio *bp;
2244 		u_int8_t tag_code;
2245 
2246 		bp = cam_iosched_next_bio(softc->cam_iosched);
2247 		if (bp == NULL) {
2248 			xpt_release_ccb(start_ccb);
2249 			break;
2250 		}
2251 
2252 		if ((bp->bio_flags & BIO_ORDERED) != 0 ||
2253 		    (bp->bio_cmd != BIO_DELETE && (softc->flags & ADA_FLAG_NEED_OTAG) != 0)) {
2254 			softc->flags &= ~ADA_FLAG_NEED_OTAG;
2255 			softc->flags |= ADA_FLAG_WAS_OTAG;
2256 			tag_code = 0;
2257 		} else {
2258 			tag_code = 1;
2259 		}
2260 		switch (bp->bio_cmd) {
2261 		case BIO_WRITE:
2262 		case BIO_READ:
2263 		{
2264 			uint64_t lba = bp->bio_pblkno;
2265 			uint16_t count = bp->bio_bcount / softc->params.secsize;
2266 			void *data_ptr;
2267 			int rw_op;
2268 
2269 			if (bp->bio_cmd == BIO_WRITE) {
2270 				softc->flags |= ADA_FLAG_DIRTY;
2271 				rw_op = CAM_DIR_OUT;
2272 			} else {
2273 				rw_op = CAM_DIR_IN;
2274 			}
2275 
2276 			data_ptr = bp->bio_data;
2277 			if ((bp->bio_flags & (BIO_UNMAPPED|BIO_VLIST)) != 0) {
2278 				rw_op |= CAM_DATA_BIO;
2279 				data_ptr = bp;
2280 			}
2281 
2282 #ifdef ADA_TEST_FAILURE
2283 			int fail = 0;
2284 
2285 			/*
2286 			 * Support the failure ioctls.  If the command is a
2287 			 * read, and there are pending forced read errors, or
2288 			 * if a write and pending write errors, then fail this
2289 			 * operation with EIO.  This is useful for testing
2290 			 * purposes.  Also, support having every Nth read fail.
2291 			 *
2292 			 * This is a rather blunt tool.
2293 			 */
2294 			if (bp->bio_cmd == BIO_READ) {
2295 				if (softc->force_read_error) {
2296 					softc->force_read_error--;
2297 					fail = 1;
2298 				}
2299 				if (softc->periodic_read_error > 0) {
2300 					if (++softc->periodic_read_count >=
2301 					    softc->periodic_read_error) {
2302 						softc->periodic_read_count = 0;
2303 						fail = 1;
2304 					}
2305 				}
2306 			} else {
2307 				if (softc->force_write_error) {
2308 					softc->force_write_error--;
2309 					fail = 1;
2310 				}
2311 			}
2312 			if (fail) {
2313 				biofinish(bp, NULL, EIO);
2314 				xpt_release_ccb(start_ccb);
2315 				adaschedule(periph);
2316 				return;
2317 			}
2318 #endif
2319 			KASSERT((bp->bio_flags & BIO_UNMAPPED) == 0 ||
2320 			    round_page(bp->bio_bcount + bp->bio_ma_offset) /
2321 			    PAGE_SIZE == bp->bio_ma_n,
2322 			    ("Short bio %p", bp));
2323 			cam_fill_ataio(ataio,
2324 			    ada_retry_count,
2325 			    adadone,
2326 			    rw_op,
2327 			    0,
2328 			    data_ptr,
2329 			    bp->bio_bcount,
2330 			    ada_default_timeout*1000);
2331 
2332 			if ((softc->flags & ADA_FLAG_CAN_NCQ) && tag_code) {
2333 				if (bp->bio_cmd == BIO_READ) {
2334 					ata_ncq_cmd(ataio, ATA_READ_FPDMA_QUEUED,
2335 					    lba, count);
2336 				} else {
2337 					ata_ncq_cmd(ataio, ATA_WRITE_FPDMA_QUEUED,
2338 					    lba, count);
2339 				}
2340 			} else if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
2341 			    (lba + count >= ATA_MAX_28BIT_LBA ||
2342 			    count > 256)) {
2343 				if (softc->flags & ADA_FLAG_CAN_DMA48) {
2344 					if (bp->bio_cmd == BIO_READ) {
2345 						ata_48bit_cmd(ataio, ATA_READ_DMA48,
2346 						    0, lba, count);
2347 					} else {
2348 						ata_48bit_cmd(ataio, ATA_WRITE_DMA48,
2349 						    0, lba, count);
2350 					}
2351 				} else {
2352 					if (bp->bio_cmd == BIO_READ) {
2353 						ata_48bit_cmd(ataio, ATA_READ_MUL48,
2354 						    0, lba, count);
2355 					} else {
2356 						ata_48bit_cmd(ataio, ATA_WRITE_MUL48,
2357 						    0, lba, count);
2358 					}
2359 				}
2360 			} else {
2361 				if (count == 256)
2362 					count = 0;
2363 				if (softc->flags & ADA_FLAG_CAN_DMA) {
2364 					if (bp->bio_cmd == BIO_READ) {
2365 						ata_28bit_cmd(ataio, ATA_READ_DMA,
2366 						    0, lba, count);
2367 					} else {
2368 						ata_28bit_cmd(ataio, ATA_WRITE_DMA,
2369 						    0, lba, count);
2370 					}
2371 				} else {
2372 					if (bp->bio_cmd == BIO_READ) {
2373 						ata_28bit_cmd(ataio, ATA_READ_MUL,
2374 						    0, lba, count);
2375 					} else {
2376 						ata_28bit_cmd(ataio, ATA_WRITE_MUL,
2377 						    0, lba, count);
2378 					}
2379 				}
2380 			}
2381 			break;
2382 		}
2383 		case BIO_DELETE:
2384 			switch (softc->delete_method) {
2385 			case ADA_DELETE_NCQ_DSM_TRIM:
2386 				ada_ncq_dsmtrim(softc, bp, ataio);
2387 				break;
2388 			case ADA_DELETE_DSM_TRIM:
2389 				ada_dsmtrim(softc, bp, ataio);
2390 				break;
2391 			case ADA_DELETE_CFA_ERASE:
2392 				ada_cfaerase(softc, bp, ataio);
2393 				break;
2394 			default:
2395 				biofinish(bp, NULL, EOPNOTSUPP);
2396 				xpt_release_ccb(start_ccb);
2397 				adaschedule(periph);
2398 				return;
2399 			}
2400 			start_ccb->ccb_h.ccb_state = ADA_CCB_TRIM;
2401 			start_ccb->ccb_h.flags |= CAM_UNLOCKED;
2402 			cam_iosched_submit_trim(softc->cam_iosched);
2403 			goto out;
2404 		case BIO_FLUSH:
2405 			cam_fill_ataio(ataio,
2406 			    1,
2407 			    adadone,
2408 			    CAM_DIR_NONE,
2409 			    0,
2410 			    NULL,
2411 			    0,
2412 			    ada_default_timeout*1000);
2413 
2414 			if (softc->flags & ADA_FLAG_CAN_48BIT)
2415 				ata_48bit_cmd(ataio, ATA_FLUSHCACHE48, 0, 0, 0);
2416 			else
2417 				ata_28bit_cmd(ataio, ATA_FLUSHCACHE, 0, 0, 0);
2418 			break;
2419 		case BIO_ZONE: {
2420 			int error, queue_ccb;
2421 
2422 			queue_ccb = 0;
2423 
2424 			error = ada_zone_cmd(periph, start_ccb, bp, &queue_ccb);
2425 			if ((error != 0)
2426 			 || (queue_ccb == 0)) {
2427 				biofinish(bp, NULL, error);
2428 				xpt_release_ccb(start_ccb);
2429 				return;
2430 			}
2431 			break;
2432 		}
2433 		}
2434 		start_ccb->ccb_h.ccb_state = ADA_CCB_BUFFER_IO;
2435 		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
2436 out:
2437 		start_ccb->ccb_h.ccb_bp = bp;
2438 		softc->outstanding_cmds++;
2439 		softc->refcount++;
2440 		cam_periph_unlock(periph);
2441 		xpt_action(start_ccb);
2442 		cam_periph_lock(periph);
2443 		softc->refcount--;
2444 
2445 		/* May have more work to do, so ensure we stay scheduled */
2446 		adaschedule(periph);
2447 		break;
2448 	}
2449 	case ADA_STATE_RAHEAD:
2450 	case ADA_STATE_WCACHE:
2451 	{
2452 		cam_fill_ataio(ataio,
2453 		    1,
2454 		    adadone,
2455 		    CAM_DIR_NONE,
2456 		    0,
2457 		    NULL,
2458 		    0,
2459 		    ada_default_timeout*1000);
2460 
2461 		if (softc->state == ADA_STATE_RAHEAD) {
2462 			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_RA ?
2463 			    ATA_SF_ENAB_RCACHE : ATA_SF_DIS_RCACHE, 0, 0);
2464 			start_ccb->ccb_h.ccb_state = ADA_CCB_RAHEAD;
2465 		} else {
2466 			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_WC ?
2467 			    ATA_SF_ENAB_WCACHE : ATA_SF_DIS_WCACHE, 0, 0);
2468 			start_ccb->ccb_h.ccb_state = ADA_CCB_WCACHE;
2469 		}
2470 		start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2471 		xpt_action(start_ccb);
2472 		break;
2473 	}
2474 	case ADA_STATE_LOGDIR:
2475 	{
2476 		struct ata_gp_log_dir *log_dir;
2477 
2478 		if ((softc->flags & ADA_FLAG_CAN_LOG) == 0) {
2479 			adaprobedone(periph, start_ccb);
2480 			break;
2481 		}
2482 
2483 		log_dir = malloc(sizeof(*log_dir), M_ATADA, M_NOWAIT|M_ZERO);
2484 		if (log_dir == NULL) {
2485 			xpt_print(periph->path, "Couldn't malloc log_dir "
2486 			    "data\n");
2487 			softc->state = ADA_STATE_NORMAL;
2488 			xpt_release_ccb(start_ccb);
2489 			break;
2490 		}
2491 
2492 
2493 		ata_read_log(ataio,
2494 		    /*retries*/1,
2495 		    /*cbfcnp*/adadone,
2496 		    /*log_address*/ ATA_LOG_DIRECTORY,
2497 		    /*page_number*/ 0,
2498 		    /*block_count*/ 1,
2499 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2500 				 CAM_ATAIO_DMA : 0,
2501 		    /*data_ptr*/ (uint8_t *)log_dir,
2502 		    /*dxfer_len*/sizeof(*log_dir),
2503 		    /*timeout*/ada_default_timeout*1000);
2504 
2505 		start_ccb->ccb_h.ccb_state = ADA_CCB_LOGDIR;
2506 		xpt_action(start_ccb);
2507 		break;
2508 	}
2509 	case ADA_STATE_IDDIR:
2510 	{
2511 		struct ata_identify_log_pages *id_dir;
2512 
2513 		id_dir = malloc(sizeof(*id_dir), M_ATADA, M_NOWAIT | M_ZERO);
2514 		if (id_dir == NULL) {
2515 			xpt_print(periph->path, "Couldn't malloc id_dir "
2516 			    "data\n");
2517 			adaprobedone(periph, start_ccb);
2518 			break;
2519 		}
2520 
2521 		ata_read_log(ataio,
2522 		    /*retries*/1,
2523 		    /*cbfcnp*/adadone,
2524 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
2525 		    /*page_number*/ ATA_IDL_PAGE_LIST,
2526 		    /*block_count*/ 1,
2527 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2528 				 CAM_ATAIO_DMA : 0,
2529 		    /*data_ptr*/ (uint8_t *)id_dir,
2530 		    /*dxfer_len*/ sizeof(*id_dir),
2531 		    /*timeout*/ada_default_timeout*1000);
2532 
2533 		start_ccb->ccb_h.ccb_state = ADA_CCB_IDDIR;
2534 		xpt_action(start_ccb);
2535 		break;
2536 	}
2537 	case ADA_STATE_SUP_CAP:
2538 	{
2539 		struct ata_identify_log_sup_cap *sup_cap;
2540 
2541 		sup_cap = malloc(sizeof(*sup_cap), M_ATADA, M_NOWAIT|M_ZERO);
2542 		if (sup_cap == NULL) {
2543 			xpt_print(periph->path, "Couldn't malloc sup_cap "
2544 			    "data\n");
2545 			adaprobedone(periph, start_ccb);
2546 			break;
2547 		}
2548 
2549 		ata_read_log(ataio,
2550 		    /*retries*/1,
2551 		    /*cbfcnp*/adadone,
2552 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
2553 		    /*page_number*/ ATA_IDL_SUP_CAP,
2554 		    /*block_count*/ 1,
2555 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2556 				 CAM_ATAIO_DMA : 0,
2557 		    /*data_ptr*/ (uint8_t *)sup_cap,
2558 		    /*dxfer_len*/ sizeof(*sup_cap),
2559 		    /*timeout*/ada_default_timeout*1000);
2560 
2561 		start_ccb->ccb_h.ccb_state = ADA_CCB_SUP_CAP;
2562 		xpt_action(start_ccb);
2563 		break;
2564 	}
2565 	case ADA_STATE_ZONE:
2566 	{
2567 		struct ata_zoned_info_log *ata_zone;
2568 
2569 		ata_zone = malloc(sizeof(*ata_zone), M_ATADA, M_NOWAIT|M_ZERO);
2570 		if (ata_zone == NULL) {
2571 			xpt_print(periph->path, "Couldn't malloc ata_zone "
2572 			    "data\n");
2573 			adaprobedone(periph, start_ccb);
2574 			break;
2575 		}
2576 
2577 		ata_read_log(ataio,
2578 		    /*retries*/1,
2579 		    /*cbfcnp*/adadone,
2580 		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
2581 		    /*page_number*/ ATA_IDL_ZDI,
2582 		    /*block_count*/ 1,
2583 		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
2584 				 CAM_ATAIO_DMA : 0,
2585 		    /*data_ptr*/ (uint8_t *)ata_zone,
2586 		    /*dxfer_len*/ sizeof(*ata_zone),
2587 		    /*timeout*/ada_default_timeout*1000);
2588 
2589 		start_ccb->ccb_h.ccb_state = ADA_CCB_ZONE;
2590 		xpt_action(start_ccb);
2591 		break;
2592 	}
2593 	}
2594 }
2595 
2596 static void
2597 adaprobedone(struct cam_periph *periph, union ccb *ccb)
2598 {
2599 	struct ada_softc *softc;
2600 
2601 	softc = (struct ada_softc *)periph->softc;
2602 
2603 	if (ccb != NULL)
2604 		xpt_release_ccb(ccb);
2605 
2606 	softc->state = ADA_STATE_NORMAL;
2607 	softc->flags |= ADA_FLAG_PROBED;
2608 	adaschedule(periph);
2609 	if ((softc->flags & ADA_FLAG_ANNOUNCED) == 0) {
2610 		softc->flags |= ADA_FLAG_ANNOUNCED;
2611 		cam_periph_unhold(periph);
2612 	} else {
2613 		cam_periph_release_locked(periph);
2614 	}
2615 }
2616 
2617 static void
2618 adazonedone(struct cam_periph *periph, union ccb *ccb)
2619 {
2620 	struct ada_softc *softc;
2621 	struct bio *bp;
2622 
2623 	softc = periph->softc;
2624 	bp = (struct bio *)ccb->ccb_h.ccb_bp;
2625 
2626 	switch (bp->bio_zone.zone_cmd) {
2627 	case DISK_ZONE_OPEN:
2628 	case DISK_ZONE_CLOSE:
2629 	case DISK_ZONE_FINISH:
2630 	case DISK_ZONE_RWP:
2631 		break;
2632 	case DISK_ZONE_REPORT_ZONES: {
2633 		uint32_t avail_len;
2634 		struct disk_zone_report *rep;
2635 		struct scsi_report_zones_hdr *hdr;
2636 		struct scsi_report_zones_desc *desc;
2637 		struct disk_zone_rep_entry *entry;
2638 		uint32_t num_alloced, hdr_len, num_avail;
2639 		uint32_t num_to_fill, i;
2640 
2641 		rep = &bp->bio_zone.zone_params.report;
2642 		avail_len = ccb->ataio.dxfer_len - ccb->ataio.resid;
2643 		/*
2644 		 * Note that bio_resid isn't normally used for zone
2645 		 * commands, but it is used by devstat_end_transaction_bio()
2646 		 * to determine how much data was transferred.  Because
2647 		 * the size of the SCSI/ATA data structures is different
2648 		 * than the size of the BIO interface structures, the
2649 		 * amount of data actually transferred from the drive will
2650 		 * be different than the amount of data transferred to
2651 		 * the user.
2652 		 */
2653 		num_alloced = rep->entries_allocated;
2654 		hdr = (struct scsi_report_zones_hdr *)ccb->ataio.data_ptr;
2655 		if (avail_len < sizeof(*hdr)) {
2656 			/*
2657 			 * Is there a better error than EIO here?  We asked
2658 			 * for at least the header, and we got less than
2659 			 * that.
2660 			 */
2661 			bp->bio_error = EIO;
2662 			bp->bio_flags |= BIO_ERROR;
2663 			bp->bio_resid = bp->bio_bcount;
2664 			break;
2665 		}
2666 
2667 		hdr_len = le32dec(hdr->length);
2668 		if (hdr_len > 0)
2669 			rep->entries_available = hdr_len / sizeof(*desc);
2670 		else
2671 			rep->entries_available = 0;
2672 		/*
2673 		 * NOTE: using the same values for the BIO version of the
2674 		 * same field as the SCSI/ATA values.  This means we could
2675 		 * get some additional values that aren't defined in bio.h
2676 		 * if more values of the same field are defined later.
2677 		 */
2678 		rep->header.same = hdr->byte4 & SRZ_SAME_MASK;
2679 		rep->header.maximum_lba = le64dec(hdr->maximum_lba);
2680 		/*
2681 		 * If the drive reports no entries that match the query,
2682 		 * we're done.
2683 		 */
2684 		if (hdr_len == 0) {
2685 			rep->entries_filled = 0;
2686 			bp->bio_resid = bp->bio_bcount;
2687 			break;
2688 		}
2689 
2690 		num_avail = min((avail_len - sizeof(*hdr)) / sizeof(*desc),
2691 				hdr_len / sizeof(*desc));
2692 		/*
2693 		 * If the drive didn't return any data, then we're done.
2694 		 */
2695 		if (num_avail == 0) {
2696 			rep->entries_filled = 0;
2697 			bp->bio_resid = bp->bio_bcount;
2698 			break;
2699 		}
2700 
2701 		num_to_fill = min(num_avail, rep->entries_allocated);
2702 		/*
2703 		 * If the user didn't allocate any entries for us to fill,
2704 		 * we're done.
2705 		 */
2706 		if (num_to_fill == 0) {
2707 			rep->entries_filled = 0;
2708 			bp->bio_resid = bp->bio_bcount;
2709 			break;
2710 		}
2711 
2712 		for (i = 0, desc = &hdr->desc_list[0], entry=&rep->entries[0];
2713 		     i < num_to_fill; i++, desc++, entry++) {
2714 			/*
2715 			 * NOTE: we're mapping the values here directly
2716 			 * from the SCSI/ATA bit definitions to the bio.h
2717 			 * definitions.  There is also a warning in
2718 			 * disk_zone.h, but the impact is that if
2719 			 * additional values are added in the SCSI/ATA
2720 			 * specs these will be visible to consumers of
2721 			 * this interface.
2722 			 */
2723 			entry->zone_type = desc->zone_type & SRZ_TYPE_MASK;
2724 			entry->zone_condition =
2725 			    (desc->zone_flags & SRZ_ZONE_COND_MASK) >>
2726 			    SRZ_ZONE_COND_SHIFT;
2727 			entry->zone_flags |= desc->zone_flags &
2728 			    (SRZ_ZONE_NON_SEQ|SRZ_ZONE_RESET);
2729 			entry->zone_length = le64dec(desc->zone_length);
2730 			entry->zone_start_lba = le64dec(desc->zone_start_lba);
2731 			entry->write_pointer_lba =
2732 			    le64dec(desc->write_pointer_lba);
2733 		}
2734 		rep->entries_filled = num_to_fill;
2735 		/*
2736 		 * Note that this residual is accurate from the user's
2737 		 * standpoint, but the amount transferred isn't accurate
2738 		 * from the standpoint of what actually came back from the
2739 		 * drive.
2740 		 */
2741 		bp->bio_resid = bp->bio_bcount - (num_to_fill * sizeof(*entry));
2742 		break;
2743 	}
2744 	case DISK_ZONE_GET_PARAMS:
2745 	default:
2746 		/*
2747 		 * In theory we should not get a GET_PARAMS bio, since it
2748 		 * should be handled without queueing the command to the
2749 		 * drive.
2750 		 */
2751 		panic("%s: Invalid zone command %d", __func__,
2752 		    bp->bio_zone.zone_cmd);
2753 		break;
2754 	}
2755 
2756 	if (bp->bio_zone.zone_cmd == DISK_ZONE_REPORT_ZONES)
2757 		free(ccb->ataio.data_ptr, M_ATADA);
2758 }
2759 
2760 
2761 static void
2762 adadone(struct cam_periph *periph, union ccb *done_ccb)
2763 {
2764 	struct ada_softc *softc;
2765 	struct ccb_ataio *ataio;
2766 	struct cam_path *path;
2767 	uint32_t priority;
2768 	int state;
2769 
2770 	softc = (struct ada_softc *)periph->softc;
2771 	ataio = &done_ccb->ataio;
2772 	path = done_ccb->ccb_h.path;
2773 	priority = done_ccb->ccb_h.pinfo.priority;
2774 
2775 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("adadone\n"));
2776 
2777 	state = ataio->ccb_h.ccb_state & ADA_CCB_TYPE_MASK;
2778 	switch (state) {
2779 	case ADA_CCB_BUFFER_IO:
2780 	case ADA_CCB_TRIM:
2781 	{
2782 		struct bio *bp;
2783 		int error;
2784 
2785 		cam_periph_lock(periph);
2786 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2787 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2788 			error = adaerror(done_ccb, 0, 0);
2789 			if (error == ERESTART) {
2790 				/* A retry was scheduled, so just return. */
2791 				cam_periph_unlock(periph);
2792 				return;
2793 			}
2794 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2795 				cam_release_devq(path,
2796 						 /*relsim_flags*/0,
2797 						 /*reduction*/0,
2798 						 /*timeout*/0,
2799 						 /*getcount_only*/0);
2800 			/*
2801 			 * If we get an error on an NCQ DSM TRIM, fall back
2802 			 * to a non-NCQ DSM TRIM forever. Please note that if
2803 			 * CAN_NCQ_TRIM is set, CAN_TRIM is necessarily set too.
2804 			 * However, for this one trim, we treat it as advisory
2805 			 * and return success up the stack.
2806 			 */
2807 			if (state == ADA_CCB_TRIM &&
2808 			    error != 0 &&
2809 			    (softc->flags & ADA_FLAG_CAN_NCQ_TRIM) != 0) {
2810 				softc->flags &= ~ADA_FLAG_CAN_NCQ_TRIM;
2811 				error = 0;
2812 				adasetdeletemethod(softc);
2813 			}
2814 		} else {
2815 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2816 				panic("REQ_CMP with QFRZN");
2817 
2818 			error = 0;
2819 		}
2820 		bp->bio_error = error;
2821 		if (error != 0) {
2822 			bp->bio_resid = bp->bio_bcount;
2823 			bp->bio_flags |= BIO_ERROR;
2824 		} else {
2825 			if (bp->bio_cmd == BIO_ZONE)
2826 				adazonedone(periph, done_ccb);
2827 			else if (state == ADA_CCB_TRIM)
2828 				bp->bio_resid = 0;
2829 			else
2830 				bp->bio_resid = ataio->resid;
2831 
2832 			if ((bp->bio_resid > 0)
2833 			 && (bp->bio_cmd != BIO_ZONE))
2834 				bp->bio_flags |= BIO_ERROR;
2835 		}
2836 		softc->outstanding_cmds--;
2837 		if (softc->outstanding_cmds == 0)
2838 			softc->flags |= ADA_FLAG_WAS_OTAG;
2839 
2840 		cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb);
2841 		xpt_release_ccb(done_ccb);
2842 		if (state == ADA_CCB_TRIM) {
2843 			TAILQ_HEAD(, bio) queue;
2844 			struct bio *bp1;
2845 
2846 			TAILQ_INIT(&queue);
2847 			TAILQ_CONCAT(&queue, &softc->trim_req.bps, bio_queue);
2848 			/*
2849 			 * Normally, the xpt_release_ccb() above would make sure
2850 			 * that when we have more work to do, that work would
2851 			 * get kicked off. However, we specifically keep
2852 			 * trim_running set to 0 before the call above to allow
2853 			 * other I/O to progress when many BIO_DELETE requests
2854 			 * are pushed down. We set trim_running to 0 and call
2855 			 * daschedule again so that we don't stall if there are
2856 			 * no other I/Os pending apart from BIO_DELETEs.
2857 			 */
2858 			cam_iosched_trim_done(softc->cam_iosched);
2859 			adaschedule(periph);
2860 			cam_periph_unlock(periph);
2861 			while ((bp1 = TAILQ_FIRST(&queue)) != NULL) {
2862 				TAILQ_REMOVE(&queue, bp1, bio_queue);
2863 				bp1->bio_error = error;
2864 				if (error != 0) {
2865 					bp1->bio_flags |= BIO_ERROR;
2866 					bp1->bio_resid = bp1->bio_bcount;
2867 				} else
2868 					bp1->bio_resid = 0;
2869 				biodone(bp1);
2870 			}
2871 		} else {
2872 			adaschedule(periph);
2873 			cam_periph_unlock(periph);
2874 			biodone(bp);
2875 		}
2876 		return;
2877 	}
2878 	case ADA_CCB_RAHEAD:
2879 	{
2880 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2881 			if (adaerror(done_ccb, 0, 0) == ERESTART) {
2882 				/* Drop freeze taken due to CAM_DEV_QFREEZE */
2883 				cam_release_devq(path, 0, 0, 0, FALSE);
2884 				return;
2885 			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
2886 				cam_release_devq(path,
2887 				    /*relsim_flags*/0,
2888 				    /*reduction*/0,
2889 				    /*timeout*/0,
2890 				    /*getcount_only*/0);
2891 			}
2892 		}
2893 
2894 		/*
2895 		 * Since our peripheral may be invalidated by an error
2896 		 * above or an external event, we must release our CCB
2897 		 * before releasing the reference on the peripheral.
2898 		 * The peripheral will only go away once the last reference
2899 		 * is removed, and we need it around for the CCB release
2900 		 * operation.
2901 		 */
2902 
2903 		xpt_release_ccb(done_ccb);
2904 		softc->state = ADA_STATE_WCACHE;
2905 		xpt_schedule(periph, priority);
2906 		/* Drop freeze taken due to CAM_DEV_QFREEZE */
2907 		cam_release_devq(path, 0, 0, 0, FALSE);
2908 		return;
2909 	}
2910 	case ADA_CCB_WCACHE:
2911 	{
2912 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2913 			if (adaerror(done_ccb, 0, 0) == ERESTART) {
2914 				/* Drop freeze taken due to CAM_DEV_QFREEZE */
2915 				cam_release_devq(path, 0, 0, 0, FALSE);
2916 				return;
2917 			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
2918 				cam_release_devq(path,
2919 				    /*relsim_flags*/0,
2920 				    /*reduction*/0,
2921 				    /*timeout*/0,
2922 				    /*getcount_only*/0);
2923 			}
2924 		}
2925 
2926 		/* Drop freeze taken due to CAM_DEV_QFREEZE */
2927 		cam_release_devq(path, 0, 0, 0, FALSE);
2928 
2929 		if ((softc->flags & ADA_FLAG_CAN_LOG)
2930 		 && (softc->zone_mode != ADA_ZONE_NONE)) {
2931 			xpt_release_ccb(done_ccb);
2932 			softc->state = ADA_STATE_LOGDIR;
2933 			xpt_schedule(periph, priority);
2934 		} else {
2935 			adaprobedone(periph, done_ccb);
2936 		}
2937 		return;
2938 	}
2939 	case ADA_CCB_LOGDIR:
2940 	{
2941 		int error;
2942 
2943 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2944 			error = 0;
2945 			softc->valid_logdir_len = 0;
2946 			bzero(&softc->ata_logdir, sizeof(softc->ata_logdir));
2947 			softc->valid_logdir_len =
2948 				ataio->dxfer_len - ataio->resid;
2949 			if (softc->valid_logdir_len > 0)
2950 				bcopy(ataio->data_ptr, &softc->ata_logdir,
2951 				    min(softc->valid_logdir_len,
2952 					sizeof(softc->ata_logdir)));
2953 			/*
2954 			 * Figure out whether the Identify Device log is
2955 			 * supported.  The General Purpose log directory
2956 			 * has a header, and lists the number of pages
2957 			 * available for each GP log identified by the
2958 			 * offset into the list.
2959 			 */
2960 			if ((softc->valid_logdir_len >=
2961 			    ((ATA_IDENTIFY_DATA_LOG + 1) * sizeof(uint16_t)))
2962 			 && (le16dec(softc->ata_logdir.header) ==
2963 			     ATA_GP_LOG_DIR_VERSION)
2964 			 && (le16dec(&softc->ata_logdir.num_pages[
2965 			     (ATA_IDENTIFY_DATA_LOG *
2966 			     sizeof(uint16_t)) - sizeof(uint16_t)]) > 0)){
2967 				softc->flags |= ADA_FLAG_CAN_IDLOG;
2968 			} else {
2969 				softc->flags &= ~ADA_FLAG_CAN_IDLOG;
2970 			}
2971 		} else {
2972 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
2973 					 SF_RETRY_UA|SF_NO_PRINT);
2974 			if (error == ERESTART)
2975 				return;
2976 			else if (error != 0) {
2977 				/*
2978 				 * If we can't get the ATA log directory,
2979 				 * then ATA logs are effectively not
2980 				 * supported even if the bit is set in the
2981 				 * identify data.
2982 				 */
2983 				softc->flags &= ~(ADA_FLAG_CAN_LOG |
2984 						  ADA_FLAG_CAN_IDLOG);
2985 				if ((done_ccb->ccb_h.status &
2986 				     CAM_DEV_QFRZN) != 0) {
2987 					/* Don't wedge this device's queue */
2988 					cam_release_devq(done_ccb->ccb_h.path,
2989 							 /*relsim_flags*/0,
2990 							 /*reduction*/0,
2991 							 /*timeout*/0,
2992 							 /*getcount_only*/0);
2993 				}
2994 			}
2995 
2996 
2997 		}
2998 
2999 		free(ataio->data_ptr, M_ATADA);
3000 
3001 		if ((error == 0)
3002 		 && (softc->flags & ADA_FLAG_CAN_IDLOG)) {
3003 			softc->state = ADA_STATE_IDDIR;
3004 			xpt_release_ccb(done_ccb);
3005 			xpt_schedule(periph, priority);
3006 		} else
3007 			adaprobedone(periph, done_ccb);
3008 
3009 		return;
3010 	}
3011 	case ADA_CCB_IDDIR: {
3012 		int error;
3013 
3014 		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3015 			off_t entries_offset, max_entries;
3016 			error = 0;
3017 
3018 			softc->valid_iddir_len = 0;
3019 			bzero(&softc->ata_iddir, sizeof(softc->ata_iddir));
3020 			softc->flags &= ~(ADA_FLAG_CAN_SUPCAP |
3021 					  ADA_FLAG_CAN_ZONE);
3022 			softc->valid_iddir_len =
3023 				ataio->dxfer_len - ataio->resid;
3024 			if (softc->valid_iddir_len > 0)
3025 				bcopy(ataio->data_ptr, &softc->ata_iddir,
3026 				    min(softc->valid_iddir_len,
3027 					sizeof(softc->ata_iddir)));
3028 
3029 			entries_offset =
3030 			    __offsetof(struct ata_identify_log_pages,entries);
3031 			max_entries = softc->valid_iddir_len - entries_offset;
3032 			if ((softc->valid_iddir_len > (entries_offset + 1))
3033 			 && (le64dec(softc->ata_iddir.header) ==
3034 			     ATA_IDLOG_REVISION)
3035 			 && (softc->ata_iddir.entry_count > 0)) {
3036 				int num_entries, i;
3037 
3038 				num_entries = softc->ata_iddir.entry_count;
3039 				num_entries = min(num_entries,
3040 				   softc->valid_iddir_len - entries_offset);
3041 				for (i = 0; i < num_entries &&
3042 				     i < max_entries; i++) {
3043 					if (softc->ata_iddir.entries[i] ==
3044 					    ATA_IDL_SUP_CAP)
3045 						softc->flags |=
3046 						    ADA_FLAG_CAN_SUPCAP;
3047 					else if (softc->ata_iddir.entries[i]==
3048 						 ATA_IDL_ZDI)
3049 						softc->flags |=
3050 						    ADA_FLAG_CAN_ZONE;
3051 
3052 					if ((softc->flags &
3053 					     ADA_FLAG_CAN_SUPCAP)
3054 					 && (softc->flags &
3055 					     ADA_FLAG_CAN_ZONE))
3056 						break;
3057 				}
3058 			}
3059 		} else {
3060 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3061 					 SF_RETRY_UA|SF_NO_PRINT);
3062 			if (error == ERESTART)
3063 				return;
3064 			else if (error != 0) {
3065 				/*
3066 				 * If we can't get the ATA Identify Data log
3067 				 * directory, then it effectively isn't
3068 				 * supported even if the ATA Log directory
3069 				 * a non-zero number of pages present for
3070 				 * this log.
3071 				 */
3072 				softc->flags &= ~ADA_FLAG_CAN_IDLOG;
3073 				if ((done_ccb->ccb_h.status &
3074 				     CAM_DEV_QFRZN) != 0) {
3075 					/* Don't wedge this device's queue */
3076 					cam_release_devq(done_ccb->ccb_h.path,
3077 							 /*relsim_flags*/0,
3078 							 /*reduction*/0,
3079 							 /*timeout*/0,
3080 							 /*getcount_only*/0);
3081 				}
3082 			}
3083 		}
3084 
3085 		free(ataio->data_ptr, M_ATADA);
3086 
3087 		if ((error == 0)
3088 		 && (softc->flags & ADA_FLAG_CAN_SUPCAP)) {
3089 			softc->state = ADA_STATE_SUP_CAP;
3090 			xpt_release_ccb(done_ccb);
3091 			xpt_schedule(periph, priority);
3092 		} else
3093 			adaprobedone(periph, done_ccb);
3094 		return;
3095 	}
3096 	case ADA_CCB_SUP_CAP: {
3097 		int error;
3098 
3099 		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3100 			uint32_t valid_len;
3101 			size_t needed_size;
3102 			struct ata_identify_log_sup_cap *sup_cap;
3103 			error = 0;
3104 
3105 			sup_cap = (struct ata_identify_log_sup_cap *)
3106 			    ataio->data_ptr;
3107 			valid_len = ataio->dxfer_len - ataio->resid;
3108 			needed_size =
3109 			    __offsetof(struct ata_identify_log_sup_cap,
3110 			    sup_zac_cap) + 1 + sizeof(sup_cap->sup_zac_cap);
3111 			if (valid_len >= needed_size) {
3112 				uint64_t zoned, zac_cap;
3113 
3114 				zoned = le64dec(sup_cap->zoned_cap);
3115 				if (zoned & ATA_ZONED_VALID) {
3116 					/*
3117 					 * This should have already been
3118 					 * set, because this is also in the
3119 					 * ATA identify data.
3120 					 */
3121 					if ((zoned & ATA_ZONED_MASK) ==
3122 					    ATA_SUPPORT_ZONE_HOST_AWARE)
3123 						softc->zone_mode =
3124 						    ADA_ZONE_HOST_AWARE;
3125 					else if ((zoned & ATA_ZONED_MASK) ==
3126 					    ATA_SUPPORT_ZONE_DEV_MANAGED)
3127 						softc->zone_mode =
3128 						    ADA_ZONE_DRIVE_MANAGED;
3129 				}
3130 
3131 				zac_cap = le64dec(sup_cap->sup_zac_cap);
3132 				if (zac_cap & ATA_SUP_ZAC_CAP_VALID) {
3133 					if (zac_cap & ATA_REPORT_ZONES_SUP)
3134 						softc->zone_flags |=
3135 						    ADA_ZONE_FLAG_RZ_SUP;
3136 					if (zac_cap & ATA_ND_OPEN_ZONE_SUP)
3137 						softc->zone_flags |=
3138 						    ADA_ZONE_FLAG_OPEN_SUP;
3139 					if (zac_cap & ATA_ND_CLOSE_ZONE_SUP)
3140 						softc->zone_flags |=
3141 						    ADA_ZONE_FLAG_CLOSE_SUP;
3142 					if (zac_cap & ATA_ND_FINISH_ZONE_SUP)
3143 						softc->zone_flags |=
3144 						    ADA_ZONE_FLAG_FINISH_SUP;
3145 					if (zac_cap & ATA_ND_RWP_SUP)
3146 						softc->zone_flags |=
3147 						    ADA_ZONE_FLAG_RWP_SUP;
3148 				} else {
3149 					/*
3150 					 * This field was introduced in
3151 					 * ACS-4, r08 on April 28th, 2015.
3152 					 * If the drive firmware was written
3153 					 * to an earlier spec, it won't have
3154 					 * the field.  So, assume all
3155 					 * commands are supported.
3156 					 */
3157 					softc->zone_flags |=
3158 					    ADA_ZONE_FLAG_SUP_MASK;
3159 				}
3160 
3161 			}
3162 		} else {
3163 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3164 					 SF_RETRY_UA|SF_NO_PRINT);
3165 			if (error == ERESTART)
3166 				return;
3167 			else if (error != 0) {
3168 				/*
3169 				 * If we can't get the ATA Identify Data
3170 				 * Supported Capabilities page, clear the
3171 				 * flag...
3172 				 */
3173 				softc->flags &= ~ADA_FLAG_CAN_SUPCAP;
3174 				/*
3175 				 * And clear zone capabilities.
3176 				 */
3177 				softc->zone_flags &= ~ADA_ZONE_FLAG_SUP_MASK;
3178 				if ((done_ccb->ccb_h.status &
3179 				     CAM_DEV_QFRZN) != 0) {
3180 					/* Don't wedge this device's queue */
3181 					cam_release_devq(done_ccb->ccb_h.path,
3182 							 /*relsim_flags*/0,
3183 							 /*reduction*/0,
3184 							 /*timeout*/0,
3185 							 /*getcount_only*/0);
3186 				}
3187 			}
3188 		}
3189 
3190 		free(ataio->data_ptr, M_ATADA);
3191 
3192 		if ((error == 0)
3193 		 && (softc->flags & ADA_FLAG_CAN_ZONE)) {
3194 			softc->state = ADA_STATE_ZONE;
3195 			xpt_release_ccb(done_ccb);
3196 			xpt_schedule(periph, priority);
3197 		} else
3198 			adaprobedone(periph, done_ccb);
3199 		return;
3200 	}
3201 	case ADA_CCB_ZONE: {
3202 		int error;
3203 
3204 		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3205 			struct ata_zoned_info_log *zi_log;
3206 			uint32_t valid_len;
3207 			size_t needed_size;
3208 
3209 			zi_log = (struct ata_zoned_info_log *)ataio->data_ptr;
3210 
3211 			valid_len = ataio->dxfer_len - ataio->resid;
3212 			needed_size = __offsetof(struct ata_zoned_info_log,
3213 			    version_info) + 1 + sizeof(zi_log->version_info);
3214 			if (valid_len >= needed_size) {
3215 				uint64_t tmpvar;
3216 
3217 				tmpvar = le64dec(zi_log->zoned_cap);
3218 				if (tmpvar & ATA_ZDI_CAP_VALID) {
3219 					if (tmpvar & ATA_ZDI_CAP_URSWRZ)
3220 						softc->zone_flags |=
3221 						    ADA_ZONE_FLAG_URSWRZ;
3222 					else
3223 						softc->zone_flags &=
3224 						    ~ADA_ZONE_FLAG_URSWRZ;
3225 				}
3226 				tmpvar = le64dec(zi_log->optimal_seq_zones);
3227 				if (tmpvar & ATA_ZDI_OPT_SEQ_VALID) {
3228 					softc->zone_flags |=
3229 					    ADA_ZONE_FLAG_OPT_SEQ_SET;
3230 					softc->optimal_seq_zones = (tmpvar &
3231 					    ATA_ZDI_OPT_SEQ_MASK);
3232 				} else {
3233 					softc->zone_flags &=
3234 					    ~ADA_ZONE_FLAG_OPT_SEQ_SET;
3235 					softc->optimal_seq_zones = 0;
3236 				}
3237 
3238 				tmpvar =le64dec(zi_log->optimal_nonseq_zones);
3239 				if (tmpvar & ATA_ZDI_OPT_NS_VALID) {
3240 					softc->zone_flags |=
3241 					    ADA_ZONE_FLAG_OPT_NONSEQ_SET;
3242 					softc->optimal_nonseq_zones =
3243 					    (tmpvar & ATA_ZDI_OPT_NS_MASK);
3244 				} else {
3245 					softc->zone_flags &=
3246 					    ~ADA_ZONE_FLAG_OPT_NONSEQ_SET;
3247 					softc->optimal_nonseq_zones = 0;
3248 				}
3249 
3250 				tmpvar = le64dec(zi_log->max_seq_req_zones);
3251 				if (tmpvar & ATA_ZDI_MAX_SEQ_VALID) {
3252 					softc->zone_flags |=
3253 					    ADA_ZONE_FLAG_MAX_SEQ_SET;
3254 					softc->max_seq_zones =
3255 					    (tmpvar & ATA_ZDI_MAX_SEQ_MASK);
3256 				} else {
3257 					softc->zone_flags &=
3258 					    ~ADA_ZONE_FLAG_MAX_SEQ_SET;
3259 					softc->max_seq_zones = 0;
3260 				}
3261 			}
3262 		} else {
3263 			error = adaerror(done_ccb, CAM_RETRY_SELTO,
3264 					 SF_RETRY_UA|SF_NO_PRINT);
3265 			if (error == ERESTART)
3266 				return;
3267 			else if (error != 0) {
3268 				softc->flags &= ~ADA_FLAG_CAN_ZONE;
3269 				softc->flags &= ~ADA_ZONE_FLAG_SET_MASK;
3270 
3271 				if ((done_ccb->ccb_h.status &
3272 				     CAM_DEV_QFRZN) != 0) {
3273 					/* Don't wedge this device's queue */
3274 					cam_release_devq(done_ccb->ccb_h.path,
3275 							 /*relsim_flags*/0,
3276 							 /*reduction*/0,
3277 							 /*timeout*/0,
3278 							 /*getcount_only*/0);
3279 				}
3280 			}
3281 
3282 		}
3283 		free(ataio->data_ptr, M_ATADA);
3284 
3285 		adaprobedone(periph, done_ccb);
3286 		return;
3287 	}
3288 	case ADA_CCB_DUMP:
3289 		/* No-op.  We're polling */
3290 		return;
3291 	default:
3292 		break;
3293 	}
3294 	xpt_release_ccb(done_ccb);
3295 }
3296 
3297 static int
3298 adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3299 {
3300 #ifdef CAM_IO_STATS
3301 	struct ada_softc *softc;
3302 	struct cam_periph *periph;
3303 
3304 	periph = xpt_path_periph(ccb->ccb_h.path);
3305 	softc = (struct ada_softc *)periph->softc;
3306 
3307 	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
3308 	case CAM_CMD_TIMEOUT:
3309 		softc->timeouts++;
3310 		break;
3311 	case CAM_REQ_ABORTED:
3312 	case CAM_REQ_CMP_ERR:
3313 	case CAM_REQ_TERMIO:
3314 	case CAM_UNREC_HBA_ERROR:
3315 	case CAM_DATA_RUN_ERR:
3316 	case CAM_ATA_STATUS_ERROR:
3317 		softc->errors++;
3318 		break;
3319 	default:
3320 		break;
3321 	}
3322 #endif
3323 
3324 	return(cam_periph_error(ccb, cam_flags, sense_flags, NULL));
3325 }
3326 
3327 static void
3328 adagetparams(struct cam_periph *periph, struct ccb_getdev *cgd)
3329 {
3330 	struct ada_softc *softc = (struct ada_softc *)periph->softc;
3331 	struct disk_params *dp = &softc->params;
3332 	u_int64_t lbasize48;
3333 	u_int32_t lbasize;
3334 
3335 	dp->secsize = ata_logical_sector_size(&cgd->ident_data);
3336 	if ((cgd->ident_data.atavalid & ATA_FLAG_54_58) &&
3337 		cgd->ident_data.current_heads && cgd->ident_data.current_sectors) {
3338 		dp->heads = cgd->ident_data.current_heads;
3339 		dp->secs_per_track = cgd->ident_data.current_sectors;
3340 		dp->cylinders = cgd->ident_data.cylinders;
3341 		dp->sectors = (u_int32_t)cgd->ident_data.current_size_1 |
3342 			  ((u_int32_t)cgd->ident_data.current_size_2 << 16);
3343 	} else {
3344 		dp->heads = cgd->ident_data.heads;
3345 		dp->secs_per_track = cgd->ident_data.sectors;
3346 		dp->cylinders = cgd->ident_data.cylinders;
3347 		dp->sectors = cgd->ident_data.cylinders * dp->heads * dp->secs_per_track;
3348 	}
3349 	lbasize = (u_int32_t)cgd->ident_data.lba_size_1 |
3350 		  ((u_int32_t)cgd->ident_data.lba_size_2 << 16);
3351 
3352 	/* use the 28bit LBA size if valid or bigger than the CHS mapping */
3353 	if (cgd->ident_data.cylinders == 16383 || dp->sectors < lbasize)
3354 		dp->sectors = lbasize;
3355 
3356 	/* use the 48bit LBA size if valid */
3357 	lbasize48 = ((u_int64_t)cgd->ident_data.lba_size48_1) |
3358 		    ((u_int64_t)cgd->ident_data.lba_size48_2 << 16) |
3359 		    ((u_int64_t)cgd->ident_data.lba_size48_3 << 32) |
3360 		    ((u_int64_t)cgd->ident_data.lba_size48_4 << 48);
3361 	if ((cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) &&
3362 	    lbasize48 > ATA_MAX_28BIT_LBA)
3363 		dp->sectors = lbasize48;
3364 }
3365 
3366 static void
3367 adasendorderedtag(void *arg)
3368 {
3369 	struct ada_softc *softc = arg;
3370 
3371 	if (ada_send_ordered) {
3372 		if (softc->outstanding_cmds > 0) {
3373 			if ((softc->flags & ADA_FLAG_WAS_OTAG) == 0)
3374 				softc->flags |= ADA_FLAG_NEED_OTAG;
3375 			softc->flags &= ~ADA_FLAG_WAS_OTAG;
3376 		}
3377 	}
3378 	/* Queue us up again */
3379 	callout_reset(&softc->sendordered_c,
3380 	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
3381 	    adasendorderedtag, softc);
3382 }
3383 
3384 /*
3385  * Step through all ADA peripheral drivers, and if the device is still open,
3386  * sync the disk cache to physical media.
3387  */
3388 static void
3389 adaflush(void)
3390 {
3391 	struct cam_periph *periph;
3392 	struct ada_softc *softc;
3393 	union ccb *ccb;
3394 	int error;
3395 
3396 	CAM_PERIPH_FOREACH(periph, &adadriver) {
3397 		softc = (struct ada_softc *)periph->softc;
3398 		if (SCHEDULER_STOPPED()) {
3399 			/* If we paniced with the lock held, do not recurse. */
3400 			if (!cam_periph_owned(periph) &&
3401 			    (softc->flags & ADA_FLAG_OPEN)) {
3402 				adadump(softc->disk, NULL, 0, 0, 0);
3403 			}
3404 			continue;
3405 		}
3406 		cam_periph_lock(periph);
3407 		/*
3408 		 * We only sync the cache if the drive is still open, and
3409 		 * if the drive is capable of it..
3410 		 */
3411 		if (((softc->flags & ADA_FLAG_OPEN) == 0) ||
3412 		    (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) == 0) {
3413 			cam_periph_unlock(periph);
3414 			continue;
3415 		}
3416 
3417 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3418 		cam_fill_ataio(&ccb->ataio,
3419 				    0,
3420 				    adadone,
3421 				    CAM_DIR_NONE,
3422 				    0,
3423 				    NULL,
3424 				    0,
3425 				    ada_default_timeout*1000);
3426 		if (softc->flags & ADA_FLAG_CAN_48BIT)
3427 			ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
3428 		else
3429 			ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
3430 
3431 		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
3432 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
3433 		    softc->disk->d_devstat);
3434 		if (error != 0)
3435 			xpt_print(periph->path, "Synchronize cache failed\n");
3436 		xpt_release_ccb(ccb);
3437 		cam_periph_unlock(periph);
3438 	}
3439 }
3440 
3441 static void
3442 adaspindown(uint8_t cmd, int flags)
3443 {
3444 	struct cam_periph *periph;
3445 	struct ada_softc *softc;
3446 	union ccb *ccb;
3447 	int error;
3448 
3449 	CAM_PERIPH_FOREACH(periph, &adadriver) {
3450 		/* If we paniced with lock held - not recurse here. */
3451 		if (cam_periph_owned(periph))
3452 			continue;
3453 		cam_periph_lock(periph);
3454 		softc = (struct ada_softc *)periph->softc;
3455 		/*
3456 		 * We only spin-down the drive if it is capable of it..
3457 		 */
3458 		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
3459 			cam_periph_unlock(periph);
3460 			continue;
3461 		}
3462 
3463 		if (bootverbose)
3464 			xpt_print(periph->path, "spin-down\n");
3465 
3466 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3467 		cam_fill_ataio(&ccb->ataio,
3468 				    0,
3469 				    adadone,
3470 				    CAM_DIR_NONE | flags,
3471 				    0,
3472 				    NULL,
3473 				    0,
3474 				    ada_default_timeout*1000);
3475 		ata_28bit_cmd(&ccb->ataio, cmd, 0, 0, 0);
3476 
3477 		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
3478 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
3479 		    softc->disk->d_devstat);
3480 		if (error != 0)
3481 			xpt_print(periph->path, "Spin-down disk failed\n");
3482 		xpt_release_ccb(ccb);
3483 		cam_periph_unlock(periph);
3484 	}
3485 }
3486 
3487 static void
3488 adashutdown(void *arg, int howto)
3489 {
3490 
3491 	adaflush();
3492 	if (ada_spindown_shutdown != 0 &&
3493 	    (howto & (RB_HALT | RB_POWEROFF)) != 0)
3494 		adaspindown(ATA_STANDBY_IMMEDIATE, 0);
3495 }
3496 
3497 static void
3498 adasuspend(void *arg)
3499 {
3500 
3501 	adaflush();
3502 	if (ada_spindown_suspend != 0)
3503 		adaspindown(ATA_SLEEP, CAM_DEV_QFREEZE);
3504 }
3505 
3506 static void
3507 adaresume(void *arg)
3508 {
3509 	struct cam_periph *periph;
3510 	struct ada_softc *softc;
3511 
3512 	if (ada_spindown_suspend == 0)
3513 		return;
3514 
3515 	CAM_PERIPH_FOREACH(periph, &adadriver) {
3516 		cam_periph_lock(periph);
3517 		softc = (struct ada_softc *)periph->softc;
3518 		/*
3519 		 * We only spin-down the drive if it is capable of it..
3520 		 */
3521 		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
3522 			cam_periph_unlock(periph);
3523 			continue;
3524 		}
3525 
3526 		if (bootverbose)
3527 			xpt_print(periph->path, "resume\n");
3528 
3529 		/*
3530 		 * Drop freeze taken due to CAM_DEV_QFREEZE flag set on
3531 		 * sleep request.
3532 		 */
3533 		cam_release_devq(periph->path,
3534 			 /*relsim_flags*/0,
3535 			 /*openings*/0,
3536 			 /*timeout*/0,
3537 			 /*getcount_only*/0);
3538 
3539 		cam_periph_unlock(periph);
3540 	}
3541 }
3542 
3543 #endif /* _KERNEL */
3544