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