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