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