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