xref: /freebsd/sys/cam/ata/ata_da.c (revision b2d48be1bc7df45ddd13b143a160d0acb5a383c5)
1 /*-
2  * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_ada.h"
31 
32 #include <sys/param.h>
33 
34 #ifdef _KERNEL
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/bio.h>
38 #include <sys/sysctl.h>
39 #include <sys/taskqueue.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/conf.h>
43 #include <sys/devicestat.h>
44 #include <sys/eventhandler.h>
45 #include <sys/malloc.h>
46 #include <sys/cons.h>
47 #include <sys/proc.h>
48 #include <sys/reboot.h>
49 #include <geom/geom_disk.h>
50 #endif /* _KERNEL */
51 
52 #ifndef _KERNEL
53 #include <stdio.h>
54 #include <string.h>
55 #endif /* _KERNEL */
56 
57 #include <cam/cam.h>
58 #include <cam/cam_ccb.h>
59 #include <cam/cam_periph.h>
60 #include <cam/cam_xpt_periph.h>
61 #include <cam/cam_sim.h>
62 
63 #include <cam/ata/ata_all.h>
64 
65 #include <machine/md_var.h>	/* geometry translation */
66 
67 #ifdef _KERNEL
68 
69 #define ATA_MAX_28BIT_LBA               268435455UL
70 
71 typedef enum {
72 	ADA_STATE_RAHEAD,
73 	ADA_STATE_WCACHE,
74 	ADA_STATE_NORMAL
75 } ada_state;
76 
77 typedef enum {
78 	ADA_FLAG_CAN_48BIT	= 0x0002,
79 	ADA_FLAG_CAN_FLUSHCACHE	= 0x0004,
80 	ADA_FLAG_CAN_NCQ	= 0x0008,
81 	ADA_FLAG_CAN_DMA	= 0x0010,
82 	ADA_FLAG_NEED_OTAG	= 0x0020,
83 	ADA_FLAG_WAS_OTAG	= 0x0040,
84 	ADA_FLAG_CAN_TRIM	= 0x0080,
85 	ADA_FLAG_OPEN		= 0x0100,
86 	ADA_FLAG_SCTX_INIT	= 0x0200,
87 	ADA_FLAG_CAN_CFA        = 0x0400,
88 	ADA_FLAG_CAN_POWERMGT   = 0x0800,
89 	ADA_FLAG_CAN_DMA48	= 0x1000,
90 	ADA_FLAG_DIRTY		= 0x2000
91 } ada_flags;
92 
93 typedef enum {
94 	ADA_Q_NONE		= 0x00,
95 	ADA_Q_4K		= 0x01,
96 } ada_quirks;
97 
98 #define ADA_Q_BIT_STRING	\
99 	"\020"			\
100 	"\0014K"
101 
102 typedef enum {
103 	ADA_CCB_RAHEAD		= 0x01,
104 	ADA_CCB_WCACHE		= 0x02,
105 	ADA_CCB_BUFFER_IO	= 0x03,
106 	ADA_CCB_DUMP		= 0x05,
107 	ADA_CCB_TRIM		= 0x06,
108 	ADA_CCB_TYPE_MASK	= 0x0F,
109 } ada_ccb_state;
110 
111 /* Offsets into our private area for storing information */
112 #define ccb_state	ppriv_field0
113 #define ccb_bp		ppriv_ptr1
114 
115 struct disk_params {
116 	u_int8_t  heads;
117 	u_int8_t  secs_per_track;
118 	u_int32_t cylinders;
119 	u_int32_t secsize;	/* Number of bytes/logical sector */
120 	u_int64_t sectors;	/* Total number sectors */
121 };
122 
123 #define TRIM_MAX_BLOCKS	8
124 #define TRIM_MAX_RANGES	(TRIM_MAX_BLOCKS * ATA_DSM_BLK_RANGES)
125 struct trim_request {
126 	uint8_t		data[TRIM_MAX_RANGES * ATA_DSM_RANGE_SIZE];
127 	TAILQ_HEAD(, bio) bps;
128 };
129 
130 struct ada_softc {
131 	struct	 bio_queue_head bio_queue;
132 	struct	 bio_queue_head trim_queue;
133 	int	 outstanding_cmds;	/* Number of active commands */
134 	int	 refcount;		/* Active xpt_action() calls */
135 	ada_state state;
136 	ada_flags flags;
137 	ada_quirks quirks;
138 	int	 sort_io_queue;
139 	int	 trim_max_ranges;
140 	int	 trim_running;
141 	int	 read_ahead;
142 	int	 write_cache;
143 #ifdef ADA_TEST_FAILURE
144 	int      force_read_error;
145 	int      force_write_error;
146 	int      periodic_read_error;
147 	int      periodic_read_count;
148 #endif
149 	struct	 disk_params params;
150 	struct	 disk *disk;
151 	struct task		sysctl_task;
152 	struct sysctl_ctx_list	sysctl_ctx;
153 	struct sysctl_oid	*sysctl_tree;
154 	struct callout		sendordered_c;
155 	struct trim_request	trim_req;
156 };
157 
158 struct ada_quirk_entry {
159 	struct scsi_inquiry_pattern inq_pat;
160 	ada_quirks quirks;
161 };
162 
163 static struct ada_quirk_entry ada_quirk_table[] =
164 {
165 	{
166 		/* Hitachi Advanced Format (4k) drives */
167 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Hitachi H??????????E3*", "*" },
168 		/*quirks*/ADA_Q_4K
169 	},
170 	{
171 		/* Samsung Advanced Format (4k) drives */
172 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD155UI*", "*" },
173 		/*quirks*/ADA_Q_4K
174 	},
175 	{
176 		/* Samsung Advanced Format (4k) drives */
177 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD204UI*", "*" },
178 		/*quirks*/ADA_Q_4K
179 	},
180 	{
181 		/* Seagate Barracuda Green Advanced Format (4k) drives */
182 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DL*", "*" },
183 		/*quirks*/ADA_Q_4K
184 	},
185 	{
186 		/* Seagate Barracuda Advanced Format (4k) drives */
187 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???DM*", "*" },
188 		/*quirks*/ADA_Q_4K
189 	},
190 	{
191 		/* Seagate Barracuda Advanced Format (4k) drives */
192 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DM*", "*" },
193 		/*quirks*/ADA_Q_4K
194 	},
195 	{
196 		/* Seagate Momentus Advanced Format (4k) drives */
197 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500423AS*", "*" },
198 		/*quirks*/ADA_Q_4K
199 	},
200 	{
201 		/* Seagate Momentus Advanced Format (4k) drives */
202 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500424AS*", "*" },
203 		/*quirks*/ADA_Q_4K
204 	},
205 	{
206 		/* Seagate Momentus Advanced Format (4k) drives */
207 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640423AS*", "*" },
208 		/*quirks*/ADA_Q_4K
209 	},
210 	{
211 		/* Seagate Momentus Advanced Format (4k) drives */
212 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640424AS*", "*" },
213 		/*quirks*/ADA_Q_4K
214 	},
215 	{
216 		/* Seagate Momentus Advanced Format (4k) drives */
217 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750420AS*", "*" },
218 		/*quirks*/ADA_Q_4K
219 	},
220 	{
221 		/* Seagate Momentus Advanced Format (4k) drives */
222 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750422AS*", "*" },
223 		/*quirks*/ADA_Q_4K
224 	},
225 	{
226 		/* Seagate Momentus Advanced Format (4k) drives */
227 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750423AS*", "*" },
228 		/*quirks*/ADA_Q_4K
229 	},
230 	{
231 		/* Seagate Momentus Thin Advanced Format (4k) drives */
232 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???LT*", "*" },
233 		/*quirks*/ADA_Q_4K
234 	},
235 	{
236 		/* WDC Caviar Red Advanced Format (4k) drives */
237 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????CX*", "*" },
238 		/*quirks*/ADA_Q_4K
239 	},
240 	{
241 		/* WDC Caviar Green Advanced Format (4k) drives */
242 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RS*", "*" },
243 		/*quirks*/ADA_Q_4K
244 	},
245 	{
246 		/* WDC Caviar Green/Red Advanced Format (4k) drives */
247 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RX*", "*" },
248 		/*quirks*/ADA_Q_4K
249 	},
250 	{
251 		/* WDC Caviar Red Advanced Format (4k) drives */
252 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????CX*", "*" },
253 		/*quirks*/ADA_Q_4K
254 	},
255 	{
256 		/* WDC Caviar Black Advanced Format (4k) drives */
257 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????EX*", "*" },
258 		/*quirks*/ADA_Q_4K
259 	},
260 	{
261 		/* WDC Caviar Green Advanced Format (4k) drives */
262 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RS*", "*" },
263 		/*quirks*/ADA_Q_4K
264 	},
265 	{
266 		/* WDC Caviar Green Advanced Format (4k) drives */
267 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RX*", "*" },
268 		/*quirks*/ADA_Q_4K
269 	},
270 	{
271 		/* WDC Scorpio Black Advanced Format (4k) drives */
272 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PKT*", "*" },
273 		/*quirks*/ADA_Q_4K
274 	},
275 	{
276 		/* WDC Scorpio Black Advanced Format (4k) drives */
277 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PKT*", "*" },
278 		/*quirks*/ADA_Q_4K
279 	},
280 	{
281 		/* WDC Scorpio Blue Advanced Format (4k) drives */
282 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PVT*", "*" },
283 		/*quirks*/ADA_Q_4K
284 	},
285 	{
286 		/* WDC Scorpio Blue Advanced Format (4k) drives */
287 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PVT*", "*" },
288 		/*quirks*/ADA_Q_4K
289 	},
290 	/* SSDs */
291 	{
292 		/*
293 		 * Corsair Force 2 SSDs
294 		 * 4k optimised & trim only works in 4k requests + 4k aligned
295 		 */
296 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair CSSD-F*", "*" },
297 		/*quirks*/ADA_Q_4K
298 	},
299 	{
300 		/*
301 		 * Corsair Force 3 SSDs
302 		 * 4k optimised & trim only works in 4k requests + 4k aligned
303 		 */
304 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force 3*", "*" },
305 		/*quirks*/ADA_Q_4K
306 	},
307 	{
308 		/*
309 		 * Corsair Neutron GTX SSDs
310 		 * 4k optimised & trim only works in 4k requests + 4k aligned
311 		 */
312 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Neutron GTX*", "*" },
313 		/*quirks*/ADA_Q_4K
314 	},
315 	{
316 		/*
317 		 * Corsair Force GT & GS SSDs
318 		 * 4k optimised & trim only works in 4k requests + 4k aligned
319 		 */
320 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force G*", "*" },
321 		/*quirks*/ADA_Q_4K
322 	},
323 	{
324 		/*
325 		 * Crucial M4 SSDs
326 		 * 4k optimised & trim only works in 4k requests + 4k aligned
327 		 */
328 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "M4-CT???M4SSD2*", "*" },
329 		/*quirks*/ADA_Q_4K
330 	},
331 	{
332 		/*
333 		 * Crucial RealSSD C300 SSDs
334 		 * 4k optimised
335 		 */
336 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "C300-CTFDDAC???MAG*",
337 		"*" }, /*quirks*/ADA_Q_4K
338 	},
339 	{
340 		/*
341 		 * Intel 320 Series SSDs
342 		 * 4k optimised & trim only works in 4k requests + 4k aligned
343 		 */
344 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSA2CW*", "*" },
345 		/*quirks*/ADA_Q_4K
346 	},
347 	{
348 		/*
349 		 * Intel 330 Series SSDs
350 		 * 4k optimised & trim only works in 4k requests + 4k aligned
351 		 */
352 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2CT*", "*" },
353 		/*quirks*/ADA_Q_4K
354 	},
355 	{
356 		/*
357 		 * Intel 510 Series SSDs
358 		 * 4k optimised & trim only works in 4k requests + 4k aligned
359 		 */
360 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2MH*", "*" },
361 		/*quirks*/ADA_Q_4K
362 	},
363 	{
364 		/*
365 		 * Intel 520 Series SSDs
366 		 * 4k optimised & trim only works in 4k requests + 4k aligned
367 		 */
368 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2BW*", "*" },
369 		/*quirks*/ADA_Q_4K
370 	},
371 	{
372 		/*
373 		 * Intel X25-M Series SSDs
374 		 * 4k optimised & trim only works in 4k requests + 4k aligned
375 		 */
376 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSA2M*", "*" },
377 		/*quirks*/ADA_Q_4K
378 	},
379 	{
380 		/*
381 		 * Kingston E100 Series SSDs
382 		 * 4k optimised & trim only works in 4k requests + 4k aligned
383 		 */
384 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SE100S3*", "*" },
385 		/*quirks*/ADA_Q_4K
386 	},
387 	{
388 		/*
389 		 * Kingston HyperX 3k SSDs
390 		 * 4k optimised & trim only works in 4k requests + 4k aligned
391 		 */
392 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SH103S3*", "*" },
393 		/*quirks*/ADA_Q_4K
394 	},
395 	{
396 		/*
397 		 * Marvell SSDs (entry taken from OpenSolaris)
398 		 * 4k optimised & trim only works in 4k requests + 4k aligned
399 		 */
400 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "MARVELL SD88SA02*", "*" },
401 		/*quirks*/ADA_Q_4K
402 	},
403 	{
404 		/*
405 		 * OCZ Agility 2 SSDs
406 		 * 4k optimised & trim only works in 4k requests + 4k aligned
407 		 */
408 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY2*", "*" },
409 		/*quirks*/ADA_Q_4K
410 	},
411 	{
412 		/*
413 		 * OCZ Agility 3 SSDs
414 		 * 4k optimised & trim only works in 4k requests + 4k aligned
415 		 */
416 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY3*", "*" },
417 		/*quirks*/ADA_Q_4K
418 	},
419 	{
420 		/*
421 		 * OCZ Deneva R Series SSDs
422 		 * 4k optimised & trim only works in 4k requests + 4k aligned
423 		 */
424 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "DENRSTE251M45*", "*" },
425 		/*quirks*/ADA_Q_4K
426 	},
427 	{
428 		/*
429 		 * OCZ Vertex 2 SSDs (inc pro series)
430 		 * 4k optimised & trim only works in 4k requests + 4k aligned
431 		 */
432 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ?VERTEX2*", "*" },
433 		/*quirks*/ADA_Q_4K
434 	},
435 	{
436 		/*
437 		 * OCZ Vertex 3 SSDs
438 		 * 4k optimised & trim only works in 4k requests + 4k aligned
439 		 */
440 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-VERTEX3*", "*" },
441 		/*quirks*/ADA_Q_4K
442 	},
443 	{
444 		/*
445 		 * OCZ Vertex 4 SSDs
446 		 * 4k optimised & trim only works in 4k requests + 4k aligned
447 		 */
448 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-VERTEX4*", "*" },
449 		/*quirks*/ADA_Q_4K
450 	},
451 	{
452 		/*
453 		 * Samsung 830 Series SSDs
454 		 * 4k optimised
455 		 */
456 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG SSD 830 Series*", "*" },
457 		/*quirks*/ADA_Q_4K
458 	},
459 	{
460 		/*
461 		 * Samsung 840 SSDs
462 		 * 4k optimised
463 		 */
464 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 840*", "*" },
465 		/*quirks*/ADA_Q_4K
466 	},
467 	{
468 		/*
469 		 * Samsung 843T Series SSDs
470 		 * 4k optimised
471 		 */
472 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7WD*", "*" },
473 		/*quirks*/ADA_Q_4K
474 	},
475  	{
476  		/*
477 		 * Samsung 850 SSDs
478 		 * 4k optimised
479 		 */
480 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 850*", "*" },
481 		/*quirks*/ADA_Q_4K
482 	},
483 	{
484 		/*
485 		 * Samsung PM853T Series SSDs
486 		 * 4k optimised
487 		 */
488 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7GE*", "*" },
489 		/*quirks*/ADA_Q_4K
490 	},
491 	{
492 		/*
493 		 * SuperTalent TeraDrive CT SSDs
494 		 * 4k optimised & trim only works in 4k requests + 4k aligned
495 		 */
496 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "FTM??CT25H*", "*" },
497 		/*quirks*/ADA_Q_4K
498 	},
499 	{
500 		/*
501 		 * XceedIOPS SATA SSDs
502 		 * 4k optimised
503 		 */
504 		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SG9XCS2D*", "*" },
505 		/*quirks*/ADA_Q_4K
506 	},
507 	{
508 		/* Default */
509 		{
510 		  T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
511 		  /*vendor*/"*", /*product*/"*", /*revision*/"*"
512 		},
513 		/*quirks*/0
514 	},
515 };
516 
517 static	disk_strategy_t	adastrategy;
518 static	dumper_t	adadump;
519 static	periph_init_t	adainit;
520 static	void		adaasync(void *callback_arg, u_int32_t code,
521 				struct cam_path *path, void *arg);
522 static	void		adasysctlinit(void *context, int pending);
523 static	periph_ctor_t	adaregister;
524 static	periph_dtor_t	adacleanup;
525 static	periph_start_t	adastart;
526 static	periph_oninv_t	adaoninvalidate;
527 static	void		adadone(struct cam_periph *periph,
528 			       union ccb *done_ccb);
529 static  int		adaerror(union ccb *ccb, u_int32_t cam_flags,
530 				u_int32_t sense_flags);
531 static void		adagetparams(struct cam_periph *periph,
532 				struct ccb_getdev *cgd);
533 static timeout_t	adasendorderedtag;
534 static void		adashutdown(void *arg, int howto);
535 static void		adasuspend(void *arg);
536 static void		adaresume(void *arg);
537 
538 #ifndef	ADA_DEFAULT_LEGACY_ALIASES
539 #define	ADA_DEFAULT_LEGACY_ALIASES	1
540 #endif
541 
542 #ifndef ADA_DEFAULT_TIMEOUT
543 #define ADA_DEFAULT_TIMEOUT 30	/* Timeout in seconds */
544 #endif
545 
546 #ifndef	ADA_DEFAULT_RETRY
547 #define	ADA_DEFAULT_RETRY	4
548 #endif
549 
550 #ifndef	ADA_DEFAULT_SEND_ORDERED
551 #define	ADA_DEFAULT_SEND_ORDERED	1
552 #endif
553 
554 #ifndef	ADA_DEFAULT_SPINDOWN_SHUTDOWN
555 #define	ADA_DEFAULT_SPINDOWN_SHUTDOWN	1
556 #endif
557 
558 #ifndef	ADA_DEFAULT_SPINDOWN_SUSPEND
559 #define	ADA_DEFAULT_SPINDOWN_SUSPEND	1
560 #endif
561 
562 #ifndef	ADA_DEFAULT_READ_AHEAD
563 #define	ADA_DEFAULT_READ_AHEAD	1
564 #endif
565 
566 #ifndef	ADA_DEFAULT_WRITE_CACHE
567 #define	ADA_DEFAULT_WRITE_CACHE	1
568 #endif
569 
570 #define	ADA_RA	(softc->read_ahead >= 0 ? \
571 		 softc->read_ahead : ada_read_ahead)
572 #define	ADA_WC	(softc->write_cache >= 0 ? \
573 		 softc->write_cache : ada_write_cache)
574 #define	ADA_SIO	(softc->sort_io_queue >= 0 ? \
575 		 softc->sort_io_queue : cam_sort_io_queues)
576 
577 /*
578  * Most platforms map firmware geometry to actual, but some don't.  If
579  * not overridden, default to nothing.
580  */
581 #ifndef ata_disk_firmware_geom_adjust
582 #define	ata_disk_firmware_geom_adjust(disk)
583 #endif
584 
585 static int ada_retry_count = ADA_DEFAULT_RETRY;
586 static int ada_default_timeout = ADA_DEFAULT_TIMEOUT;
587 static int ada_send_ordered = ADA_DEFAULT_SEND_ORDERED;
588 static int ada_spindown_shutdown = ADA_DEFAULT_SPINDOWN_SHUTDOWN;
589 static int ada_spindown_suspend = ADA_DEFAULT_SPINDOWN_SUSPEND;
590 static int ada_read_ahead = ADA_DEFAULT_READ_AHEAD;
591 static int ada_write_cache = ADA_DEFAULT_WRITE_CACHE;
592 
593 static SYSCTL_NODE(_kern_cam, OID_AUTO, ada, CTLFLAG_RD, 0,
594             "CAM Direct Access Disk driver");
595 SYSCTL_INT(_kern_cam_ada, OID_AUTO, retry_count, CTLFLAG_RWTUN,
596            &ada_retry_count, 0, "Normal I/O retry count");
597 SYSCTL_INT(_kern_cam_ada, OID_AUTO, default_timeout, CTLFLAG_RWTUN,
598            &ada_default_timeout, 0, "Normal I/O timeout (in seconds)");
599 SYSCTL_INT(_kern_cam_ada, OID_AUTO, send_ordered, CTLFLAG_RWTUN,
600            &ada_send_ordered, 0, "Send Ordered Tags");
601 SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_shutdown, CTLFLAG_RWTUN,
602            &ada_spindown_shutdown, 0, "Spin down upon shutdown");
603 SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_suspend, CTLFLAG_RWTUN,
604            &ada_spindown_suspend, 0, "Spin down upon suspend");
605 SYSCTL_INT(_kern_cam_ada, OID_AUTO, read_ahead, CTLFLAG_RWTUN,
606            &ada_read_ahead, 0, "Enable disk read-ahead");
607 SYSCTL_INT(_kern_cam_ada, OID_AUTO, write_cache, CTLFLAG_RWTUN,
608            &ada_write_cache, 0, "Enable disk write cache");
609 
610 /*
611  * ADA_ORDEREDTAG_INTERVAL determines how often, relative
612  * to the default timeout, we check to see whether an ordered
613  * tagged transaction is appropriate to prevent simple tag
614  * starvation.  Since we'd like to ensure that there is at least
615  * 1/2 of the timeout length left for a starved transaction to
616  * complete after we've sent an ordered tag, we must poll at least
617  * four times in every timeout period.  This takes care of the worst
618  * case where a starved transaction starts during an interval that
619  * meets the requirement "don't send an ordered tag" test so it takes
620  * us two intervals to determine that a tag must be sent.
621  */
622 #ifndef ADA_ORDEREDTAG_INTERVAL
623 #define ADA_ORDEREDTAG_INTERVAL 4
624 #endif
625 
626 static struct periph_driver adadriver =
627 {
628 	adainit, "ada",
629 	TAILQ_HEAD_INITIALIZER(adadriver.units), /* generation */ 0
630 };
631 
632 PERIPHDRIVER_DECLARE(ada, adadriver);
633 
634 static MALLOC_DEFINE(M_ATADA, "ata_da", "ata_da buffers");
635 
636 static int
637 adaopen(struct disk *dp)
638 {
639 	struct cam_periph *periph;
640 	struct ada_softc *softc;
641 	int error;
642 
643 	periph = (struct cam_periph *)dp->d_drv1;
644 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
645 		return(ENXIO);
646 	}
647 
648 	cam_periph_lock(periph);
649 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
650 		cam_periph_unlock(periph);
651 		cam_periph_release(periph);
652 		return (error);
653 	}
654 
655 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
656 	    ("adaopen\n"));
657 
658 	softc = (struct ada_softc *)periph->softc;
659 	softc->flags |= ADA_FLAG_OPEN;
660 
661 	cam_periph_unhold(periph);
662 	cam_periph_unlock(periph);
663 	return (0);
664 }
665 
666 static int
667 adaclose(struct disk *dp)
668 {
669 	struct	cam_periph *periph;
670 	struct	ada_softc *softc;
671 	union ccb *ccb;
672 	int error;
673 
674 	periph = (struct cam_periph *)dp->d_drv1;
675 	softc = (struct ada_softc *)periph->softc;
676 	cam_periph_lock(periph);
677 
678 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
679 	    ("adaclose\n"));
680 
681 	/* We only sync the cache if the drive is capable of it. */
682 	if ((softc->flags & ADA_FLAG_DIRTY) != 0 &&
683 	    (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) != 0 &&
684 	    (periph->flags & CAM_PERIPH_INVALID) == 0 &&
685 	    cam_periph_hold(periph, PRIBIO) == 0) {
686 
687 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
688 		cam_fill_ataio(&ccb->ataio,
689 				    1,
690 				    adadone,
691 				    CAM_DIR_NONE,
692 				    0,
693 				    NULL,
694 				    0,
695 				    ada_default_timeout*1000);
696 
697 		if (softc->flags & ADA_FLAG_CAN_48BIT)
698 			ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
699 		else
700 			ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
701 		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
702 		    /*sense_flags*/0, softc->disk->d_devstat);
703 
704 		if (error != 0)
705 			xpt_print(periph->path, "Synchronize cache failed\n");
706 		else
707 			softc->flags &= ~ADA_FLAG_DIRTY;
708 		xpt_release_ccb(ccb);
709 		cam_periph_unhold(periph);
710 	}
711 
712 	softc->flags &= ~ADA_FLAG_OPEN;
713 
714 	while (softc->refcount != 0)
715 		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "adaclose", 1);
716 	cam_periph_unlock(periph);
717 	cam_periph_release(periph);
718 	return (0);
719 }
720 
721 static void
722 adaschedule(struct cam_periph *periph)
723 {
724 	struct ada_softc *softc = (struct ada_softc *)periph->softc;
725 
726 	if (softc->state != ADA_STATE_NORMAL)
727 		return;
728 
729 	/* Check if we have more work to do. */
730 	if (bioq_first(&softc->bio_queue) ||
731 	    (!softc->trim_running && bioq_first(&softc->trim_queue))) {
732 		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
733 	}
734 }
735 
736 /*
737  * Actually translate the requested transfer into one the physical driver
738  * can understand.  The transfer is described by a buf and will include
739  * only one physical transfer.
740  */
741 static void
742 adastrategy(struct bio *bp)
743 {
744 	struct cam_periph *periph;
745 	struct ada_softc *softc;
746 
747 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
748 	softc = (struct ada_softc *)periph->softc;
749 
750 	cam_periph_lock(periph);
751 
752 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastrategy(%p)\n", bp));
753 
754 	/*
755 	 * If the device has been made invalid, error out
756 	 */
757 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
758 		cam_periph_unlock(periph);
759 		biofinish(bp, NULL, ENXIO);
760 		return;
761 	}
762 
763 	/*
764 	 * Place it in the queue of disk activities for this disk
765 	 */
766 	if (bp->bio_cmd == BIO_DELETE) {
767 		bioq_disksort(&softc->trim_queue, bp);
768 	} else {
769 		if (ADA_SIO)
770 		    bioq_disksort(&softc->bio_queue, bp);
771 		else
772 		    bioq_insert_tail(&softc->bio_queue, bp);
773 	}
774 
775 	/*
776 	 * Schedule ourselves for performing the work.
777 	 */
778 	adaschedule(periph);
779 	cam_periph_unlock(periph);
780 
781 	return;
782 }
783 
784 static int
785 adadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
786 {
787 	struct	    cam_periph *periph;
788 	struct	    ada_softc *softc;
789 	u_int	    secsize;
790 	union	    ccb ccb;
791 	struct	    disk *dp;
792 	uint64_t    lba;
793 	uint16_t    count;
794 	int	    error = 0;
795 
796 	dp = arg;
797 	periph = dp->d_drv1;
798 	softc = (struct ada_softc *)periph->softc;
799 	cam_periph_lock(periph);
800 	secsize = softc->params.secsize;
801 	lba = offset / secsize;
802 	count = length / secsize;
803 
804 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
805 		cam_periph_unlock(periph);
806 		return (ENXIO);
807 	}
808 
809 	if (length > 0) {
810 		xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
811 		ccb.ccb_h.ccb_state = ADA_CCB_DUMP;
812 		cam_fill_ataio(&ccb.ataio,
813 		    0,
814 		    adadone,
815 		    CAM_DIR_OUT,
816 		    0,
817 		    (u_int8_t *) virtual,
818 		    length,
819 		    ada_default_timeout*1000);
820 		if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
821 		    (lba + count >= ATA_MAX_28BIT_LBA ||
822 		    count >= 256)) {
823 			ata_48bit_cmd(&ccb.ataio, ATA_WRITE_DMA48,
824 			    0, lba, count);
825 		} else {
826 			ata_28bit_cmd(&ccb.ataio, ATA_WRITE_DMA,
827 			    0, lba, count);
828 		}
829 		xpt_polled_action(&ccb);
830 
831 		error = cam_periph_error(&ccb,
832 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
833 		if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
834 			cam_release_devq(ccb.ccb_h.path, /*relsim_flags*/0,
835 			    /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
836 		if (error != 0)
837 			printf("Aborting dump due to I/O error.\n");
838 
839 		cam_periph_unlock(periph);
840 		return (error);
841 	}
842 
843 	if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) {
844 		xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
845 
846 		ccb.ccb_h.ccb_state = ADA_CCB_DUMP;
847 		cam_fill_ataio(&ccb.ataio,
848 				    0,
849 				    adadone,
850 				    CAM_DIR_NONE,
851 				    0,
852 				    NULL,
853 				    0,
854 				    ada_default_timeout*1000);
855 
856 		if (softc->flags & ADA_FLAG_CAN_48BIT)
857 			ata_48bit_cmd(&ccb.ataio, ATA_FLUSHCACHE48, 0, 0, 0);
858 		else
859 			ata_28bit_cmd(&ccb.ataio, ATA_FLUSHCACHE, 0, 0, 0);
860 		xpt_polled_action(&ccb);
861 
862 		error = cam_periph_error(&ccb,
863 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
864 		if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
865 			cam_release_devq(ccb.ccb_h.path, /*relsim_flags*/0,
866 			    /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
867 		if (error != 0)
868 			xpt_print(periph->path, "Synchronize cache failed\n");
869 	}
870 	cam_periph_unlock(periph);
871 	return (error);
872 }
873 
874 static void
875 adainit(void)
876 {
877 	cam_status status;
878 
879 	/*
880 	 * Install a global async callback.  This callback will
881 	 * receive async callbacks like "new device found".
882 	 */
883 	status = xpt_register_async(AC_FOUND_DEVICE, adaasync, NULL, NULL);
884 
885 	if (status != CAM_REQ_CMP) {
886 		printf("ada: Failed to attach master async callback "
887 		       "due to status 0x%x!\n", status);
888 	} else if (ada_send_ordered) {
889 
890 		/* Register our event handlers */
891 		if ((EVENTHANDLER_REGISTER(power_suspend, adasuspend,
892 					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
893 		    printf("adainit: power event registration failed!\n");
894 		if ((EVENTHANDLER_REGISTER(power_resume, adaresume,
895 					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
896 		    printf("adainit: power event registration failed!\n");
897 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, adashutdown,
898 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
899 		    printf("adainit: shutdown event registration failed!\n");
900 	}
901 }
902 
903 /*
904  * Callback from GEOM, called when it has finished cleaning up its
905  * resources.
906  */
907 static void
908 adadiskgonecb(struct disk *dp)
909 {
910 	struct cam_periph *periph;
911 
912 	periph = (struct cam_periph *)dp->d_drv1;
913 
914 	cam_periph_release(periph);
915 }
916 
917 static void
918 adaoninvalidate(struct cam_periph *periph)
919 {
920 	struct ada_softc *softc;
921 
922 	softc = (struct ada_softc *)periph->softc;
923 
924 	/*
925 	 * De-register any async callbacks.
926 	 */
927 	xpt_register_async(0, adaasync, periph, periph->path);
928 
929 	/*
930 	 * Return all queued I/O with ENXIO.
931 	 * XXX Handle any transactions queued to the card
932 	 *     with XPT_ABORT_CCB.
933 	 */
934 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
935 	bioq_flush(&softc->trim_queue, NULL, ENXIO);
936 
937 	disk_gone(softc->disk);
938 }
939 
940 static void
941 adacleanup(struct cam_periph *periph)
942 {
943 	struct ada_softc *softc;
944 
945 	softc = (struct ada_softc *)periph->softc;
946 
947 	cam_periph_unlock(periph);
948 
949 	/*
950 	 * If we can't free the sysctl tree, oh well...
951 	 */
952 	if ((softc->flags & ADA_FLAG_SCTX_INIT) != 0
953 	    && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
954 		xpt_print(periph->path, "can't remove sysctl context\n");
955 	}
956 
957 	disk_destroy(softc->disk);
958 	callout_drain(&softc->sendordered_c);
959 	free(softc, M_DEVBUF);
960 	cam_periph_lock(periph);
961 }
962 
963 static void
964 adaasync(void *callback_arg, u_int32_t code,
965 	struct cam_path *path, void *arg)
966 {
967 	struct ccb_getdev cgd;
968 	struct cam_periph *periph;
969 	struct ada_softc *softc;
970 
971 	periph = (struct cam_periph *)callback_arg;
972 	switch (code) {
973 	case AC_FOUND_DEVICE:
974 	{
975 		struct ccb_getdev *cgd;
976 		cam_status status;
977 
978 		cgd = (struct ccb_getdev *)arg;
979 		if (cgd == NULL)
980 			break;
981 
982 		if (cgd->protocol != PROTO_ATA)
983 			break;
984 
985 		/*
986 		 * Allocate a peripheral instance for
987 		 * this device and start the probe
988 		 * process.
989 		 */
990 		status = cam_periph_alloc(adaregister, adaoninvalidate,
991 					  adacleanup, adastart,
992 					  "ada", CAM_PERIPH_BIO,
993 					  path, adaasync,
994 					  AC_FOUND_DEVICE, cgd);
995 
996 		if (status != CAM_REQ_CMP
997 		 && status != CAM_REQ_INPROG)
998 			printf("adaasync: Unable to attach to new device "
999 				"due to status 0x%x\n", status);
1000 		break;
1001 	}
1002 	case AC_GETDEV_CHANGED:
1003 	{
1004 		softc = (struct ada_softc *)periph->softc;
1005 		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1006 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1007 		xpt_action((union ccb *)&cgd);
1008 
1009 		if ((cgd.ident_data.capabilities1 & ATA_SUPPORT_DMA) &&
1010 		    (cgd.inq_flags & SID_DMA))
1011 			softc->flags |= ADA_FLAG_CAN_DMA;
1012 		else
1013 			softc->flags &= ~ADA_FLAG_CAN_DMA;
1014 		if (cgd.ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) {
1015 			softc->flags |= ADA_FLAG_CAN_48BIT;
1016 			if (cgd.inq_flags & SID_DMA48)
1017 				softc->flags |= ADA_FLAG_CAN_DMA48;
1018 			else
1019 				softc->flags &= ~ADA_FLAG_CAN_DMA48;
1020 		} else
1021 			softc->flags &= ~(ADA_FLAG_CAN_48BIT |
1022 			    ADA_FLAG_CAN_DMA48);
1023 		if ((cgd.ident_data.satacapabilities & ATA_SUPPORT_NCQ) &&
1024 		    (cgd.inq_flags & SID_DMA) && (cgd.inq_flags & SID_CmdQue))
1025 			softc->flags |= ADA_FLAG_CAN_NCQ;
1026 		else
1027 			softc->flags &= ~ADA_FLAG_CAN_NCQ;
1028 		if ((cgd.ident_data.support_dsm & ATA_SUPPORT_DSM_TRIM) &&
1029 		    (cgd.inq_flags & SID_DMA))
1030 			softc->flags |= ADA_FLAG_CAN_TRIM;
1031 		else
1032 			softc->flags &= ~ADA_FLAG_CAN_TRIM;
1033 
1034 		cam_periph_async(periph, code, path, arg);
1035 		break;
1036 	}
1037 	case AC_ADVINFO_CHANGED:
1038 	{
1039 		uintptr_t buftype;
1040 
1041 		buftype = (uintptr_t)arg;
1042 		if (buftype == CDAI_TYPE_PHYS_PATH) {
1043 			struct ada_softc *softc;
1044 
1045 			softc = periph->softc;
1046 			disk_attr_changed(softc->disk, "GEOM::physpath",
1047 					  M_NOWAIT);
1048 		}
1049 		break;
1050 	}
1051 	case AC_SENT_BDR:
1052 	case AC_BUS_RESET:
1053 	{
1054 		softc = (struct ada_softc *)periph->softc;
1055 		cam_periph_async(periph, code, path, arg);
1056 		if (softc->state != ADA_STATE_NORMAL)
1057 			break;
1058 		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1059 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1060 		xpt_action((union ccb *)&cgd);
1061 		if (ADA_RA >= 0 &&
1062 		    cgd.ident_data.support.command1 & ATA_SUPPORT_LOOKAHEAD)
1063 			softc->state = ADA_STATE_RAHEAD;
1064 		else if (ADA_WC >= 0 &&
1065 		    cgd.ident_data.support.command1 & ATA_SUPPORT_WRITECACHE)
1066 			softc->state = ADA_STATE_WCACHE;
1067 		else
1068 		    break;
1069 		if (cam_periph_acquire(periph) != CAM_REQ_CMP)
1070 			softc->state = ADA_STATE_NORMAL;
1071 		else
1072 			xpt_schedule(periph, CAM_PRIORITY_DEV);
1073 	}
1074 	default:
1075 		cam_periph_async(periph, code, path, arg);
1076 		break;
1077 	}
1078 }
1079 
1080 static void
1081 adasysctlinit(void *context, int pending)
1082 {
1083 	struct cam_periph *periph;
1084 	struct ada_softc *softc;
1085 	char tmpstr[80], tmpstr2[80];
1086 
1087 	periph = (struct cam_periph *)context;
1088 
1089 	/* periph was held for us when this task was enqueued */
1090 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
1091 		cam_periph_release(periph);
1092 		return;
1093 	}
1094 
1095 	softc = (struct ada_softc *)periph->softc;
1096 	snprintf(tmpstr, sizeof(tmpstr), "CAM ADA unit %d", periph->unit_number);
1097 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1098 
1099 	sysctl_ctx_init(&softc->sysctl_ctx);
1100 	softc->flags |= ADA_FLAG_SCTX_INIT;
1101 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1102 		SYSCTL_STATIC_CHILDREN(_kern_cam_ada), OID_AUTO, tmpstr2,
1103 		CTLFLAG_RD, 0, tmpstr);
1104 	if (softc->sysctl_tree == NULL) {
1105 		printf("adasysctlinit: unable to allocate sysctl tree\n");
1106 		cam_periph_release(periph);
1107 		return;
1108 	}
1109 
1110 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1111 		OID_AUTO, "read_ahead", CTLFLAG_RW | CTLFLAG_MPSAFE,
1112 		&softc->read_ahead, 0, "Enable disk read ahead.");
1113 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1114 		OID_AUTO, "write_cache", CTLFLAG_RW | CTLFLAG_MPSAFE,
1115 		&softc->write_cache, 0, "Enable disk write cache.");
1116 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1117 		OID_AUTO, "sort_io_queue", CTLFLAG_RW | CTLFLAG_MPSAFE,
1118 		&softc->sort_io_queue, 0,
1119 		"Sort IO queue to try and optimise disk access patterns");
1120 #ifdef ADA_TEST_FAILURE
1121 	/*
1122 	 * Add a 'door bell' sysctl which allows one to set it from userland
1123 	 * and cause something bad to happen.  For the moment, we only allow
1124 	 * whacking the next read or write.
1125 	 */
1126 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1127 		OID_AUTO, "force_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1128 		&softc->force_read_error, 0,
1129 		"Force a read error for the next N reads.");
1130 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1131 		OID_AUTO, "force_write_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1132 		&softc->force_write_error, 0,
1133 		"Force a write error for the next N writes.");
1134 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1135 		OID_AUTO, "periodic_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1136 		&softc->periodic_read_error, 0,
1137 		"Force a read error every N reads (don't set too low).");
1138 #endif
1139 	cam_periph_release(periph);
1140 }
1141 
1142 static int
1143 adagetattr(struct bio *bp)
1144 {
1145 	int ret;
1146 	struct cam_periph *periph;
1147 
1148 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1149 	cam_periph_lock(periph);
1150 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1151 	    periph->path);
1152 	cam_periph_unlock(periph);
1153 	if (ret == 0)
1154 		bp->bio_completed = bp->bio_length;
1155 	return ret;
1156 }
1157 
1158 static cam_status
1159 adaregister(struct cam_periph *periph, void *arg)
1160 {
1161 	struct ada_softc *softc;
1162 	struct ccb_pathinq cpi;
1163 	struct ccb_getdev *cgd;
1164 	char   announce_buf[80];
1165 	struct disk_params *dp;
1166 	caddr_t match;
1167 	u_int maxio;
1168 	int quirks;
1169 
1170 	cgd = (struct ccb_getdev *)arg;
1171 	if (cgd == NULL) {
1172 		printf("adaregister: no getdev CCB, can't register device\n");
1173 		return(CAM_REQ_CMP_ERR);
1174 	}
1175 
1176 	softc = (struct ada_softc *)malloc(sizeof(*softc), M_DEVBUF,
1177 	    M_NOWAIT|M_ZERO);
1178 
1179 	if (softc == NULL) {
1180 		printf("adaregister: Unable to probe new device. "
1181 		    "Unable to allocate softc\n");
1182 		return(CAM_REQ_CMP_ERR);
1183 	}
1184 
1185 	bioq_init(&softc->bio_queue);
1186 	bioq_init(&softc->trim_queue);
1187 
1188 	if ((cgd->ident_data.capabilities1 & ATA_SUPPORT_DMA) &&
1189 	    (cgd->inq_flags & SID_DMA))
1190 		softc->flags |= ADA_FLAG_CAN_DMA;
1191 	if (cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) {
1192 		softc->flags |= ADA_FLAG_CAN_48BIT;
1193 		if (cgd->inq_flags & SID_DMA48)
1194 			softc->flags |= ADA_FLAG_CAN_DMA48;
1195 	}
1196 	if (cgd->ident_data.support.command2 & ATA_SUPPORT_FLUSHCACHE)
1197 		softc->flags |= ADA_FLAG_CAN_FLUSHCACHE;
1198 	if (cgd->ident_data.support.command1 & ATA_SUPPORT_POWERMGT)
1199 		softc->flags |= ADA_FLAG_CAN_POWERMGT;
1200 	if ((cgd->ident_data.satacapabilities & ATA_SUPPORT_NCQ) &&
1201 	    (cgd->inq_flags & SID_DMA) && (cgd->inq_flags & SID_CmdQue))
1202 		softc->flags |= ADA_FLAG_CAN_NCQ;
1203 	if ((cgd->ident_data.support_dsm & ATA_SUPPORT_DSM_TRIM) &&
1204 	    (cgd->inq_flags & SID_DMA)) {
1205 		softc->flags |= ADA_FLAG_CAN_TRIM;
1206 		softc->trim_max_ranges = TRIM_MAX_RANGES;
1207 		if (cgd->ident_data.max_dsm_blocks != 0) {
1208 			softc->trim_max_ranges =
1209 			    min(cgd->ident_data.max_dsm_blocks *
1210 				ATA_DSM_BLK_RANGES, softc->trim_max_ranges);
1211 		}
1212 	}
1213 	if (cgd->ident_data.support.command2 & ATA_SUPPORT_CFA)
1214 		softc->flags |= ADA_FLAG_CAN_CFA;
1215 
1216 	periph->softc = softc;
1217 
1218 	/*
1219 	 * See if this device has any quirks.
1220 	 */
1221 	match = cam_quirkmatch((caddr_t)&cgd->ident_data,
1222 			       (caddr_t)ada_quirk_table,
1223 			       sizeof(ada_quirk_table)/sizeof(*ada_quirk_table),
1224 			       sizeof(*ada_quirk_table), ata_identify_match);
1225 	if (match != NULL)
1226 		softc->quirks = ((struct ada_quirk_entry *)match)->quirks;
1227 	else
1228 		softc->quirks = ADA_Q_NONE;
1229 
1230 	bzero(&cpi, sizeof(cpi));
1231 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NONE);
1232 	cpi.ccb_h.func_code = XPT_PATH_INQ;
1233 	xpt_action((union ccb *)&cpi);
1234 
1235 	TASK_INIT(&softc->sysctl_task, 0, adasysctlinit, periph);
1236 
1237 	/*
1238 	 * Register this media as a disk
1239 	 */
1240 	(void)cam_periph_hold(periph, PRIBIO);
1241 	cam_periph_unlock(periph);
1242 	snprintf(announce_buf, sizeof(announce_buf),
1243 	    "kern.cam.ada.%d.quirks", periph->unit_number);
1244 	quirks = softc->quirks;
1245 	TUNABLE_INT_FETCH(announce_buf, &quirks);
1246 	softc->quirks = quirks;
1247 	softc->read_ahead = -1;
1248 	snprintf(announce_buf, sizeof(announce_buf),
1249 	    "kern.cam.ada.%d.read_ahead", periph->unit_number);
1250 	TUNABLE_INT_FETCH(announce_buf, &softc->read_ahead);
1251 	softc->write_cache = -1;
1252 	snprintf(announce_buf, sizeof(announce_buf),
1253 	    "kern.cam.ada.%d.write_cache", periph->unit_number);
1254 	TUNABLE_INT_FETCH(announce_buf, &softc->write_cache);
1255 	/* Disable queue sorting for non-rotational media by default. */
1256 	if (cgd->ident_data.media_rotation_rate == ATA_RATE_NON_ROTATING)
1257 		softc->sort_io_queue = 0;
1258 	else
1259 		softc->sort_io_queue = -1;
1260 	adagetparams(periph, cgd);
1261 	softc->disk = disk_alloc();
1262 	softc->disk->d_rotation_rate = cgd->ident_data.media_rotation_rate;
1263 	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
1264 			  periph->unit_number, softc->params.secsize,
1265 			  DEVSTAT_ALL_SUPPORTED,
1266 			  DEVSTAT_TYPE_DIRECT |
1267 			  XPORT_DEVSTAT_TYPE(cpi.transport),
1268 			  DEVSTAT_PRIORITY_DISK);
1269 	softc->disk->d_open = adaopen;
1270 	softc->disk->d_close = adaclose;
1271 	softc->disk->d_strategy = adastrategy;
1272 	softc->disk->d_getattr = adagetattr;
1273 	softc->disk->d_dump = adadump;
1274 	softc->disk->d_gone = adadiskgonecb;
1275 	softc->disk->d_name = "ada";
1276 	softc->disk->d_drv1 = periph;
1277 	maxio = cpi.maxio;		/* Honor max I/O size of SIM */
1278 	if (maxio == 0)
1279 		maxio = DFLTPHYS;	/* traditional default */
1280 	else if (maxio > MAXPHYS)
1281 		maxio = MAXPHYS;	/* for safety */
1282 	if (softc->flags & ADA_FLAG_CAN_48BIT)
1283 		maxio = min(maxio, 65536 * softc->params.secsize);
1284 	else					/* 28bit ATA command limit */
1285 		maxio = min(maxio, 256 * softc->params.secsize);
1286 	softc->disk->d_maxsize = maxio;
1287 	softc->disk->d_unit = periph->unit_number;
1288 	softc->disk->d_flags = DISKFLAG_DIRECT_COMPLETION;
1289 	if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE)
1290 		softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
1291 	if (softc->flags & ADA_FLAG_CAN_TRIM) {
1292 		softc->disk->d_flags |= DISKFLAG_CANDELETE;
1293 		softc->disk->d_delmaxsize = softc->params.secsize *
1294 					    ATA_DSM_RANGE_MAX *
1295 					    softc->trim_max_ranges;
1296 	} else if ((softc->flags & ADA_FLAG_CAN_CFA) &&
1297 	    !(softc->flags & ADA_FLAG_CAN_48BIT)) {
1298 		softc->disk->d_flags |= DISKFLAG_CANDELETE;
1299 		softc->disk->d_delmaxsize = 256 * softc->params.secsize;
1300 	} else
1301 		softc->disk->d_delmaxsize = maxio;
1302 	if ((cpi.hba_misc & PIM_UNMAPPED) != 0)
1303 		softc->disk->d_flags |= DISKFLAG_UNMAPPED_BIO;
1304 	strlcpy(softc->disk->d_descr, cgd->ident_data.model,
1305 	    MIN(sizeof(softc->disk->d_descr), sizeof(cgd->ident_data.model)));
1306 	strlcpy(softc->disk->d_ident, cgd->ident_data.serial,
1307 	    MIN(sizeof(softc->disk->d_ident), sizeof(cgd->ident_data.serial)));
1308 	softc->disk->d_hba_vendor = cpi.hba_vendor;
1309 	softc->disk->d_hba_device = cpi.hba_device;
1310 	softc->disk->d_hba_subvendor = cpi.hba_subvendor;
1311 	softc->disk->d_hba_subdevice = cpi.hba_subdevice;
1312 
1313 	softc->disk->d_sectorsize = softc->params.secsize;
1314 	softc->disk->d_mediasize = (off_t)softc->params.sectors *
1315 	    softc->params.secsize;
1316 	if (ata_physical_sector_size(&cgd->ident_data) !=
1317 	    softc->params.secsize) {
1318 		softc->disk->d_stripesize =
1319 		    ata_physical_sector_size(&cgd->ident_data);
1320 		softc->disk->d_stripeoffset = (softc->disk->d_stripesize -
1321 		    ata_logical_sector_offset(&cgd->ident_data)) %
1322 		    softc->disk->d_stripesize;
1323 	} else if (softc->quirks & ADA_Q_4K) {
1324 		softc->disk->d_stripesize = 4096;
1325 		softc->disk->d_stripeoffset = 0;
1326 	}
1327 	softc->disk->d_fwsectors = softc->params.secs_per_track;
1328 	softc->disk->d_fwheads = softc->params.heads;
1329 	ata_disk_firmware_geom_adjust(softc->disk);
1330 
1331 	/*
1332 	 * Acquire a reference to the periph before we register with GEOM.
1333 	 * We'll release this reference once GEOM calls us back (via
1334 	 * adadiskgonecb()) telling us that our provider has been freed.
1335 	 */
1336 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
1337 		xpt_print(periph->path, "%s: lost periph during "
1338 			  "registration!\n", __func__);
1339 		cam_periph_lock(periph);
1340 		return (CAM_REQ_CMP_ERR);
1341 	}
1342 	disk_create(softc->disk, DISK_VERSION);
1343 	cam_periph_lock(periph);
1344 	cam_periph_unhold(periph);
1345 
1346 	dp = &softc->params;
1347 	snprintf(announce_buf, sizeof(announce_buf),
1348 	    "%juMB (%ju %u byte sectors)",
1349 	    ((uintmax_t)dp->secsize * dp->sectors) / (1024 * 1024),
1350 	    (uintmax_t)dp->sectors, dp->secsize);
1351 	xpt_announce_periph(periph, announce_buf);
1352 	xpt_announce_quirks(periph, softc->quirks, ADA_Q_BIT_STRING);
1353 
1354 	/*
1355 	 * Create our sysctl variables, now that we know
1356 	 * we have successfully attached.
1357 	 */
1358 	if (cam_periph_acquire(periph) == CAM_REQ_CMP)
1359 		taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
1360 
1361 	/*
1362 	 * Add async callbacks for bus reset and
1363 	 * bus device reset calls.  I don't bother
1364 	 * checking if this fails as, in most cases,
1365 	 * the system will function just fine without
1366 	 * them and the only alternative would be to
1367 	 * not attach the device on failure.
1368 	 */
1369 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
1370 	    AC_GETDEV_CHANGED | AC_ADVINFO_CHANGED,
1371 	    adaasync, periph, periph->path);
1372 
1373 	/*
1374 	 * Schedule a periodic event to occasionally send an
1375 	 * ordered tag to a device.
1376 	 */
1377 	callout_init_mtx(&softc->sendordered_c, cam_periph_mtx(periph), 0);
1378 	callout_reset(&softc->sendordered_c,
1379 	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
1380 	    adasendorderedtag, softc);
1381 
1382 	if (ADA_RA >= 0 &&
1383 	    cgd->ident_data.support.command1 & ATA_SUPPORT_LOOKAHEAD) {
1384 		softc->state = ADA_STATE_RAHEAD;
1385 	} else if (ADA_WC >= 0 &&
1386 	    cgd->ident_data.support.command1 & ATA_SUPPORT_WRITECACHE) {
1387 		softc->state = ADA_STATE_WCACHE;
1388 	} else {
1389 		softc->state = ADA_STATE_NORMAL;
1390 		return(CAM_REQ_CMP);
1391 	}
1392 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
1393 		softc->state = ADA_STATE_NORMAL;
1394 	else
1395 		xpt_schedule(periph, CAM_PRIORITY_DEV);
1396 	return(CAM_REQ_CMP);
1397 }
1398 
1399 static void
1400 ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
1401 {
1402 	struct trim_request *req = &softc->trim_req;
1403 	uint64_t lastlba = (uint64_t)-1;
1404 	int c, lastcount = 0, off, ranges = 0;
1405 
1406 	bzero(req, sizeof(*req));
1407 	TAILQ_INIT(&req->bps);
1408 	do {
1409 		uint64_t lba = bp->bio_pblkno;
1410 		int count = bp->bio_bcount / softc->params.secsize;
1411 
1412 		bioq_remove(&softc->trim_queue, bp);
1413 
1414 		/* Try to extend the previous range. */
1415 		if (lba == lastlba) {
1416 			c = min(count, ATA_DSM_RANGE_MAX - lastcount);
1417 			lastcount += c;
1418 			off = (ranges - 1) * ATA_DSM_RANGE_SIZE;
1419 			req->data[off + 6] = lastcount & 0xff;
1420 			req->data[off + 7] =
1421 				(lastcount >> 8) & 0xff;
1422 			count -= c;
1423 			lba += c;
1424 		}
1425 
1426 		while (count > 0) {
1427 			c = min(count, ATA_DSM_RANGE_MAX);
1428 			off = ranges * ATA_DSM_RANGE_SIZE;
1429 			req->data[off + 0] = lba & 0xff;
1430 			req->data[off + 1] = (lba >> 8) & 0xff;
1431 			req->data[off + 2] = (lba >> 16) & 0xff;
1432 			req->data[off + 3] = (lba >> 24) & 0xff;
1433 			req->data[off + 4] = (lba >> 32) & 0xff;
1434 			req->data[off + 5] = (lba >> 40) & 0xff;
1435 			req->data[off + 6] = c & 0xff;
1436 			req->data[off + 7] = (c >> 8) & 0xff;
1437 			lba += c;
1438 			count -= c;
1439 			lastcount = c;
1440 			ranges++;
1441 			/*
1442 			 * Its the caller's responsibility to ensure the
1443 			 * request will fit so we don't need to check for
1444 			 * overrun here
1445 			 */
1446 		}
1447 		lastlba = lba;
1448 		TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);
1449 		bp = bioq_first(&softc->trim_queue);
1450 		if (bp == NULL ||
1451 		    bp->bio_bcount / softc->params.secsize >
1452 		    (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX)
1453 			break;
1454 	} while (1);
1455 	cam_fill_ataio(ataio,
1456 	    ada_retry_count,
1457 	    adadone,
1458 	    CAM_DIR_OUT,
1459 	    0,
1460 	    req->data,
1461 	    ((ranges + ATA_DSM_BLK_RANGES - 1) /
1462 	    ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
1463 	    ada_default_timeout * 1000);
1464 	ata_48bit_cmd(ataio, ATA_DATA_SET_MANAGEMENT,
1465 	    ATA_DSM_TRIM, 0, (ranges + ATA_DSM_BLK_RANGES -
1466 	    1) / ATA_DSM_BLK_RANGES);
1467 }
1468 
1469 static void
1470 ada_cfaerase(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
1471 {
1472 	struct trim_request *req = &softc->trim_req;
1473 	uint64_t lba = bp->bio_pblkno;
1474 	uint16_t count = bp->bio_bcount / softc->params.secsize;
1475 
1476 	bzero(req, sizeof(*req));
1477 	TAILQ_INIT(&req->bps);
1478 	bioq_remove(&softc->trim_queue, bp);
1479 	TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);
1480 
1481 	cam_fill_ataio(ataio,
1482 	    ada_retry_count,
1483 	    adadone,
1484 	    CAM_DIR_NONE,
1485 	    0,
1486 	    NULL,
1487 	    0,
1488 	    ada_default_timeout*1000);
1489 
1490 	if (count >= 256)
1491 		count = 0;
1492 	ata_28bit_cmd(ataio, ATA_CFA_ERASE, 0, lba, count);
1493 }
1494 
1495 static void
1496 adastart(struct cam_periph *periph, union ccb *start_ccb)
1497 {
1498 	struct ada_softc *softc = (struct ada_softc *)periph->softc;
1499 	struct ccb_ataio *ataio = &start_ccb->ataio;
1500 
1501 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastart\n"));
1502 
1503 	switch (softc->state) {
1504 	case ADA_STATE_NORMAL:
1505 	{
1506 		struct bio *bp;
1507 		u_int8_t tag_code;
1508 
1509 		/* Run TRIM if not running yet. */
1510 		if (!softc->trim_running &&
1511 		    (bp = bioq_first(&softc->trim_queue)) != 0) {
1512 			if (softc->flags & ADA_FLAG_CAN_TRIM) {
1513 				ada_dsmtrim(softc, bp, ataio);
1514 			} else if ((softc->flags & ADA_FLAG_CAN_CFA) &&
1515 			    !(softc->flags & ADA_FLAG_CAN_48BIT)) {
1516 				ada_cfaerase(softc, bp, ataio);
1517 			} else {
1518 				/* This can happen if DMA was disabled. */
1519 				bioq_remove(&softc->trim_queue, bp);
1520 				biofinish(bp, NULL, EOPNOTSUPP);
1521 				xpt_release_ccb(start_ccb);
1522 				adaschedule(periph);
1523 				return;
1524 			}
1525 			softc->trim_running = 1;
1526 			start_ccb->ccb_h.ccb_state = ADA_CCB_TRIM;
1527 			start_ccb->ccb_h.flags |= CAM_UNLOCKED;
1528 			goto out;
1529 		}
1530 		/* Run regular command. */
1531 		bp = bioq_first(&softc->bio_queue);
1532 		if (bp == NULL) {
1533 			xpt_release_ccb(start_ccb);
1534 			break;
1535 		}
1536 		bioq_remove(&softc->bio_queue, bp);
1537 
1538 		if ((bp->bio_flags & BIO_ORDERED) != 0
1539 		 || (softc->flags & ADA_FLAG_NEED_OTAG) != 0) {
1540 			softc->flags &= ~ADA_FLAG_NEED_OTAG;
1541 			softc->flags |= ADA_FLAG_WAS_OTAG;
1542 			tag_code = 0;
1543 		} else {
1544 			tag_code = 1;
1545 		}
1546 		switch (bp->bio_cmd) {
1547 		case BIO_WRITE:
1548 			softc->flags |= ADA_FLAG_DIRTY;
1549 			/* FALLTHROUGH */
1550 		case BIO_READ:
1551 		{
1552 			uint64_t lba = bp->bio_pblkno;
1553 			uint16_t count = bp->bio_bcount / softc->params.secsize;
1554 #ifdef ADA_TEST_FAILURE
1555 			int fail = 0;
1556 
1557 			/*
1558 			 * Support the failure ioctls.  If the command is a
1559 			 * read, and there are pending forced read errors, or
1560 			 * if a write and pending write errors, then fail this
1561 			 * operation with EIO.  This is useful for testing
1562 			 * purposes.  Also, support having every Nth read fail.
1563 			 *
1564 			 * This is a rather blunt tool.
1565 			 */
1566 			if (bp->bio_cmd == BIO_READ) {
1567 				if (softc->force_read_error) {
1568 					softc->force_read_error--;
1569 					fail = 1;
1570 				}
1571 				if (softc->periodic_read_error > 0) {
1572 					if (++softc->periodic_read_count >=
1573 					    softc->periodic_read_error) {
1574 						softc->periodic_read_count = 0;
1575 						fail = 1;
1576 					}
1577 				}
1578 			} else {
1579 				if (softc->force_write_error) {
1580 					softc->force_write_error--;
1581 					fail = 1;
1582 				}
1583 			}
1584 			if (fail) {
1585 				biofinish(bp, NULL, EIO);
1586 				xpt_release_ccb(start_ccb);
1587 				adaschedule(periph);
1588 				return;
1589 			}
1590 #endif
1591 			KASSERT((bp->bio_flags & BIO_UNMAPPED) == 0 ||
1592 			    round_page(bp->bio_bcount + bp->bio_ma_offset) /
1593 			    PAGE_SIZE == bp->bio_ma_n,
1594 			    ("Short bio %p", bp));
1595 			cam_fill_ataio(ataio,
1596 			    ada_retry_count,
1597 			    adadone,
1598 			    (bp->bio_cmd == BIO_READ ? CAM_DIR_IN :
1599 				CAM_DIR_OUT) | ((bp->bio_flags & BIO_UNMAPPED)
1600 				!= 0 ? CAM_DATA_BIO : 0),
1601 			    tag_code,
1602 			    ((bp->bio_flags & BIO_UNMAPPED) != 0) ? (void *)bp :
1603 				bp->bio_data,
1604 			    bp->bio_bcount,
1605 			    ada_default_timeout*1000);
1606 
1607 			if ((softc->flags & ADA_FLAG_CAN_NCQ) && tag_code) {
1608 				if (bp->bio_cmd == BIO_READ) {
1609 					ata_ncq_cmd(ataio, ATA_READ_FPDMA_QUEUED,
1610 					    lba, count);
1611 				} else {
1612 					ata_ncq_cmd(ataio, ATA_WRITE_FPDMA_QUEUED,
1613 					    lba, count);
1614 				}
1615 			} else if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
1616 			    (lba + count >= ATA_MAX_28BIT_LBA ||
1617 			    count > 256)) {
1618 				if (softc->flags & ADA_FLAG_CAN_DMA48) {
1619 					if (bp->bio_cmd == BIO_READ) {
1620 						ata_48bit_cmd(ataio, ATA_READ_DMA48,
1621 						    0, lba, count);
1622 					} else {
1623 						ata_48bit_cmd(ataio, ATA_WRITE_DMA48,
1624 						    0, lba, count);
1625 					}
1626 				} else {
1627 					if (bp->bio_cmd == BIO_READ) {
1628 						ata_48bit_cmd(ataio, ATA_READ_MUL48,
1629 						    0, lba, count);
1630 					} else {
1631 						ata_48bit_cmd(ataio, ATA_WRITE_MUL48,
1632 						    0, lba, count);
1633 					}
1634 				}
1635 			} else {
1636 				if (count == 256)
1637 					count = 0;
1638 				if (softc->flags & ADA_FLAG_CAN_DMA) {
1639 					if (bp->bio_cmd == BIO_READ) {
1640 						ata_28bit_cmd(ataio, ATA_READ_DMA,
1641 						    0, lba, count);
1642 					} else {
1643 						ata_28bit_cmd(ataio, ATA_WRITE_DMA,
1644 						    0, lba, count);
1645 					}
1646 				} else {
1647 					if (bp->bio_cmd == BIO_READ) {
1648 						ata_28bit_cmd(ataio, ATA_READ_MUL,
1649 						    0, lba, count);
1650 					} else {
1651 						ata_28bit_cmd(ataio, ATA_WRITE_MUL,
1652 						    0, lba, count);
1653 					}
1654 				}
1655 			}
1656 			break;
1657 		}
1658 		case BIO_FLUSH:
1659 			cam_fill_ataio(ataio,
1660 			    1,
1661 			    adadone,
1662 			    CAM_DIR_NONE,
1663 			    0,
1664 			    NULL,
1665 			    0,
1666 			    ada_default_timeout*1000);
1667 
1668 			if (softc->flags & ADA_FLAG_CAN_48BIT)
1669 				ata_48bit_cmd(ataio, ATA_FLUSHCACHE48, 0, 0, 0);
1670 			else
1671 				ata_28bit_cmd(ataio, ATA_FLUSHCACHE, 0, 0, 0);
1672 			break;
1673 		}
1674 		start_ccb->ccb_h.ccb_state = ADA_CCB_BUFFER_IO;
1675 		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
1676 out:
1677 		start_ccb->ccb_h.ccb_bp = bp;
1678 		softc->outstanding_cmds++;
1679 		softc->refcount++;
1680 		cam_periph_unlock(periph);
1681 		xpt_action(start_ccb);
1682 		cam_periph_lock(periph);
1683 		softc->refcount--;
1684 
1685 		/* May have more work to do, so ensure we stay scheduled */
1686 		adaschedule(periph);
1687 		break;
1688 	}
1689 	case ADA_STATE_RAHEAD:
1690 	case ADA_STATE_WCACHE:
1691 	{
1692 		cam_fill_ataio(ataio,
1693 		    1,
1694 		    adadone,
1695 		    CAM_DIR_NONE,
1696 		    0,
1697 		    NULL,
1698 		    0,
1699 		    ada_default_timeout*1000);
1700 
1701 		if (softc->state == ADA_STATE_RAHEAD) {
1702 			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_RA ?
1703 			    ATA_SF_ENAB_RCACHE : ATA_SF_DIS_RCACHE, 0, 0);
1704 			start_ccb->ccb_h.ccb_state = ADA_CCB_RAHEAD;
1705 		} else {
1706 			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_WC ?
1707 			    ATA_SF_ENAB_WCACHE : ATA_SF_DIS_WCACHE, 0, 0);
1708 			start_ccb->ccb_h.ccb_state = ADA_CCB_WCACHE;
1709 		}
1710 		start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1711 		xpt_action(start_ccb);
1712 		break;
1713 	}
1714 	}
1715 }
1716 
1717 static void
1718 adadone(struct cam_periph *periph, union ccb *done_ccb)
1719 {
1720 	struct ada_softc *softc;
1721 	struct ccb_ataio *ataio;
1722 	struct ccb_getdev *cgd;
1723 	struct cam_path *path;
1724 	int state;
1725 
1726 	softc = (struct ada_softc *)periph->softc;
1727 	ataio = &done_ccb->ataio;
1728 	path = done_ccb->ccb_h.path;
1729 
1730 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("adadone\n"));
1731 
1732 	state = ataio->ccb_h.ccb_state & ADA_CCB_TYPE_MASK;
1733 	switch (state) {
1734 	case ADA_CCB_BUFFER_IO:
1735 	case ADA_CCB_TRIM:
1736 	{
1737 		struct bio *bp;
1738 		int error;
1739 
1740 		cam_periph_lock(periph);
1741 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1742 			error = adaerror(done_ccb, 0, 0);
1743 			if (error == ERESTART) {
1744 				/* A retry was scheduled, so just return. */
1745 				cam_periph_unlock(periph);
1746 				return;
1747 			}
1748 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1749 				cam_release_devq(path,
1750 						 /*relsim_flags*/0,
1751 						 /*reduction*/0,
1752 						 /*timeout*/0,
1753 						 /*getcount_only*/0);
1754 		} else {
1755 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1756 				panic("REQ_CMP with QFRZN");
1757 			error = 0;
1758 		}
1759 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1760 		bp->bio_error = error;
1761 		if (error != 0) {
1762 			bp->bio_resid = bp->bio_bcount;
1763 			bp->bio_flags |= BIO_ERROR;
1764 		} else {
1765 			if (state == ADA_CCB_TRIM)
1766 				bp->bio_resid = 0;
1767 			else
1768 				bp->bio_resid = ataio->resid;
1769 			if (bp->bio_resid > 0)
1770 				bp->bio_flags |= BIO_ERROR;
1771 		}
1772 		softc->outstanding_cmds--;
1773 		if (softc->outstanding_cmds == 0)
1774 			softc->flags |= ADA_FLAG_WAS_OTAG;
1775 		xpt_release_ccb(done_ccb);
1776 		if (state == ADA_CCB_TRIM) {
1777 			TAILQ_HEAD(, bio) queue;
1778 			struct bio *bp1;
1779 
1780 			TAILQ_INIT(&queue);
1781 			TAILQ_CONCAT(&queue, &softc->trim_req.bps, bio_queue);
1782 			/*
1783 			 * Normally, the xpt_release_ccb() above would make sure
1784 			 * that when we have more work to do, that work would
1785 			 * get kicked off. However, we specifically keep
1786 			 * trim_running set to 0 before the call above to allow
1787 			 * other I/O to progress when many BIO_DELETE requests
1788 			 * are pushed down. We set trim_running to 0 and call
1789 			 * daschedule again so that we don't stall if there are
1790 			 * no other I/Os pending apart from BIO_DELETEs.
1791 			 */
1792 			softc->trim_running = 0;
1793 			adaschedule(periph);
1794 			cam_periph_unlock(periph);
1795 			while ((bp1 = TAILQ_FIRST(&queue)) != NULL) {
1796 				TAILQ_REMOVE(&queue, bp1, bio_queue);
1797 				bp1->bio_error = error;
1798 				if (error != 0) {
1799 					bp1->bio_flags |= BIO_ERROR;
1800 					bp1->bio_resid = bp1->bio_bcount;
1801 				} else
1802 					bp1->bio_resid = 0;
1803 				biodone(bp1);
1804 			}
1805 		} else {
1806 			cam_periph_unlock(periph);
1807 			biodone(bp);
1808 		}
1809 		return;
1810 	}
1811 	case ADA_CCB_RAHEAD:
1812 	{
1813 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1814 			if (adaerror(done_ccb, 0, 0) == ERESTART) {
1815 out:
1816 				/* Drop freeze taken due to CAM_DEV_QFREEZE */
1817 				cam_release_devq(path, 0, 0, 0, FALSE);
1818 				return;
1819 			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1820 				cam_release_devq(path,
1821 				    /*relsim_flags*/0,
1822 				    /*reduction*/0,
1823 				    /*timeout*/0,
1824 				    /*getcount_only*/0);
1825 			}
1826 		}
1827 
1828 		/*
1829 		 * Since our peripheral may be invalidated by an error
1830 		 * above or an external event, we must release our CCB
1831 		 * before releasing the reference on the peripheral.
1832 		 * The peripheral will only go away once the last reference
1833 		 * is removed, and we need it around for the CCB release
1834 		 * operation.
1835 		 */
1836 		cgd = (struct ccb_getdev *)done_ccb;
1837 		xpt_setup_ccb(&cgd->ccb_h, path, CAM_PRIORITY_NORMAL);
1838 		cgd->ccb_h.func_code = XPT_GDEV_TYPE;
1839 		xpt_action((union ccb *)cgd);
1840 		if (ADA_WC >= 0 &&
1841 		    cgd->ident_data.support.command1 & ATA_SUPPORT_WRITECACHE) {
1842 			softc->state = ADA_STATE_WCACHE;
1843 			xpt_release_ccb(done_ccb);
1844 			xpt_schedule(periph, CAM_PRIORITY_DEV);
1845 			goto out;
1846 		}
1847 		softc->state = ADA_STATE_NORMAL;
1848 		xpt_release_ccb(done_ccb);
1849 		/* Drop freeze taken due to CAM_DEV_QFREEZE */
1850 		cam_release_devq(path, 0, 0, 0, FALSE);
1851 		adaschedule(periph);
1852 		cam_periph_release_locked(periph);
1853 		return;
1854 	}
1855 	case ADA_CCB_WCACHE:
1856 	{
1857 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1858 			if (adaerror(done_ccb, 0, 0) == ERESTART) {
1859 				goto out;
1860 			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1861 				cam_release_devq(path,
1862 				    /*relsim_flags*/0,
1863 				    /*reduction*/0,
1864 				    /*timeout*/0,
1865 				    /*getcount_only*/0);
1866 			}
1867 		}
1868 
1869 		softc->state = ADA_STATE_NORMAL;
1870 		/*
1871 		 * Since our peripheral may be invalidated by an error
1872 		 * above or an external event, we must release our CCB
1873 		 * before releasing the reference on the peripheral.
1874 		 * The peripheral will only go away once the last reference
1875 		 * is removed, and we need it around for the CCB release
1876 		 * operation.
1877 		 */
1878 		xpt_release_ccb(done_ccb);
1879 		/* Drop freeze taken due to CAM_DEV_QFREEZE */
1880 		cam_release_devq(path, 0, 0, 0, FALSE);
1881 		adaschedule(periph);
1882 		cam_periph_release_locked(periph);
1883 		return;
1884 	}
1885 	case ADA_CCB_DUMP:
1886 		/* No-op.  We're polling */
1887 		return;
1888 	default:
1889 		break;
1890 	}
1891 	xpt_release_ccb(done_ccb);
1892 }
1893 
1894 static int
1895 adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1896 {
1897 
1898 	return(cam_periph_error(ccb, cam_flags, sense_flags, NULL));
1899 }
1900 
1901 static void
1902 adagetparams(struct cam_periph *periph, struct ccb_getdev *cgd)
1903 {
1904 	struct ada_softc *softc = (struct ada_softc *)periph->softc;
1905 	struct disk_params *dp = &softc->params;
1906 	u_int64_t lbasize48;
1907 	u_int32_t lbasize;
1908 
1909 	dp->secsize = ata_logical_sector_size(&cgd->ident_data);
1910 	if ((cgd->ident_data.atavalid & ATA_FLAG_54_58) &&
1911 		cgd->ident_data.current_heads && cgd->ident_data.current_sectors) {
1912 		dp->heads = cgd->ident_data.current_heads;
1913 		dp->secs_per_track = cgd->ident_data.current_sectors;
1914 		dp->cylinders = cgd->ident_data.cylinders;
1915 		dp->sectors = (u_int32_t)cgd->ident_data.current_size_1 |
1916 			  ((u_int32_t)cgd->ident_data.current_size_2 << 16);
1917 	} else {
1918 		dp->heads = cgd->ident_data.heads;
1919 		dp->secs_per_track = cgd->ident_data.sectors;
1920 		dp->cylinders = cgd->ident_data.cylinders;
1921 		dp->sectors = cgd->ident_data.cylinders * dp->heads * dp->secs_per_track;
1922 	}
1923 	lbasize = (u_int32_t)cgd->ident_data.lba_size_1 |
1924 		  ((u_int32_t)cgd->ident_data.lba_size_2 << 16);
1925 
1926 	/* use the 28bit LBA size if valid or bigger than the CHS mapping */
1927 	if (cgd->ident_data.cylinders == 16383 || dp->sectors < lbasize)
1928 		dp->sectors = lbasize;
1929 
1930 	/* use the 48bit LBA size if valid */
1931 	lbasize48 = ((u_int64_t)cgd->ident_data.lba_size48_1) |
1932 		    ((u_int64_t)cgd->ident_data.lba_size48_2 << 16) |
1933 		    ((u_int64_t)cgd->ident_data.lba_size48_3 << 32) |
1934 		    ((u_int64_t)cgd->ident_data.lba_size48_4 << 48);
1935 	if ((cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) &&
1936 	    lbasize48 > ATA_MAX_28BIT_LBA)
1937 		dp->sectors = lbasize48;
1938 }
1939 
1940 static void
1941 adasendorderedtag(void *arg)
1942 {
1943 	struct ada_softc *softc = arg;
1944 
1945 	if (ada_send_ordered) {
1946 		if (softc->outstanding_cmds > 0) {
1947 			if ((softc->flags & ADA_FLAG_WAS_OTAG) == 0)
1948 				softc->flags |= ADA_FLAG_NEED_OTAG;
1949 			softc->flags &= ~ADA_FLAG_WAS_OTAG;
1950 		}
1951 	}
1952 	/* Queue us up again */
1953 	callout_reset(&softc->sendordered_c,
1954 	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
1955 	    adasendorderedtag, softc);
1956 }
1957 
1958 /*
1959  * Step through all ADA peripheral drivers, and if the device is still open,
1960  * sync the disk cache to physical media.
1961  */
1962 static void
1963 adaflush(void)
1964 {
1965 	struct cam_periph *periph;
1966 	struct ada_softc *softc;
1967 	union ccb *ccb;
1968 	int error;
1969 
1970 	CAM_PERIPH_FOREACH(periph, &adadriver) {
1971 		softc = (struct ada_softc *)periph->softc;
1972 		if (SCHEDULER_STOPPED()) {
1973 			/* If we paniced with the lock held, do not recurse. */
1974 			if (!cam_periph_owned(periph) &&
1975 			    (softc->flags & ADA_FLAG_OPEN)) {
1976 				adadump(softc->disk, NULL, 0, 0, 0);
1977 			}
1978 			continue;
1979 		}
1980 		cam_periph_lock(periph);
1981 		/*
1982 		 * We only sync the cache if the drive is still open, and
1983 		 * if the drive is capable of it..
1984 		 */
1985 		if (((softc->flags & ADA_FLAG_OPEN) == 0) ||
1986 		    (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) == 0) {
1987 			cam_periph_unlock(periph);
1988 			continue;
1989 		}
1990 
1991 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1992 		cam_fill_ataio(&ccb->ataio,
1993 				    0,
1994 				    adadone,
1995 				    CAM_DIR_NONE,
1996 				    0,
1997 				    NULL,
1998 				    0,
1999 				    ada_default_timeout*1000);
2000 		if (softc->flags & ADA_FLAG_CAN_48BIT)
2001 			ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
2002 		else
2003 			ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
2004 
2005 		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
2006 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
2007 		    softc->disk->d_devstat);
2008 		if (error != 0)
2009 			xpt_print(periph->path, "Synchronize cache failed\n");
2010 		xpt_release_ccb(ccb);
2011 		cam_periph_unlock(periph);
2012 	}
2013 }
2014 
2015 static void
2016 adaspindown(uint8_t cmd, int flags)
2017 {
2018 	struct cam_periph *periph;
2019 	struct ada_softc *softc;
2020 	union ccb *ccb;
2021 	int error;
2022 
2023 	CAM_PERIPH_FOREACH(periph, &adadriver) {
2024 		/* If we paniced with lock held - not recurse here. */
2025 		if (cam_periph_owned(periph))
2026 			continue;
2027 		cam_periph_lock(periph);
2028 		softc = (struct ada_softc *)periph->softc;
2029 		/*
2030 		 * We only spin-down the drive if it is capable of it..
2031 		 */
2032 		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
2033 			cam_periph_unlock(periph);
2034 			continue;
2035 		}
2036 
2037 		if (bootverbose)
2038 			xpt_print(periph->path, "spin-down\n");
2039 
2040 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2041 		cam_fill_ataio(&ccb->ataio,
2042 				    0,
2043 				    adadone,
2044 				    CAM_DIR_NONE | flags,
2045 				    0,
2046 				    NULL,
2047 				    0,
2048 				    ada_default_timeout*1000);
2049 		ata_28bit_cmd(&ccb->ataio, cmd, 0, 0, 0);
2050 
2051 		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
2052 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
2053 		    softc->disk->d_devstat);
2054 		if (error != 0)
2055 			xpt_print(periph->path, "Spin-down disk failed\n");
2056 		xpt_release_ccb(ccb);
2057 		cam_periph_unlock(periph);
2058 	}
2059 }
2060 
2061 static void
2062 adashutdown(void *arg, int howto)
2063 {
2064 
2065 	adaflush();
2066 	if (ada_spindown_shutdown != 0 &&
2067 	    (howto & (RB_HALT | RB_POWEROFF)) != 0)
2068 		adaspindown(ATA_STANDBY_IMMEDIATE, 0);
2069 }
2070 
2071 static void
2072 adasuspend(void *arg)
2073 {
2074 
2075 	adaflush();
2076 	if (ada_spindown_suspend != 0)
2077 		adaspindown(ATA_SLEEP, CAM_DEV_QFREEZE);
2078 }
2079 
2080 static void
2081 adaresume(void *arg)
2082 {
2083 	struct cam_periph *periph;
2084 	struct ada_softc *softc;
2085 
2086 	if (ada_spindown_suspend == 0)
2087 		return;
2088 
2089 	CAM_PERIPH_FOREACH(periph, &adadriver) {
2090 		cam_periph_lock(periph);
2091 		softc = (struct ada_softc *)periph->softc;
2092 		/*
2093 		 * We only spin-down the drive if it is capable of it..
2094 		 */
2095 		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
2096 			cam_periph_unlock(periph);
2097 			continue;
2098 		}
2099 
2100 		if (bootverbose)
2101 			xpt_print(periph->path, "resume\n");
2102 
2103 		/*
2104 		 * Drop freeze taken due to CAM_DEV_QFREEZE flag set on
2105 		 * sleep request.
2106 		 */
2107 		cam_release_devq(periph->path,
2108 			 /*relsim_flags*/0,
2109 			 /*openings*/0,
2110 			 /*timeout*/0,
2111 			 /*getcount_only*/0);
2112 
2113 		cam_periph_unlock(periph);
2114 	}
2115 }
2116 
2117 #endif /* _KERNEL */
2118