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