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