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