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