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