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