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