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