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