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