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