xref: /freebsd/sys/powerpc/mpc85xx/fsl_sata.c (revision 2008043f386721d58158e37e0d7e50df8095942d)
1 /*-
2  * Copyright (c) 2009-2012 Alexander Motin <mav@FreeBSD.org>
3  * Copyright (c) 2017 Justin Hibbits <jhibbits@FreeBSD.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer,
11  *    without modification, immediately at the beginning of the file.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 #include <sys/param.h>
30 #include <sys/module.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/bus.h>
34 #include <sys/conf.h>
35 #include <sys/endian.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mutex.h>
39 #include <sys/rman.h>
40 
41 #include <cam/cam.h>
42 #include <cam/cam_ccb.h>
43 #include <cam/cam_sim.h>
44 #include <cam/cam_xpt_sim.h>
45 #include <cam/cam_debug.h>
46 
47 #include <dev/ofw/ofw_bus_subr.h>
48 
49 #include <machine/bus.h>
50 #include <machine/resource.h>
51 
52 #include "fsl_sata.h"
53 
54 struct fsl_sata_channel;
55 struct fsl_sata_slot;
56 enum fsl_sata_err_type;
57 struct fsl_sata_cmd_tab;
58 
59 /* local prototypes */
60 static int fsl_sata_init(device_t dev);
61 static int fsl_sata_deinit(device_t dev);
62 static int fsl_sata_suspend(device_t dev);
63 static int fsl_sata_resume(device_t dev);
64 static void fsl_sata_pm(void *arg);
65 static void fsl_sata_intr(void *arg);
66 static void fsl_sata_intr_main(struct fsl_sata_channel *ch, uint32_t istatus);
67 static void fsl_sata_begin_transaction(struct fsl_sata_channel *ch, union ccb *ccb);
68 static void fsl_sata_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
69 static void fsl_sata_execute_transaction(struct fsl_sata_slot *slot);
70 static void fsl_sata_timeout(void *arg);
71 static void fsl_sata_end_transaction(struct fsl_sata_slot *slot, enum fsl_sata_err_type et);
72 static int fsl_sata_setup_fis(struct fsl_sata_channel *ch, struct fsl_sata_cmd_tab *ctp, union ccb *ccb, int tag);
73 static void fsl_sata_dmainit(device_t dev);
74 static void fsl_sata_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error);
75 static void fsl_sata_dmafini(device_t dev);
76 static void fsl_sata_slotsalloc(device_t dev);
77 static void fsl_sata_slotsfree(device_t dev);
78 static void fsl_sata_reset(struct fsl_sata_channel *ch);
79 static void fsl_sata_start(struct fsl_sata_channel *ch);
80 static void fsl_sata_stop(struct fsl_sata_channel *ch);
81 
82 static void fsl_sata_issue_recovery(struct fsl_sata_channel *ch);
83 static void fsl_sata_process_read_log(struct fsl_sata_channel *ch, union ccb *ccb);
84 static void fsl_sata_process_request_sense(struct fsl_sata_channel *ch, union ccb *ccb);
85 
86 static void fsl_sataaction(struct cam_sim *sim, union ccb *ccb);
87 static void fsl_satapoll(struct cam_sim *sim);
88 
89 static MALLOC_DEFINE(M_FSL_SATA, "FSL SATA driver", "FSL SATA driver data buffers");
90 
91 #define	recovery_type		spriv_field0
92 #define	RECOVERY_NONE		0
93 #define	RECOVERY_READ_LOG	1
94 #define	RECOVERY_REQUEST_SENSE	2
95 #define	recovery_slot		spriv_field1
96 
97 #define	FSL_SATA_P_CQR		0x0
98 #define	FSL_SATA_P_CAR		0x4
99 #define	FSL_SATA_P_CCR		0x10
100 #define	FSL_SATA_P_CER			0x18
101 #define	FSL_SATA_P_DER		0x20
102 #define	FSL_SATA_P_CHBA		0x24
103 #define	FSL_SATA_P_HSTS		0x28
104 #define	  FSL_SATA_P_HSTS_HS_ON	  0x80000000
105 #define	  FSL_SATA_P_HSTS_ME	  0x00040000
106 #define	  FSL_SATA_P_HSTS_DLM	  0x00001000
107 #define	  FSL_SATA_P_HSTS_FOT	  0x00000200
108 #define	  FSL_SATA_P_HSTS_FOR	  0x00000100
109 #define	  FSL_SATA_P_HSTS_FE	  0x00000020
110 #define	  FSL_SATA_P_HSTS_PR	  0x00000010
111 #define	  FSL_SATA_P_HSTS_SNTFU	  0x00000004
112 #define	  FSL_SATA_P_HSTS_DE	  0x00000002
113 #define	FSL_SATA_P_HCTRL	0x2c
114 #define	  FSL_SATA_P_HCTRL_HC_ON  0x80000000
115 #define	  FSL_SATA_P_HCTRL_HC_FORCE_OFF  0x40000000
116 #define	  FSL_SATA_P_HCTRL_ENT	  0x10000000
117 #define	  FSL_SATA_P_HCTRL_SNOOP  0x00000400
118 #define	  FSL_SATA_P_HCTRL_PM	  0x00000200
119 #define	  FSL_SATA_P_HCTRL_FATAL  0x00000020
120 #define	  FSL_SATA_P_HCTRL_PHYRDY 0x00000010
121 #define	  FSL_SATA_P_HCTRL_SIG	  0x00000008
122 #define	  FSL_SATA_P_HCTRL_SNTFY  0x00000004
123 #define	  FSL_SATA_P_HCTRL_DE	  0x00000002
124 #define	  FSL_SATA_P_HCTRL_CC	  0x00000001
125 #define	  FSL_SATA_P_HCTRL_INT_MASK	0x0000003f
126 #define	FSL_SATA_P_CQPMP	0x30
127 #define	FSL_SATA_P_SIG		0x34
128 #define	FSL_SATA_P_ICC		0x38
129 #define	  FSL_SATA_P_ICC_ITC_M	  0x1f000000
130 #define	  FSL_SATA_P_ICC_ITC_S	  24
131 #define	  FSL_SATA_P_ICC_ITTCV_M	  0x0007ffff
132 #define	FSL_SATA_P_PCC		0x15c
133 #define	  FSL_SATA_P_PCC_SLUMBER	  0x0000000c
134 #define	  FSL_SATA_P_PCC_PARTIAL	  0x0000000a
135 #define	  FSL_SATA_PCC_LPB_EN		  0x0000000e
136 
137 #define	FSL_SATA_MAX_SLOTS		16
138 /* FSL_SATA register defines */
139 
140 #define	FSL_SATA_P_SSTS		0x100
141 #define	FSL_SATA_P_SERR		0x104
142 #define	FSL_SATA_P_SCTL		0x108
143 #define	FSL_SATA_P_SNTF		0x10c
144 
145 /* Pessimistic prognosis on number of required S/G entries */
146 #define	FSL_SATA_SG_ENTRIES	63
147 /* Command list. 16 commands. First, 1Kbyte aligned. */
148 #define	FSL_SATA_CL_OFFSET	0
149 #define	FSL_SATA_CL_SIZE	16
150 /* Command tables. Up to 32 commands, Each, 4-byte aligned. */
151 #define	FSL_SATA_CT_OFFSET	(FSL_SATA_CL_OFFSET + FSL_SATA_CL_SIZE * FSL_SATA_MAX_SLOTS)
152 #define	FSL_SATA_CT_SIZE	(96 + FSL_SATA_SG_ENTRIES * 16)
153 /* Total main work area. */
154 #define	FSL_SATA_WORK_SIZE	(FSL_SATA_CT_OFFSET + FSL_SATA_CT_SIZE * FSL_SATA_MAX_SLOTS)
155 #define	FSL_SATA_MAX_XFER	(64 * 1024 * 1024)
156 
157 /* Some convenience macros for getting the CTP and CLP */
158 #define	FSL_SATA_CTP_BUS(ch, slot)	\
159     ((ch->dma.work_bus + FSL_SATA_CT_OFFSET + (FSL_SATA_CT_SIZE * slot->slot)))
160 #define FSL_SATA_PRD_OFFSET(prd) (96 + (prd) * 16)
161 #define	FSL_SATA_CTP(ch, slot)		\
162     ((struct fsl_sata_cmd_tab *)(ch->dma.work + FSL_SATA_CT_OFFSET + \
163      (FSL_SATA_CT_SIZE * slot->slot)))
164 #define	FSL_SATA_CLP(ch, slot)		\
165 	((struct fsl_sata_cmd_list *) (ch->dma.work + FSL_SATA_CL_OFFSET + \
166 	 (FSL_SATA_CL_SIZE * slot->slot)))
167 
168 struct fsl_sata_dma_prd {
169 	uint32_t		dba;
170 	uint32_t		reserved;
171 	uint32_t		reserved2;
172 	uint32_t		dwc_flg;		/* 0 based */
173 #define	FSL_SATA_PRD_MASK		0x01fffffc	/* max 32MB */
174 #define	FSL_SATA_PRD_MAX		(FSL_SATA_PRD_MASK + 4)
175 #define	FSL_SATA_PRD_SNOOP		0x10000000
176 #define	FSL_SATA_PRD_EXT		0x80000000
177 } __packed;
178 
179 struct fsl_sata_cmd_tab {
180 	uint8_t			cfis[32];
181 	uint8_t			sfis[32];
182 	uint8_t			acmd[16];
183 	uint8_t			reserved[16];
184 	struct fsl_sata_dma_prd	prd_tab[FSL_SATA_SG_ENTRIES];
185 #define	FSL_SATA_PRD_EXT_INDEX	15
186 #define FSL_SATA_PRD_MAX_DIRECT	16
187 } __packed;
188 
189 struct fsl_sata_cmd_list {
190 	uint32_t			cda;		/* word aligned */
191 	uint16_t			fis_length;	/* length in bytes (aligned to words) */
192 	uint16_t			prd_length;	/* PRD entries */
193 	uint32_t			ttl;
194 	uint32_t			cmd_flags;
195 #define	FSL_SATA_CMD_TAG_MASK		0x001f
196 #define	FSL_SATA_CMD_ATAPI		0x0020
197 #define	FSL_SATA_CMD_BIST		0x0040
198 #define	FSL_SATA_CMD_RESET		0x0080
199 #define	FSL_SATA_CMD_QUEUED		0x0100
200 #define	FSL_SATA_CMD_SNOOP		0x0200
201 #define	FSL_SATA_CMD_VBIST		0x0400
202 #define	FSL_SATA_CMD_WRITE		0x0800
203 
204 } __packed;
205 
206 /* misc defines */
207 #define	ATA_IRQ_RID		0
208 #define	ATA_INTR_FLAGS		(INTR_MPSAFE|INTR_TYPE_BIO|INTR_ENTROPY)
209 
210 struct ata_dmaslot {
211 	bus_dmamap_t		data_map;	/* data DMA map */
212 	int			nsegs;		/* Number of segs loaded */
213 };
214 
215 /* structure holding DMA related information */
216 struct ata_dma {
217 	bus_dma_tag_t		 work_tag;	/* workspace DMA tag */
218 	bus_dmamap_t		 work_map;	/* workspace DMA map */
219 	uint8_t			*work;		/* workspace */
220 	bus_addr_t		 work_bus;	/* bus address of work */
221 	bus_dma_tag_t		data_tag;	/* data DMA tag */
222 };
223 
224 enum fsl_sata_slot_states {
225 	FSL_SATA_SLOT_EMPTY,
226 	FSL_SATA_SLOT_LOADING,
227 	FSL_SATA_SLOT_RUNNING,
228 	FSL_SATA_SLOT_EXECUTING
229 };
230 
231 struct fsl_sata_slot {
232 	struct fsl_sata_channel		*ch;		/* Channel */
233 	uint8_t				 slot;		/* Number of this slot */
234 	enum fsl_sata_slot_states	 state;	/* Slot state */
235 	union ccb			*ccb;		/* CCB occupying slot */
236 	struct ata_dmaslot		 dma;	/* DMA data of this slot */
237 	struct callout			 timeout;	/* Execution timeout */
238 	uint32_t			 ttl;
239 };
240 
241 struct fsl_sata_device {
242 	int			revision;
243 	int			mode;
244 	u_int			bytecount;
245 	u_int			atapi;
246 	u_int			tags;
247 	u_int			caps;
248 };
249 
250 /* structure describing an ATA channel */
251 struct fsl_sata_channel {
252 	device_t		dev;		/* Device handle */
253 	int			 r_mid;		/* Physical channel RID */
254 	struct resource		*r_mem;		/* Memory of this channel */
255 	struct resource		*r_irq;		/* Interrupt of this channel */
256 	void			*ih;		/* Interrupt handle */
257 	struct ata_dma		dma;		/* DMA data */
258 	struct cam_sim		*sim;
259 	struct cam_path		*path;
260 	uint32_t		caps;		/* Controller capabilities */
261 	int			pm_level;	/* power management level */
262 	int			devices;	/* What is present */
263 	int			pm_present;	/* PM presence reported */
264 
265 	union ccb		*hold[FSL_SATA_MAX_SLOTS];
266 	struct fsl_sata_slot	slot[FSL_SATA_MAX_SLOTS];
267 	uint32_t		oslots;		/* Occupied slots */
268 	uint32_t		rslots;		/* Running slots */
269 	uint32_t		aslots;		/* Slots with atomic commands  */
270 	uint32_t		eslots;		/* Slots in error */
271 	uint32_t		toslots;	/* Slots in timeout */
272 	int			lastslot;	/* Last used slot */
273 	int			taggedtarget;	/* Last tagged target */
274 	int			numrslots;	/* Number of running slots */
275 	int			numrslotspd[16];/* Number of running slots per dev */
276 	int			numtslots;	/* Number of tagged slots */
277 	int			numtslotspd[16];/* Number of tagged slots per dev */
278 	int			numhslots;	/* Number of held slots */
279 	int			recoverycmd;	/* Our READ LOG active */
280 	int			fatalerr;	/* Fatal error happend */
281 	int			resetting;	/* Hard-reset in progress. */
282 	int			resetpolldiv;	/* Hard-reset poll divider. */
283 	union ccb		*frozen;	/* Frozen command */
284 	struct callout		pm_timer;	/* Power management events */
285 	struct callout		reset_timer;	/* Hard-reset timeout */
286 
287 	struct fsl_sata_device	user[16];	/* User-specified settings */
288 	struct fsl_sata_device	curr[16];	/* Current settings */
289 
290 	struct mtx_padalign	mtx;		/* state lock */
291 	STAILQ_HEAD(, ccb_hdr)	doneq;		/* queue of completed CCBs */
292 	int			batch;		/* doneq is in use */
293 };
294 
295 enum fsl_sata_err_type {
296 	FSL_SATA_ERR_NONE,		/* No error */
297 	FSL_SATA_ERR_INVALID,	/* Error detected by us before submitting. */
298 	FSL_SATA_ERR_INNOCENT,	/* Innocent victim. */
299 	FSL_SATA_ERR_TFE,		/* Task File Error. */
300 	FSL_SATA_ERR_SATA,		/* SATA error. */
301 	FSL_SATA_ERR_TIMEOUT,	/* Command execution timeout. */
302 	FSL_SATA_ERR_NCQ,		/* NCQ command error. CCB should be put on hold
303 				 * until READ LOG executed to reveal error. */
304 };
305 
306 /* macros to hide busspace uglyness */
307 #define	ATA_INL(res, offset) \
308 	bus_read_4((res), (offset))
309 #define	ATA_OUTL(res, offset, value) \
310 	bus_write_4((res), (offset), (value))
311 
312 static int
313 fsl_sata_probe(device_t dev)
314 {
315 
316 	if (!ofw_bus_is_compatible(dev, "fsl,pq-sata-v2") &&
317 	    !ofw_bus_is_compatible(dev, "fsl,pq-sata"))
318 		return (ENXIO);
319 
320 	device_set_desc_copy(dev, "Freescale Integrated SATA Controller");
321 	return (BUS_PROBE_DEFAULT);
322 }
323 
324 static int
325 fsl_sata_attach(device_t dev)
326 {
327 	struct fsl_sata_channel *ch = device_get_softc(dev);
328 	struct cam_devq *devq;
329 	int rid, error, i, sata_rev = 0;
330 
331 	ch->dev = dev;
332 	mtx_init(&ch->mtx, "FSL SATA channel lock", NULL, MTX_DEF);
333 	ch->pm_level = 0;
334 	resource_int_value(device_get_name(dev),
335 	    device_get_unit(dev), "pm_level", &ch->pm_level);
336 	STAILQ_INIT(&ch->doneq);
337 	if (ch->pm_level > 3)
338 		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
339 	resource_int_value(device_get_name(dev),
340 	    device_get_unit(dev), "sata_rev", &sata_rev);
341 	for (i = 0; i < 16; i++) {
342 		ch->user[i].revision = sata_rev;
343 		ch->user[i].mode = 0;
344 		ch->user[i].bytecount = 8192;
345 		ch->user[i].tags = FSL_SATA_MAX_SLOTS;
346 		ch->user[i].caps = 0;
347 		ch->curr[i] = ch->user[i];
348 		if (ch->pm_level) {
349 			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ |
350 			    CTS_SATA_CAPS_D_PMREQ;
351 		}
352 		ch->user[i].caps |= CTS_SATA_CAPS_H_AN;
353 	}
354 	ch->r_mid = 0;
355 	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
356 	    &ch->r_mid, RF_ACTIVE)))
357 		return (ENXIO);
358 	rman_set_bustag(ch->r_mem, &bs_le_tag);
359 	fsl_sata_dmainit(dev);
360 	fsl_sata_slotsalloc(dev);
361 	fsl_sata_init(dev);
362 	rid = ATA_IRQ_RID;
363 	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
364 	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
365 		device_printf(dev, "Unable to map interrupt\n");
366 		error = ENXIO;
367 		goto err0;
368 	}
369 	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
370 	    fsl_sata_intr, ch, &ch->ih))) {
371 		device_printf(dev, "Unable to setup interrupt\n");
372 		error = ENXIO;
373 		goto err1;
374 	}
375 	mtx_lock(&ch->mtx);
376 	/* Create the device queue for our SIM. */
377 	devq = cam_simq_alloc(FSL_SATA_MAX_SLOTS);
378 	if (devq == NULL) {
379 		device_printf(dev, "Unable to allocate simq\n");
380 		error = ENOMEM;
381 		goto err1;
382 	}
383 	/* Construct SIM entry */
384 	ch->sim = cam_sim_alloc(fsl_sataaction, fsl_satapoll, "fslsata", ch,
385 	    device_get_unit(dev), (struct mtx *)&ch->mtx, 2, FSL_SATA_MAX_SLOTS,
386 	    devq);
387 	if (ch->sim == NULL) {
388 		cam_simq_free(devq);
389 		device_printf(dev, "unable to allocate sim\n");
390 		error = ENOMEM;
391 		goto err1;
392 	}
393 	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
394 		device_printf(dev, "unable to register xpt bus\n");
395 		error = ENXIO;
396 		goto err2;
397 	}
398 	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
399 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
400 		device_printf(dev, "unable to create path\n");
401 		error = ENXIO;
402 		goto err3;
403 	}
404 	if (ch->pm_level > 3) {
405 		callout_reset(&ch->pm_timer,
406 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
407 		    fsl_sata_pm, ch);
408 	}
409 	mtx_unlock(&ch->mtx);
410 	return (0);
411 
412 err3:
413 	xpt_bus_deregister(cam_sim_path(ch->sim));
414 err2:
415 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
416 err1:
417 	mtx_unlock(&ch->mtx);
418 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
419 err0:
420 	bus_release_resource(dev, SYS_RES_MEMORY, ch->r_mid, ch->r_mem);
421 	mtx_destroy(&ch->mtx);
422 	return (error);
423 }
424 
425 static int
426 fsl_sata_detach(device_t dev)
427 {
428 	struct fsl_sata_channel *ch = device_get_softc(dev);
429 
430 	mtx_lock(&ch->mtx);
431 	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
432 
433 	xpt_free_path(ch->path);
434 	xpt_bus_deregister(cam_sim_path(ch->sim));
435 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
436 	mtx_unlock(&ch->mtx);
437 
438 	if (ch->pm_level > 3)
439 		callout_drain(&ch->pm_timer);
440 	bus_teardown_intr(dev, ch->r_irq, ch->ih);
441 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
442 
443 	fsl_sata_deinit(dev);
444 	fsl_sata_slotsfree(dev);
445 	fsl_sata_dmafini(dev);
446 
447 	bus_release_resource(dev, SYS_RES_MEMORY, ch->r_mid, ch->r_mem);
448 	mtx_destroy(&ch->mtx);
449 	return (0);
450 }
451 
452 static int
453 fsl_sata_wait_register(struct fsl_sata_channel *ch, bus_size_t off,
454     unsigned int mask, unsigned int val, int t)
455 {
456 	int timeout = 0;
457 	uint32_t rval;
458 
459 	while (((rval = ATA_INL(ch->r_mem, off)) & mask) != val) {
460 		if (timeout > t) {
461 			return (EBUSY);
462 		}
463 		DELAY(1000);
464 		timeout++;
465 	}
466 	return (0);
467 }
468 
469 static int
470 fsl_sata_init(device_t dev)
471 {
472 	struct fsl_sata_channel *ch = device_get_softc(dev);
473 	uint64_t work;
474 	uint32_t r;
475 
476 	/* Disable port interrupts */
477 	r = ATA_INL(ch->r_mem, FSL_SATA_P_HCTRL);
478 	r &= ~FSL_SATA_P_HCTRL_HC_ON;
479 	r |= FSL_SATA_P_HCTRL_HC_FORCE_OFF;
480 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HCTRL, r & ~FSL_SATA_P_HCTRL_INT_MASK);
481 	fsl_sata_wait_register(ch, FSL_SATA_P_HSTS,
482 	    FSL_SATA_P_HSTS_HS_ON, 0, 1000);
483 	/* Setup work areas */
484 	work = ch->dma.work_bus + FSL_SATA_CL_OFFSET;
485 	ATA_OUTL(ch->r_mem, FSL_SATA_P_CHBA, work);
486 	r &= ~FSL_SATA_P_HCTRL_ENT;
487 	r &= ~FSL_SATA_P_HCTRL_PM;
488 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HCTRL, r);
489 	r = ATA_INL(ch->r_mem, FSL_SATA_P_PCC);
490 	ATA_OUTL(ch->r_mem, FSL_SATA_P_PCC, r & ~FSL_SATA_PCC_LPB_EN);
491 	ATA_OUTL(ch->r_mem, FSL_SATA_P_ICC, (1 << FSL_SATA_P_ICC_ITC_S));
492 	fsl_sata_start(ch);
493 	return (0);
494 }
495 
496 static int
497 fsl_sata_deinit(device_t dev)
498 {
499 	struct fsl_sata_channel *ch = device_get_softc(dev);
500 	uint32_t r;
501 
502 	/* Disable port interrupts. */
503 	r = ATA_INL(ch->r_mem, FSL_SATA_P_HCTRL);
504 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HCTRL, r & ~FSL_SATA_P_HCTRL_INT_MASK);
505 	/* Reset command register. */
506 	fsl_sata_stop(ch);
507 	/* Allow everything, including partial and slumber modes. */
508 	ATA_OUTL(ch->r_mem, FSL_SATA_P_SCTL, 0);
509 	DELAY(100);
510 	/* Disable PHY. */
511 	ATA_OUTL(ch->r_mem, FSL_SATA_P_SCTL, ATA_SC_DET_DISABLE);
512 	r = ATA_INL(ch->r_mem, FSL_SATA_P_HCTRL);
513 	/* Turn off the controller. */
514 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HCTRL, r & ~FSL_SATA_P_HCTRL_HC_ON);
515 	return (0);
516 }
517 
518 static int
519 fsl_sata_suspend(device_t dev)
520 {
521 	struct fsl_sata_channel *ch = device_get_softc(dev);
522 
523 	mtx_lock(&ch->mtx);
524 	xpt_freeze_simq(ch->sim, 1);
525 	while (ch->oslots)
526 		msleep(ch, &ch->mtx, PRIBIO, "fsl_satasusp", hz/100);
527 	fsl_sata_deinit(dev);
528 	mtx_unlock(&ch->mtx);
529 	return (0);
530 }
531 
532 static int
533 fsl_sata_resume(device_t dev)
534 {
535 	struct fsl_sata_channel *ch = device_get_softc(dev);
536 
537 	mtx_lock(&ch->mtx);
538 	fsl_sata_init(dev);
539 	fsl_sata_reset(ch);
540 	xpt_release_simq(ch->sim, TRUE);
541 	mtx_unlock(&ch->mtx);
542 	return (0);
543 }
544 
545 static device_method_t fsl_satach_methods[] = {
546 	DEVMETHOD(device_probe,     fsl_sata_probe),
547 	DEVMETHOD(device_attach,    fsl_sata_attach),
548 	DEVMETHOD(device_detach,    fsl_sata_detach),
549 	DEVMETHOD(device_suspend,   fsl_sata_suspend),
550 	DEVMETHOD(device_resume,    fsl_sata_resume),
551 	DEVMETHOD_END
552 };
553 
554 static driver_t fsl_satach_driver = {
555 	"fslsata",
556 	fsl_satach_methods,
557 	sizeof(struct fsl_sata_channel)
558 };
559 
560 DRIVER_MODULE(fsl_satach, simplebus, fsl_satach_driver, NULL, NULL);
561 
562 struct fsl_sata_dc_cb_args {
563 	bus_addr_t maddr;
564 	int error;
565 };
566 
567 static void
568 fsl_sata_dmainit(device_t dev)
569 {
570 	struct fsl_sata_channel *ch = device_get_softc(dev);
571 	struct fsl_sata_dc_cb_args dcba;
572 
573 	/* Command area. */
574 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
575 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
576 	    NULL, NULL, FSL_SATA_WORK_SIZE, 1, FSL_SATA_WORK_SIZE,
577 	    0, NULL, NULL, &ch->dma.work_tag))
578 		goto error;
579 	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work,
580 	    BUS_DMA_ZERO, &ch->dma.work_map))
581 		goto error;
582 	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
583 	    FSL_SATA_WORK_SIZE, fsl_sata_dmasetupc_cb, &dcba, 0) || dcba.error) {
584 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
585 		goto error;
586 	}
587 	ch->dma.work_bus = dcba.maddr;
588 	/* Data area. */
589 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 4, 0,
590 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
591 	    NULL, NULL, FSL_SATA_MAX_XFER,
592 	    FSL_SATA_SG_ENTRIES - 1, FSL_SATA_PRD_MAX,
593 	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
594 		goto error;
595 	}
596 	if (bootverbose)
597 		device_printf(dev, "work area: %p\n", ch->dma.work);
598 	return;
599 
600 error:
601 	device_printf(dev, "WARNING - DMA initialization failed\n");
602 	fsl_sata_dmafini(dev);
603 }
604 
605 static void
606 fsl_sata_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
607 {
608 	struct fsl_sata_dc_cb_args *dcba = (struct fsl_sata_dc_cb_args *)xsc;
609 
610 	if (!(dcba->error = error))
611 		dcba->maddr = segs[0].ds_addr;
612 }
613 
614 static void
615 fsl_sata_dmafini(device_t dev)
616 {
617 	struct fsl_sata_channel *ch = device_get_softc(dev);
618 
619 	if (ch->dma.data_tag) {
620 		bus_dma_tag_destroy(ch->dma.data_tag);
621 		ch->dma.data_tag = NULL;
622 	}
623 	if (ch->dma.work_bus) {
624 		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
625 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
626 		ch->dma.work_bus = 0;
627 		ch->dma.work = NULL;
628 	}
629 	if (ch->dma.work_tag) {
630 		bus_dma_tag_destroy(ch->dma.work_tag);
631 		ch->dma.work_tag = NULL;
632 	}
633 }
634 
635 static void
636 fsl_sata_slotsalloc(device_t dev)
637 {
638 	struct fsl_sata_channel *ch = device_get_softc(dev);
639 	int i;
640 
641 	/* Alloc and setup command/dma slots */
642 	bzero(ch->slot, sizeof(ch->slot));
643 	for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
644 		struct fsl_sata_slot *slot = &ch->slot[i];
645 
646 		slot->ch = ch;
647 		slot->slot = i;
648 		slot->state = FSL_SATA_SLOT_EMPTY;
649 		slot->ccb = NULL;
650 		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
651 
652 		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
653 			device_printf(ch->dev, "FAILURE - create data_map\n");
654 	}
655 }
656 
657 static void
658 fsl_sata_slotsfree(device_t dev)
659 {
660 	struct fsl_sata_channel *ch = device_get_softc(dev);
661 	int i;
662 
663 	/* Free all dma slots */
664 	for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
665 		struct fsl_sata_slot *slot = &ch->slot[i];
666 
667 		callout_drain(&slot->timeout);
668 		if (slot->dma.data_map) {
669 			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
670 			slot->dma.data_map = NULL;
671 		}
672 	}
673 }
674 
675 static int
676 fsl_sata_phy_check_events(struct fsl_sata_channel *ch, u_int32_t serr)
677 {
678 
679 	if (((ch->pm_level == 0) && (serr & ATA_SE_PHY_CHANGED)) ||
680 	    ((ch->pm_level != 0) && (serr & ATA_SE_EXCHANGED))) {
681 		u_int32_t status = ATA_INL(ch->r_mem, FSL_SATA_P_SSTS);
682 		union ccb *ccb;
683 
684 		if (bootverbose) {
685 			if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
686 				device_printf(ch->dev, "CONNECT requested\n");
687 			else
688 				device_printf(ch->dev, "DISCONNECT requested\n");
689 		}
690 		/* Issue soft reset */
691 		xpt_async(AC_BUS_RESET, ch->path, NULL);
692 		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
693 			return (0);
694 		if (xpt_create_path(&ccb->ccb_h.path, NULL,
695 		    cam_sim_path(ch->sim),
696 		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
697 			xpt_free_ccb(ccb);
698 			return (0);
699 		}
700 		xpt_rescan(ccb);
701 		return (1);
702 	}
703 	return (0);
704 }
705 
706 static void
707 fsl_sata_notify_events(struct fsl_sata_channel *ch, u_int32_t status)
708 {
709 	struct cam_path *dpath;
710 	int i;
711 
712 	ATA_OUTL(ch->r_mem, FSL_SATA_P_SNTF, status);
713 	if (bootverbose)
714 		device_printf(ch->dev, "SNTF 0x%04x\n", status);
715 	for (i = 0; i < 16; i++) {
716 		if ((status & (1 << i)) == 0)
717 			continue;
718 		if (xpt_create_path(&dpath, NULL,
719 		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
720 			xpt_async(AC_SCSI_AEN, dpath, NULL);
721 			xpt_free_path(dpath);
722 		}
723 	}
724 }
725 
726 static void
727 fsl_sata_done(struct fsl_sata_channel *ch, union ccb *ccb)
728 {
729 
730 	mtx_assert(&ch->mtx, MA_OWNED);
731 	if ((ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0 ||
732 	    ch->batch == 0) {
733 		xpt_done(ccb);
734 		return;
735 	}
736 
737 	STAILQ_INSERT_TAIL(&ch->doneq, &ccb->ccb_h, sim_links.stqe);
738 }
739 
740 static void
741 fsl_sata_intr(void *arg)
742 {
743 	struct fsl_sata_channel *ch = (struct fsl_sata_channel *)arg;
744 	struct ccb_hdr *ccb_h;
745 	uint32_t istatus;
746 	STAILQ_HEAD(, ccb_hdr) tmp_doneq = STAILQ_HEAD_INITIALIZER(tmp_doneq);
747 
748 	/* Read interrupt statuses. */
749 	istatus = ATA_INL(ch->r_mem, FSL_SATA_P_HSTS) & 0x7ffff;
750 	if ((istatus & 0x3f) == 0)
751 		return;
752 
753 	mtx_lock(&ch->mtx);
754 	ch->batch = 1;
755 	fsl_sata_intr_main(ch, istatus);
756 	ch->batch = 0;
757 	/*
758 	 * Prevent the possibility of issues caused by processing the queue
759 	 * while unlocked below by moving the contents to a local queue.
760 	 */
761 	STAILQ_CONCAT(&tmp_doneq, &ch->doneq);
762 	mtx_unlock(&ch->mtx);
763 	while ((ccb_h = STAILQ_FIRST(&tmp_doneq)) != NULL) {
764 		STAILQ_REMOVE_HEAD(&tmp_doneq, sim_links.stqe);
765 		xpt_done_direct((union ccb *)ccb_h);
766 	}
767 	/* Clear interrupt statuses. */
768 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HSTS, istatus & 0x3f);
769 
770 }
771 
772 static void
773 fsl_sata_pm(void *arg)
774 {
775 	struct fsl_sata_channel *ch = (struct fsl_sata_channel *)arg;
776 	uint32_t work;
777 
778 	if (ch->numrslots != 0)
779 		return;
780 	work = ATA_INL(ch->r_mem, FSL_SATA_P_PCC) & ~FSL_SATA_PCC_LPB_EN;
781 	if (ch->pm_level == 4)
782 		work |= FSL_SATA_P_PCC_PARTIAL;
783 	else
784 		work |= FSL_SATA_P_PCC_SLUMBER;
785 	ATA_OUTL(ch->r_mem, FSL_SATA_P_PCC, work);
786 }
787 
788 /* XXX: interrupt todo */
789 static void
790 fsl_sata_intr_main(struct fsl_sata_channel *ch, uint32_t istatus)
791 {
792 	uint32_t cer, der, serr = 0, sntf = 0, ok, err;
793 	enum fsl_sata_err_type et;
794 	int i;
795 
796 	/* Complete all successful commands. */
797 	ok = ATA_INL(ch->r_mem, FSL_SATA_P_CCR);
798 	/* Mark all commands complete, to complete the interrupt. */
799 	ATA_OUTL(ch->r_mem, FSL_SATA_P_CCR, ok);
800 	if (ch->aslots == 0 && ok != 0) {
801 		for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
802 			if (((ok >> i) & 1) && ch->slot[i].ccb != NULL)
803 				fsl_sata_end_transaction(&ch->slot[i],
804 				    FSL_SATA_ERR_NONE);
805 		}
806 	}
807 	/* Read command statuses. */
808 	if (istatus & FSL_SATA_P_HSTS_SNTFU)
809 		sntf = ATA_INL(ch->r_mem, FSL_SATA_P_SNTF);
810 	/* XXX: Process PHY events */
811 	serr = ATA_INL(ch->r_mem, FSL_SATA_P_SERR);
812 	ATA_OUTL(ch->r_mem, FSL_SATA_P_SERR, serr);
813 	if (istatus & (FSL_SATA_P_HSTS_PR)) {
814 		if (serr) {
815 			fsl_sata_phy_check_events(ch, serr);
816 		}
817 	}
818 	/* Process command errors */
819 	err = (istatus & (FSL_SATA_P_HSTS_FE | FSL_SATA_P_HSTS_DE));
820 	cer = ATA_INL(ch->r_mem, FSL_SATA_P_CER);
821 	ATA_OUTL(ch->r_mem, FSL_SATA_P_CER, cer);
822 	der = ATA_INL(ch->r_mem, FSL_SATA_P_DER);
823 	ATA_OUTL(ch->r_mem, FSL_SATA_P_DER, der);
824 	/* On error, complete the rest of commands with error statuses. */
825 	if (err) {
826 		if (ch->frozen) {
827 			union ccb *fccb = ch->frozen;
828 			ch->frozen = NULL;
829 			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
830 			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
831 				xpt_freeze_devq(fccb->ccb_h.path, 1);
832 				fccb->ccb_h.status |= CAM_DEV_QFRZN;
833 			}
834 			fsl_sata_done(ch, fccb);
835 		}
836 		for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
837 			if (ch->slot[i].ccb == NULL)
838 				continue;
839 			if ((cer & (1 << i)) != 0)
840 				et = FSL_SATA_ERR_TFE;
841 			else if ((der & (1 << ch->slot[i].ccb->ccb_h.target_id)) != 0)
842 				et = FSL_SATA_ERR_SATA;
843 			else
844 				et = FSL_SATA_ERR_INVALID;
845 			fsl_sata_end_transaction(&ch->slot[i], et);
846 		}
847 	}
848 	/* Process NOTIFY events */
849 	if (sntf)
850 		fsl_sata_notify_events(ch, sntf);
851 }
852 
853 /* Must be called with channel locked. */
854 static int
855 fsl_sata_check_collision(struct fsl_sata_channel *ch, union ccb *ccb)
856 {
857 	int t = ccb->ccb_h.target_id;
858 
859 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
860 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
861 		/* Tagged command while we have no supported tag free. */
862 		if (((~ch->oslots) & (0xffff >> (16 - ch->curr[t].tags))) == 0)
863 			return (1);
864 		/* Tagged command while untagged are active. */
865 		if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] == 0)
866 			return (1);
867 	} else {
868 		/* Untagged command while tagged are active. */
869 		if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] != 0)
870 			return (1);
871 	}
872 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
873 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
874 		/* Atomic command while anything active. */
875 		if (ch->numrslots != 0)
876 			return (1);
877 	}
878 	/* We have some atomic command running. */
879 	if (ch->aslots != 0)
880 		return (1);
881 	return (0);
882 }
883 
884 /* Must be called with channel locked. */
885 static void
886 fsl_sata_begin_transaction(struct fsl_sata_channel *ch, union ccb *ccb)
887 {
888 	struct fsl_sata_slot *slot;
889 	int tag, tags;
890 
891 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
892 	    ("fsl_sata_begin_transaction func_code=0x%x\n", ccb->ccb_h.func_code));
893 	/* Choose empty slot. */
894 	tags = FSL_SATA_MAX_SLOTS;
895 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
896 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
897 		tags = ch->curr[ccb->ccb_h.target_id].tags;
898 	if (ch->lastslot + 1 < tags)
899 		tag = ffs(~(ch->oslots >> (ch->lastslot + 1)));
900 	else
901 		tag = 0;
902 	if (tag == 0 || tag + ch->lastslot >= tags)
903 		tag = ffs(~ch->oslots) - 1;
904 	else
905 		tag += ch->lastslot;
906 	ch->lastslot = tag;
907 	/* Occupy chosen slot. */
908 	slot = &ch->slot[tag];
909 	slot->ccb = ccb;
910 	slot->ttl = 0;
911 	/* Stop PM timer. */
912 	if (ch->numrslots == 0 && ch->pm_level > 3)
913 		callout_stop(&ch->pm_timer);
914 	/* Update channel stats. */
915 	ch->oslots |= (1 << tag);
916 	ch->numrslots++;
917 	ch->numrslotspd[ccb->ccb_h.target_id]++;
918 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
919 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
920 		ch->numtslots++;
921 		ch->numtslotspd[ccb->ccb_h.target_id]++;
922 		ch->taggedtarget = ccb->ccb_h.target_id;
923 	}
924 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
925 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
926 		ch->aslots |= (1 << tag);
927 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
928 		slot->state = FSL_SATA_SLOT_LOADING;
929 		bus_dmamap_load_ccb(ch->dma.data_tag, slot->dma.data_map, ccb,
930 		    fsl_sata_dmasetprd, slot, 0);
931 	} else {
932 		slot->dma.nsegs = 0;
933 		fsl_sata_execute_transaction(slot);
934 	}
935 
936 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
937 	    ("fsl_sata_begin_transaction exit\n"));
938 }
939 
940 /* Locked by busdma engine. */
941 static void
942 fsl_sata_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
943 {
944 	struct fsl_sata_slot *slot = arg;
945 	struct fsl_sata_channel *ch = slot->ch;
946 	struct fsl_sata_cmd_tab *ctp;
947 	struct fsl_sata_dma_prd *prd;
948 	int i, j, len, extlen;
949 
950 	if (error) {
951 		device_printf(ch->dev, "DMA load error %d\n", error);
952 		fsl_sata_end_transaction(slot, FSL_SATA_ERR_INVALID);
953 		return;
954 	}
955 	KASSERT(nsegs <= FSL_SATA_SG_ENTRIES - 1,
956 	    ("too many DMA segment entries\n"));
957 	/* Get a piece of the workspace for this request */
958 	ctp = FSL_SATA_CTP(ch, slot);
959 	/* Fill S/G table */
960 	prd = &ctp->prd_tab[0];
961 	for (i = 0, j = 0; i < nsegs; i++, j++) {
962 		if (j == FSL_SATA_PRD_EXT_INDEX &&
963 		    FSL_SATA_PRD_MAX_DIRECT < nsegs) {
964 			prd[j].dba = htole32(FSL_SATA_CTP_BUS(ch, slot) +
965 				     FSL_SATA_PRD_OFFSET(j+1));
966 			j++;
967 			extlen = 0;
968 		}
969 		len = segs[i].ds_len;
970 		len = roundup2(len, sizeof(uint32_t));
971 		prd[j].dba = htole32((uint32_t)segs[i].ds_addr);
972 		prd[j].dwc_flg = htole32(FSL_SATA_PRD_SNOOP | len);
973 		slot->ttl += len;
974 		if (j > FSL_SATA_PRD_MAX_DIRECT)
975 			extlen += len;
976 	}
977 	slot->dma.nsegs = j;
978 	if (j > FSL_SATA_PRD_MAX_DIRECT)
979 		prd[FSL_SATA_PRD_EXT_INDEX].dwc_flg =
980 		    htole32(FSL_SATA_PRD_SNOOP | FSL_SATA_PRD_EXT | extlen);
981 	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
982 	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
983 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
984 	fsl_sata_execute_transaction(slot);
985 }
986 
987 /* Must be called with channel locked. */
988 static void
989 fsl_sata_execute_transaction(struct fsl_sata_slot *slot)
990 {
991 	struct fsl_sata_channel *ch = slot->ch;
992 	struct fsl_sata_cmd_tab *ctp;
993 	struct fsl_sata_cmd_list *clp;
994 	union ccb *ccb = slot->ccb;
995 	int port = ccb->ccb_h.target_id & 0x0f;
996 	int fis_size, i, softreset;
997 	uint32_t tmp;
998 	uint32_t cmd_flags = FSL_SATA_CMD_WRITE | FSL_SATA_CMD_SNOOP;
999 
1000 	softreset = 0;
1001 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
1002 	    ("fsl_sata_execute_transaction func_code=0x%x\n", ccb->ccb_h.func_code));
1003 	/* Get a piece of the workspace for this request */
1004 	ctp = FSL_SATA_CTP(ch, slot);
1005 	/* Setup the FIS for this request */
1006 	if (!(fis_size = fsl_sata_setup_fis(ch, ctp, ccb, slot->slot))) {
1007 		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1008 		fsl_sata_end_transaction(slot, FSL_SATA_ERR_INVALID);
1009 		return;
1010 	}
1011 	/* Setup the command list entry */
1012 	clp = FSL_SATA_CLP(ch, slot);
1013 	clp->fis_length = htole16(fis_size);
1014 	clp->prd_length = htole16(slot->dma.nsegs);
1015 	/* Special handling for Soft Reset command. */
1016 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1017 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1018 		if (ccb->ataio.cmd.control & ATA_A_RESET) {
1019 			softreset = 1;
1020 			cmd_flags |= FSL_SATA_CMD_RESET;
1021 		} else {
1022 			/* Prepare FIS receive area for check. */
1023 			for (i = 0; i < 32; i++)
1024 				ctp->sfis[i] = 0xff;
1025 			softreset = 2;
1026 		}
1027 	}
1028 	if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)
1029 		cmd_flags |= FSL_SATA_CMD_QUEUED;
1030 	clp->cmd_flags = htole32(cmd_flags |
1031 	    (ccb->ccb_h.func_code == XPT_SCSI_IO ?  FSL_SATA_CMD_ATAPI : 0) |
1032 	    slot->slot);
1033 	clp->ttl = htole32(slot->ttl);
1034 	clp->cda = htole32(FSL_SATA_CTP_BUS(ch, slot));
1035 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1036 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1037 	/* Issue command to the controller. */
1038 	slot->state = FSL_SATA_SLOT_RUNNING;
1039 	ch->rslots |= (1 << slot->slot);
1040 	ATA_OUTL(ch->r_mem, FSL_SATA_P_CQPMP, port);
1041 	ATA_OUTL(ch->r_mem, FSL_SATA_P_CQR, (1 << slot->slot));
1042 	/* Device reset commands don't interrupt. Poll them. */
1043 	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1044 	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET || softreset)) {
1045 		int count, timeout = ccb->ccb_h.timeout * 100;
1046 		enum fsl_sata_err_type et = FSL_SATA_ERR_NONE;
1047 
1048 		for (count = 0; count < timeout; count++) {
1049 			DELAY(10);
1050 			tmp = 0;
1051 			if (softreset == 2) {
1052 				tmp = ATA_INL(ch->r_mem, FSL_SATA_P_SIG);
1053 				if (tmp != 0 && tmp != 0xffffffff)
1054 					break;
1055 				continue;
1056 			}
1057 			if ((ATA_INL(ch->r_mem, FSL_SATA_P_CCR) & (1 << slot->slot)) != 0)
1058 				break;
1059 		}
1060 
1061 		if (timeout && (count >= timeout)) {
1062 			device_printf(ch->dev, "Poll timeout on slot %d port %d (round %d)\n",
1063 			    slot->slot, port, softreset);
1064 			device_printf(ch->dev, "hsts %08x cqr %08x ccr %08x ss %08x "
1065 			    "rs %08x cer %08x der %08x serr %08x car %08x sig %08x\n",
1066 			    ATA_INL(ch->r_mem, FSL_SATA_P_HSTS),
1067 			    ATA_INL(ch->r_mem, FSL_SATA_P_CQR),
1068 			    ATA_INL(ch->r_mem, FSL_SATA_P_CCR),
1069 			    ATA_INL(ch->r_mem, FSL_SATA_P_SSTS), ch->rslots,
1070 			    ATA_INL(ch->r_mem, FSL_SATA_P_CER),
1071 			    ATA_INL(ch->r_mem, FSL_SATA_P_DER),
1072 			    ATA_INL(ch->r_mem, FSL_SATA_P_SERR),
1073 			    ATA_INL(ch->r_mem, FSL_SATA_P_CAR),
1074 			    ATA_INL(ch->r_mem, FSL_SATA_P_SIG));
1075 			et = FSL_SATA_ERR_TIMEOUT;
1076 		}
1077 
1078 		fsl_sata_end_transaction(slot, et);
1079 		return;
1080 	}
1081 	/* Start command execution timeout */
1082 	callout_reset_sbt(&slot->timeout, SBT_1MS * ccb->ccb_h.timeout / 2,
1083 	    0, fsl_sata_timeout, slot, 0);
1084 	return;
1085 }
1086 
1087 /* Must be called with channel locked. */
1088 static void
1089 fsl_sata_process_timeout(struct fsl_sata_channel *ch)
1090 {
1091 	int i;
1092 
1093 	mtx_assert(&ch->mtx, MA_OWNED);
1094 	/* Handle the rest of commands. */
1095 	for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
1096 		/* Do we have a running request on slot? */
1097 		if (ch->slot[i].state < FSL_SATA_SLOT_RUNNING)
1098 			continue;
1099 		fsl_sata_end_transaction(&ch->slot[i], FSL_SATA_ERR_TIMEOUT);
1100 	}
1101 }
1102 
1103 /* Must be called with channel locked. */
1104 static void
1105 fsl_sata_rearm_timeout(struct fsl_sata_channel *ch)
1106 {
1107 	int i;
1108 
1109 	mtx_assert(&ch->mtx, MA_OWNED);
1110 	for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
1111 		struct fsl_sata_slot *slot = &ch->slot[i];
1112 
1113 		/* Do we have a running request on slot? */
1114 		if (slot->state < FSL_SATA_SLOT_RUNNING)
1115 			continue;
1116 		if ((ch->toslots & (1 << i)) == 0)
1117 			continue;
1118 		callout_reset_sbt(&slot->timeout,
1119  	    	    SBT_1MS * slot->ccb->ccb_h.timeout / 2, 0,
1120 		    fsl_sata_timeout, slot, 0);
1121 	}
1122 }
1123 
1124 /* Locked by callout mechanism. */
1125 static void
1126 fsl_sata_timeout(void *arg)
1127 {
1128 	struct fsl_sata_slot *slot = arg;
1129 	struct fsl_sata_channel *ch = slot->ch;
1130 	device_t dev = ch->dev;
1131 	uint32_t sstatus;
1132 
1133 	/* Check for stale timeout. */
1134 	if (slot->state < FSL_SATA_SLOT_RUNNING)
1135 		return;
1136 
1137 	/* Check if slot was not being executed last time we checked. */
1138 	if (slot->state < FSL_SATA_SLOT_EXECUTING) {
1139 		/* Check if slot started executing. */
1140 		sstatus = ATA_INL(ch->r_mem, FSL_SATA_P_CAR);
1141 		if ((sstatus & (1 << slot->slot)) != 0)
1142 			slot->state = FSL_SATA_SLOT_EXECUTING;
1143 
1144 		callout_reset_sbt(&slot->timeout,
1145 	    	    SBT_1MS * slot->ccb->ccb_h.timeout / 2, 0,
1146 		    fsl_sata_timeout, slot, 0);
1147 		return;
1148 	}
1149 
1150 	device_printf(dev, "Timeout on slot %d port %d\n",
1151 	    slot->slot, slot->ccb->ccb_h.target_id & 0x0f);
1152 
1153 	/* Handle frozen command. */
1154 	if (ch->frozen) {
1155 		union ccb *fccb = ch->frozen;
1156 		ch->frozen = NULL;
1157 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1158 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1159 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1160 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1161 		}
1162 		fsl_sata_done(ch, fccb);
1163 	}
1164 	if (ch->toslots == 0)
1165 		xpt_freeze_simq(ch->sim, 1);
1166 	ch->toslots |= (1 << slot->slot);
1167 	if ((ch->rslots & ~ch->toslots) == 0)
1168 		fsl_sata_process_timeout(ch);
1169 	else
1170 		device_printf(dev, " ... waiting for slots %08x\n",
1171 		    ch->rslots & ~ch->toslots);
1172 }
1173 
1174 /* Must be called with channel locked. */
1175 static void
1176 fsl_sata_end_transaction(struct fsl_sata_slot *slot, enum fsl_sata_err_type et)
1177 {
1178 	struct fsl_sata_channel *ch = slot->ch;
1179 	union ccb *ccb = slot->ccb;
1180 	struct fsl_sata_cmd_list *clp;
1181 	int lastto;
1182 	uint32_t sig;
1183 
1184 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1185 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1186 	clp = FSL_SATA_CLP(ch, slot);
1187 	/* Read result registers to the result struct */
1188 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1189 		struct ata_res *res = &ccb->ataio.res;
1190 
1191 		if ((et == FSL_SATA_ERR_TFE) ||
1192 		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1193 			struct fsl_sata_cmd_tab *ctp = FSL_SATA_CTP(ch, slot);
1194 			uint8_t *fis = ctp->sfis;
1195 
1196 			res->status = fis[2];
1197 			res->error = fis[3];
1198 			res->lba_low = fis[4];
1199 			res->lba_mid = fis[5];
1200 			res->lba_high = fis[6];
1201 			res->device = fis[7];
1202 			res->lba_low_exp = fis[8];
1203 			res->lba_mid_exp = fis[9];
1204 			res->lba_high_exp = fis[10];
1205 			res->sector_count = fis[12];
1206 			res->sector_count_exp = fis[13];
1207 
1208 			if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1209 			    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
1210 				sig = ATA_INL(ch->r_mem,  FSL_SATA_P_SIG);
1211 				res->lba_high = sig >> 24;
1212 				res->lba_mid = sig >> 16;
1213 				res->lba_low = sig >> 8;
1214 				res->sector_count = sig;
1215 			}
1216 		} else
1217 			bzero(res, sizeof(*res));
1218 		if ((ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) == 0 &&
1219 		    (ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1220 			ccb->ataio.resid =
1221 			    ccb->ataio.dxfer_len - le32toh(clp->ttl);
1222 		}
1223 	} else {
1224 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1225 			ccb->csio.resid =
1226 			    ccb->csio.dxfer_len - le32toh(clp->ttl);
1227 		}
1228 	}
1229 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1230 		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1231 		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1232 		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1233 		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1234 	}
1235 	if (et != FSL_SATA_ERR_NONE)
1236 		ch->eslots |= (1 << slot->slot);
1237 	/* In case of error, freeze device for proper recovery. */
1238 	if ((et != FSL_SATA_ERR_NONE) && (!ch->recoverycmd) &&
1239 	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1240 		xpt_freeze_devq(ccb->ccb_h.path, 1);
1241 		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1242 	}
1243 	/* Set proper result status. */
1244 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1245 	switch (et) {
1246 	case FSL_SATA_ERR_NONE:
1247 		ccb->ccb_h.status |= CAM_REQ_CMP;
1248 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1249 			ccb->csio.scsi_status = SCSI_STATUS_OK;
1250 		break;
1251 	case FSL_SATA_ERR_INVALID:
1252 		ch->fatalerr = 1;
1253 		ccb->ccb_h.status |= CAM_REQ_INVALID;
1254 		break;
1255 	case FSL_SATA_ERR_INNOCENT:
1256 		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1257 		break;
1258 	case FSL_SATA_ERR_TFE:
1259 	case FSL_SATA_ERR_NCQ:
1260 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1261 			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1262 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1263 		} else {
1264 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1265 		}
1266 		break;
1267 	case FSL_SATA_ERR_SATA:
1268 		ch->fatalerr = 1;
1269 		if (!ch->recoverycmd) {
1270 			xpt_freeze_simq(ch->sim, 1);
1271 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1272 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1273 		}
1274 		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1275 		break;
1276 	case FSL_SATA_ERR_TIMEOUT:
1277 		if (!ch->recoverycmd) {
1278 			xpt_freeze_simq(ch->sim, 1);
1279 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1280 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1281 		}
1282 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1283 		break;
1284 	default:
1285 		ch->fatalerr = 1;
1286 		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1287 	}
1288 	/* Free slot. */
1289 	ch->oslots &= ~(1 << slot->slot);
1290 	ch->rslots &= ~(1 << slot->slot);
1291 	ch->aslots &= ~(1 << slot->slot);
1292 	slot->state = FSL_SATA_SLOT_EMPTY;
1293 	slot->ccb = NULL;
1294 	/* Update channel stats. */
1295 	ch->numrslots--;
1296 	ch->numrslotspd[ccb->ccb_h.target_id]--;
1297 	ATA_OUTL(ch->r_mem, FSL_SATA_P_CCR, 1 << slot->slot);
1298 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1299 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1300 		ch->numtslots--;
1301 		ch->numtslotspd[ccb->ccb_h.target_id]--;
1302 	}
1303 	/* Cancel timeout state if request completed normally. */
1304 	if (et != FSL_SATA_ERR_TIMEOUT) {
1305 		lastto = (ch->toslots == (1 << slot->slot));
1306 		ch->toslots &= ~(1 << slot->slot);
1307 		if (lastto)
1308 			xpt_release_simq(ch->sim, TRUE);
1309 	}
1310 	/* If it was first request of reset sequence and there is no error,
1311 	 * proceed to second request. */
1312 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1313 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1314 	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
1315 	    et == FSL_SATA_ERR_NONE) {
1316 		ccb->ataio.cmd.control &= ~ATA_A_RESET;
1317 		fsl_sata_begin_transaction(ch, ccb);
1318 		return;
1319 	}
1320 	/* If it was our READ LOG command - process it. */
1321 	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
1322 		fsl_sata_process_read_log(ch, ccb);
1323 	/* If it was our REQUEST SENSE command - process it. */
1324 	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
1325 		fsl_sata_process_request_sense(ch, ccb);
1326 	/* If it was NCQ or ATAPI command error, put result on hold. */
1327 	} else if (et == FSL_SATA_ERR_NCQ ||
1328 	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
1329 	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
1330 		ch->hold[slot->slot] = ccb;
1331 		ch->numhslots++;
1332 	} else
1333 		fsl_sata_done(ch, ccb);
1334 	/* If we have no other active commands, ... */
1335 	if (ch->rslots == 0) {
1336 		/* if there was fatal error - reset port. */
1337 		if (ch->toslots != 0 || ch->fatalerr) {
1338 			fsl_sata_reset(ch);
1339 		} else {
1340 			/* if we have slots in error, we can reinit port. */
1341 			if (ch->eslots != 0) {
1342 				fsl_sata_stop(ch);
1343 				fsl_sata_start(ch);
1344 			}
1345 			/* if there commands on hold, we can do READ LOG. */
1346 			if (!ch->recoverycmd && ch->numhslots)
1347 				fsl_sata_issue_recovery(ch);
1348 		}
1349 	/* If all the rest of commands are in timeout - give them chance. */
1350 	} else if ((ch->rslots & ~ch->toslots) == 0 &&
1351 	    et != FSL_SATA_ERR_TIMEOUT)
1352 		fsl_sata_rearm_timeout(ch);
1353 	/* Unfreeze frozen command. */
1354 	if (ch->frozen && !fsl_sata_check_collision(ch, ch->frozen)) {
1355 		union ccb *fccb = ch->frozen;
1356 		ch->frozen = NULL;
1357 		fsl_sata_begin_transaction(ch, fccb);
1358 		xpt_release_simq(ch->sim, TRUE);
1359 	}
1360 	/* Start PM timer. */
1361 	if (ch->numrslots == 0 && ch->pm_level > 3 &&
1362 	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
1363 		callout_schedule(&ch->pm_timer,
1364 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1365 	}
1366 }
1367 
1368 static void
1369 fsl_sata_issue_recovery(struct fsl_sata_channel *ch)
1370 {
1371 	union ccb *ccb;
1372 	struct ccb_ataio *ataio;
1373 	struct ccb_scsiio *csio;
1374 	int i;
1375 
1376 	/* Find some held command. */
1377 	for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
1378 		if (ch->hold[i])
1379 			break;
1380 	}
1381 	ccb = xpt_alloc_ccb_nowait();
1382 	if (ccb == NULL) {
1383 		device_printf(ch->dev, "Unable to allocate recovery command\n");
1384 completeall:
1385 		/* We can't do anything -- complete held commands. */
1386 		for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
1387 			if (ch->hold[i] == NULL)
1388 				continue;
1389 			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1390 			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
1391 			fsl_sata_done(ch, ch->hold[i]);
1392 			ch->hold[i] = NULL;
1393 			ch->numhslots--;
1394 		}
1395 		fsl_sata_reset(ch);
1396 		return;
1397 	}
1398 	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1399 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1400 		/* READ LOG */
1401 		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
1402 		ccb->ccb_h.func_code = XPT_ATA_IO;
1403 		ccb->ccb_h.flags = CAM_DIR_IN;
1404 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1405 		ataio = &ccb->ataio;
1406 		ataio->data_ptr = malloc(512, M_FSL_SATA, M_NOWAIT);
1407 		if (ataio->data_ptr == NULL) {
1408 			xpt_free_ccb(ccb);
1409 			device_printf(ch->dev,
1410 			    "Unable to allocate memory for READ LOG command\n");
1411 			goto completeall;
1412 		}
1413 		ataio->dxfer_len = 512;
1414 		bzero(&ataio->cmd, sizeof(ataio->cmd));
1415 		ataio->cmd.flags = CAM_ATAIO_48BIT;
1416 		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1417 		ataio->cmd.sector_count = 1;
1418 		ataio->cmd.sector_count_exp = 0;
1419 		ataio->cmd.lba_low = 0x10;
1420 		ataio->cmd.lba_mid = 0;
1421 		ataio->cmd.lba_mid_exp = 0;
1422 	} else {
1423 		/* REQUEST SENSE */
1424 		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
1425 		ccb->ccb_h.recovery_slot = i;
1426 		ccb->ccb_h.func_code = XPT_SCSI_IO;
1427 		ccb->ccb_h.flags = CAM_DIR_IN;
1428 		ccb->ccb_h.status = 0;
1429 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1430 		csio = &ccb->csio;
1431 		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
1432 		csio->dxfer_len = ch->hold[i]->csio.sense_len;
1433 		csio->cdb_len = 6;
1434 		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
1435 		csio->cdb_io.cdb_bytes[0] = 0x03;
1436 		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
1437 	}
1438 	/* Freeze SIM while doing recovery. */
1439 	ch->recoverycmd = 1;
1440 	xpt_freeze_simq(ch->sim, 1);
1441 	fsl_sata_begin_transaction(ch, ccb);
1442 }
1443 
1444 static void
1445 fsl_sata_process_read_log(struct fsl_sata_channel *ch, union ccb *ccb)
1446 {
1447 	uint8_t *data;
1448 	struct ata_res *res;
1449 	int i;
1450 
1451 	ch->recoverycmd = 0;
1452 
1453 	data = ccb->ataio.data_ptr;
1454 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1455 	    (data[0] & 0x80) == 0) {
1456 		for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
1457 			if (!ch->hold[i])
1458 				continue;
1459 			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
1460 				continue;
1461 			if ((data[0] & 0x1F) == i) {
1462 				res = &ch->hold[i]->ataio.res;
1463 				res->status = data[2];
1464 				res->error = data[3];
1465 				res->lba_low = data[4];
1466 				res->lba_mid = data[5];
1467 				res->lba_high = data[6];
1468 				res->device = data[7];
1469 				res->lba_low_exp = data[8];
1470 				res->lba_mid_exp = data[9];
1471 				res->lba_high_exp = data[10];
1472 				res->sector_count = data[12];
1473 				res->sector_count_exp = data[13];
1474 			} else {
1475 				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1476 				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1477 			}
1478 			fsl_sata_done(ch, ch->hold[i]);
1479 			ch->hold[i] = NULL;
1480 			ch->numhslots--;
1481 		}
1482 	} else {
1483 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1484 			device_printf(ch->dev, "Error while READ LOG EXT\n");
1485 		else if ((data[0] & 0x80) == 0) {
1486 			device_printf(ch->dev, "Non-queued command error in READ LOG EXT\n");
1487 		}
1488 		for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
1489 			if (!ch->hold[i])
1490 				continue;
1491 			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
1492 				continue;
1493 			fsl_sata_done(ch, ch->hold[i]);
1494 			ch->hold[i] = NULL;
1495 			ch->numhslots--;
1496 		}
1497 	}
1498 	free(ccb->ataio.data_ptr, M_FSL_SATA);
1499 	xpt_free_ccb(ccb);
1500 	xpt_release_simq(ch->sim, TRUE);
1501 }
1502 
1503 static void
1504 fsl_sata_process_request_sense(struct fsl_sata_channel *ch, union ccb *ccb)
1505 {
1506 	int i;
1507 
1508 	ch->recoverycmd = 0;
1509 
1510 	i = ccb->ccb_h.recovery_slot;
1511 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1512 		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
1513 	} else {
1514 		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1515 		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
1516 	}
1517 	fsl_sata_done(ch, ch->hold[i]);
1518 	ch->hold[i] = NULL;
1519 	ch->numhslots--;
1520 	xpt_free_ccb(ccb);
1521 	xpt_release_simq(ch->sim, TRUE);
1522 }
1523 
1524 static void
1525 fsl_sata_start(struct fsl_sata_channel *ch)
1526 {
1527 	u_int32_t cmd;
1528 
1529 	/* Clear SATA error register */
1530 	ATA_OUTL(ch->r_mem, FSL_SATA_P_SERR, 0xFFFFFFFF);
1531 	/* Clear any interrupts pending on this channel */
1532 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HSTS, 0x3F);
1533 	ATA_OUTL(ch->r_mem, FSL_SATA_P_CER, 0xFFFF);
1534 	ATA_OUTL(ch->r_mem, FSL_SATA_P_DER, 0xFFFF);
1535 	/* Start operations on this channel */
1536 	cmd = ATA_INL(ch->r_mem, FSL_SATA_P_HCTRL);
1537 	cmd |= FSL_SATA_P_HCTRL_HC_ON | FSL_SATA_P_HCTRL_SNOOP;
1538 	cmd &= ~FSL_SATA_P_HCTRL_HC_FORCE_OFF;
1539 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HCTRL, cmd |
1540 	    (ch->pm_present ? FSL_SATA_P_HCTRL_PM : 0));
1541 	fsl_sata_wait_register(ch, FSL_SATA_P_HSTS,
1542 	    FSL_SATA_P_HSTS_PR, FSL_SATA_P_HSTS_PR, 500);
1543 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HSTS,
1544 	    ATA_INL(ch->r_mem, FSL_SATA_P_HSTS) & FSL_SATA_P_HSTS_PR);
1545 }
1546 
1547 static void
1548 fsl_sata_stop(struct fsl_sata_channel *ch)
1549 {
1550 	uint32_t cmd;
1551 	int i;
1552 
1553 	/* Kill all activity on this channel */
1554 	cmd = ATA_INL(ch->r_mem, FSL_SATA_P_HCTRL);
1555 	cmd &= ~FSL_SATA_P_HCTRL_HC_ON;
1556 
1557 	for (i = 0; i < 2; i++) {
1558 		ATA_OUTL(ch->r_mem, FSL_SATA_P_HCTRL, cmd);
1559 		if (fsl_sata_wait_register(ch, FSL_SATA_P_HSTS,
1560 		    FSL_SATA_P_HSTS_HS_ON, 0, 500)) {
1561 			if (i != 0)
1562 				device_printf(ch->dev,
1563 				    "stopping FSL SATA engine failed\n");
1564 			cmd |= FSL_SATA_P_HCTRL_HC_FORCE_OFF;
1565 		} else
1566 			break;
1567 	}
1568 	ch->eslots = 0;
1569 }
1570 
1571 static void
1572 fsl_sata_reset(struct fsl_sata_channel *ch)
1573 {
1574 	uint32_t ctrl;
1575 	int i;
1576 
1577 	xpt_freeze_simq(ch->sim, 1);
1578 	if (bootverbose)
1579 		device_printf(ch->dev, "FSL SATA reset...\n");
1580 
1581 	/* Requeue freezed command. */
1582 	if (ch->frozen) {
1583 		union ccb *fccb = ch->frozen;
1584 		ch->frozen = NULL;
1585 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1586 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1587 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1588 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1589 		}
1590 		fsl_sata_done(ch, fccb);
1591 	}
1592 	/* Kill the engine and requeue all running commands. */
1593 	fsl_sata_stop(ch);
1594 	DELAY(1000);	/* sleep for 1ms */
1595 	for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
1596 		/* Do we have a running request on slot? */
1597 		if (ch->slot[i].state < FSL_SATA_SLOT_RUNNING)
1598 			continue;
1599 		/* XXX; Commands in loading state. */
1600 		fsl_sata_end_transaction(&ch->slot[i], FSL_SATA_ERR_INNOCENT);
1601 	}
1602 	for (i = 0; i < FSL_SATA_MAX_SLOTS; i++) {
1603 		if (!ch->hold[i])
1604 			continue;
1605 		fsl_sata_done(ch, ch->hold[i]);
1606 		ch->hold[i] = NULL;
1607 		ch->numhslots--;
1608 	}
1609 	if (ch->toslots != 0)
1610 		xpt_release_simq(ch->sim, TRUE);
1611 	ch->eslots = 0;
1612 	ch->toslots = 0;
1613 	ch->fatalerr = 0;
1614 	/* Tell the XPT about the event */
1615 	xpt_async(AC_BUS_RESET, ch->path, NULL);
1616 	/* Disable port interrupts */
1617 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HCTRL,
1618 	    ATA_INL(ch->r_mem, FSL_SATA_P_HCTRL) & ~0x3f);
1619 	/* Reset and reconnect PHY, */
1620 	fsl_sata_start(ch);
1621 	if (fsl_sata_wait_register(ch, FSL_SATA_P_HSTS, 0x08, 0x08, 500)) {
1622 		if (bootverbose)
1623 			device_printf(ch->dev,
1624 			    "FSL SATA reset: device not found\n");
1625 		ch->devices = 0;
1626 		/* Enable wanted port interrupts */
1627 		ATA_OUTL(ch->r_mem, FSL_SATA_P_HCTRL,
1628 		    ATA_INL(ch->r_mem, FSL_SATA_P_HCTRL) | FSL_SATA_P_HCTRL_PHYRDY);
1629 		xpt_release_simq(ch->sim, TRUE);
1630 		return;
1631 	}
1632 	if (bootverbose)
1633 		device_printf(ch->dev, "FSL SATA reset: device found\n");
1634 	ch->devices = 1;
1635 	/* Enable wanted port interrupts */
1636 	ctrl = ATA_INL(ch->r_mem, FSL_SATA_P_HCTRL) & ~0x3f;
1637 	ATA_OUTL(ch->r_mem, FSL_SATA_P_HCTRL,
1638 	    ctrl | FSL_SATA_P_HCTRL_FATAL | FSL_SATA_P_HCTRL_PHYRDY |
1639 	    FSL_SATA_P_HCTRL_SIG | FSL_SATA_P_HCTRL_SNTFY |
1640 	    FSL_SATA_P_HCTRL_DE | FSL_SATA_P_HCTRL_CC);
1641 	xpt_release_simq(ch->sim, TRUE);
1642 }
1643 
1644 static int
1645 fsl_sata_setup_fis(struct fsl_sata_channel *ch, struct fsl_sata_cmd_tab *ctp, union ccb *ccb, int tag)
1646 {
1647 	uint8_t *fis = &ctp->cfis[0];
1648 
1649 	bzero(fis, 32);
1650 	fis[0] = 0x27;  		/* host to device */
1651 	fis[1] = (ccb->ccb_h.target_id & 0x0f);
1652 	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1653 		fis[1] |= 0x80;
1654 		fis[2] = ATA_PACKET_CMD;
1655 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1656 		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
1657 			fis[3] = ATA_F_DMA;
1658 		else {
1659 			fis[5] = ccb->csio.dxfer_len;
1660 			fis[6] = ccb->csio.dxfer_len >> 8;
1661 		}
1662 		fis[7] = ATA_D_LBA;
1663 		fis[15] = ATA_A_4BIT;
1664 		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1665 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
1666 		    ctp->acmd, ccb->csio.cdb_len);
1667 		bzero(ctp->acmd + ccb->csio.cdb_len, 32 - ccb->csio.cdb_len);
1668 	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
1669 		fis[1] |= 0x80;
1670 		fis[2] = ccb->ataio.cmd.command;
1671 		fis[3] = ccb->ataio.cmd.features;
1672 		fis[4] = ccb->ataio.cmd.lba_low;
1673 		fis[5] = ccb->ataio.cmd.lba_mid;
1674 		fis[6] = ccb->ataio.cmd.lba_high;
1675 		fis[7] = ccb->ataio.cmd.device;
1676 		fis[8] = ccb->ataio.cmd.lba_low_exp;
1677 		fis[9] = ccb->ataio.cmd.lba_mid_exp;
1678 		fis[10] = ccb->ataio.cmd.lba_high_exp;
1679 		fis[11] = ccb->ataio.cmd.features_exp;
1680 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1681 			fis[12] = tag << 3;
1682 			fis[13] = 0;
1683 		} else {
1684 			fis[12] = ccb->ataio.cmd.sector_count;
1685 			fis[13] = ccb->ataio.cmd.sector_count_exp;
1686 		}
1687 		fis[15] = ATA_A_4BIT;
1688 	} else {
1689 		fis[15] = ccb->ataio.cmd.control;
1690 	}
1691 	return (20);
1692 }
1693 
1694 static int
1695 fsl_sata_check_ids(struct fsl_sata_channel *ch, union ccb *ccb)
1696 {
1697 
1698 	if (ccb->ccb_h.target_id > 15) {
1699 		ccb->ccb_h.status = CAM_TID_INVALID;
1700 		fsl_sata_done(ch, ccb);
1701 		return (-1);
1702 	}
1703 	if (ccb->ccb_h.target_lun != 0) {
1704 		ccb->ccb_h.status = CAM_LUN_INVALID;
1705 		fsl_sata_done(ch, ccb);
1706 		return (-1);
1707 	}
1708 	return (0);
1709 }
1710 
1711 static void
1712 fsl_sataaction(struct cam_sim *sim, union ccb *ccb)
1713 {
1714 	struct fsl_sata_channel *ch;
1715 
1716 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
1717 	    ("fsl_sataaction func_code=0x%x\n", ccb->ccb_h.func_code));
1718 
1719 	ch = (struct fsl_sata_channel *)cam_sim_softc(sim);
1720 	switch (ccb->ccb_h.func_code) {
1721 	/* Common cases first */
1722 	case XPT_ATA_IO:	/* Execute the requested I/O operation */
1723 	case XPT_SCSI_IO:
1724 		if (fsl_sata_check_ids(ch, ccb))
1725 			return;
1726 		if (ch->devices == 0 ||
1727 		    (ch->pm_present == 0 &&
1728 		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
1729 			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
1730 			break;
1731 		}
1732 		ccb->ccb_h.recovery_type = RECOVERY_NONE;
1733 		/* Check for command collision. */
1734 		if (fsl_sata_check_collision(ch, ccb)) {
1735 			/* Freeze command. */
1736 			ch->frozen = ccb;
1737 			/* We have only one frozen slot, so freeze simq also. */
1738 			xpt_freeze_simq(ch->sim, 1);
1739 			return;
1740 		}
1741 		fsl_sata_begin_transaction(ch, ccb);
1742 		return;
1743 	case XPT_ABORT:			/* Abort the specified CCB */
1744 		/* XXX Implement */
1745 		ccb->ccb_h.status = CAM_REQ_INVALID;
1746 		break;
1747 	case XPT_SET_TRAN_SETTINGS:
1748 	{
1749 		struct	ccb_trans_settings *cts = &ccb->cts;
1750 		struct	fsl_sata_device *d;
1751 
1752 		if (fsl_sata_check_ids(ch, ccb))
1753 			return;
1754 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
1755 			d = &ch->curr[ccb->ccb_h.target_id];
1756 		else
1757 			d = &ch->user[ccb->ccb_h.target_id];
1758 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
1759 			d->revision = cts->xport_specific.sata.revision;
1760 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
1761 			d->mode = cts->xport_specific.sata.mode;
1762 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
1763 			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
1764 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
1765 			d->tags = min(FSL_SATA_MAX_SLOTS, cts->xport_specific.sata.tags);
1766 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
1767 			ch->pm_present = cts->xport_specific.sata.pm_present;
1768 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
1769 			d->atapi = cts->xport_specific.sata.atapi;
1770 		ccb->ccb_h.status = CAM_REQ_CMP;
1771 		break;
1772 	}
1773 	case XPT_GET_TRAN_SETTINGS:
1774 	/* Get default/user set transfer settings for the target */
1775 	{
1776 		struct	ccb_trans_settings *cts = &ccb->cts;
1777 		struct  fsl_sata_device *d;
1778 		uint32_t status;
1779 
1780 		if (fsl_sata_check_ids(ch, ccb))
1781 			return;
1782 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
1783 			d = &ch->curr[ccb->ccb_h.target_id];
1784 		else
1785 			d = &ch->user[ccb->ccb_h.target_id];
1786 		cts->protocol = PROTO_UNSPECIFIED;
1787 		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
1788 		cts->transport = XPORT_SATA;
1789 		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
1790 		cts->proto_specific.valid = 0;
1791 		cts->xport_specific.sata.valid = 0;
1792 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
1793 		    (ccb->ccb_h.target_id == 15 ||
1794 		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
1795 			status = ATA_INL(ch->r_mem, FSL_SATA_P_SSTS) & ATA_SS_SPD_MASK;
1796 			if (status & 0x0f0) {
1797 				cts->xport_specific.sata.revision =
1798 				    (status & 0x0f0) >> 4;
1799 				cts->xport_specific.sata.valid |=
1800 				    CTS_SATA_VALID_REVISION;
1801 			}
1802 			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
1803 			if (ch->pm_level) {
1804 				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
1805 			}
1806 			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
1807 			cts->xport_specific.sata.caps &=
1808 			    ch->user[ccb->ccb_h.target_id].caps;
1809 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
1810 		} else {
1811 			cts->xport_specific.sata.revision = d->revision;
1812 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
1813 			cts->xport_specific.sata.caps = d->caps;
1814 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
1815 		}
1816 		cts->xport_specific.sata.mode = d->mode;
1817 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
1818 		cts->xport_specific.sata.bytecount = d->bytecount;
1819 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
1820 		cts->xport_specific.sata.pm_present = ch->pm_present;
1821 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
1822 		cts->xport_specific.sata.tags = d->tags;
1823 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
1824 		cts->xport_specific.sata.atapi = d->atapi;
1825 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
1826 		ccb->ccb_h.status = CAM_REQ_CMP;
1827 		break;
1828 	}
1829 	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
1830 	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
1831 		fsl_sata_reset(ch);
1832 		ccb->ccb_h.status = CAM_REQ_CMP;
1833 		break;
1834 	case XPT_TERM_IO:		/* Terminate the I/O process */
1835 		/* XXX Implement */
1836 		ccb->ccb_h.status = CAM_REQ_INVALID;
1837 		break;
1838 	case XPT_PATH_INQ:		/* Path routing inquiry */
1839 	{
1840 		struct ccb_pathinq *cpi = &ccb->cpi;
1841 
1842 		cpi->version_num = 1; /* XXX??? */
1843 		cpi->hba_inquiry = PI_SDTR_ABLE;
1844 		cpi->hba_inquiry |= PI_TAG_ABLE;
1845 #if 0
1846 		/*
1847 		 * XXX: CAM tries to reset port 15 if it sees port multiplier
1848 		 * support.  Disable it for now.
1849 		 */
1850 		cpi->hba_inquiry |= PI_SATAPM;
1851 #endif
1852 		cpi->target_sprt = 0;
1853 		cpi->hba_misc = PIM_SEQSCAN | PIM_UNMAPPED;
1854 		cpi->hba_eng_cnt = 0;
1855 		/*
1856 		 * XXX: This should be 15, since hardware *does* support a port
1857 		 * multiplier.  See above.
1858 		 */
1859 		cpi->max_target = 0;
1860 		cpi->max_lun = 0;
1861 		cpi->initiator_id = 0;
1862 		cpi->bus_id = cam_sim_bus(sim);
1863 		cpi->base_transfer_speed = 150000;
1864 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1865 		strncpy(cpi->hba_vid, "FSL SATA", HBA_IDLEN);
1866 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1867 		cpi->unit_number = cam_sim_unit(sim);
1868 		cpi->transport = XPORT_SATA;
1869 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
1870 		cpi->protocol = PROTO_ATA;
1871 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
1872 		cpi->maxio = (FSL_SATA_SG_ENTRIES - 1) * PAGE_SIZE;
1873 		cpi->ccb_h.status = CAM_REQ_CMP;
1874 		break;
1875 	}
1876 	default:
1877 		ccb->ccb_h.status = CAM_REQ_INVALID;
1878 		break;
1879 	}
1880 	fsl_sata_done(ch, ccb);
1881 }
1882 
1883 static void
1884 fsl_satapoll(struct cam_sim *sim)
1885 {
1886 	struct fsl_sata_channel *ch = (struct fsl_sata_channel *)cam_sim_softc(sim);
1887 	uint32_t istatus;
1888 
1889 	/* Read interrupt statuses and process if any. */
1890 	istatus = ATA_INL(ch->r_mem, FSL_SATA_P_HSTS);
1891 	if (istatus != 0)
1892 		fsl_sata_intr_main(ch, istatus);
1893 }
1894 MODULE_VERSION(fsl_sata, 1);
1895 MODULE_DEPEND(fsl_sata, cam, 1, 1, 1);
1896