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