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