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