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