audio soc dma : add audio getposition dma
[firefly-linux-kernel-4.4.55.git] / drivers / dma / pl330.c
1 /*
2  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
3  *              http://www.samsung.com
4  *
5  * Copyright (C) 2010 Samsung Electronics Co. Ltd.
6  *      Jaswinder Singh <jassi.brar@samsung.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  */
13
14 #include <linux/kernel.h>
15 #include <linux/io.h>
16 #include <linux/init.h>
17 #include <linux/slab.h>
18 #include <linux/module.h>
19 #include <linux/string.h>
20 #include <linux/delay.h>
21 #include <linux/interrupt.h>
22 #include <linux/dma-mapping.h>
23 #include <linux/dmaengine.h>
24 #include <linux/amba/bus.h>
25 #include <linux/amba/pl330.h>
26 #include <linux/scatterlist.h>
27 #include <linux/of.h>
28 #include <linux/of_dma.h>
29 #include <linux/err.h>
30 #include <asm/unaligned.h>
31
32 #include "dmaengine.h"
33 #define PL330_MAX_CHAN          8
34 #define PL330_MAX_IRQS          32
35 #define PL330_MAX_PERI          32
36
37 enum pl330_srccachectrl {
38         SCCTRL0,        /* Noncacheable and nonbufferable */
39         SCCTRL1,        /* Bufferable only */
40         SCCTRL2,        /* Cacheable, but do not allocate */
41         SCCTRL3,        /* Cacheable and bufferable, but do not allocate */
42         SINVALID1,
43         SINVALID2,
44         SCCTRL6,        /* Cacheable write-through, allocate on reads only */
45         SCCTRL7,        /* Cacheable write-back, allocate on reads only */
46 };
47
48 enum pl330_dstcachectrl {
49         DCCTRL0,        /* Noncacheable and nonbufferable */
50         DCCTRL1,        /* Bufferable only */
51         DCCTRL2,        /* Cacheable, but do not allocate */
52         DCCTRL3,        /* Cacheable and bufferable, but do not allocate */
53         DINVALID1,      /* AWCACHE = 0x1000 */
54         DINVALID2,
55         DCCTRL6,        /* Cacheable write-through, allocate on writes only */
56         DCCTRL7,        /* Cacheable write-back, allocate on writes only */
57 };
58
59 enum pl330_byteswap {
60         SWAP_NO,
61         SWAP_2,
62         SWAP_4,
63         SWAP_8,
64         SWAP_16,
65 };
66
67 enum pl330_reqtype {
68         MEMTOMEM,
69         MEMTODEV,
70         DEVTOMEM,
71         DEVTODEV,
72 };
73
74 /* Register and Bit field Definitions */
75 #define DS                      0x0
76 #define DS_ST_STOP              0x0
77 #define DS_ST_EXEC              0x1
78 #define DS_ST_CMISS             0x2
79 #define DS_ST_UPDTPC            0x3
80 #define DS_ST_WFE               0x4
81 #define DS_ST_ATBRR             0x5
82 #define DS_ST_QBUSY             0x6
83 #define DS_ST_WFP               0x7
84 #define DS_ST_KILL              0x8
85 #define DS_ST_CMPLT             0x9
86 #define DS_ST_FLTCMP            0xe
87 #define DS_ST_FAULT             0xf
88
89 #define DPC                     0x4
90 #define INTEN                   0x20
91 #define ES                      0x24
92 #define INTSTATUS               0x28
93 #define INTCLR                  0x2c
94 #define FSM                     0x30
95 #define FSC                     0x34
96 #define FTM                     0x38
97
98 #define _FTC                    0x40
99 #define FTC(n)                  (_FTC + (n)*0x4)
100
101 #define _CS                     0x100
102 #define CS(n)                   (_CS + (n)*0x8)
103 #define CS_CNS                  (1 << 21)
104
105 #define _CPC                    0x104
106 #define CPC(n)                  (_CPC + (n)*0x8)
107
108 #define _SA                     0x400
109 #define SA(n)                   (_SA + (n)*0x20)
110
111 #define _DA                     0x404
112 #define DA(n)                   (_DA + (n)*0x20)
113
114 #define _CC                     0x408
115 #define CC(n)                   (_CC + (n)*0x20)
116
117 #define CC_SRCINC               (1 << 0)
118 #define CC_DSTINC               (1 << 14)
119 #define CC_SRCPRI               (1 << 8)
120 #define CC_DSTPRI               (1 << 22)
121 #define CC_SRCNS                (1 << 9)
122 #define CC_DSTNS                (1 << 23)
123 #define CC_SRCIA                (1 << 10)
124 #define CC_DSTIA                (1 << 24)
125 #define CC_SRCBRSTLEN_SHFT      4
126 #define CC_DSTBRSTLEN_SHFT      18
127 #define CC_SRCBRSTSIZE_SHFT     1
128 #define CC_DSTBRSTSIZE_SHFT     15
129 #define CC_SRCCCTRL_SHFT        11
130 #define CC_SRCCCTRL_MASK        0x7
131 #define CC_DSTCCTRL_SHFT        25
132 #define CC_DRCCCTRL_MASK        0x7
133 #define CC_SWAP_SHFT            28
134
135 #define _LC0                    0x40c
136 #define LC0(n)                  (_LC0 + (n)*0x20)
137
138 #define _LC1                    0x410
139 #define LC1(n)                  (_LC1 + (n)*0x20)
140
141 #define DBGSTATUS               0xd00
142 #define DBG_BUSY                (1 << 0)
143
144 #define DBGCMD                  0xd04
145 #define DBGINST0                0xd08
146 #define DBGINST1                0xd0c
147
148 #define CR0                     0xe00
149 #define CR1                     0xe04
150 #define CR2                     0xe08
151 #define CR3                     0xe0c
152 #define CR4                     0xe10
153 #define CRD                     0xe14
154
155 #define PERIPH_ID               0xfe0
156 #define PERIPH_REV_SHIFT        20
157 #define PERIPH_REV_MASK         0xf
158 #define PERIPH_REV_R0P0         0
159 #define PERIPH_REV_R1P0         1
160 #define PERIPH_REV_R1P1         2
161 #define PCELL_ID                0xff0
162
163 #define CR0_PERIPH_REQ_SET      (1 << 0)
164 #define CR0_BOOT_EN_SET         (1 << 1)
165 #define CR0_BOOT_MAN_NS         (1 << 2)
166 #define CR0_NUM_CHANS_SHIFT     4
167 #define CR0_NUM_CHANS_MASK      0x7
168 #define CR0_NUM_PERIPH_SHIFT    12
169 #define CR0_NUM_PERIPH_MASK     0x1f
170 #define CR0_NUM_EVENTS_SHIFT    17
171 #define CR0_NUM_EVENTS_MASK     0x1f
172
173 #define CR1_ICACHE_LEN_SHIFT    0
174 #define CR1_ICACHE_LEN_MASK     0x7
175 #define CR1_NUM_ICACHELINES_SHIFT       4
176 #define CR1_NUM_ICACHELINES_MASK        0xf
177
178 #define CRD_DATA_WIDTH_SHIFT    0
179 #define CRD_DATA_WIDTH_MASK     0x7
180 #define CRD_WR_CAP_SHIFT        4
181 #define CRD_WR_CAP_MASK         0x7
182 #define CRD_WR_Q_DEP_SHIFT      8
183 #define CRD_WR_Q_DEP_MASK       0xf
184 #define CRD_RD_CAP_SHIFT        12
185 #define CRD_RD_CAP_MASK         0x7
186 #define CRD_RD_Q_DEP_SHIFT      16
187 #define CRD_RD_Q_DEP_MASK       0xf
188 #define CRD_DATA_BUFF_SHIFT     20
189 #define CRD_DATA_BUFF_MASK      0x3ff
190
191 #define PART                    0x330
192 #define DESIGNER                0x41
193 #define REVISION                0x0
194 #define INTEG_CFG               0x0
195 #define PERIPH_ID_VAL           ((PART << 0) | (DESIGNER << 12))
196
197 #define PCELL_ID_VAL            0xb105f00d
198
199 #define PL330_STATE_STOPPED             (1 << 0)
200 #define PL330_STATE_EXECUTING           (1 << 1)
201 #define PL330_STATE_WFE                 (1 << 2)
202 #define PL330_STATE_FAULTING            (1 << 3)
203 #define PL330_STATE_COMPLETING          (1 << 4)
204 #define PL330_STATE_WFP                 (1 << 5)
205 #define PL330_STATE_KILLING             (1 << 6)
206 #define PL330_STATE_FAULT_COMPLETING    (1 << 7)
207 #define PL330_STATE_CACHEMISS           (1 << 8)
208 #define PL330_STATE_UPDTPC              (1 << 9)
209 #define PL330_STATE_ATBARRIER           (1 << 10)
210 #define PL330_STATE_QUEUEBUSY           (1 << 11)
211 #define PL330_STATE_INVALID             (1 << 15)
212
213 #define PL330_STABLE_STATES (PL330_STATE_STOPPED | PL330_STATE_EXECUTING \
214                                 | PL330_STATE_WFE | PL330_STATE_FAULTING)
215
216 #define CMD_DMAADDH             0x54
217 #define CMD_DMAEND              0x00
218 #define CMD_DMAFLUSHP           0x35
219 #define CMD_DMAGO               0xa0
220 #define CMD_DMALD               0x04
221 #define CMD_DMALDP              0x25
222 #define CMD_DMALP               0x20
223 #define CMD_DMALPEND            0x28
224 #define CMD_DMAKILL             0x01
225 #define CMD_DMAMOV              0xbc
226 #define CMD_DMANOP              0x18
227 #define CMD_DMARMB              0x12
228 #define CMD_DMASEV              0x34
229 #define CMD_DMAST               0x08
230 #define CMD_DMASTP              0x29
231 #define CMD_DMASTZ              0x0c
232 #define CMD_DMAWFE              0x36
233 #define CMD_DMAWFP              0x30
234 #define CMD_DMAWMB              0x13
235
236 #define SZ_DMAADDH              3
237 #define SZ_DMAEND               1
238 #define SZ_DMAFLUSHP            2
239 #define SZ_DMALD                1
240 #define SZ_DMALDP               2
241 #define SZ_DMALP                2
242 #define SZ_DMALPEND             2
243 #define SZ_DMAKILL              1
244 #define SZ_DMAMOV               6
245 #define SZ_DMANOP               1
246 #define SZ_DMARMB               1
247 #define SZ_DMASEV               2
248 #define SZ_DMAST                1
249 #define SZ_DMASTP               2
250 #define SZ_DMASTZ               1
251 #define SZ_DMAWFE               2
252 #define SZ_DMAWFP               2
253 #define SZ_DMAWMB               1
254 #define SZ_DMAGO                6
255
256 #define BRST_LEN(ccr)           ((((ccr) >> CC_SRCBRSTLEN_SHFT) & 0xf) + 1)
257 #define BRST_SIZE(ccr)          (1 << (((ccr) >> CC_SRCBRSTSIZE_SHFT) & 0x7))
258
259 #define BYTE_TO_BURST(b, ccr)   ((b) / BRST_SIZE(ccr) / BRST_LEN(ccr))
260 #define BURST_TO_BYTE(c, ccr)   ((c) * BRST_SIZE(ccr) * BRST_LEN(ccr))
261
262 /*
263  * With 256 bytes, we can do more than 2.5MB and 5MB xfers per req
264  * at 1byte/burst for P<->M and M<->M respectively.
265  * For typical scenario, at 1word/burst, 10MB and 20MB xfers per req
266  * should be enough for P<->M and M<->M respectively.
267  */
268 #define MCODE_BUFF_PER_REQ      256
269
270 /* If the _pl330_req is available to the client */
271 #define IS_FREE(req)    (*((u8 *)((req)->mc_cpu)) == CMD_DMAEND)
272
273 /* Use this _only_ to wait on transient states */
274 #define UNTIL(t, s)     while (!(_state(t) & (s))) cpu_relax();
275
276 #ifdef PL330_DEBUG_MCGEN
277 static unsigned cmd_line;
278 #define PL330_DBGCMD_DUMP(off, x...)    do { \
279                                                 printk("%x:", cmd_line); \
280                                                 printk(x); \
281                                                 cmd_line += off; \
282                                         } while (0)
283 #define PL330_DBGMC_START(addr)         (cmd_line = addr)
284 #else
285 #define PL330_DBGCMD_DUMP(off, x...)    do {} while (0)
286 #define PL330_DBGMC_START(addr)         do {} while (0)
287 #endif
288
289 /* The number of default descriptors */
290
291 #define NR_DEFAULT_DESC 16
292
293 /* Populated by the PL330 core driver for DMA API driver's info */
294 struct pl330_config {
295         u32     periph_id;
296         u32     pcell_id;
297 #define DMAC_MODE_NS    (1 << 0)
298         unsigned int    mode;
299         unsigned int    data_bus_width:10; /* In number of bits */
300         unsigned int    data_buf_dep:10;
301         unsigned int    num_chan:4;
302         unsigned int    num_peri:6;
303         u32             peri_ns;
304         unsigned int    num_events:6;
305         u32             irq_ns;
306 };
307
308 /* Handle to the DMAC provided to the PL330 core */
309 struct pl330_info {
310         /* Owning device */
311         struct device *dev;
312         /* Size of MicroCode buffers for each channel. */
313         unsigned mcbufsz;
314         /* ioremap'ed address of PL330 registers. */
315         void __iomem    *base;
316         /* Client can freely use it. */
317         void    *client_data;
318         /* PL330 core data, Client must not touch it. */
319         void    *pl330_data;
320         /* Populated by the PL330 core driver during pl330_add */
321         struct pl330_config     pcfg;
322         /*
323          * If the DMAC has some reset mechanism, then the
324          * client may want to provide pointer to the method.
325          */
326         void (*dmac_reset)(struct pl330_info *pi);
327 };
328
329 /**
330  * Request Configuration.
331  * The PL330 core does not modify this and uses the last
332  * working configuration if the request doesn't provide any.
333  *
334  * The Client may want to provide this info only for the
335  * first request and a request with new settings.
336  */
337 struct pl330_reqcfg {
338         /* Address Incrementing */
339         unsigned dst_inc:1;
340         unsigned src_inc:1;
341
342         /*
343          * For now, the SRC & DST protection levels
344          * and burst size/length are assumed same.
345          */
346         bool nonsecure;
347         bool privileged;
348         bool insnaccess;
349         unsigned brst_len:5;
350         unsigned brst_size:3; /* in power of 2 */
351
352         enum pl330_dstcachectrl dcctl;
353         enum pl330_srccachectrl scctl;
354         enum pl330_byteswap swap;
355         struct pl330_config *pcfg;
356 };
357
358 /*
359  * One cycle of DMAC operation.
360  * There may be more than one xfer in a request.
361  */
362 struct pl330_xfer {
363         u32 src_addr;
364         u32 dst_addr;
365         /* Size to xfer */
366         u32 bytes;
367         /*
368          * Pointer to next xfer in the list.
369          * The last xfer in the req must point to NULL.
370          */
371         struct pl330_xfer *next;
372 };
373
374 /* The xfer callbacks are made with one of these arguments. */
375 enum pl330_op_err {
376         /* The all xfers in the request were success. */
377         PL330_ERR_NONE,
378         /* If req aborted due to global error. */
379         PL330_ERR_ABORT,
380         /* If req failed due to problem with Channel. */
381         PL330_ERR_FAIL,
382 };
383
384 /* A request defining Scatter-Gather List ending with NULL xfer. */
385 struct pl330_req {
386         enum pl330_reqtype rqtype;
387         /* Index of peripheral for the xfer. */
388         unsigned peri:5;
389         /* Unique token for this xfer, set by the client. */
390         void *token;
391         /* Callback to be called after xfer. */
392         void (*xfer_cb)(void *token, enum pl330_op_err err);
393         /* If NULL, req will be done at last set parameters. */
394         struct pl330_reqcfg *cfg;
395         /* Pointer to first xfer in the request. */
396         struct pl330_xfer *x;
397         /* Hook to attach to DMAC's list of reqs with due callback */
398         struct list_head rqd;
399         unsigned int infiniteloop;
400 };
401
402 /*
403  * To know the status of the channel and DMAC, the client
404  * provides a pointer to this structure. The PL330 core
405  * fills it with current information.
406  */
407 struct pl330_chanstatus {
408         /*
409          * If the DMAC engine halted due to some error,
410          * the client should remove-add DMAC.
411          */
412         bool dmac_halted;
413         /*
414          * If channel is halted due to some error,
415          * the client should ABORT/FLUSH and START the channel.
416          */
417         bool faulting;
418         /* Location of last load */
419         u32 src_addr;
420         /* Location of last store */
421         u32 dst_addr;
422         /*
423          * Pointer to the currently active req, NULL if channel is
424          * inactive, even though the requests may be present.
425          */
426         struct pl330_req *top_req;
427         /* Pointer to req waiting second in the queue if any. */
428         struct pl330_req *wait_req;
429 };
430
431 enum pl330_chan_op {
432         /* Start the channel */
433         PL330_OP_START,
434         /* Abort the active xfer */
435         PL330_OP_ABORT,
436         /* Stop xfer and flush queue */
437         PL330_OP_FLUSH,
438 };
439
440 struct _xfer_spec {
441         u32 ccr;
442         struct pl330_req *r;
443         struct pl330_xfer *x;
444 };
445
446 enum dmamov_dst {
447         SAR = 0,
448         CCR,
449         DAR,
450 };
451
452 enum pl330_dst {
453         SRC = 0,
454         DST,
455 };
456
457 enum pl330_cond {
458         SINGLE,
459         BURST,
460         ALWAYS,
461 };
462
463 struct _pl330_req {
464         u32 mc_bus;
465         void *mc_cpu;
466         /* Number of bytes taken to setup MC for the req */
467         u32 mc_len;
468         struct pl330_req *r;
469 };
470
471 /* ToBeDone for tasklet */
472 struct _pl330_tbd {
473         bool reset_dmac;
474         bool reset_mngr;
475         u8 reset_chan;
476 };
477
478 /* A DMAC Thread */
479 struct pl330_thread {
480         u8 id;
481         int ev;
482         /* If the channel is not yet acquired by any client */
483         bool free;
484         /* Parent DMAC */
485         struct pl330_dmac *dmac;
486         /* Only two at a time */
487         struct _pl330_req req[2];
488         /* Index of the last enqueued request */
489         unsigned lstenq;
490         /* Index of the last submitted request or -1 if the DMA is stopped */
491         int req_running;
492 };
493
494 enum pl330_dmac_state {
495         UNINIT,
496         INIT,
497         DYING,
498 };
499
500 /* A DMAC */
501 struct pl330_dmac {
502         spinlock_t              lock;
503         /* Holds list of reqs with due callbacks */
504         struct list_head        req_done;
505         /* Pointer to platform specific stuff */
506         struct pl330_info       *pinfo;
507         /* Maximum possible events/irqs */
508         int                     events[32];
509         /* BUS address of MicroCode buffer */
510         u32                     mcode_bus;
511         /* CPU address of MicroCode buffer */
512         void                    *mcode_cpu;
513         /* List of all Channel threads */
514         struct pl330_thread     *channels;
515         /* Pointer to the MANAGER thread */
516         struct pl330_thread     *manager;
517         /* To handle bad news in interrupt */
518         struct tasklet_struct   tasks;
519         struct _pl330_tbd       dmac_tbd;
520         /* State of DMAC operation */
521         enum pl330_dmac_state   state;
522 };
523
524 enum desc_status {
525         /* In the DMAC pool */
526         FREE,
527         /*
528          * Allocated to some channel during prep_xxx
529          * Also may be sitting on the work_list.
530          */
531         PREP,
532         /*
533          * Sitting on the work_list and already submitted
534          * to the PL330 core. Not more than two descriptors
535          * of a channel can be BUSY at any time.
536          */
537         BUSY,
538         /*
539          * Sitting on the channel work_list but xfer done
540          * by PL330 core
541          */
542         DONE,
543 };
544
545 struct dma_pl330_chan {
546         /* Schedule desc completion */
547         struct tasklet_struct task;
548
549         /* DMA-Engine Channel */
550         struct dma_chan chan;
551
552         /* List of to be xfered descriptors */
553         struct list_head work_list;
554
555         /* Pointer to the DMAC that manages this channel,
556          * NULL if the channel is available to be acquired.
557          * As the parent, this DMAC also provides descriptors
558          * to the channel.
559          */
560         struct dma_pl330_dmac *dmac;
561
562         /* To protect channel manipulation */
563         spinlock_t lock;
564
565         /* Token of a hardware channel thread of PL330 DMAC
566          * NULL if the channel is available to be acquired.
567          */
568         void *pl330_chid;
569
570         /* For D-to-M and M-to-D channels */
571         int burst_sz; /* the peripheral fifo width */
572         int burst_len; /* the number of burst */
573         dma_addr_t fifo_addr;
574
575         /* for cyclic capability */
576         bool cyclic;
577 };
578
579 struct dma_pl330_dmac {
580         struct pl330_info pif;
581
582         /* DMA-Engine Device */
583         struct dma_device ddma;
584
585         /* Pool of descriptors available for the DMAC's channels */
586         struct list_head desc_pool;
587         /* To protect desc_pool manipulation */
588         spinlock_t pool_lock;
589
590         /* Peripheral channels connected to this DMAC */
591         struct dma_pl330_chan *peripherals; /* keep at end */
592 };
593
594 struct dma_pl330_desc {
595         /* To attach to a queue as child */
596         struct list_head node;
597
598         /* Descriptor for the DMA Engine API */
599         struct dma_async_tx_descriptor txd;
600
601         /* Xfer for PL330 core */
602         struct pl330_xfer px;
603
604         struct pl330_reqcfg rqcfg;
605         struct pl330_req req;
606
607         enum desc_status status;
608
609         /* The channel which currently holds this desc */
610         struct dma_pl330_chan *pchan;
611 };
612
613 struct dma_pl330_filter_args {
614         struct dma_pl330_dmac *pdmac;
615         unsigned int chan_id;
616 };
617
618 static inline void _callback(struct pl330_req *r, enum pl330_op_err err)
619 {
620         if (r && r->xfer_cb)
621                 r->xfer_cb(r->token, err);
622 }
623
624 static inline bool _queue_empty(struct pl330_thread *thrd)
625 {
626         return (IS_FREE(&thrd->req[0]) && IS_FREE(&thrd->req[1]))
627                 ? true : false;
628 }
629
630 static inline bool _queue_full(struct pl330_thread *thrd)
631 {
632         return (IS_FREE(&thrd->req[0]) || IS_FREE(&thrd->req[1]))
633                 ? false : true;
634 }
635
636 static inline bool is_manager(struct pl330_thread *thrd)
637 {
638         struct pl330_dmac *pl330 = thrd->dmac;
639
640         /* MANAGER is indexed at the end */
641         if (thrd->id == pl330->pinfo->pcfg.num_chan)
642                 return true;
643         else
644                 return false;
645 }
646
647 /* If manager of the thread is in Non-Secure mode */
648 static inline bool _manager_ns(struct pl330_thread *thrd)
649 {
650         struct pl330_dmac *pl330 = thrd->dmac;
651
652         return (pl330->pinfo->pcfg.mode & DMAC_MODE_NS) ? true : false;
653 }
654
655 static inline u32 get_id(struct pl330_info *pi, u32 off)
656 {
657         void __iomem *regs = pi->base;
658         u32 id = 0;
659
660 #ifdef CONFIG_ARCH_ROCKCHIP
661         id |= ((readl(regs + off + 0x0) & 0xff) << 0);
662         id |= ((readl(regs + off + 0x4) & 0xff) << 8);
663         id |= ((readl(regs + off + 0x8) & 0xff) << 16);
664         id |= ((readl(regs + off + 0xc) & 0xff) << 24);
665 #else
666         id |= (readb(regs + off + 0x0) << 0);
667         id |= (readb(regs + off + 0x4) << 8);
668         id |= (readb(regs + off + 0x8) << 16);
669         id |= (readb(regs + off + 0xc) << 24);
670 #endif
671
672         return id;
673 }
674
675 static inline u32 get_revision(u32 periph_id)
676 {
677         return (periph_id >> PERIPH_REV_SHIFT) & PERIPH_REV_MASK;
678 }
679
680 static inline u32 _emit_ADDH(unsigned dry_run, u8 buf[],
681                 enum pl330_dst da, u16 val)
682 {
683         if (dry_run)
684                 return SZ_DMAADDH;
685
686         buf[0] = CMD_DMAADDH;
687         buf[0] |= (da << 1);
688         put_unaligned(val, (u16 *)&buf[1]);     //*((u16 *)&buf[1]) = val;
689
690         PL330_DBGCMD_DUMP(SZ_DMAADDH, "\tDMAADDH %s %u\n",
691                 da == 1 ? "DA" : "SA", val);
692
693         return SZ_DMAADDH;
694 }
695
696 static inline u32 _emit_END(unsigned dry_run, u8 buf[])
697 {
698         if (dry_run)
699                 return SZ_DMAEND;
700
701         buf[0] = CMD_DMAEND;
702
703         PL330_DBGCMD_DUMP(SZ_DMAEND, "\tDMAEND\n");
704
705         return SZ_DMAEND;
706 }
707
708 static inline u32 _emit_FLUSHP(unsigned dry_run, u8 buf[], u8 peri)
709 {
710         if (dry_run)
711                 return SZ_DMAFLUSHP;
712
713         buf[0] = CMD_DMAFLUSHP;
714
715         peri &= 0x1f;
716         peri <<= 3;
717         buf[1] = peri;
718
719         PL330_DBGCMD_DUMP(SZ_DMAFLUSHP, "\tDMAFLUSHP %u\n", peri >> 3);
720
721         return SZ_DMAFLUSHP;
722 }
723
724 static inline u32 _emit_LD(unsigned dry_run, u8 buf[],  enum pl330_cond cond)
725 {
726         if (dry_run)
727                 return SZ_DMALD;
728
729         buf[0] = CMD_DMALD;
730
731         if (cond == SINGLE)
732                 buf[0] |= (0 << 1) | (1 << 0);
733         else if (cond == BURST)
734                 buf[0] |= (1 << 1) | (1 << 0);
735
736         PL330_DBGCMD_DUMP(SZ_DMALD, "\tDMALD%c\n",
737                 cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'A'));
738
739         return SZ_DMALD;
740 }
741
742 static inline u32 _emit_LDP(unsigned dry_run, u8 buf[],
743                 enum pl330_cond cond, u8 peri)
744 {
745         if (dry_run)
746                 return SZ_DMALDP;
747
748         buf[0] = CMD_DMALDP;
749
750         if (cond == BURST)
751                 buf[0] |= (1 << 1);
752
753         peri &= 0x1f;
754         peri <<= 3;
755         buf[1] = peri;
756
757         PL330_DBGCMD_DUMP(SZ_DMALDP, "\tDMALDP%c %u\n",
758                 cond == SINGLE ? 'S' : 'B', peri >> 3);
759
760         return SZ_DMALDP;
761 }
762
763 static inline u32 _emit_LP(unsigned dry_run, u8 buf[],
764                 unsigned loop, u8 cnt)
765 {
766         if (dry_run)
767                 return SZ_DMALP;
768
769         buf[0] = CMD_DMALP;
770
771         if (loop)
772                 buf[0] |= (1 << 1);
773
774         cnt--; /* DMAC increments by 1 internally */
775         buf[1] = cnt;
776
777         PL330_DBGCMD_DUMP(SZ_DMALP, "\tDMALP_%c %u\n", loop ? '1' : '0', cnt);
778
779         return SZ_DMALP;
780 }
781
782 struct _arg_LPEND {
783         enum pl330_cond cond;
784         bool forever;
785         unsigned loop;
786         u8 bjump;
787 };
788
789 static inline u32 _emit_LPEND(unsigned dry_run, u8 buf[],
790                 const struct _arg_LPEND *arg)
791 {
792         enum pl330_cond cond = arg->cond;
793         bool forever = arg->forever;
794         unsigned loop = arg->loop;
795         u8 bjump = arg->bjump;
796
797         if (dry_run)
798                 return SZ_DMALPEND;
799
800         buf[0] = CMD_DMALPEND;
801
802         if (loop)
803                 buf[0] |= (1 << 2);
804
805         if (!forever)
806                 buf[0] |= (1 << 4);
807
808         if (cond == SINGLE)
809                 buf[0] |= (0 << 1) | (1 << 0);
810         else if (cond == BURST)
811                 buf[0] |= (1 << 1) | (1 << 0);
812
813         buf[1] = bjump;
814
815         PL330_DBGCMD_DUMP(SZ_DMALPEND, "\tDMALP%s%c_%c bjmpto_%x\n",
816                         forever ? "FE" : "END",
817                         cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'A'),
818                         loop ? '1' : '0',
819                         bjump);
820
821         return SZ_DMALPEND;
822 }
823
824 static inline u32 _emit_KILL(unsigned dry_run, u8 buf[])
825 {
826         if (dry_run)
827                 return SZ_DMAKILL;
828
829         buf[0] = CMD_DMAKILL;
830
831         return SZ_DMAKILL;
832 }
833
834 static inline u32 _emit_MOV(unsigned dry_run, u8 buf[],
835                 enum dmamov_dst dst, u32 val)
836 {
837         if (dry_run)
838                 return SZ_DMAMOV;
839
840         buf[0] = CMD_DMAMOV;
841         buf[1] = dst;
842         put_unaligned(val, (u32 *)&buf[2]);     //*((u32 *)&buf[2]) = val;
843
844         PL330_DBGCMD_DUMP(SZ_DMAMOV, "\tDMAMOV %s 0x%x\n",
845                 dst == SAR ? "SAR" : (dst == DAR ? "DAR" : "CCR"), val);
846
847         return SZ_DMAMOV;
848 }
849
850 static inline u32 _emit_NOP(unsigned dry_run, u8 buf[])
851 {
852         if (dry_run)
853                 return SZ_DMANOP;
854
855         buf[0] = CMD_DMANOP;
856
857         PL330_DBGCMD_DUMP(SZ_DMANOP, "\tDMANOP\n");
858
859         return SZ_DMANOP;
860 }
861
862 static inline u32 _emit_RMB(unsigned dry_run, u8 buf[])
863 {
864         if (dry_run)
865                 return SZ_DMARMB;
866
867         buf[0] = CMD_DMARMB;
868
869         PL330_DBGCMD_DUMP(SZ_DMARMB, "\tDMARMB\n");
870
871         return SZ_DMARMB;
872 }
873
874 static inline u32 _emit_SEV(unsigned dry_run, u8 buf[], u8 ev)
875 {
876         if (dry_run)
877                 return SZ_DMASEV;
878
879         buf[0] = CMD_DMASEV;
880
881         ev &= 0x1f;
882         ev <<= 3;
883         buf[1] = ev;
884
885         PL330_DBGCMD_DUMP(SZ_DMASEV, "\tDMASEV %u\n", ev >> 3);
886
887         return SZ_DMASEV;
888 }
889
890 static inline u32 _emit_ST(unsigned dry_run, u8 buf[], enum pl330_cond cond)
891 {
892         if (dry_run)
893                 return SZ_DMAST;
894
895         buf[0] = CMD_DMAST;
896
897         if (cond == SINGLE)
898                 buf[0] |= (0 << 1) | (1 << 0);
899         else if (cond == BURST)
900                 buf[0] |= (1 << 1) | (1 << 0);
901
902         PL330_DBGCMD_DUMP(SZ_DMAST, "\tDMAST%c\n",
903                 cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'A'));
904
905         return SZ_DMAST;
906 }
907
908 static inline u32 _emit_STP(unsigned dry_run, u8 buf[],
909                 enum pl330_cond cond, u8 peri)
910 {
911         if (dry_run)
912                 return SZ_DMASTP;
913
914         buf[0] = CMD_DMASTP;
915
916         if (cond == BURST)
917                 buf[0] |= (1 << 1);
918
919         peri &= 0x1f;
920         peri <<= 3;
921         buf[1] = peri;
922
923         PL330_DBGCMD_DUMP(SZ_DMASTP, "\tDMASTP%c %u\n",
924                 cond == SINGLE ? 'S' : 'B', peri >> 3);
925
926         return SZ_DMASTP;
927 }
928
929 static inline u32 _emit_STZ(unsigned dry_run, u8 buf[])
930 {
931         if (dry_run)
932                 return SZ_DMASTZ;
933
934         buf[0] = CMD_DMASTZ;
935
936         PL330_DBGCMD_DUMP(SZ_DMASTZ, "\tDMASTZ\n");
937
938         return SZ_DMASTZ;
939 }
940
941 static inline u32 _emit_WFE(unsigned dry_run, u8 buf[], u8 ev,
942                 unsigned invalidate)
943 {
944         if (dry_run)
945                 return SZ_DMAWFE;
946
947         buf[0] = CMD_DMAWFE;
948
949         ev &= 0x1f;
950         ev <<= 3;
951         buf[1] = ev;
952
953         if (invalidate)
954                 buf[1] |= (1 << 1);
955
956         PL330_DBGCMD_DUMP(SZ_DMAWFE, "\tDMAWFE %u%s\n",
957                 ev >> 3, invalidate ? ", I" : "");
958
959         return SZ_DMAWFE;
960 }
961
962 static inline u32 _emit_WFP(unsigned dry_run, u8 buf[],
963                 enum pl330_cond cond, u8 peri)
964 {
965         if (dry_run)
966                 return SZ_DMAWFP;
967
968         buf[0] = CMD_DMAWFP;
969
970         if (cond == SINGLE)
971                 buf[0] |= (0 << 1) | (0 << 0);
972         else if (cond == BURST)
973                 buf[0] |= (1 << 1) | (0 << 0);
974         else
975                 buf[0] |= (0 << 1) | (1 << 0);
976
977         peri &= 0x1f;
978         peri <<= 3;
979         buf[1] = peri;
980
981         PL330_DBGCMD_DUMP(SZ_DMAWFP, "\tDMAWFP%c %u\n",
982                 cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'P'), peri >> 3);
983
984         return SZ_DMAWFP;
985 }
986
987 static inline u32 _emit_WMB(unsigned dry_run, u8 buf[])
988 {
989         if (dry_run)
990                 return SZ_DMAWMB;
991
992         buf[0] = CMD_DMAWMB;
993
994         PL330_DBGCMD_DUMP(SZ_DMAWMB, "\tDMAWMB\n");
995
996         return SZ_DMAWMB;
997 }
998
999 struct _arg_GO {
1000         u8 chan;
1001         u32 addr;
1002         unsigned ns;
1003 };
1004
1005 static inline u32 _emit_GO(unsigned dry_run, u8 buf[],
1006                 const struct _arg_GO *arg)
1007 {
1008         u8 chan = arg->chan;
1009         u32 addr = arg->addr;
1010         unsigned ns = arg->ns;
1011
1012         if (dry_run)
1013                 return SZ_DMAGO;
1014
1015         buf[0] = CMD_DMAGO;
1016         buf[0] |= (ns << 1);
1017
1018         buf[1] = chan & 0x7;
1019
1020         put_unaligned(addr, (u32 *)&buf[2]);    //*((u32 *)&buf[2]) = addr;
1021
1022         return SZ_DMAGO;
1023 }
1024
1025 #define msecs_to_loops(t) (loops_per_jiffy / 1000 * HZ * t)
1026
1027 /* Returns Time-Out */
1028 static bool _until_dmac_idle(struct pl330_thread *thrd)
1029 {
1030         void __iomem *regs = thrd->dmac->pinfo->base;
1031         unsigned long loops = msecs_to_loops(5);
1032
1033         do {
1034                 /* Until Manager is Idle */
1035                 if (!(readl(regs + DBGSTATUS) & DBG_BUSY))
1036                         break;
1037
1038                 cpu_relax();
1039         } while (--loops);
1040
1041         if (!loops)
1042                 return true;
1043
1044         return false;
1045 }
1046
1047 static inline void _execute_DBGINSN(struct pl330_thread *thrd,
1048                 u8 insn[], bool as_manager)
1049 {
1050         void __iomem *regs = thrd->dmac->pinfo->base;
1051         u32 val;
1052
1053         val = (insn[0] << 16) | (insn[1] << 24);
1054         if (!as_manager) {
1055                 val |= (1 << 0);
1056                 val |= (thrd->id << 8); /* Channel Number */
1057         }
1058         writel(val, regs + DBGINST0);
1059
1060         val = *((u32 *)&insn[2]);
1061         writel(val, regs + DBGINST1);
1062
1063         /* If timed out due to halted state-machine */
1064         if (_until_dmac_idle(thrd)) {
1065                 dev_err(thrd->dmac->pinfo->dev, "DMAC halted!\n");
1066                 return;
1067         }
1068
1069         /* Get going */
1070         writel(0, regs + DBGCMD);
1071 }
1072
1073 /*
1074  * Mark a _pl330_req as free.
1075  * We do it by writing DMAEND as the first instruction
1076  * because no valid request is going to have DMAEND as
1077  * its first instruction to execute.
1078  */
1079 static void mark_free(struct pl330_thread *thrd, int idx)
1080 {
1081         struct _pl330_req *req = &thrd->req[idx];
1082
1083         _emit_END(0, req->mc_cpu);
1084         req->mc_len = 0;
1085
1086         thrd->req_running = -1;
1087 }
1088
1089 static inline u32 _state(struct pl330_thread *thrd)
1090 {
1091         void __iomem *regs = thrd->dmac->pinfo->base;
1092         u32 val;
1093
1094         if (is_manager(thrd))
1095                 val = readl(regs + DS) & 0xf;
1096         else
1097                 val = readl(regs + CS(thrd->id)) & 0xf;
1098
1099         switch (val) {
1100         case DS_ST_STOP:
1101                 return PL330_STATE_STOPPED;
1102         case DS_ST_EXEC:
1103                 return PL330_STATE_EXECUTING;
1104         case DS_ST_CMISS:
1105                 return PL330_STATE_CACHEMISS;
1106         case DS_ST_UPDTPC:
1107                 return PL330_STATE_UPDTPC;
1108         case DS_ST_WFE:
1109                 return PL330_STATE_WFE;
1110         case DS_ST_FAULT:
1111                 return PL330_STATE_FAULTING;
1112         case DS_ST_ATBRR:
1113                 if (is_manager(thrd))
1114                         return PL330_STATE_INVALID;
1115                 else
1116                         return PL330_STATE_ATBARRIER;
1117         case DS_ST_QBUSY:
1118                 if (is_manager(thrd))
1119                         return PL330_STATE_INVALID;
1120                 else
1121                         return PL330_STATE_QUEUEBUSY;
1122         case DS_ST_WFP:
1123                 if (is_manager(thrd))
1124                         return PL330_STATE_INVALID;
1125                 else
1126                         return PL330_STATE_WFP;
1127         case DS_ST_KILL:
1128                 if (is_manager(thrd))
1129                         return PL330_STATE_INVALID;
1130                 else
1131                         return PL330_STATE_KILLING;
1132         case DS_ST_CMPLT:
1133                 if (is_manager(thrd))
1134                         return PL330_STATE_INVALID;
1135                 else
1136                         return PL330_STATE_COMPLETING;
1137         case DS_ST_FLTCMP:
1138                 if (is_manager(thrd))
1139                         return PL330_STATE_INVALID;
1140                 else
1141                         return PL330_STATE_FAULT_COMPLETING;
1142         default:
1143                 return PL330_STATE_INVALID;
1144         }
1145 }
1146
1147 static void _stop(struct pl330_thread *thrd)
1148 {
1149         void __iomem *regs = thrd->dmac->pinfo->base;
1150         u8 insn[6] = {0, 0, 0, 0, 0, 0};
1151
1152         if (_state(thrd) == PL330_STATE_FAULT_COMPLETING)
1153                 UNTIL(thrd, PL330_STATE_FAULTING | PL330_STATE_KILLING);
1154
1155         /* Return if nothing needs to be done */
1156         if (_state(thrd) == PL330_STATE_COMPLETING
1157                   || _state(thrd) == PL330_STATE_KILLING
1158                   || _state(thrd) == PL330_STATE_STOPPED)
1159                 return;
1160
1161         _emit_KILL(0, insn);
1162
1163         /* Stop generating interrupts for SEV */
1164         writel(readl(regs + INTEN) & ~(1 << thrd->ev), regs + INTEN);
1165
1166         _execute_DBGINSN(thrd, insn, is_manager(thrd));
1167 }
1168
1169 /* Start doing req 'idx' of thread 'thrd' */
1170 static bool _trigger(struct pl330_thread *thrd)
1171 {
1172         void __iomem *regs = thrd->dmac->pinfo->base;
1173         struct _pl330_req *req;
1174         struct pl330_req *r;
1175         struct _arg_GO go;
1176         unsigned ns;
1177         u8 insn[6] = {0, 0, 0, 0, 0, 0};
1178         int idx;
1179
1180         /* Return if already ACTIVE */
1181         if (_state(thrd) != PL330_STATE_STOPPED)
1182                 return true;
1183
1184         idx = 1 - thrd->lstenq;
1185         if (!IS_FREE(&thrd->req[idx]))
1186                 req = &thrd->req[idx];
1187         else {
1188                 idx = thrd->lstenq;
1189                 if (!IS_FREE(&thrd->req[idx]))
1190                         req = &thrd->req[idx];
1191                 else
1192                         req = NULL;
1193         }
1194
1195         /* Return if no request */
1196         if (!req || !req->r)
1197                 return true;
1198
1199         r = req->r;
1200
1201         if (r->cfg)
1202                 ns = r->cfg->nonsecure ? 1 : 0;
1203         else if (readl(regs + CS(thrd->id)) & CS_CNS)
1204                 ns = 1;
1205         else
1206                 ns = 0;
1207
1208         /* See 'Abort Sources' point-4 at Page 2-25 */
1209         if (_manager_ns(thrd) && !ns)
1210                 dev_info(thrd->dmac->pinfo->dev, "%s:%d Recipe for ABORT!\n",
1211                         __func__, __LINE__);
1212
1213         go.chan = thrd->id;
1214         go.addr = req->mc_bus;
1215         go.ns = ns;
1216         _emit_GO(0, insn, &go);
1217
1218         /* Set to generate interrupts for SEV */
1219         writel(readl(regs + INTEN) | (1 << thrd->ev), regs + INTEN);
1220
1221         /* Only manager can execute GO */
1222         _execute_DBGINSN(thrd, insn, true);
1223
1224         thrd->req_running = idx;
1225
1226         return true;
1227 }
1228
1229 static bool _start(struct pl330_thread *thrd)
1230 {
1231         switch (_state(thrd)) {
1232         case PL330_STATE_FAULT_COMPLETING:
1233                 UNTIL(thrd, PL330_STATE_FAULTING | PL330_STATE_KILLING);
1234
1235                 if (_state(thrd) == PL330_STATE_KILLING)
1236                         UNTIL(thrd, PL330_STATE_STOPPED)
1237
1238         case PL330_STATE_FAULTING:
1239                 _stop(thrd);
1240
1241         case PL330_STATE_KILLING:
1242         case PL330_STATE_COMPLETING:
1243                 UNTIL(thrd, PL330_STATE_STOPPED)
1244
1245         case PL330_STATE_STOPPED:
1246                 return _trigger(thrd);
1247
1248         case PL330_STATE_WFP:
1249         case PL330_STATE_QUEUEBUSY:
1250         case PL330_STATE_ATBARRIER:
1251         case PL330_STATE_UPDTPC:
1252         case PL330_STATE_CACHEMISS:
1253         case PL330_STATE_EXECUTING:
1254                 return true;
1255
1256         case PL330_STATE_WFE: /* For RESUME, nothing yet */
1257         default:
1258                 return false;
1259         }
1260 }
1261
1262 static inline int _ldst_memtomem(unsigned dry_run, u8 buf[],
1263                 const struct _xfer_spec *pxs, int cyc)
1264 {
1265         int off = 0;
1266         struct pl330_config *pcfg = pxs->r->cfg->pcfg;
1267
1268         /* check lock-up free version */
1269         if (get_revision(pcfg->periph_id) >= PERIPH_REV_R1P0) {
1270                 while (cyc--) {
1271                         off += _emit_LD(dry_run, &buf[off], ALWAYS);
1272                         off += _emit_ST(dry_run, &buf[off], ALWAYS);
1273                 }
1274         } else {
1275                 while (cyc--) {
1276                         off += _emit_LD(dry_run, &buf[off], ALWAYS);
1277                         off += _emit_RMB(dry_run, &buf[off]);
1278                         off += _emit_ST(dry_run, &buf[off], ALWAYS);
1279                         off += _emit_WMB(dry_run, &buf[off]);
1280                 }
1281         }
1282
1283         return off;
1284 }
1285
1286 static inline int _ldst_devtomem(unsigned dry_run, u8 buf[],
1287                 const struct _xfer_spec *pxs, int cyc)
1288 {
1289         int off = 0;
1290
1291         while (cyc--) {
1292 #ifdef CONFIG_ARCH_ROCKCHIP
1293                 off += _emit_WFP(dry_run, &buf[off], BURST, pxs->r->peri);
1294                 off += _emit_LDP(dry_run, &buf[off], BURST, pxs->r->peri);
1295                 off += _emit_ST(dry_run, &buf[off], ALWAYS);
1296                 //off += _emit_FLUSHP(dry_run, &buf[off], pxs->r->peri);    //for sdmmc sdio
1297 #else
1298                 off += _emit_WFP(dry_run, &buf[off], SINGLE, pxs->r->peri);
1299                 off += _emit_LDP(dry_run, &buf[off], SINGLE, pxs->r->peri);
1300                 off += _emit_ST(dry_run, &buf[off], ALWAYS);
1301                 off += _emit_FLUSHP(dry_run, &buf[off], pxs->r->peri);
1302 #endif
1303         }
1304
1305         return off;
1306 }
1307
1308 static inline int _ldst_memtodev(unsigned dry_run, u8 buf[],
1309                 const struct _xfer_spec *pxs, int cyc)
1310 {
1311         int off = 0;
1312
1313         while (cyc--) {
1314 #ifdef CONFIG_ARCH_ROCKCHIP
1315                 off += _emit_WFP(dry_run, &buf[off], BURST, pxs->r->peri);
1316                 off += _emit_LD(dry_run, &buf[off], ALWAYS);
1317                 off += _emit_STP(dry_run, &buf[off], BURST, pxs->r->peri);
1318                 //off += _emit_FLUSHP(dry_run, &buf[off], pxs->r->peri);
1319 #else
1320                 off += _emit_WFP(dry_run, &buf[off], SINGLE, pxs->r->peri);
1321                 off += _emit_LD(dry_run, &buf[off], ALWAYS);
1322                 off += _emit_STP(dry_run, &buf[off], SINGLE, pxs->r->peri);
1323                 off += _emit_FLUSHP(dry_run, &buf[off], pxs->r->peri);
1324 #endif  
1325         }
1326
1327         return off;
1328 }
1329
1330 static int _bursts(unsigned dry_run, u8 buf[],
1331                 const struct _xfer_spec *pxs, int cyc)
1332 {
1333         int off = 0;
1334
1335         switch (pxs->r->rqtype) {
1336         case MEMTODEV:
1337                 off += _ldst_memtodev(dry_run, &buf[off], pxs, cyc);
1338                 break;
1339         case DEVTOMEM:
1340                 off += _ldst_devtomem(dry_run, &buf[off], pxs, cyc);
1341                 break;
1342         case MEMTOMEM:
1343                 off += _ldst_memtomem(dry_run, &buf[off], pxs, cyc);
1344                 break;
1345         default:
1346                 off += 0x40000000; /* Scare off the Client */
1347                 break;
1348         }
1349
1350         return off;
1351 }
1352
1353 /* Returns bytes consumed */
1354 static inline int _loop_infiniteloop(unsigned dry_run, u8 buf[],
1355                 unsigned long bursts, const struct _xfer_spec *pxs, int ev)
1356 {
1357         int cyc, off;
1358         unsigned lcnt0, lcnt1, ljmp0, ljmp1, ljmpfe;
1359         struct _arg_LPEND lpend;
1360
1361         off = 0;
1362         ljmpfe = off;
1363         lcnt0 = pxs->r->infiniteloop;
1364
1365         if (bursts > 256) {
1366                 lcnt1 = 256;
1367                 cyc = bursts / 256;
1368         } else {
1369                 lcnt1 = bursts;
1370                 cyc = 1;
1371         }
1372
1373         /* forever loop */
1374         off += _emit_MOV(dry_run, &buf[off], SAR, pxs->x->src_addr);
1375         off += _emit_MOV(dry_run, &buf[off], DAR, pxs->x->dst_addr);
1376         if (pxs->r->rqtype !=  MEMTOMEM)
1377                 off += _emit_FLUSHP(dry_run, &buf[off], pxs->r->peri);
1378
1379         /* loop0 */
1380         off += _emit_LP(dry_run, &buf[off], 0,  lcnt0);
1381         ljmp0 = off;
1382
1383         /* loop1 */
1384         off += _emit_LP(dry_run, &buf[off], 1, lcnt1);
1385         ljmp1 = off;
1386         off += _bursts(dry_run, &buf[off], pxs, cyc);
1387         lpend.cond = ALWAYS;
1388         lpend.forever = false;
1389         lpend.loop = 1;
1390         lpend.bjump = off - ljmp1;
1391         off += _emit_LPEND(dry_run, &buf[off], &lpend);
1392
1393         /* remainder */
1394         lcnt1 = bursts - (lcnt1 * cyc);
1395
1396         if (lcnt1) {
1397                 off += _emit_LP(dry_run, &buf[off], 1, lcnt1);
1398                 ljmp1 = off;
1399                 off += _bursts(dry_run, &buf[off], pxs, 1);
1400                 lpend.cond = ALWAYS;
1401                 lpend.forever = false;
1402                 lpend.loop = 1;
1403                 lpend.bjump = off - ljmp1;
1404                 off += _emit_LPEND(dry_run, &buf[off], &lpend);
1405         }
1406
1407         off += _emit_SEV(dry_run, &buf[off], ev);
1408
1409         lpend.cond = ALWAYS;
1410         lpend.forever = false;
1411         lpend.loop = 0;
1412         lpend.bjump = off - ljmp0;
1413         off += _emit_LPEND(dry_run, &buf[off], &lpend);
1414
1415         lpend.cond = ALWAYS;
1416         lpend.forever = true;
1417         lpend.loop = 1;
1418         lpend.bjump = off - ljmpfe;
1419         off +=  _emit_LPEND(dry_run, &buf[off], &lpend);
1420
1421         return off;
1422 }
1423
1424 /* Returns bytes consumed and updates bursts */
1425 static inline int _loop(unsigned dry_run, u8 buf[],
1426                 unsigned long *bursts, const struct _xfer_spec *pxs)
1427 {
1428         int cyc, cycmax, szlp, szlpend, szbrst, off;
1429         unsigned lcnt0, lcnt1, ljmp0, ljmp1;
1430         struct _arg_LPEND lpend;
1431
1432         /* Max iterations possible in DMALP is 256 */
1433         if (*bursts >= 256*256) {
1434                 lcnt1 = 256;
1435                 lcnt0 = 256;
1436                 cyc = *bursts / lcnt1 / lcnt0;
1437         } else if (*bursts > 256) {
1438                 lcnt1 = 256;
1439                 lcnt0 = *bursts / lcnt1;
1440                 cyc = 1;
1441         } else {
1442                 lcnt1 = *bursts;
1443                 lcnt0 = 0;
1444                 cyc = 1;
1445         }
1446
1447         szlp = _emit_LP(1, buf, 0, 0);
1448         szbrst = _bursts(1, buf, pxs, 1);
1449
1450         lpend.cond = ALWAYS;
1451         lpend.forever = false;
1452         lpend.loop = 0;
1453         lpend.bjump = 0;
1454         szlpend = _emit_LPEND(1, buf, &lpend);
1455
1456         if (lcnt0) {
1457                 szlp *= 2;
1458                 szlpend *= 2;
1459         }
1460
1461         /*
1462          * Max bursts that we can unroll due to limit on the
1463          * size of backward jump that can be encoded in DMALPEND
1464          * which is 8-bits and hence 255
1465          */
1466         cycmax = (255 - (szlp + szlpend)) / szbrst;
1467
1468         cyc = (cycmax < cyc) ? cycmax : cyc;
1469
1470         off = 0;
1471
1472         if (lcnt0) {
1473                 off += _emit_LP(dry_run, &buf[off], 0, lcnt0);
1474                 ljmp0 = off;
1475         }
1476
1477         off += _emit_LP(dry_run, &buf[off], 1, lcnt1);
1478         ljmp1 = off;
1479
1480         off += _bursts(dry_run, &buf[off], pxs, cyc);
1481
1482         lpend.cond = ALWAYS;
1483         lpend.forever = false;
1484         lpend.loop = 1;
1485         lpend.bjump = off - ljmp1;
1486         off += _emit_LPEND(dry_run, &buf[off], &lpend);
1487
1488         if (lcnt0) {
1489                 lpend.cond = ALWAYS;
1490                 lpend.forever = false;
1491                 lpend.loop = 0;
1492                 lpend.bjump = off - ljmp0;
1493                 off += _emit_LPEND(dry_run, &buf[off], &lpend);
1494         }
1495
1496         *bursts = lcnt1 * cyc;
1497         if (lcnt0)
1498                 *bursts *= lcnt0;
1499
1500         return off;
1501 }
1502
1503 static inline int _setup_xfer_infiniteloop(unsigned dry_run, u8 buf[],
1504                 const struct _xfer_spec *pxs, int ev)
1505 {
1506         struct pl330_xfer *x = pxs->x;
1507         u32 ccr = pxs->ccr;
1508         unsigned long bursts = BYTE_TO_BURST(x->bytes, ccr);
1509         int off = 0;
1510
1511         /* Setup Loop(s) */
1512         off += _loop_infiniteloop(dry_run, &buf[off], bursts, pxs, ev);
1513
1514         return off;
1515 }
1516
1517 static inline int _setup_loops(unsigned dry_run, u8 buf[],
1518                 const struct _xfer_spec *pxs)
1519 {
1520         struct pl330_xfer *x = pxs->x;
1521         u32 ccr = pxs->ccr;
1522         unsigned long c, bursts = BYTE_TO_BURST(x->bytes, ccr);
1523         int off = 0;
1524
1525         while (bursts) {
1526                 c = bursts;
1527                 off += _loop(dry_run, &buf[off], &c, pxs);
1528                 bursts -= c;
1529         }
1530
1531         return off;
1532 }
1533
1534 static inline int _setup_xfer(unsigned dry_run, u8 buf[],
1535                 const struct _xfer_spec *pxs)
1536 {
1537         struct pl330_xfer *x = pxs->x;
1538         int off = 0;
1539
1540         /* DMAMOV SAR, x->src_addr */
1541         off += _emit_MOV(dry_run, &buf[off], SAR, x->src_addr);
1542         /* DMAMOV DAR, x->dst_addr */
1543         off += _emit_MOV(dry_run, &buf[off], DAR, x->dst_addr);
1544
1545         /* Setup Loop(s) */
1546         off += _setup_loops(dry_run, &buf[off], pxs);
1547
1548         return off;
1549 }
1550
1551 /*
1552  * A req is a sequence of one or more xfer units.
1553  * Returns the number of bytes taken to setup the MC for the req.
1554  */
1555 static int _setup_req(unsigned dry_run, struct pl330_thread *thrd,
1556                 unsigned index, struct _xfer_spec *pxs)
1557 {
1558         struct _pl330_req *req = &thrd->req[index];
1559         struct pl330_xfer *x;
1560         u8 *buf = req->mc_cpu;
1561         int off = 0;
1562
1563         PL330_DBGMC_START(req->mc_bus);
1564
1565         /* DMAMOV CCR, ccr */
1566         off += _emit_MOV(dry_run, &buf[off], CCR, pxs->ccr);
1567
1568         x = pxs->r->x;
1569         if (!pxs->r->infiniteloop) {
1570                 do {
1571                         /* Error if xfer length is not aligned at burst size */
1572                         if (x->bytes % (BRST_SIZE(pxs->ccr) *
1573                                         BRST_LEN(pxs->ccr)))
1574                                 return -EINVAL;
1575
1576                         pxs->x = x;
1577                         off += _setup_xfer(dry_run, &buf[off], pxs);
1578
1579                         x = x->next;
1580                 } while (x);
1581
1582                 /* DMASEV peripheral/event */
1583                 off += _emit_SEV(dry_run, &buf[off], thrd->ev);
1584                 /* DMAEND */
1585                 off += _emit_END(dry_run, &buf[off]);
1586         } else {
1587                 /* Error if xfer length is not aligned at burst size */
1588                 if (x->bytes % (BRST_SIZE(pxs->ccr) * BRST_LEN(pxs->ccr)))
1589                         return -EINVAL;
1590
1591                 pxs->x = x;
1592                 off += _setup_xfer_infiniteloop(dry_run, &buf[off],
1593                                                 pxs, thrd->ev);
1594         }
1595
1596         return off;
1597 }
1598
1599 static inline u32 _prepare_ccr(const struct pl330_reqcfg *rqc)
1600 {
1601         u32 ccr = 0;
1602
1603         if (rqc->src_inc)
1604                 ccr |= CC_SRCINC;
1605
1606         if (rqc->dst_inc)
1607                 ccr |= CC_DSTINC;
1608
1609         /* We set same protection levels for Src and DST for now */
1610         if (rqc->privileged)
1611                 ccr |= CC_SRCPRI | CC_DSTPRI;
1612         if (rqc->nonsecure)
1613                 ccr |= CC_SRCNS | CC_DSTNS;
1614         if (rqc->insnaccess)
1615                 ccr |= CC_SRCIA | CC_DSTIA;
1616
1617         ccr |= (((rqc->brst_len - 1) & 0xf) << CC_SRCBRSTLEN_SHFT);
1618         ccr |= (((rqc->brst_len - 1) & 0xf) << CC_DSTBRSTLEN_SHFT);
1619
1620         ccr |= (rqc->brst_size << CC_SRCBRSTSIZE_SHFT);
1621         ccr |= (rqc->brst_size << CC_DSTBRSTSIZE_SHFT);
1622
1623         ccr |= (rqc->scctl << CC_SRCCCTRL_SHFT);
1624         ccr |= (rqc->dcctl << CC_DSTCCTRL_SHFT);
1625
1626         ccr |= (rqc->swap << CC_SWAP_SHFT);
1627
1628         return ccr;
1629 }
1630
1631 static inline bool _is_valid(u32 ccr)
1632 {
1633         enum pl330_dstcachectrl dcctl;
1634         enum pl330_srccachectrl scctl;
1635
1636         dcctl = (ccr >> CC_DSTCCTRL_SHFT) & CC_DRCCCTRL_MASK;
1637         scctl = (ccr >> CC_SRCCCTRL_SHFT) & CC_SRCCCTRL_MASK;
1638
1639         if (dcctl == DINVALID1 || dcctl == DINVALID2
1640                         || scctl == SINVALID1 || scctl == SINVALID2)
1641                 return false;
1642         else
1643                 return true;
1644 }
1645
1646 /*
1647  * Submit a list of xfers after which the client wants notification.
1648  * Client is not notified after each xfer unit, just once after all
1649  * xfer units are done or some error occurs.
1650  */
1651 static int pl330_submit_req(void *ch_id, struct pl330_req *r)
1652 {
1653         struct pl330_thread *thrd = ch_id;
1654         struct pl330_dmac *pl330;
1655         struct pl330_info *pi;
1656         struct _xfer_spec xs;
1657         unsigned long flags;
1658         void __iomem *regs;
1659         unsigned idx;
1660         u32 ccr;
1661         int ret = 0;
1662
1663         /* No Req or Unacquired Channel or DMAC */
1664         if (!r || !thrd || thrd->free)
1665                 return -EINVAL;
1666
1667         pl330 = thrd->dmac;
1668         pi = pl330->pinfo;
1669         regs = pi->base;
1670
1671         if (pl330->state == DYING
1672                 || pl330->dmac_tbd.reset_chan & (1 << thrd->id)) {
1673                 dev_info(thrd->dmac->pinfo->dev, "%s:%d\n",
1674                         __func__, __LINE__);
1675                 return -EAGAIN;
1676         }
1677
1678         /* If request for non-existing peripheral */
1679         if (r->rqtype != MEMTOMEM && r->peri >= pi->pcfg.num_peri) {
1680                 dev_info(thrd->dmac->pinfo->dev,
1681                                 "%s:%d Invalid peripheral(%u)!\n",
1682                                 __func__, __LINE__, r->peri);
1683                 return -EINVAL;
1684         }
1685
1686         spin_lock_irqsave(&pl330->lock, flags);
1687
1688         if (_queue_full(thrd)) {
1689                 ret = -EAGAIN;
1690                 goto xfer_exit;
1691         }
1692
1693
1694         /* Use last settings, if not provided */
1695         if (r->cfg) {
1696                 /* Prefer Secure Channel */
1697                 if (!_manager_ns(thrd))
1698                         r->cfg->nonsecure = 0;
1699                 else
1700                         r->cfg->nonsecure = 1;
1701
1702                 ccr = _prepare_ccr(r->cfg);
1703         } else {
1704                 ccr = readl(regs + CC(thrd->id));
1705         }
1706
1707         /* If this req doesn't have valid xfer settings */
1708         if (!_is_valid(ccr)) {
1709                 ret = -EINVAL;
1710                 dev_info(thrd->dmac->pinfo->dev, "%s:%d Invalid CCR(%x)!\n",
1711                         __func__, __LINE__, ccr);
1712                 goto xfer_exit;
1713         }
1714
1715         idx = IS_FREE(&thrd->req[0]) ? 0 : 1;
1716
1717         xs.ccr = ccr;
1718         xs.r = r;
1719
1720         /* First dry run to check if req is acceptable */
1721         ret = _setup_req(1, thrd, idx, &xs);
1722         if (ret < 0)
1723                 goto xfer_exit;
1724
1725         if (ret > pi->mcbufsz / 2) {
1726                 dev_info(thrd->dmac->pinfo->dev,
1727                         "%s:%d Trying increasing mcbufsz\n",
1728                                 __func__, __LINE__);
1729                 ret = -ENOMEM;
1730                 goto xfer_exit;
1731         }
1732
1733         /* Hook the request */
1734         thrd->lstenq = idx;
1735         thrd->req[idx].mc_len = _setup_req(0, thrd, idx, &xs);
1736         thrd->req[idx].r = r;
1737
1738         ret = 0;
1739
1740 xfer_exit:
1741         spin_unlock_irqrestore(&pl330->lock, flags);
1742
1743         return ret;
1744 }
1745
1746 static void pl330_dotask(unsigned long data)
1747 {
1748         struct pl330_dmac *pl330 = (struct pl330_dmac *) data;
1749         struct pl330_info *pi = pl330->pinfo;
1750         unsigned long flags;
1751         int i;
1752
1753         spin_lock_irqsave(&pl330->lock, flags);
1754
1755         /* The DMAC itself gone nuts */
1756         if (pl330->dmac_tbd.reset_dmac) {
1757                 pl330->state = DYING;
1758                 /* Reset the manager too */
1759                 pl330->dmac_tbd.reset_mngr = true;
1760                 /* Clear the reset flag */
1761                 pl330->dmac_tbd.reset_dmac = false;
1762         }
1763
1764         if (pl330->dmac_tbd.reset_mngr) {
1765                 _stop(pl330->manager);
1766                 /* Reset all channels */
1767                 pl330->dmac_tbd.reset_chan = (1 << pi->pcfg.num_chan) - 1;
1768                 /* Clear the reset flag */
1769                 pl330->dmac_tbd.reset_mngr = false;
1770         }
1771
1772         for (i = 0; i < pi->pcfg.num_chan; i++) {
1773
1774                 if (pl330->dmac_tbd.reset_chan & (1 << i)) {
1775                         struct pl330_thread *thrd = &pl330->channels[i];
1776                         void __iomem *regs = pi->base;
1777                         enum pl330_op_err err;
1778
1779                         _stop(thrd);
1780
1781                         if (readl(regs + FSC) & (1 << thrd->id))
1782                                 err = PL330_ERR_FAIL;
1783                         else
1784                                 err = PL330_ERR_ABORT;
1785
1786                         spin_unlock_irqrestore(&pl330->lock, flags);
1787
1788                         _callback(thrd->req[1 - thrd->lstenq].r, err);
1789                         _callback(thrd->req[thrd->lstenq].r, err);
1790
1791                         spin_lock_irqsave(&pl330->lock, flags);
1792
1793                         thrd->req[0].r = NULL;
1794                         thrd->req[1].r = NULL;
1795                         mark_free(thrd, 0);
1796                         mark_free(thrd, 1);
1797
1798                         /* Clear the reset flag */
1799                         pl330->dmac_tbd.reset_chan &= ~(1 << i);
1800                 }
1801         }
1802
1803         spin_unlock_irqrestore(&pl330->lock, flags);
1804
1805         return;
1806 }
1807
1808 /* Returns 1 if state was updated, 0 otherwise */
1809 static int pl330_update(const struct pl330_info *pi)
1810 {
1811         struct pl330_req *rqdone, *tmp;
1812         struct pl330_dmac *pl330;
1813         unsigned long flags;
1814         void __iomem *regs;
1815         u32 val;
1816         int id, ev, ret = 0;
1817
1818         if (!pi || !pi->pl330_data)
1819                 return 0;
1820
1821         regs = pi->base;
1822         pl330 = pi->pl330_data;
1823
1824         spin_lock_irqsave(&pl330->lock, flags);
1825
1826         val = readl(regs + FSM) & 0x1;
1827         if (val)
1828                 pl330->dmac_tbd.reset_mngr = true;
1829         else
1830                 pl330->dmac_tbd.reset_mngr = false;
1831
1832         val = readl(regs + FSC) & ((1 << pi->pcfg.num_chan) - 1);
1833         pl330->dmac_tbd.reset_chan |= val;
1834         if (val) {
1835                 int i = 0;
1836                 while (i < pi->pcfg.num_chan) {
1837                         if (val & (1 << i)) {
1838                                 dev_info(pi->dev,
1839                                         "Reset Channel-%d\t CS-%x FTC-%x\n",
1840                                                 i, readl(regs + CS(i)),
1841                                                 readl(regs + FTC(i)));
1842                                 _stop(&pl330->channels[i]);
1843                         }
1844                         i++;
1845                 }
1846         }
1847
1848         /* Check which event happened i.e, thread notified */
1849         val = readl(regs + ES);
1850         if (pi->pcfg.num_events < 32
1851                         && val & ~((1 << pi->pcfg.num_events) - 1)) {
1852                 pl330->dmac_tbd.reset_dmac = true;
1853                 dev_err(pi->dev, "%s:%d Unexpected!\n", __func__, __LINE__);
1854                 ret = 1;
1855                 goto updt_exit;
1856         }
1857
1858         for (ev = 0; ev < pi->pcfg.num_events; ev++) {
1859                 if (val & (1 << ev)) { /* Event occurred */
1860                         struct pl330_thread *thrd;
1861                         u32 inten = readl(regs + INTEN);
1862                         int active;
1863
1864                         /* Clear the event */
1865                         if (inten & (1 << ev))
1866                                 writel(1 << ev, regs + INTCLR);
1867
1868                         ret = 1;
1869
1870                         id = pl330->events[ev];
1871
1872                         if (id == -1)
1873                                 continue;
1874
1875                         thrd = &pl330->channels[id];
1876
1877                         active = thrd->req_running;
1878                         if (active == -1) /* Aborted */
1879                                 continue;
1880
1881                         /* Detach the req */
1882                         rqdone = thrd->req[active].r;
1883                         if (!rqdone->infiniteloop) {
1884
1885                                 /* Detach the req */
1886                                 thrd->req[active].r = NULL;
1887
1888                                 mark_free(thrd, active);
1889
1890                                 /* Get going again ASAP */
1891                                 _start(thrd);
1892                         }
1893
1894                         /* For now, just make a list of callbacks to be done */
1895                         list_add_tail(&rqdone->rqd, &pl330->req_done);
1896                 }
1897         }
1898
1899         /* Now that we are in no hurry, do the callbacks */
1900         list_for_each_entry_safe(rqdone, tmp, &pl330->req_done, rqd) {
1901                 list_del(&rqdone->rqd);
1902
1903                 spin_unlock_irqrestore(&pl330->lock, flags);
1904                 _callback(rqdone, PL330_ERR_NONE);
1905                 spin_lock_irqsave(&pl330->lock, flags);
1906         }
1907
1908 updt_exit:
1909         spin_unlock_irqrestore(&pl330->lock, flags);
1910
1911         if (pl330->dmac_tbd.reset_dmac
1912                         || pl330->dmac_tbd.reset_mngr
1913                         || pl330->dmac_tbd.reset_chan) {
1914                 ret = 1;
1915                 tasklet_schedule(&pl330->tasks);
1916         }
1917
1918         return ret;
1919 }
1920
1921 static int pl330_chan_ctrl(void *ch_id, enum pl330_chan_op op)
1922 {
1923         struct pl330_thread *thrd = ch_id;
1924         struct pl330_dmac *pl330;
1925         unsigned long flags;
1926         int ret = 0, active;
1927
1928         if (!thrd || thrd->free || thrd->dmac->state == DYING)
1929                 return -EINVAL;
1930
1931         pl330 = thrd->dmac;
1932         active = thrd->req_running;
1933
1934         spin_lock_irqsave(&pl330->lock, flags);
1935
1936         switch (op) {
1937         case PL330_OP_FLUSH:
1938                 /* Make sure the channel is stopped */
1939                 _stop(thrd);
1940
1941                 thrd->req[0].r = NULL;
1942                 thrd->req[1].r = NULL;
1943                 mark_free(thrd, 0);
1944                 mark_free(thrd, 1);
1945                 break;
1946
1947         case PL330_OP_ABORT:
1948                 /* Make sure the channel is stopped */
1949                 _stop(thrd);
1950
1951                 /* ABORT is only for the active req */
1952                 if (active == -1)
1953                         break;
1954
1955                 thrd->req[active].r = NULL;
1956                 mark_free(thrd, active);
1957
1958                 /* Start the next */
1959         case PL330_OP_START:
1960                 if ((active == -1) && !_start(thrd))
1961                         ret = -EIO;
1962                 break;
1963
1964         default:
1965                 ret = -EINVAL;
1966         }
1967
1968         spin_unlock_irqrestore(&pl330->lock, flags);
1969         return ret;
1970 }
1971
1972 /* Reserve an event */
1973 static inline int _alloc_event(struct pl330_thread *thrd)
1974 {
1975         struct pl330_dmac *pl330 = thrd->dmac;
1976         struct pl330_info *pi = pl330->pinfo;
1977         int ev;
1978
1979         for (ev = 0; ev < pi->pcfg.num_events; ev++)
1980                 if (pl330->events[ev] == -1) {
1981                         pl330->events[ev] = thrd->id;
1982                         return ev;
1983                 }
1984
1985         return -1;
1986 }
1987
1988 static bool _chan_ns(const struct pl330_info *pi, int i)
1989 {
1990         return pi->pcfg.irq_ns & (1 << i);
1991 }
1992
1993 /* Upon success, returns IdentityToken for the
1994  * allocated channel, NULL otherwise.
1995  */
1996 static void *pl330_request_channel(const struct pl330_info *pi)
1997 {
1998         struct pl330_thread *thrd = NULL;
1999         struct pl330_dmac *pl330;
2000         unsigned long flags;
2001         int chans, i;
2002
2003         if (!pi || !pi->pl330_data)
2004                 return NULL;
2005
2006         pl330 = pi->pl330_data;
2007
2008         if (pl330->state == DYING)
2009                 return NULL;
2010
2011         chans = pi->pcfg.num_chan;
2012
2013         spin_lock_irqsave(&pl330->lock, flags);
2014
2015         for (i = 0; i < chans; i++) {
2016                 thrd = &pl330->channels[i];
2017                 if ((thrd->free) && (!_manager_ns(thrd) ||
2018                                         _chan_ns(pi, i))) {
2019                         thrd->ev = _alloc_event(thrd);
2020                         if (thrd->ev >= 0) {
2021                                 thrd->free = false;
2022                                 thrd->lstenq = 1;
2023                                 thrd->req[0].r = NULL;
2024                                 mark_free(thrd, 0);
2025                                 thrd->req[1].r = NULL;
2026                                 mark_free(thrd, 1);
2027                                 break;
2028                         }
2029                 }
2030                 thrd = NULL;
2031         }
2032
2033         spin_unlock_irqrestore(&pl330->lock, flags);
2034
2035         return thrd;
2036 }
2037
2038 /* Release an event */
2039 static inline void _free_event(struct pl330_thread *thrd, int ev)
2040 {
2041         struct pl330_dmac *pl330 = thrd->dmac;
2042         struct pl330_info *pi = pl330->pinfo;
2043         void __iomem *regs = pi->base;
2044         u32 inten = readl(regs + INTEN);
2045
2046         /* If the event is valid and was held by the thread */
2047         if (ev >= 0 && ev < pi->pcfg.num_events
2048                         && pl330->events[ev] == thrd->id) {
2049                 pl330->events[ev] = -1;
2050
2051                 if (readl(regs + ES) & (1 << ev)) {
2052                         if (!(inten & (1 << ev)))
2053                                 writel(inten | (1 << ev), regs + INTEN);
2054                         writel(1 << ev, regs + INTCLR);
2055                         writel(inten & ~(1 << ev) , regs + INTEN);
2056                 }
2057         }
2058 }
2059
2060 static void pl330_release_channel(void *ch_id)
2061 {
2062         struct pl330_thread *thrd = ch_id;
2063         struct pl330_dmac *pl330;
2064         unsigned long flags;
2065
2066         if (!thrd || thrd->free)
2067                 return;
2068
2069         _stop(thrd);
2070
2071         _callback(thrd->req[1 - thrd->lstenq].r, PL330_ERR_ABORT);
2072         _callback(thrd->req[thrd->lstenq].r, PL330_ERR_ABORT);
2073
2074         pl330 = thrd->dmac;
2075
2076         spin_lock_irqsave(&pl330->lock, flags);
2077         _free_event(thrd, thrd->ev);
2078         thrd->free = true;
2079         spin_unlock_irqrestore(&pl330->lock, flags);
2080 }
2081
2082 /* Initialize the structure for PL330 configuration, that can be used
2083  * by the client driver the make best use of the DMAC
2084  */
2085 static void read_dmac_config(struct pl330_info *pi)
2086 {
2087         void __iomem *regs = pi->base;
2088         u32 val;
2089
2090         val = readl(regs + CRD) >> CRD_DATA_WIDTH_SHIFT;
2091         val &= CRD_DATA_WIDTH_MASK;
2092         pi->pcfg.data_bus_width = 8 * (1 << val);
2093
2094         val = readl(regs + CRD) >> CRD_DATA_BUFF_SHIFT;
2095         val &= CRD_DATA_BUFF_MASK;
2096         pi->pcfg.data_buf_dep = val + 1;
2097
2098         val = readl(regs + CR0) >> CR0_NUM_CHANS_SHIFT;
2099         val &= CR0_NUM_CHANS_MASK;
2100         val += 1;
2101         pi->pcfg.num_chan = val;
2102
2103         val = readl(regs + CR0);
2104         if (val & CR0_PERIPH_REQ_SET) {
2105                 val = (val >> CR0_NUM_PERIPH_SHIFT) & CR0_NUM_PERIPH_MASK;
2106                 val += 1;
2107                 pi->pcfg.num_peri = val;
2108                 pi->pcfg.peri_ns = readl(regs + CR4);
2109         } else {
2110                 pi->pcfg.num_peri = 0;
2111         }
2112
2113         val = readl(regs + CR0);
2114         if (val & CR0_BOOT_MAN_NS)
2115                 pi->pcfg.mode |= DMAC_MODE_NS;
2116         else
2117                 pi->pcfg.mode &= ~DMAC_MODE_NS;
2118
2119         val = readl(regs + CR0) >> CR0_NUM_EVENTS_SHIFT;
2120         val &= CR0_NUM_EVENTS_MASK;
2121         val += 1;
2122         pi->pcfg.num_events = val;
2123
2124         pi->pcfg.irq_ns = readl(regs + CR3);
2125
2126         pi->pcfg.periph_id = get_id(pi, PERIPH_ID);
2127         pi->pcfg.pcell_id = get_id(pi, PCELL_ID);
2128 }
2129
2130 static inline void _reset_thread(struct pl330_thread *thrd)
2131 {
2132         struct pl330_dmac *pl330 = thrd->dmac;
2133         struct pl330_info *pi = pl330->pinfo;
2134
2135         thrd->req[0].mc_cpu = pl330->mcode_cpu
2136                                 + (thrd->id * pi->mcbufsz);
2137         thrd->req[0].mc_bus = pl330->mcode_bus
2138                                 + (thrd->id * pi->mcbufsz);
2139         thrd->req[0].r = NULL;
2140         mark_free(thrd, 0);
2141
2142         thrd->req[1].mc_cpu = thrd->req[0].mc_cpu
2143                                 + pi->mcbufsz / 2;
2144         thrd->req[1].mc_bus = thrd->req[0].mc_bus
2145                                 + pi->mcbufsz / 2;
2146         thrd->req[1].r = NULL;
2147         mark_free(thrd, 1);
2148 }
2149
2150 static int dmac_alloc_threads(struct pl330_dmac *pl330)
2151 {
2152         struct pl330_info *pi = pl330->pinfo;
2153         int chans = pi->pcfg.num_chan;
2154         struct pl330_thread *thrd;
2155         int i;
2156
2157         /* Allocate 1 Manager and 'chans' Channel threads */
2158         pl330->channels = kzalloc((1 + chans) * sizeof(*thrd),
2159                                         GFP_KERNEL);
2160         if (!pl330->channels)
2161                 return -ENOMEM;
2162
2163         /* Init Channel threads */
2164         for (i = 0; i < chans; i++) {
2165                 thrd = &pl330->channels[i];
2166                 thrd->id = i;
2167                 thrd->dmac = pl330;
2168                 _reset_thread(thrd);
2169                 thrd->free = true;
2170         }
2171
2172         /* MANAGER is indexed at the end */
2173         thrd = &pl330->channels[chans];
2174         thrd->id = chans;
2175         thrd->dmac = pl330;
2176         thrd->free = false;
2177         pl330->manager = thrd;
2178
2179         return 0;
2180 }
2181
2182 static int dmac_alloc_resources(struct pl330_dmac *pl330)
2183 {
2184         struct pl330_info *pi = pl330->pinfo;
2185         int chans = pi->pcfg.num_chan;
2186         int ret;
2187
2188         /*
2189          * Alloc MicroCode buffer for 'chans' Channel threads.
2190          * A channel's buffer offset is (Channel_Id * MCODE_BUFF_PERCHAN)
2191          */
2192         pl330->mcode_cpu = dma_alloc_coherent(pi->dev,
2193                                 chans * pi->mcbufsz,
2194                                 &pl330->mcode_bus, GFP_KERNEL);
2195         if (!pl330->mcode_cpu) {
2196                 dev_err(pi->dev, "%s:%d Can't allocate memory!\n",
2197                         __func__, __LINE__);
2198                 return -ENOMEM;
2199         }
2200
2201         ret = dmac_alloc_threads(pl330);
2202         if (ret) {
2203                 dev_err(pi->dev, "%s:%d Can't to create channels for DMAC!\n",
2204                         __func__, __LINE__);
2205                 dma_free_coherent(pi->dev,
2206                                 chans * pi->mcbufsz,
2207                                 pl330->mcode_cpu, pl330->mcode_bus);
2208                 return ret;
2209         }
2210
2211         return 0;
2212 }
2213
2214 static int pl330_add(struct pl330_info *pi)
2215 {
2216         struct pl330_dmac *pl330;
2217         void __iomem *regs;
2218         int i, ret;
2219
2220         if (!pi || !pi->dev)
2221                 return -EINVAL;
2222
2223         /* If already added */
2224         if (pi->pl330_data)
2225                 return -EINVAL;
2226
2227         /*
2228          * If the SoC can perform reset on the DMAC, then do it
2229          * before reading its configuration.
2230          */
2231         if (pi->dmac_reset)
2232                 pi->dmac_reset(pi);
2233
2234         regs = pi->base;
2235
2236         /* Check if we can handle this DMAC */
2237         if ((get_id(pi, PERIPH_ID) & 0xfffff) != PERIPH_ID_VAL
2238            || get_id(pi, PCELL_ID) != PCELL_ID_VAL) {
2239                 dev_err(pi->dev, "PERIPH_ID 0x%x, PCELL_ID 0x%x !\n",
2240                         get_id(pi, PERIPH_ID), get_id(pi, PCELL_ID));
2241                 return -EINVAL;
2242         }
2243
2244         /* Read the configuration of the DMAC */
2245         read_dmac_config(pi);
2246
2247         if (pi->pcfg.num_events == 0) {
2248                 dev_err(pi->dev, "%s:%d Can't work without events!\n",
2249                         __func__, __LINE__);
2250                 return -EINVAL;
2251         }
2252
2253         pl330 = kzalloc(sizeof(*pl330), GFP_KERNEL);
2254         if (!pl330) {
2255                 dev_err(pi->dev, "%s:%d Can't allocate memory!\n",
2256                         __func__, __LINE__);
2257                 return -ENOMEM;
2258         }
2259
2260         /* Assign the info structure and private data */
2261         pl330->pinfo = pi;
2262         pi->pl330_data = pl330;
2263
2264         spin_lock_init(&pl330->lock);
2265
2266         INIT_LIST_HEAD(&pl330->req_done);
2267
2268         /* Use default MC buffer size if not provided */
2269         if (!pi->mcbufsz)
2270                 pi->mcbufsz = MCODE_BUFF_PER_REQ * 2;
2271
2272         /* Mark all events as free */
2273         for (i = 0; i < pi->pcfg.num_events; i++)
2274                 pl330->events[i] = -1;
2275
2276         /* Allocate resources needed by the DMAC */
2277         ret = dmac_alloc_resources(pl330);
2278         if (ret) {
2279                 dev_err(pi->dev, "Unable to create channels for DMAC\n");
2280                 kfree(pl330);
2281                 return ret;
2282         }
2283
2284         tasklet_init(&pl330->tasks, pl330_dotask, (unsigned long) pl330);
2285
2286         pl330->state = INIT;
2287
2288         return 0;
2289 }
2290
2291 static int dmac_free_threads(struct pl330_dmac *pl330)
2292 {
2293         struct pl330_info *pi = pl330->pinfo;
2294         int chans = pi->pcfg.num_chan;
2295         struct pl330_thread *thrd;
2296         int i;
2297
2298         /* Release Channel threads */
2299         for (i = 0; i < chans; i++) {
2300                 thrd = &pl330->channels[i];
2301                 pl330_release_channel((void *)thrd);
2302         }
2303
2304         /* Free memory */
2305         kfree(pl330->channels);
2306
2307         return 0;
2308 }
2309
2310 static void dmac_free_resources(struct pl330_dmac *pl330)
2311 {
2312         struct pl330_info *pi = pl330->pinfo;
2313         int chans = pi->pcfg.num_chan;
2314
2315         dmac_free_threads(pl330);
2316
2317         dma_free_coherent(pi->dev, chans * pi->mcbufsz,
2318                                 pl330->mcode_cpu, pl330->mcode_bus);
2319 }
2320
2321 static void pl330_del(struct pl330_info *pi)
2322 {
2323         struct pl330_dmac *pl330;
2324
2325         if (!pi || !pi->pl330_data)
2326                 return;
2327
2328         pl330 = pi->pl330_data;
2329
2330         pl330->state = UNINIT;
2331
2332         tasklet_kill(&pl330->tasks);
2333
2334         /* Free DMAC resources */
2335         dmac_free_resources(pl330);
2336
2337         kfree(pl330);
2338         pi->pl330_data = NULL;
2339 }
2340
2341 /* forward declaration */
2342 static struct amba_driver pl330_driver;
2343
2344 static inline struct dma_pl330_chan *
2345 to_pchan(struct dma_chan *ch)
2346 {
2347         if (!ch)
2348                 return NULL;
2349
2350         return container_of(ch, struct dma_pl330_chan, chan);
2351 }
2352
2353 static inline struct dma_pl330_desc *
2354 to_desc(struct dma_async_tx_descriptor *tx)
2355 {
2356         return container_of(tx, struct dma_pl330_desc, txd);
2357 }
2358
2359 static inline void free_desc_list(struct list_head *list)
2360 {
2361         struct dma_pl330_dmac *pdmac;
2362         struct dma_pl330_desc *desc;
2363         struct dma_pl330_chan *pch = NULL;
2364         unsigned long flags;
2365
2366         /* Finish off the work list */
2367         list_for_each_entry(desc, list, node) {
2368                 dma_async_tx_callback callback;
2369                 void *param;
2370
2371                 /* All desc in a list belong to same channel */
2372                 pch = desc->pchan;
2373                 callback = desc->txd.callback;
2374                 param = desc->txd.callback_param;
2375
2376                 if (callback)
2377                         callback(param);
2378
2379                 desc->pchan = NULL;
2380         }
2381
2382         /* pch will be unset if list was empty */
2383         if (!pch)
2384                 return;
2385
2386         pdmac = pch->dmac;
2387
2388         spin_lock_irqsave(&pdmac->pool_lock, flags);
2389         list_splice_tail_init(list, &pdmac->desc_pool);
2390         spin_unlock_irqrestore(&pdmac->pool_lock, flags);
2391 }
2392
2393 static inline void handle_cyclic_desc_list(struct list_head *list)
2394 {
2395         struct dma_pl330_desc *desc;
2396         struct dma_pl330_chan *pch = NULL;
2397         unsigned long flags;
2398
2399         list_for_each_entry(desc, list, node) {
2400                 dma_async_tx_callback callback;
2401
2402                 /* Change status to reload it */
2403                 desc->status = PREP;
2404                 pch = desc->pchan;
2405                 callback = desc->txd.callback;
2406                 if (callback)
2407                         callback(desc->txd.callback_param);
2408         }
2409
2410         /* pch will be unset if list was empty */
2411         if (!pch)
2412                 return;
2413
2414         spin_lock_irqsave(&pch->lock, flags);
2415         list_splice_tail_init(list, &pch->work_list);
2416         spin_unlock_irqrestore(&pch->lock, flags);
2417 }
2418
2419 static inline void fill_queue(struct dma_pl330_chan *pch)
2420 {
2421         struct dma_pl330_desc *desc;
2422         int ret;
2423
2424         list_for_each_entry(desc, &pch->work_list, node) {
2425
2426                 /* If already submitted */
2427                 if (desc->status == BUSY)
2428                         continue;
2429
2430                 ret = pl330_submit_req(pch->pl330_chid,
2431                                                 &desc->req);
2432                 if (!ret) {
2433                         desc->status = BUSY;
2434                 } else if (ret == -EAGAIN) {
2435                         /* QFull or DMAC Dying */
2436                         break;
2437                 } else {
2438                         /* Unacceptable request */
2439                         desc->status = DONE;
2440                         dev_err(pch->dmac->pif.dev, "%s:%d Bad Desc(%d)\n",
2441                                         __func__, __LINE__, desc->txd.cookie);
2442                         tasklet_schedule(&pch->task);
2443                 }
2444         }
2445 }
2446
2447 static void pl330_tasklet(unsigned long data)
2448 {
2449         struct dma_pl330_chan *pch = (struct dma_pl330_chan *)data;
2450         struct dma_pl330_desc *desc, *_dt;
2451         unsigned long flags;
2452         LIST_HEAD(list);
2453
2454         spin_lock_irqsave(&pch->lock, flags);
2455
2456         /* Pick up ripe tomatoes */
2457         list_for_each_entry_safe(desc, _dt, &pch->work_list, node)
2458                 if (desc->status == DONE) {
2459                         if (!pch->cyclic)
2460                                 dma_cookie_complete(&desc->txd);
2461                         list_move_tail(&desc->node, &list);
2462                 }
2463
2464         /* Try to submit a req imm. next to the last completed cookie */
2465         fill_queue(pch);
2466
2467         /* Make sure the PL330 Channel thread is active */
2468         pl330_chan_ctrl(pch->pl330_chid, PL330_OP_START);
2469
2470         spin_unlock_irqrestore(&pch->lock, flags);
2471
2472         if (pch->cyclic)
2473                 handle_cyclic_desc_list(&list);
2474         else
2475                 free_desc_list(&list);
2476 }
2477
2478 static void dma_pl330_rqcb(void *token, enum pl330_op_err err)
2479 {
2480         struct dma_pl330_desc *desc = token;
2481         struct dma_pl330_chan *pch = desc->pchan;
2482         unsigned long flags;
2483
2484         /* If desc aborted */
2485         if (!pch)
2486                 return;
2487
2488         spin_lock_irqsave(&pch->lock, flags);
2489
2490         desc->status = DONE;
2491
2492         spin_unlock_irqrestore(&pch->lock, flags);
2493
2494         tasklet_schedule(&pch->task);
2495 }
2496
2497 static bool pl330_dt_filter(struct dma_chan *chan, void *param)
2498 {
2499         struct dma_pl330_filter_args *fargs = param;
2500
2501         if (chan->device != &fargs->pdmac->ddma)
2502                 return false;
2503
2504         return (chan->chan_id == fargs->chan_id);
2505 }
2506
2507 bool pl330_filter(struct dma_chan *chan, void *param)
2508 {
2509         u8 *peri_id;
2510
2511         if (chan->device->dev->driver != &pl330_driver.drv)
2512                 return false;
2513
2514         peri_id = chan->private;
2515         return *peri_id == (unsigned)param;
2516 }
2517 EXPORT_SYMBOL(pl330_filter);
2518
2519 static struct dma_chan *of_dma_pl330_xlate(struct of_phandle_args *dma_spec,
2520                                                 struct of_dma *ofdma)
2521 {
2522         int count = dma_spec->args_count;
2523         struct dma_pl330_dmac *pdmac = ofdma->of_dma_data;
2524         struct dma_pl330_filter_args fargs;
2525         dma_cap_mask_t cap;
2526
2527         if (!pdmac)
2528                 return NULL;
2529
2530         if (count != 1)
2531                 return NULL;
2532
2533         fargs.pdmac = pdmac;
2534         fargs.chan_id = dma_spec->args[0];
2535
2536         dma_cap_zero(cap);
2537         dma_cap_set(DMA_SLAVE, cap);
2538         dma_cap_set(DMA_CYCLIC, cap);
2539
2540         return dma_request_channel(cap, pl330_dt_filter, &fargs);
2541 }
2542
2543 static int pl330_alloc_chan_resources(struct dma_chan *chan)
2544 {
2545         struct dma_pl330_chan *pch = to_pchan(chan);
2546         struct dma_pl330_dmac *pdmac = pch->dmac;
2547         unsigned long flags;
2548
2549         spin_lock_irqsave(&pch->lock, flags);
2550
2551         dma_cookie_init(chan);
2552         pch->cyclic = false;
2553
2554         pch->pl330_chid = pl330_request_channel(&pdmac->pif);
2555         if (!pch->pl330_chid) {
2556                 spin_unlock_irqrestore(&pch->lock, flags);
2557                 return -ENOMEM;
2558         }
2559
2560         tasklet_init(&pch->task, pl330_tasklet, (unsigned long) pch);
2561
2562         spin_unlock_irqrestore(&pch->lock, flags);
2563
2564         return 1;
2565 }
2566
2567 static int pl330_control(struct dma_chan *chan, enum dma_ctrl_cmd cmd, unsigned long arg)
2568 {
2569         struct dma_pl330_chan *pch = to_pchan(chan);
2570         struct dma_pl330_desc *desc, *_dt;
2571         unsigned long flags;
2572         struct dma_pl330_dmac *pdmac = pch->dmac;
2573         struct dma_slave_config *slave_config;
2574         LIST_HEAD(list);
2575
2576         switch (cmd) {
2577         case DMA_TERMINATE_ALL:
2578                 spin_lock_irqsave(&pch->lock, flags);
2579
2580                 /* FLUSH the PL330 Channel thread */
2581                 pl330_chan_ctrl(pch->pl330_chid, PL330_OP_FLUSH);
2582
2583                 /* Mark all desc done */
2584                 list_for_each_entry_safe(desc, _dt, &pch->work_list , node) {
2585                         desc->status = DONE;
2586                         list_move_tail(&desc->node, &list);
2587                 }
2588
2589                 list_splice_tail_init(&list, &pdmac->desc_pool);
2590                 spin_unlock_irqrestore(&pch->lock, flags);
2591                 break;
2592         case DMA_SLAVE_CONFIG:
2593                 slave_config = (struct dma_slave_config *)arg;
2594
2595                 if (slave_config->direction == DMA_MEM_TO_DEV) {
2596                         if (slave_config->dst_addr)
2597                                 pch->fifo_addr = slave_config->dst_addr;
2598                         if (slave_config->dst_addr_width)
2599                                 pch->burst_sz = __ffs(slave_config->dst_addr_width);
2600                         if (slave_config->dst_maxburst)
2601                                 pch->burst_len = slave_config->dst_maxburst;
2602                 } else if (slave_config->direction == DMA_DEV_TO_MEM) {
2603                         if (slave_config->src_addr)
2604                                 pch->fifo_addr = slave_config->src_addr;
2605                         if (slave_config->src_addr_width)
2606                                 pch->burst_sz = __ffs(slave_config->src_addr_width);
2607                         if (slave_config->src_maxburst)
2608                                 pch->burst_len = slave_config->src_maxburst;
2609                 }
2610                 break;
2611         default:
2612                 dev_err(pch->dmac->pif.dev, "Not supported command.\n");
2613                 return -ENXIO;
2614         }
2615
2616         return 0;
2617 }
2618
2619 static void pl330_free_chan_resources(struct dma_chan *chan)
2620 {
2621         struct dma_pl330_chan *pch = to_pchan(chan);
2622         unsigned long flags;
2623
2624         tasklet_kill(&pch->task);
2625
2626         spin_lock_irqsave(&pch->lock, flags);
2627
2628         pl330_release_channel(pch->pl330_chid);
2629         pch->pl330_chid = NULL;
2630
2631         if (pch->cyclic)
2632                 list_splice_tail_init(&pch->work_list, &pch->dmac->desc_pool);
2633
2634         spin_unlock_irqrestore(&pch->lock, flags);
2635 }
2636
2637 static enum dma_status
2638 pl330_tx_status(struct dma_chan *chan, dma_cookie_t cookie,
2639                  struct dma_tx_state *txstate)
2640 {
2641         struct dma_pl330_chan *pch = to_pchan(chan);
2642         void __iomem *regs = pch->dmac->pif.base;
2643         struct pl330_thread *pt = pch->pl330_chid;
2644         enum dma_status st; 
2645         st = dma_cookie_status(chan, cookie, txstate);
2646         txstate->residue = readl(regs + DA(pt->id));
2647         return st;
2648 }
2649
2650 static void pl330_issue_pending(struct dma_chan *chan)
2651 {
2652         pl330_tasklet((unsigned long) to_pchan(chan));
2653 }
2654
2655 /*
2656  * We returned the last one of the circular list of descriptor(s)
2657  * from prep_xxx, so the argument to submit corresponds to the last
2658  * descriptor of the list.
2659  */
2660 static dma_cookie_t pl330_tx_submit(struct dma_async_tx_descriptor *tx)
2661 {
2662         struct dma_pl330_desc *desc, *last = to_desc(tx);
2663         struct dma_pl330_chan *pch = to_pchan(tx->chan);
2664         dma_cookie_t cookie;
2665         unsigned long flags;
2666
2667         spin_lock_irqsave(&pch->lock, flags);
2668
2669         /* Assign cookies to all nodes */
2670         while (!list_empty(&last->node)) {
2671                 desc = list_entry(last->node.next, struct dma_pl330_desc, node);
2672                 if (pch->cyclic) {
2673                         desc->txd.callback = last->txd.callback;
2674                         desc->txd.callback_param = last->txd.callback_param;
2675                 }
2676
2677                 dma_cookie_assign(&desc->txd);
2678
2679                 list_move_tail(&desc->node, &pch->work_list);
2680         }
2681
2682         cookie = dma_cookie_assign(&last->txd);
2683         list_add_tail(&last->node, &pch->work_list);
2684         spin_unlock_irqrestore(&pch->lock, flags);
2685
2686         return cookie;
2687 }
2688
2689 static inline void _init_desc(struct dma_pl330_desc *desc)
2690 {
2691         desc->pchan = NULL;
2692         desc->req.x = &desc->px;
2693         desc->req.token = desc;
2694         desc->rqcfg.swap = SWAP_NO;
2695         desc->rqcfg.privileged = 0;
2696         desc->rqcfg.insnaccess = 0;
2697         desc->rqcfg.scctl = SCCTRL0;
2698         desc->rqcfg.dcctl = DCCTRL0;
2699         desc->req.cfg = &desc->rqcfg;
2700         desc->req.xfer_cb = dma_pl330_rqcb;
2701         desc->txd.tx_submit = pl330_tx_submit;
2702
2703         INIT_LIST_HEAD(&desc->node);
2704 }
2705
2706 /* Returns the number of descriptors added to the DMAC pool */
2707 static int add_desc(struct dma_pl330_dmac *pdmac, gfp_t flg, int count)
2708 {
2709         struct dma_pl330_desc *desc;
2710         unsigned long flags;
2711         int i;
2712
2713         if (!pdmac)
2714                 return 0;
2715
2716         desc = kzalloc(count * sizeof(*desc), flg);
2717         if (!desc)
2718                 return 0;
2719
2720         spin_lock_irqsave(&pdmac->pool_lock, flags);
2721
2722         for (i = 0; i < count; i++) {
2723                 _init_desc(&desc[i]);
2724                 list_add_tail(&desc[i].node, &pdmac->desc_pool);
2725         }
2726
2727         spin_unlock_irqrestore(&pdmac->pool_lock, flags);
2728
2729         return count;
2730 }
2731
2732 static struct dma_pl330_desc *
2733 pluck_desc(struct dma_pl330_dmac *pdmac)
2734 {
2735         struct dma_pl330_desc *desc = NULL;
2736         unsigned long flags;
2737
2738         if (!pdmac)
2739                 return NULL;
2740
2741         spin_lock_irqsave(&pdmac->pool_lock, flags);
2742
2743         if (!list_empty(&pdmac->desc_pool)) {
2744                 desc = list_entry(pdmac->desc_pool.next,
2745                                 struct dma_pl330_desc, node);
2746
2747                 list_del_init(&desc->node);
2748
2749                 desc->status = PREP;
2750                 desc->txd.callback = NULL;
2751         }
2752
2753         spin_unlock_irqrestore(&pdmac->pool_lock, flags);
2754
2755         return desc;
2756 }
2757
2758 static struct dma_pl330_desc *pl330_get_desc(struct dma_pl330_chan *pch)
2759 {
2760         struct dma_pl330_dmac *pdmac = pch->dmac;
2761         u8 *peri_id = pch->chan.private;
2762         struct dma_pl330_desc *desc;
2763
2764         /* Pluck one desc from the pool of DMAC */
2765         desc = pluck_desc(pdmac);
2766
2767         /* If the DMAC pool is empty, alloc new */
2768         if (!desc) {
2769                 if (!add_desc(pdmac, GFP_ATOMIC, 1))
2770                         return NULL;
2771
2772                 /* Try again */
2773                 desc = pluck_desc(pdmac);
2774                 if (!desc) {
2775                         dev_err(pch->dmac->pif.dev,
2776                                 "%s:%d ALERT!\n", __func__, __LINE__);
2777                         return NULL;
2778                 }
2779         }
2780
2781         /* Initialize the descriptor */
2782         desc->pchan = pch;
2783         desc->txd.cookie = 0;
2784         async_tx_ack(&desc->txd);
2785
2786         desc->req.infiniteloop = 0;
2787         desc->req.peri = peri_id ? pch->chan.chan_id : 0;
2788         desc->rqcfg.pcfg = &pch->dmac->pif.pcfg;
2789
2790         dma_async_tx_descriptor_init(&desc->txd, &pch->chan);
2791
2792         return desc;
2793 }
2794
2795 static inline void fill_px(struct pl330_xfer *px,
2796                 dma_addr_t dst, dma_addr_t src, size_t len)
2797 {
2798         px->next = NULL;
2799         px->bytes = len;
2800         px->dst_addr = dst;
2801         px->src_addr = src;
2802 }
2803
2804 static struct dma_pl330_desc *
2805 __pl330_prep_dma_memcpy(struct dma_pl330_chan *pch, dma_addr_t dst,
2806                 dma_addr_t src, size_t len)
2807 {
2808         struct dma_pl330_desc *desc = pl330_get_desc(pch);
2809
2810         if (!desc) {
2811                 dev_err(pch->dmac->pif.dev, "%s:%d Unable to fetch desc\n",
2812                         __func__, __LINE__);
2813                 return NULL;
2814         }
2815
2816         /*
2817          * Ideally we should lookout for reqs bigger than
2818          * those that can be programmed with 256 bytes of
2819          * MC buffer, but considering a req size is seldom
2820          * going to be word-unaligned and more than 200MB,
2821          * we take it easy.
2822          * Also, should the limit is reached we'd rather
2823          * have the platform increase MC buffer size than
2824          * complicating this API driver.
2825          */
2826         fill_px(&desc->px, dst, src, len);
2827
2828         return desc;
2829 }
2830
2831 /* Call after fixing burst size */
2832 static inline int get_burst_len(struct dma_pl330_desc *desc, size_t len)
2833 {
2834         struct dma_pl330_chan *pch = desc->pchan;
2835         struct pl330_info *pi = &pch->dmac->pif;
2836         int burst_len;
2837
2838         burst_len = pi->pcfg.data_bus_width / 8;
2839         burst_len *= pi->pcfg.data_buf_dep;
2840         burst_len >>= desc->rqcfg.brst_size;
2841
2842         /* src/dst_burst_len can't be more than 16 */
2843         if (burst_len > 16)
2844                 burst_len = 16;
2845
2846         while (burst_len > 1) {
2847                 if (!(len % (burst_len << desc->rqcfg.brst_size)))
2848                         break;
2849                 burst_len--;
2850         }
2851
2852         return burst_len;
2853 }
2854
2855 static struct dma_async_tx_descriptor *pl330_prep_dma_cyclic(
2856                 struct dma_chan *chan, dma_addr_t dma_addr, size_t len,
2857                 size_t period_len, enum dma_transfer_direction direction,
2858                 unsigned long flags, void *context)
2859 {
2860         struct dma_pl330_desc *desc = NULL, *first = NULL;
2861         struct dma_pl330_chan *pch = to_pchan(chan);
2862         struct dma_pl330_dmac *pdmac = pch->dmac;
2863         unsigned int i;
2864         dma_addr_t dst;
2865         dma_addr_t src;
2866         unsigned int *infinite = context;
2867
2868         if (len % period_len != 0)
2869                 return NULL;
2870
2871         if (!is_slave_direction(direction)) {
2872                 dev_err(pch->dmac->pif.dev, "%s:%d Invalid dma direction\n",
2873                 __func__, __LINE__);
2874                 return NULL;
2875         }
2876
2877         for (i = 0; i < len / period_len; i++) {
2878                 desc = pl330_get_desc(pch);
2879                 if (!desc) {
2880                         dev_err(pch->dmac->pif.dev, "%s:%d Unable to fetch desc\n",
2881                                 __func__, __LINE__);
2882
2883                         if (!first)
2884                                 return NULL;
2885
2886                         spin_lock_irqsave(&pdmac->pool_lock, flags);
2887
2888                         while (!list_empty(&first->node)) {
2889                                 desc = list_entry(first->node.next,
2890                                                 struct dma_pl330_desc, node);
2891                                 list_move_tail(&desc->node, &pdmac->desc_pool);
2892                         }
2893
2894                         list_move_tail(&first->node, &pdmac->desc_pool);
2895
2896                         spin_unlock_irqrestore(&pdmac->pool_lock, flags);
2897
2898                         return NULL;
2899                 }
2900
2901                 switch (direction) {
2902                 case DMA_MEM_TO_DEV:
2903                         desc->rqcfg.src_inc = 1;
2904                         desc->rqcfg.dst_inc = 0;
2905                         desc->req.rqtype = MEMTODEV;
2906                         src = dma_addr;
2907                         dst = pch->fifo_addr;
2908                         break;
2909                 case DMA_DEV_TO_MEM:
2910                         desc->rqcfg.src_inc = 0;
2911                         desc->rqcfg.dst_inc = 1;
2912                         desc->req.rqtype = DEVTOMEM;
2913                         src = pch->fifo_addr;
2914                         dst = dma_addr;
2915                         break;
2916                 default:
2917                         break;
2918                 }
2919
2920                 desc->rqcfg.brst_size = pch->burst_sz;
2921                 desc->rqcfg.brst_len = 1;
2922                 desc->req.infiniteloop = *infinite;
2923                 fill_px(&desc->px, dst, src, period_len);
2924
2925                 if (!first)
2926                         first = desc;
2927                 else
2928                         list_add_tail(&desc->node, &first->node);
2929
2930                 dma_addr += period_len;
2931         }
2932
2933         if (!desc)
2934                 return NULL;
2935
2936         pch->cyclic = true;
2937         desc->txd.flags = flags;
2938
2939         return &desc->txd;
2940 }
2941
2942 static struct dma_async_tx_descriptor *
2943 pl330_prep_dma_memcpy(struct dma_chan *chan, dma_addr_t dst,
2944                 dma_addr_t src, size_t len, unsigned long flags)
2945 {
2946         struct dma_pl330_desc *desc;
2947         struct dma_pl330_chan *pch = to_pchan(chan);
2948         struct pl330_info *pi;
2949         int burst;
2950
2951         if (unlikely(!pch || !len))
2952                 return NULL;
2953
2954         pi = &pch->dmac->pif;
2955
2956         desc = __pl330_prep_dma_memcpy(pch, dst, src, len);
2957         if (!desc)
2958                 return NULL;
2959
2960         desc->rqcfg.src_inc = 1;
2961         desc->rqcfg.dst_inc = 1;
2962         desc->req.rqtype = MEMTOMEM;
2963
2964         /* Select max possible burst size */
2965         burst = pi->pcfg.data_bus_width / 8;
2966
2967         while (burst > 1) {
2968                 if (!(len % burst))
2969                         break;
2970                 burst /= 2;
2971         }
2972
2973         desc->rqcfg.brst_size = 0;
2974         while (burst != (1 << desc->rqcfg.brst_size))
2975                 desc->rqcfg.brst_size++;
2976
2977         desc->rqcfg.brst_len = get_burst_len(desc, len);
2978
2979         desc->txd.flags = flags;
2980
2981         return &desc->txd;
2982 }
2983
2984 static struct dma_async_tx_descriptor *
2985 pl330_prep_slave_sg(struct dma_chan *chan, struct scatterlist *sgl,
2986                 unsigned int sg_len, enum dma_transfer_direction direction,
2987                 unsigned long flg, void *context)
2988 {
2989         struct dma_pl330_desc *first, *desc = NULL;
2990         struct dma_pl330_chan *pch = to_pchan(chan);
2991         struct scatterlist *sg;
2992         unsigned long flags;
2993         int i;
2994         dma_addr_t addr;
2995
2996         if (unlikely(!pch || !sgl || !sg_len))
2997                 return NULL;
2998
2999         addr = pch->fifo_addr;
3000
3001         first = NULL;
3002
3003         for_each_sg(sgl, sg, sg_len, i) {
3004
3005                 desc = pl330_get_desc(pch);
3006                 if (!desc) {
3007                         struct dma_pl330_dmac *pdmac = pch->dmac;
3008
3009                         dev_err(pch->dmac->pif.dev,
3010                                 "%s:%d Unable to fetch desc\n",
3011                                 __func__, __LINE__);
3012                         if (!first)
3013                                 return NULL;
3014
3015                         spin_lock_irqsave(&pdmac->pool_lock, flags);
3016
3017                         while (!list_empty(&first->node)) {
3018                                 desc = list_entry(first->node.next,
3019                                                 struct dma_pl330_desc, node);
3020                                 list_move_tail(&desc->node, &pdmac->desc_pool);
3021                         }
3022
3023                         list_move_tail(&first->node, &pdmac->desc_pool);
3024
3025                         spin_unlock_irqrestore(&pdmac->pool_lock, flags);
3026
3027                         return NULL;
3028                 }
3029
3030                 if (!first)
3031                         first = desc;
3032                 else
3033                         list_add_tail(&desc->node, &first->node);
3034
3035                 if (direction == DMA_MEM_TO_DEV) {
3036                         desc->rqcfg.src_inc = 1;
3037                         desc->rqcfg.dst_inc = 0;
3038                         desc->req.rqtype = MEMTODEV;
3039                         fill_px(&desc->px,
3040                                 addr, sg_dma_address(sg), sg_dma_len(sg));
3041                 } else {
3042                         desc->rqcfg.src_inc = 0;
3043                         desc->rqcfg.dst_inc = 1;
3044                         desc->req.rqtype = DEVTOMEM;
3045                         fill_px(&desc->px,
3046                                 sg_dma_address(sg), addr, sg_dma_len(sg));
3047                 }
3048
3049                 desc->rqcfg.brst_size = pch->burst_sz;
3050                 desc->rqcfg.brst_len = 1;
3051         }
3052
3053         /* Return the last desc in the chain */
3054         desc->txd.flags = flg;
3055         return &desc->txd;
3056 }
3057
3058 static irqreturn_t pl330_irq_handler(int irq, void *data)
3059 {
3060         if (pl330_update(data))
3061                 return IRQ_HANDLED;
3062         else
3063                 return IRQ_NONE;
3064 }
3065
3066 int pl330_dma_getposition(struct dma_chan *chan,
3067                 dma_addr_t *src, dma_addr_t *dst)
3068 {
3069         struct dma_pl330_chan *pch = to_pchan(chan);
3070         struct pl330_info *pi;
3071         void __iomem *regs;
3072         struct pl330_thread *thrd;
3073
3074         if (unlikely(!pch))
3075                 return -EINVAL;
3076
3077         thrd = pch->pl330_chid;
3078         pi = &pch->dmac->pif;
3079         regs = pi->base;
3080
3081         *src = readl(regs + SA(thrd->id));
3082         *dst = readl(regs + DA(thrd->id));
3083
3084         return 0;
3085 }
3086 EXPORT_SYMBOL(pl330_dma_getposition);
3087
3088 static int
3089 pl330_probe(struct amba_device *adev, const struct amba_id *id)
3090 {
3091         struct dma_pl330_platdata *pdat;
3092         struct dma_pl330_dmac *pdmac;
3093         struct dma_pl330_chan *pch, *_p;
3094         struct pl330_info *pi;
3095         struct dma_device *pd;
3096         struct resource *res;
3097         int i, ret, irq;
3098         int num_chan;
3099
3100         pdat = adev->dev.platform_data;
3101
3102         /* Allocate a new DMAC and its Channels */
3103         pdmac = devm_kzalloc(&adev->dev, sizeof(*pdmac), GFP_KERNEL);
3104         if (!pdmac) {
3105                 dev_err(&adev->dev, "unable to allocate mem\n");
3106                 return -ENOMEM;
3107         }
3108
3109         pi = &pdmac->pif;
3110         pi->dev = &adev->dev;
3111         pi->pl330_data = NULL;
3112         pi->mcbufsz = pdat ? pdat->mcbuf_sz : 0;
3113
3114         res = &adev->res;
3115         pi->base = devm_ioremap_resource(&adev->dev, res);
3116         if (IS_ERR(pi->base))
3117                 return PTR_ERR(pi->base);
3118
3119         amba_set_drvdata(adev, pdmac);
3120
3121         irq = adev->irq[0];
3122         ret = request_irq(irq, pl330_irq_handler, 0,
3123                         dev_name(&adev->dev), pi);
3124         if (ret)
3125                 return ret;
3126
3127         ret = pl330_add(pi);
3128         if (ret)
3129                 goto probe_err1;
3130
3131         INIT_LIST_HEAD(&pdmac->desc_pool);
3132         spin_lock_init(&pdmac->pool_lock);
3133
3134         /* Create a descriptor pool of default size */
3135         if (!add_desc(pdmac, GFP_KERNEL, NR_DEFAULT_DESC))
3136                 dev_warn(&adev->dev, "unable to allocate desc\n");
3137
3138         pd = &pdmac->ddma;
3139         INIT_LIST_HEAD(&pd->channels);
3140
3141         /* Initialize channel parameters */
3142         if (pdat)
3143                 num_chan = max_t(int, pdat->nr_valid_peri, pi->pcfg.num_chan);
3144         else
3145                 num_chan = max_t(int, pi->pcfg.num_peri, pi->pcfg.num_chan);
3146
3147         pdmac->peripherals = kzalloc(num_chan * sizeof(*pch), GFP_KERNEL);
3148         if (!pdmac->peripherals) {
3149                 ret = -ENOMEM;
3150                 dev_err(&adev->dev, "unable to allocate pdmac->peripherals\n");
3151                 goto probe_err2;
3152         }
3153
3154         for (i = 0; i < num_chan; i++) {
3155                 pch = &pdmac->peripherals[i];
3156                 if (!adev->dev.of_node)
3157                         pch->chan.private = pdat ? &pdat->peri_id[i] : NULL;
3158                 else
3159                         pch->chan.private = adev->dev.of_node;
3160
3161                 INIT_LIST_HEAD(&pch->work_list);
3162                 spin_lock_init(&pch->lock);
3163                 pch->pl330_chid = NULL;
3164                 pch->chan.device = pd;
3165                 pch->dmac = pdmac;
3166
3167                 /* Add the channel to the DMAC list */
3168                 list_add_tail(&pch->chan.device_node, &pd->channels);
3169         }
3170
3171         pd->dev = &adev->dev;
3172         if (pdat) {
3173                 pd->cap_mask = pdat->cap_mask;
3174         } else {
3175                 dma_cap_set(DMA_MEMCPY, pd->cap_mask);
3176                 if (pi->pcfg.num_peri) {
3177                         dma_cap_set(DMA_SLAVE, pd->cap_mask);
3178                         dma_cap_set(DMA_CYCLIC, pd->cap_mask);
3179                         dma_cap_set(DMA_PRIVATE, pd->cap_mask);
3180                 }
3181         }
3182
3183         pd->device_alloc_chan_resources = pl330_alloc_chan_resources;
3184         pd->device_free_chan_resources = pl330_free_chan_resources;
3185         pd->device_prep_dma_memcpy = pl330_prep_dma_memcpy;
3186         pd->device_prep_dma_cyclic = pl330_prep_dma_cyclic;
3187         pd->device_tx_status = pl330_tx_status;
3188         pd->device_prep_slave_sg = pl330_prep_slave_sg;
3189         pd->device_control = pl330_control;
3190         pd->device_issue_pending = pl330_issue_pending;
3191 #ifdef drivers/dma/pl330.c
3192         pd->dma_getposition = pl330_dma_getposition;
3193 #endif
3194
3195         ret = dma_async_device_register(pd);
3196         if (ret) {
3197                 dev_err(&adev->dev, "unable to register DMAC\n");
3198                 goto probe_err3;
3199         }
3200
3201         if (adev->dev.of_node) {
3202                 ret = of_dma_controller_register(adev->dev.of_node,
3203                                          of_dma_pl330_xlate, pdmac);
3204                 if (ret) {
3205                         dev_err(&adev->dev,
3206                         "unable to register DMA to the generic DT DMA helpers\n");
3207                 }
3208         }
3209
3210         dev_info(&adev->dev,
3211                 "Loaded driver for PL330 DMAC-%d\n", adev->periphid);
3212         dev_info(&adev->dev,
3213                 "\tDBUFF-%ux%ubytes Num_Chans-%u Num_Peri-%u Num_Events-%u\n",
3214                 pi->pcfg.data_buf_dep,
3215                 pi->pcfg.data_bus_width / 8, pi->pcfg.num_chan,
3216                 pi->pcfg.num_peri, pi->pcfg.num_events);
3217
3218         return 0;
3219 probe_err3:
3220         amba_set_drvdata(adev, NULL);
3221
3222         /* Idle the DMAC */
3223         list_for_each_entry_safe(pch, _p, &pdmac->ddma.channels,
3224                         chan.device_node) {
3225
3226                 /* Remove the channel */
3227                 list_del(&pch->chan.device_node);
3228
3229                 /* Flush the channel */
3230                 pl330_control(&pch->chan, DMA_TERMINATE_ALL, 0);
3231                 pl330_free_chan_resources(&pch->chan);
3232         }
3233 probe_err2:
3234         pl330_del(pi);
3235 probe_err1:
3236         free_irq(irq, pi);
3237
3238         return ret;
3239 }
3240
3241 static int pl330_remove(struct amba_device *adev)
3242 {
3243         struct dma_pl330_dmac *pdmac = amba_get_drvdata(adev);
3244         struct dma_pl330_chan *pch, *_p;
3245         struct pl330_info *pi;
3246         int irq;
3247
3248         if (!pdmac)
3249                 return 0;
3250
3251         if (adev->dev.of_node)
3252                 of_dma_controller_free(adev->dev.of_node);
3253
3254         dma_async_device_unregister(&pdmac->ddma);
3255         amba_set_drvdata(adev, NULL);
3256
3257         /* Idle the DMAC */
3258         list_for_each_entry_safe(pch, _p, &pdmac->ddma.channels,
3259                         chan.device_node) {
3260
3261                 /* Remove the channel */
3262                 list_del(&pch->chan.device_node);
3263
3264                 /* Flush the channel */
3265                 pl330_control(&pch->chan, DMA_TERMINATE_ALL, 0);
3266                 pl330_free_chan_resources(&pch->chan);
3267         }
3268
3269         pi = &pdmac->pif;
3270
3271         pl330_del(pi);
3272
3273         irq = adev->irq[0];
3274         free_irq(irq, pi);
3275
3276         return 0;
3277 }
3278
3279 static struct amba_id pl330_ids[] = {
3280         {
3281                 .id     = 0x00041330,
3282                 .mask   = 0x000fffff,
3283         },
3284         { 0, 0 },
3285 };
3286
3287 MODULE_DEVICE_TABLE(amba, pl330_ids);
3288
3289 static struct amba_driver pl330_driver = {
3290         .drv = {
3291                 .owner = THIS_MODULE,
3292                 .name = "dma-pl330",
3293         },
3294         .id_table = pl330_ids,
3295         .probe = pl330_probe,
3296         .remove = pl330_remove,
3297 };
3298
3299 module_amba_driver(pl330_driver);
3300
3301 MODULE_AUTHOR("Jaswinder Singh <jassi.brar@samsung.com>");
3302 MODULE_DESCRIPTION("API Driver for PL330 DMAC");
3303 MODULE_LICENSE("GPL");