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