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