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