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