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