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