37388d10497a58d10a4890057306d3756b1bc59b
[linux-2.6.git] / drivers / dma / ste_dma40.c
1 /*
2  * Copyright (C) Ericsson AB 2007-2008
3  * Copyright (C) ST-Ericsson SA 2008-2010
4  * Author: Per Forlin <per.forlin@stericsson.com> for ST-Ericsson
5  * Author: Jonas Aaberg <jonas.aberg@stericsson.com> for ST-Ericsson
6  * License terms: GNU General Public License (GPL) version 2
7  */
8
9 #include <linux/dma-mapping.h>
10 #include <linux/kernel.h>
11 #include <linux/slab.h>
12 #include <linux/dmaengine.h>
13 #include <linux/platform_device.h>
14 #include <linux/clk.h>
15 #include <linux/delay.h>
16 #include <linux/err.h>
17 #include <linux/amba/bus.h>
18
19 #include <plat/ste_dma40.h>
20
21 #include "ste_dma40_ll.h"
22
23 #define D40_NAME "dma40"
24
25 #define D40_PHY_CHAN -1
26
27 /* For masking out/in 2 bit channel positions */
28 #define D40_CHAN_POS(chan)  (2 * (chan / 2))
29 #define D40_CHAN_POS_MASK(chan) (0x3 << D40_CHAN_POS(chan))
30
31 /* Maximum iterations taken before giving up suspending a channel */
32 #define D40_SUSPEND_MAX_IT 500
33
34 /* Hardware requirement on LCLA alignment */
35 #define LCLA_ALIGNMENT 0x40000
36
37 /* Max number of links per event group */
38 #define D40_LCLA_LINK_PER_EVENT_GRP 128
39 #define D40_LCLA_END D40_LCLA_LINK_PER_EVENT_GRP
40
41 /* Attempts before giving up to trying to get pages that are aligned */
42 #define MAX_LCLA_ALLOC_ATTEMPTS 256
43
44 /* Bit markings for allocation map */
45 #define D40_ALLOC_FREE          (1 << 31)
46 #define D40_ALLOC_PHY           (1 << 30)
47 #define D40_ALLOC_LOG_FREE      0
48
49 /**
50  * enum 40_command - The different commands and/or statuses.
51  *
52  * @D40_DMA_STOP: DMA channel command STOP or status STOPPED,
53  * @D40_DMA_RUN: The DMA channel is RUNNING of the command RUN.
54  * @D40_DMA_SUSPEND_REQ: Request the DMA to SUSPEND as soon as possible.
55  * @D40_DMA_SUSPENDED: The DMA channel is SUSPENDED.
56  */
57 enum d40_command {
58         D40_DMA_STOP            = 0,
59         D40_DMA_RUN             = 1,
60         D40_DMA_SUSPEND_REQ     = 2,
61         D40_DMA_SUSPENDED       = 3
62 };
63
64 /**
65  * struct d40_lli_pool - Structure for keeping LLIs in memory
66  *
67  * @base: Pointer to memory area when the pre_alloc_lli's are not large
68  * enough, IE bigger than the most common case, 1 dst and 1 src. NULL if
69  * pre_alloc_lli is used.
70  * @dma_addr: DMA address, if mapped
71  * @size: The size in bytes of the memory at base or the size of pre_alloc_lli.
72  * @pre_alloc_lli: Pre allocated area for the most common case of transfers,
73  * one buffer to one buffer.
74  */
75 struct d40_lli_pool {
76         void    *base;
77         int      size;
78         dma_addr_t      dma_addr;
79         /* Space for dst and src, plus an extra for padding */
80         u8       pre_alloc_lli[3 * sizeof(struct d40_phy_lli)];
81 };
82
83 /**
84  * struct d40_desc - A descriptor is one DMA job.
85  *
86  * @lli_phy: LLI settings for physical channel. Both src and dst=
87  * points into the lli_pool, to base if lli_len > 1 or to pre_alloc_lli if
88  * lli_len equals one.
89  * @lli_log: Same as above but for logical channels.
90  * @lli_pool: The pool with two entries pre-allocated.
91  * @lli_len: Number of llis of current descriptor.
92  * @lli_current: Number of transferred llis.
93  * @lcla_alloc: Number of LCLA entries allocated.
94  * @txd: DMA engine struct. Used for among other things for communication
95  * during a transfer.
96  * @node: List entry.
97  * @is_in_client_list: true if the client owns this descriptor.
98  * the previous one.
99  *
100  * This descriptor is used for both logical and physical transfers.
101  */
102 struct d40_desc {
103         /* LLI physical */
104         struct d40_phy_lli_bidir         lli_phy;
105         /* LLI logical */
106         struct d40_log_lli_bidir         lli_log;
107
108         struct d40_lli_pool              lli_pool;
109         int                              lli_len;
110         int                              lli_current;
111         int                              lcla_alloc;
112
113         struct dma_async_tx_descriptor   txd;
114         struct list_head                 node;
115
116         bool                             is_in_client_list;
117         bool                             cyclic;
118 };
119
120 /**
121  * struct d40_lcla_pool - LCLA pool settings and data.
122  *
123  * @base: The virtual address of LCLA. 18 bit aligned.
124  * @base_unaligned: The orignal kmalloc pointer, if kmalloc is used.
125  * This pointer is only there for clean-up on error.
126  * @pages: The number of pages needed for all physical channels.
127  * Only used later for clean-up on error
128  * @lock: Lock to protect the content in this struct.
129  * @alloc_map: big map over which LCLA entry is own by which job.
130  */
131 struct d40_lcla_pool {
132         void            *base;
133         dma_addr_t      dma_addr;
134         void            *base_unaligned;
135         int              pages;
136         spinlock_t       lock;
137         struct d40_desc **alloc_map;
138 };
139
140 /**
141  * struct d40_phy_res - struct for handling eventlines mapped to physical
142  * channels.
143  *
144  * @lock: A lock protection this entity.
145  * @num: The physical channel number of this entity.
146  * @allocated_src: Bit mapped to show which src event line's are mapped to
147  * this physical channel. Can also be free or physically allocated.
148  * @allocated_dst: Same as for src but is dst.
149  * allocated_dst and allocated_src uses the D40_ALLOC* defines as well as
150  * event line number.
151  */
152 struct d40_phy_res {
153         spinlock_t lock;
154         int        num;
155         u32        allocated_src;
156         u32        allocated_dst;
157 };
158
159 struct d40_base;
160
161 /**
162  * struct d40_chan - Struct that describes a channel.
163  *
164  * @lock: A spinlock to protect this struct.
165  * @log_num: The logical number, if any of this channel.
166  * @completed: Starts with 1, after first interrupt it is set to dma engine's
167  * current cookie.
168  * @pending_tx: The number of pending transfers. Used between interrupt handler
169  * and tasklet.
170  * @busy: Set to true when transfer is ongoing on this channel.
171  * @phy_chan: Pointer to physical channel which this instance runs on. If this
172  * point is NULL, then the channel is not allocated.
173  * @chan: DMA engine handle.
174  * @tasklet: Tasklet that gets scheduled from interrupt context to complete a
175  * transfer and call client callback.
176  * @client: Cliented owned descriptor list.
177  * @pending_queue: Submitted jobs, to be issued by issue_pending()
178  * @active: Active descriptor.
179  * @queue: Queued jobs.
180  * @dma_cfg: The client configuration of this dma channel.
181  * @configured: whether the dma_cfg configuration is valid
182  * @base: Pointer to the device instance struct.
183  * @src_def_cfg: Default cfg register setting for src.
184  * @dst_def_cfg: Default cfg register setting for dst.
185  * @log_def: Default logical channel settings.
186  * @lcla: Space for one dst src pair for logical channel transfers.
187  * @lcpa: Pointer to dst and src lcpa settings.
188  * @runtime_addr: runtime configured address.
189  * @runtime_direction: runtime configured direction.
190  *
191  * This struct can either "be" a logical or a physical channel.
192  */
193 struct d40_chan {
194         spinlock_t                       lock;
195         int                              log_num;
196         /* ID of the most recent completed transfer */
197         int                              completed;
198         int                              pending_tx;
199         bool                             busy;
200         struct d40_phy_res              *phy_chan;
201         struct dma_chan                  chan;
202         struct tasklet_struct            tasklet;
203         struct list_head                 client;
204         struct list_head                 pending_queue;
205         struct list_head                 active;
206         struct list_head                 queue;
207         struct stedma40_chan_cfg         dma_cfg;
208         bool                             configured;
209         struct d40_base                 *base;
210         /* Default register configurations */
211         u32                              src_def_cfg;
212         u32                              dst_def_cfg;
213         struct d40_def_lcsp              log_def;
214         struct d40_log_lli_full         *lcpa;
215         /* Runtime reconfiguration */
216         dma_addr_t                      runtime_addr;
217         enum dma_data_direction         runtime_direction;
218 };
219
220 /**
221  * struct d40_base - The big global struct, one for each probe'd instance.
222  *
223  * @interrupt_lock: Lock used to make sure one interrupt is handle a time.
224  * @execmd_lock: Lock for execute command usage since several channels share
225  * the same physical register.
226  * @dev: The device structure.
227  * @virtbase: The virtual base address of the DMA's register.
228  * @rev: silicon revision detected.
229  * @clk: Pointer to the DMA clock structure.
230  * @phy_start: Physical memory start of the DMA registers.
231  * @phy_size: Size of the DMA register map.
232  * @irq: The IRQ number.
233  * @num_phy_chans: The number of physical channels. Read from HW. This
234  * is the number of available channels for this driver, not counting "Secure
235  * mode" allocated physical channels.
236  * @num_log_chans: The number of logical channels. Calculated from
237  * num_phy_chans.
238  * @dma_both: dma_device channels that can do both memcpy and slave transfers.
239  * @dma_slave: dma_device channels that can do only do slave transfers.
240  * @dma_memcpy: dma_device channels that can do only do memcpy transfers.
241  * @log_chans: Room for all possible logical channels in system.
242  * @lookup_log_chans: Used to map interrupt number to logical channel. Points
243  * to log_chans entries.
244  * @lookup_phy_chans: Used to map interrupt number to physical channel. Points
245  * to phy_chans entries.
246  * @plat_data: Pointer to provided platform_data which is the driver
247  * configuration.
248  * @phy_res: Vector containing all physical channels.
249  * @lcla_pool: lcla pool settings and data.
250  * @lcpa_base: The virtual mapped address of LCPA.
251  * @phy_lcpa: The physical address of the LCPA.
252  * @lcpa_size: The size of the LCPA area.
253  * @desc_slab: cache for descriptors.
254  */
255 struct d40_base {
256         spinlock_t                       interrupt_lock;
257         spinlock_t                       execmd_lock;
258         struct device                    *dev;
259         void __iomem                     *virtbase;
260         u8                                rev:4;
261         struct clk                       *clk;
262         phys_addr_t                       phy_start;
263         resource_size_t                   phy_size;
264         int                               irq;
265         int                               num_phy_chans;
266         int                               num_log_chans;
267         struct dma_device                 dma_both;
268         struct dma_device                 dma_slave;
269         struct dma_device                 dma_memcpy;
270         struct d40_chan                  *phy_chans;
271         struct d40_chan                  *log_chans;
272         struct d40_chan                 **lookup_log_chans;
273         struct d40_chan                 **lookup_phy_chans;
274         struct stedma40_platform_data    *plat_data;
275         /* Physical half channels */
276         struct d40_phy_res               *phy_res;
277         struct d40_lcla_pool              lcla_pool;
278         void                             *lcpa_base;
279         dma_addr_t                        phy_lcpa;
280         resource_size_t                   lcpa_size;
281         struct kmem_cache                *desc_slab;
282 };
283
284 /**
285  * struct d40_interrupt_lookup - lookup table for interrupt handler
286  *
287  * @src: Interrupt mask register.
288  * @clr: Interrupt clear register.
289  * @is_error: true if this is an error interrupt.
290  * @offset: start delta in the lookup_log_chans in d40_base. If equals to
291  * D40_PHY_CHAN, the lookup_phy_chans shall be used instead.
292  */
293 struct d40_interrupt_lookup {
294         u32 src;
295         u32 clr;
296         bool is_error;
297         int offset;
298 };
299
300 /**
301  * struct d40_reg_val - simple lookup struct
302  *
303  * @reg: The register.
304  * @val: The value that belongs to the register in reg.
305  */
306 struct d40_reg_val {
307         unsigned int reg;
308         unsigned int val;
309 };
310
311 static struct device *chan2dev(struct d40_chan *d40c)
312 {
313         return &d40c->chan.dev->device;
314 }
315
316 static bool chan_is_physical(struct d40_chan *chan)
317 {
318         return chan->log_num == D40_PHY_CHAN;
319 }
320
321 static bool chan_is_logical(struct d40_chan *chan)
322 {
323         return !chan_is_physical(chan);
324 }
325
326 static void __iomem *chan_base(struct d40_chan *chan)
327 {
328         return chan->base->virtbase + D40_DREG_PCBASE +
329                chan->phy_chan->num * D40_DREG_PCDELTA;
330 }
331
332 #define d40_err(dev, format, arg...)            \
333         dev_err(dev, "[%s] " format, __func__, ## arg)
334
335 #define chan_err(d40c, format, arg...)          \
336         d40_err(chan2dev(d40c), format, ## arg)
337
338 static int d40_pool_lli_alloc(struct d40_chan *d40c, struct d40_desc *d40d,
339                               int lli_len)
340 {
341         bool is_log = chan_is_logical(d40c);
342         u32 align;
343         void *base;
344
345         if (is_log)
346                 align = sizeof(struct d40_log_lli);
347         else
348                 align = sizeof(struct d40_phy_lli);
349
350         if (lli_len == 1) {
351                 base = d40d->lli_pool.pre_alloc_lli;
352                 d40d->lli_pool.size = sizeof(d40d->lli_pool.pre_alloc_lli);
353                 d40d->lli_pool.base = NULL;
354         } else {
355                 d40d->lli_pool.size = lli_len * 2 * align;
356
357                 base = kmalloc(d40d->lli_pool.size + align, GFP_NOWAIT);
358                 d40d->lli_pool.base = base;
359
360                 if (d40d->lli_pool.base == NULL)
361                         return -ENOMEM;
362         }
363
364         if (is_log) {
365                 d40d->lli_log.src = PTR_ALIGN(base, align);
366                 d40d->lli_log.dst = d40d->lli_log.src + lli_len;
367
368                 d40d->lli_pool.dma_addr = 0;
369         } else {
370                 d40d->lli_phy.src = PTR_ALIGN(base, align);
371                 d40d->lli_phy.dst = d40d->lli_phy.src + lli_len;
372
373                 d40d->lli_pool.dma_addr = dma_map_single(d40c->base->dev,
374                                                          d40d->lli_phy.src,
375                                                          d40d->lli_pool.size,
376                                                          DMA_TO_DEVICE);
377
378                 if (dma_mapping_error(d40c->base->dev,
379                                       d40d->lli_pool.dma_addr)) {
380                         kfree(d40d->lli_pool.base);
381                         d40d->lli_pool.base = NULL;
382                         d40d->lli_pool.dma_addr = 0;
383                         return -ENOMEM;
384                 }
385         }
386
387         return 0;
388 }
389
390 static void d40_pool_lli_free(struct d40_chan *d40c, struct d40_desc *d40d)
391 {
392         if (d40d->lli_pool.dma_addr)
393                 dma_unmap_single(d40c->base->dev, d40d->lli_pool.dma_addr,
394                                  d40d->lli_pool.size, DMA_TO_DEVICE);
395
396         kfree(d40d->lli_pool.base);
397         d40d->lli_pool.base = NULL;
398         d40d->lli_pool.size = 0;
399         d40d->lli_log.src = NULL;
400         d40d->lli_log.dst = NULL;
401         d40d->lli_phy.src = NULL;
402         d40d->lli_phy.dst = NULL;
403 }
404
405 static int d40_lcla_alloc_one(struct d40_chan *d40c,
406                               struct d40_desc *d40d)
407 {
408         unsigned long flags;
409         int i;
410         int ret = -EINVAL;
411         int p;
412
413         spin_lock_irqsave(&d40c->base->lcla_pool.lock, flags);
414
415         p = d40c->phy_chan->num * D40_LCLA_LINK_PER_EVENT_GRP;
416
417         /*
418          * Allocate both src and dst at the same time, therefore the half
419          * start on 1 since 0 can't be used since zero is used as end marker.
420          */
421         for (i = 1 ; i < D40_LCLA_LINK_PER_EVENT_GRP / 2; i++) {
422                 if (!d40c->base->lcla_pool.alloc_map[p + i]) {
423                         d40c->base->lcla_pool.alloc_map[p + i] = d40d;
424                         d40d->lcla_alloc++;
425                         ret = i;
426                         break;
427                 }
428         }
429
430         spin_unlock_irqrestore(&d40c->base->lcla_pool.lock, flags);
431
432         return ret;
433 }
434
435 static int d40_lcla_free_all(struct d40_chan *d40c,
436                              struct d40_desc *d40d)
437 {
438         unsigned long flags;
439         int i;
440         int ret = -EINVAL;
441
442         if (chan_is_physical(d40c))
443                 return 0;
444
445         spin_lock_irqsave(&d40c->base->lcla_pool.lock, flags);
446
447         for (i = 1 ; i < D40_LCLA_LINK_PER_EVENT_GRP / 2; i++) {
448                 if (d40c->base->lcla_pool.alloc_map[d40c->phy_chan->num *
449                                                     D40_LCLA_LINK_PER_EVENT_GRP + i] == d40d) {
450                         d40c->base->lcla_pool.alloc_map[d40c->phy_chan->num *
451                                                         D40_LCLA_LINK_PER_EVENT_GRP + i] = NULL;
452                         d40d->lcla_alloc--;
453                         if (d40d->lcla_alloc == 0) {
454                                 ret = 0;
455                                 break;
456                         }
457                 }
458         }
459
460         spin_unlock_irqrestore(&d40c->base->lcla_pool.lock, flags);
461
462         return ret;
463
464 }
465
466 static void d40_desc_remove(struct d40_desc *d40d)
467 {
468         list_del(&d40d->node);
469 }
470
471 static struct d40_desc *d40_desc_get(struct d40_chan *d40c)
472 {
473         struct d40_desc *desc = NULL;
474
475         if (!list_empty(&d40c->client)) {
476                 struct d40_desc *d;
477                 struct d40_desc *_d;
478
479                 list_for_each_entry_safe(d, _d, &d40c->client, node)
480                         if (async_tx_test_ack(&d->txd)) {
481                                 d40_desc_remove(d);
482                                 desc = d;
483                                 memset(desc, 0, sizeof(*desc));
484                                 break;
485                         }
486         }
487
488         if (!desc)
489                 desc = kmem_cache_zalloc(d40c->base->desc_slab, GFP_NOWAIT);
490
491         if (desc)
492                 INIT_LIST_HEAD(&desc->node);
493
494         return desc;
495 }
496
497 static void d40_desc_free(struct d40_chan *d40c, struct d40_desc *d40d)
498 {
499
500         d40_pool_lli_free(d40c, d40d);
501         d40_lcla_free_all(d40c, d40d);
502         kmem_cache_free(d40c->base->desc_slab, d40d);
503 }
504
505 static void d40_desc_submit(struct d40_chan *d40c, struct d40_desc *desc)
506 {
507         list_add_tail(&desc->node, &d40c->active);
508 }
509
510 static void d40_phy_lli_load(struct d40_chan *chan, struct d40_desc *desc)
511 {
512         struct d40_phy_lli *lli_dst = desc->lli_phy.dst;
513         struct d40_phy_lli *lli_src = desc->lli_phy.src;
514         void __iomem *base = chan_base(chan);
515
516         writel(lli_src->reg_cfg, base + D40_CHAN_REG_SSCFG);
517         writel(lli_src->reg_elt, base + D40_CHAN_REG_SSELT);
518         writel(lli_src->reg_ptr, base + D40_CHAN_REG_SSPTR);
519         writel(lli_src->reg_lnk, base + D40_CHAN_REG_SSLNK);
520
521         writel(lli_dst->reg_cfg, base + D40_CHAN_REG_SDCFG);
522         writel(lli_dst->reg_elt, base + D40_CHAN_REG_SDELT);
523         writel(lli_dst->reg_ptr, base + D40_CHAN_REG_SDPTR);
524         writel(lli_dst->reg_lnk, base + D40_CHAN_REG_SDLNK);
525 }
526
527 static void d40_log_lli_to_lcxa(struct d40_chan *chan, struct d40_desc *desc)
528 {
529         struct d40_lcla_pool *pool = &chan->base->lcla_pool;
530         struct d40_log_lli_bidir *lli = &desc->lli_log;
531         int lli_current = desc->lli_current;
532         int lli_len = desc->lli_len;
533         bool cyclic = desc->cyclic;
534         int curr_lcla = -EINVAL;
535         int first_lcla = 0;
536         bool linkback;
537
538         /*
539          * We may have partially running cyclic transfers, in case we did't get
540          * enough LCLA entries.
541          */
542         linkback = cyclic && lli_current == 0;
543
544         /*
545          * For linkback, we need one LCLA even with only one link, because we
546          * can't link back to the one in LCPA space
547          */
548         if (linkback || (lli_len - lli_current > 1)) {
549                 curr_lcla = d40_lcla_alloc_one(chan, desc);
550                 first_lcla = curr_lcla;
551         }
552
553         /*
554          * For linkback, we normally load the LCPA in the loop since we need to
555          * link it to the second LCLA and not the first.  However, if we
556          * couldn't even get a first LCLA, then we have to run in LCPA and
557          * reload manually.
558          */
559         if (!linkback || curr_lcla == -EINVAL) {
560                 unsigned int flags = 0;
561
562                 if (curr_lcla == -EINVAL)
563                         flags |= LLI_TERM_INT;
564
565                 d40_log_lli_lcpa_write(chan->lcpa,
566                                        &lli->dst[lli_current],
567                                        &lli->src[lli_current],
568                                        curr_lcla,
569                                        flags);
570                 lli_current++;
571         }
572
573         if (curr_lcla < 0)
574                 goto out;
575
576         for (; lli_current < lli_len; lli_current++) {
577                 unsigned int lcla_offset = chan->phy_chan->num * 1024 +
578                                            8 * curr_lcla * 2;
579                 struct d40_log_lli *lcla = pool->base + lcla_offset;
580                 unsigned int flags = 0;
581                 int next_lcla;
582
583                 if (lli_current + 1 < lli_len)
584                         next_lcla = d40_lcla_alloc_one(chan, desc);
585                 else
586                         next_lcla = linkback ? first_lcla : -EINVAL;
587
588                 if (cyclic || next_lcla == -EINVAL)
589                         flags |= LLI_TERM_INT;
590
591                 if (linkback && curr_lcla == first_lcla) {
592                         /* First link goes in both LCPA and LCLA */
593                         d40_log_lli_lcpa_write(chan->lcpa,
594                                                &lli->dst[lli_current],
595                                                &lli->src[lli_current],
596                                                next_lcla, flags);
597                 }
598
599                 /*
600                  * One unused LCLA in the cyclic case if the very first
601                  * next_lcla fails...
602                  */
603                 d40_log_lli_lcla_write(lcla,
604                                        &lli->dst[lli_current],
605                                        &lli->src[lli_current],
606                                        next_lcla, flags);
607
608                 dma_sync_single_range_for_device(chan->base->dev,
609                                         pool->dma_addr, lcla_offset,
610                                         2 * sizeof(struct d40_log_lli),
611                                         DMA_TO_DEVICE);
612
613                 curr_lcla = next_lcla;
614
615                 if (curr_lcla == -EINVAL || curr_lcla == first_lcla) {
616                         lli_current++;
617                         break;
618                 }
619         }
620
621 out:
622         desc->lli_current = lli_current;
623 }
624
625 static void d40_desc_load(struct d40_chan *d40c, struct d40_desc *d40d)
626 {
627         if (chan_is_physical(d40c)) {
628                 d40_phy_lli_load(d40c, d40d);
629                 d40d->lli_current = d40d->lli_len;
630         } else
631                 d40_log_lli_to_lcxa(d40c, d40d);
632 }
633
634 static struct d40_desc *d40_first_active_get(struct d40_chan *d40c)
635 {
636         struct d40_desc *d;
637
638         if (list_empty(&d40c->active))
639                 return NULL;
640
641         d = list_first_entry(&d40c->active,
642                              struct d40_desc,
643                              node);
644         return d;
645 }
646
647 static void d40_desc_queue(struct d40_chan *d40c, struct d40_desc *desc)
648 {
649         list_add_tail(&desc->node, &d40c->pending_queue);
650 }
651
652 static struct d40_desc *d40_first_pending(struct d40_chan *d40c)
653 {
654         struct d40_desc *d;
655
656         if (list_empty(&d40c->pending_queue))
657                 return NULL;
658
659         d = list_first_entry(&d40c->pending_queue,
660                              struct d40_desc,
661                              node);
662         return d;
663 }
664
665 static struct d40_desc *d40_first_queued(struct d40_chan *d40c)
666 {
667         struct d40_desc *d;
668
669         if (list_empty(&d40c->queue))
670                 return NULL;
671
672         d = list_first_entry(&d40c->queue,
673                              struct d40_desc,
674                              node);
675         return d;
676 }
677
678 static int d40_psize_2_burst_size(bool is_log, int psize)
679 {
680         if (is_log) {
681                 if (psize == STEDMA40_PSIZE_LOG_1)
682                         return 1;
683         } else {
684                 if (psize == STEDMA40_PSIZE_PHY_1)
685                         return 1;
686         }
687
688         return 2 << psize;
689 }
690
691 /*
692  * The dma only supports transmitting packages up to
693  * STEDMA40_MAX_SEG_SIZE << data_width. Calculate the total number of
694  * dma elements required to send the entire sg list
695  */
696 static int d40_size_2_dmalen(int size, u32 data_width1, u32 data_width2)
697 {
698         int dmalen;
699         u32 max_w = max(data_width1, data_width2);
700         u32 min_w = min(data_width1, data_width2);
701         u32 seg_max = ALIGN(STEDMA40_MAX_SEG_SIZE << min_w, 1 << max_w);
702
703         if (seg_max > STEDMA40_MAX_SEG_SIZE)
704                 seg_max -= (1 << max_w);
705
706         if (!IS_ALIGNED(size, 1 << max_w))
707                 return -EINVAL;
708
709         if (size <= seg_max)
710                 dmalen = 1;
711         else {
712                 dmalen = size / seg_max;
713                 if (dmalen * seg_max < size)
714                         dmalen++;
715         }
716         return dmalen;
717 }
718
719 static int d40_sg_2_dmalen(struct scatterlist *sgl, int sg_len,
720                            u32 data_width1, u32 data_width2)
721 {
722         struct scatterlist *sg;
723         int i;
724         int len = 0;
725         int ret;
726
727         for_each_sg(sgl, sg, sg_len, i) {
728                 ret = d40_size_2_dmalen(sg_dma_len(sg),
729                                         data_width1, data_width2);
730                 if (ret < 0)
731                         return ret;
732                 len += ret;
733         }
734         return len;
735 }
736
737 /* Support functions for logical channels */
738
739 static int d40_channel_execute_command(struct d40_chan *d40c,
740                                        enum d40_command command)
741 {
742         u32 status;
743         int i;
744         void __iomem *active_reg;
745         int ret = 0;
746         unsigned long flags;
747         u32 wmask;
748
749         spin_lock_irqsave(&d40c->base->execmd_lock, flags);
750
751         if (d40c->phy_chan->num % 2 == 0)
752                 active_reg = d40c->base->virtbase + D40_DREG_ACTIVE;
753         else
754                 active_reg = d40c->base->virtbase + D40_DREG_ACTIVO;
755
756         if (command == D40_DMA_SUSPEND_REQ) {
757                 status = (readl(active_reg) &
758                           D40_CHAN_POS_MASK(d40c->phy_chan->num)) >>
759                         D40_CHAN_POS(d40c->phy_chan->num);
760
761                 if (status == D40_DMA_SUSPENDED || status == D40_DMA_STOP)
762                         goto done;
763         }
764
765         wmask = 0xffffffff & ~(D40_CHAN_POS_MASK(d40c->phy_chan->num));
766         writel(wmask | (command << D40_CHAN_POS(d40c->phy_chan->num)),
767                active_reg);
768
769         if (command == D40_DMA_SUSPEND_REQ) {
770
771                 for (i = 0 ; i < D40_SUSPEND_MAX_IT; i++) {
772                         status = (readl(active_reg) &
773                                   D40_CHAN_POS_MASK(d40c->phy_chan->num)) >>
774                                 D40_CHAN_POS(d40c->phy_chan->num);
775
776                         cpu_relax();
777                         /*
778                          * Reduce the number of bus accesses while
779                          * waiting for the DMA to suspend.
780                          */
781                         udelay(3);
782
783                         if (status == D40_DMA_STOP ||
784                             status == D40_DMA_SUSPENDED)
785                                 break;
786                 }
787
788                 if (i == D40_SUSPEND_MAX_IT) {
789                         chan_err(d40c,
790                                 "unable to suspend the chl %d (log: %d) status %x\n",
791                                 d40c->phy_chan->num, d40c->log_num,
792                                 status);
793                         dump_stack();
794                         ret = -EBUSY;
795                 }
796
797         }
798 done:
799         spin_unlock_irqrestore(&d40c->base->execmd_lock, flags);
800         return ret;
801 }
802
803 static void d40_term_all(struct d40_chan *d40c)
804 {
805         struct d40_desc *d40d;
806
807         /* Release active descriptors */
808         while ((d40d = d40_first_active_get(d40c))) {
809                 d40_desc_remove(d40d);
810                 d40_desc_free(d40c, d40d);
811         }
812
813         /* Release queued descriptors waiting for transfer */
814         while ((d40d = d40_first_queued(d40c))) {
815                 d40_desc_remove(d40d);
816                 d40_desc_free(d40c, d40d);
817         }
818
819         /* Release pending descriptors */
820         while ((d40d = d40_first_pending(d40c))) {
821                 d40_desc_remove(d40d);
822                 d40_desc_free(d40c, d40d);
823         }
824
825         d40c->pending_tx = 0;
826         d40c->busy = false;
827 }
828
829 static void __d40_config_set_event(struct d40_chan *d40c, bool enable,
830                                    u32 event, int reg)
831 {
832         void __iomem *addr = chan_base(d40c) + reg;
833         int tries;
834
835         if (!enable) {
836                 writel((D40_DEACTIVATE_EVENTLINE << D40_EVENTLINE_POS(event))
837                        | ~D40_EVENTLINE_MASK(event), addr);
838                 return;
839         }
840
841         /*
842          * The hardware sometimes doesn't register the enable when src and dst
843          * event lines are active on the same logical channel.  Retry to ensure
844          * it does.  Usually only one retry is sufficient.
845          */
846         tries = 100;
847         while (--tries) {
848                 writel((D40_ACTIVATE_EVENTLINE << D40_EVENTLINE_POS(event))
849                        | ~D40_EVENTLINE_MASK(event), addr);
850
851                 if (readl(addr) & D40_EVENTLINE_MASK(event))
852                         break;
853         }
854
855         if (tries != 99)
856                 dev_dbg(chan2dev(d40c),
857                         "[%s] workaround enable S%cLNK (%d tries)\n",
858                         __func__, reg == D40_CHAN_REG_SSLNK ? 'S' : 'D',
859                         100 - tries);
860
861         WARN_ON(!tries);
862 }
863
864 static void d40_config_set_event(struct d40_chan *d40c, bool do_enable)
865 {
866         unsigned long flags;
867
868         spin_lock_irqsave(&d40c->phy_chan->lock, flags);
869
870         /* Enable event line connected to device (or memcpy) */
871         if ((d40c->dma_cfg.dir ==  STEDMA40_PERIPH_TO_MEM) ||
872             (d40c->dma_cfg.dir == STEDMA40_PERIPH_TO_PERIPH)) {
873                 u32 event = D40_TYPE_TO_EVENT(d40c->dma_cfg.src_dev_type);
874
875                 __d40_config_set_event(d40c, do_enable, event,
876                                        D40_CHAN_REG_SSLNK);
877         }
878
879         if (d40c->dma_cfg.dir !=  STEDMA40_PERIPH_TO_MEM) {
880                 u32 event = D40_TYPE_TO_EVENT(d40c->dma_cfg.dst_dev_type);
881
882                 __d40_config_set_event(d40c, do_enable, event,
883                                        D40_CHAN_REG_SDLNK);
884         }
885
886         spin_unlock_irqrestore(&d40c->phy_chan->lock, flags);
887 }
888
889 static u32 d40_chan_has_events(struct d40_chan *d40c)
890 {
891         void __iomem *chanbase = chan_base(d40c);
892         u32 val;
893
894         val = readl(chanbase + D40_CHAN_REG_SSLNK);
895         val |= readl(chanbase + D40_CHAN_REG_SDLNK);
896
897         return val;
898 }
899
900 static u32 d40_get_prmo(struct d40_chan *d40c)
901 {
902         static const unsigned int phy_map[] = {
903                 [STEDMA40_PCHAN_BASIC_MODE]
904                         = D40_DREG_PRMO_PCHAN_BASIC,
905                 [STEDMA40_PCHAN_MODULO_MODE]
906                         = D40_DREG_PRMO_PCHAN_MODULO,
907                 [STEDMA40_PCHAN_DOUBLE_DST_MODE]
908                         = D40_DREG_PRMO_PCHAN_DOUBLE_DST,
909         };
910         static const unsigned int log_map[] = {
911                 [STEDMA40_LCHAN_SRC_PHY_DST_LOG]
912                         = D40_DREG_PRMO_LCHAN_SRC_PHY_DST_LOG,
913                 [STEDMA40_LCHAN_SRC_LOG_DST_PHY]
914                         = D40_DREG_PRMO_LCHAN_SRC_LOG_DST_PHY,
915                 [STEDMA40_LCHAN_SRC_LOG_DST_LOG]
916                         = D40_DREG_PRMO_LCHAN_SRC_LOG_DST_LOG,
917         };
918
919         if (chan_is_physical(d40c))
920                 return phy_map[d40c->dma_cfg.mode_opt];
921         else
922                 return log_map[d40c->dma_cfg.mode_opt];
923 }
924
925 static void d40_config_write(struct d40_chan *d40c)
926 {
927         u32 addr_base;
928         u32 var;
929
930         /* Odd addresses are even addresses + 4 */
931         addr_base = (d40c->phy_chan->num % 2) * 4;
932         /* Setup channel mode to logical or physical */
933         var = ((u32)(chan_is_logical(d40c)) + 1) <<
934                 D40_CHAN_POS(d40c->phy_chan->num);
935         writel(var, d40c->base->virtbase + D40_DREG_PRMSE + addr_base);
936
937         /* Setup operational mode option register */
938         var = d40_get_prmo(d40c) << D40_CHAN_POS(d40c->phy_chan->num);
939
940         writel(var, d40c->base->virtbase + D40_DREG_PRMOE + addr_base);
941
942         if (chan_is_logical(d40c)) {
943                 int lidx = (d40c->phy_chan->num << D40_SREG_ELEM_LOG_LIDX_POS)
944                            & D40_SREG_ELEM_LOG_LIDX_MASK;
945                 void __iomem *chanbase = chan_base(d40c);
946
947                 /* Set default config for CFG reg */
948                 writel(d40c->src_def_cfg, chanbase + D40_CHAN_REG_SSCFG);
949                 writel(d40c->dst_def_cfg, chanbase + D40_CHAN_REG_SDCFG);
950
951                 /* Set LIDX for lcla */
952                 writel(lidx, chanbase + D40_CHAN_REG_SSELT);
953                 writel(lidx, chanbase + D40_CHAN_REG_SDELT);
954         }
955 }
956
957 static u32 d40_residue(struct d40_chan *d40c)
958 {
959         u32 num_elt;
960
961         if (chan_is_logical(d40c))
962                 num_elt = (readl(&d40c->lcpa->lcsp2) & D40_MEM_LCSP2_ECNT_MASK)
963                         >> D40_MEM_LCSP2_ECNT_POS;
964         else {
965                 u32 val = readl(chan_base(d40c) + D40_CHAN_REG_SDELT);
966                 num_elt = (val & D40_SREG_ELEM_PHY_ECNT_MASK)
967                           >> D40_SREG_ELEM_PHY_ECNT_POS;
968         }
969
970         return num_elt * (1 << d40c->dma_cfg.dst_info.data_width);
971 }
972
973 static bool d40_tx_is_linked(struct d40_chan *d40c)
974 {
975         bool is_link;
976
977         if (chan_is_logical(d40c))
978                 is_link = readl(&d40c->lcpa->lcsp3) &  D40_MEM_LCSP3_DLOS_MASK;
979         else
980                 is_link = readl(chan_base(d40c) + D40_CHAN_REG_SDLNK)
981                           & D40_SREG_LNK_PHYS_LNK_MASK;
982
983         return is_link;
984 }
985
986 static int d40_pause(struct d40_chan *d40c)
987 {
988         int res = 0;
989         unsigned long flags;
990
991         if (!d40c->busy)
992                 return 0;
993
994         spin_lock_irqsave(&d40c->lock, flags);
995
996         res = d40_channel_execute_command(d40c, D40_DMA_SUSPEND_REQ);
997         if (res == 0) {
998                 if (chan_is_logical(d40c)) {
999                         d40_config_set_event(d40c, false);
1000                         /* Resume the other logical channels if any */
1001                         if (d40_chan_has_events(d40c))
1002                                 res = d40_channel_execute_command(d40c,
1003                                                                   D40_DMA_RUN);
1004                 }
1005         }
1006
1007         spin_unlock_irqrestore(&d40c->lock, flags);
1008         return res;
1009 }
1010
1011 static int d40_resume(struct d40_chan *d40c)
1012 {
1013         int res = 0;
1014         unsigned long flags;
1015
1016         if (!d40c->busy)
1017                 return 0;
1018
1019         spin_lock_irqsave(&d40c->lock, flags);
1020
1021         if (d40c->base->rev == 0)
1022                 if (chan_is_logical(d40c)) {
1023                         res = d40_channel_execute_command(d40c,
1024                                                           D40_DMA_SUSPEND_REQ);
1025                         goto no_suspend;
1026                 }
1027
1028         /* If bytes left to transfer or linked tx resume job */
1029         if (d40_residue(d40c) || d40_tx_is_linked(d40c)) {
1030
1031                 if (chan_is_logical(d40c))
1032                         d40_config_set_event(d40c, true);
1033
1034                 res = d40_channel_execute_command(d40c, D40_DMA_RUN);
1035         }
1036
1037 no_suspend:
1038         spin_unlock_irqrestore(&d40c->lock, flags);
1039         return res;
1040 }
1041
1042 static int d40_terminate_all(struct d40_chan *chan)
1043 {
1044         unsigned long flags;
1045         int ret = 0;
1046
1047         ret = d40_pause(chan);
1048         if (!ret && chan_is_physical(chan))
1049                 ret = d40_channel_execute_command(chan, D40_DMA_STOP);
1050
1051         spin_lock_irqsave(&chan->lock, flags);
1052         d40_term_all(chan);
1053         spin_unlock_irqrestore(&chan->lock, flags);
1054
1055         return ret;
1056 }
1057
1058 static dma_cookie_t d40_tx_submit(struct dma_async_tx_descriptor *tx)
1059 {
1060         struct d40_chan *d40c = container_of(tx->chan,
1061                                              struct d40_chan,
1062                                              chan);
1063         struct d40_desc *d40d = container_of(tx, struct d40_desc, txd);
1064         unsigned long flags;
1065
1066         spin_lock_irqsave(&d40c->lock, flags);
1067
1068         d40c->chan.cookie++;
1069
1070         if (d40c->chan.cookie < 0)
1071                 d40c->chan.cookie = 1;
1072
1073         d40d->txd.cookie = d40c->chan.cookie;
1074
1075         d40_desc_queue(d40c, d40d);
1076
1077         spin_unlock_irqrestore(&d40c->lock, flags);
1078
1079         return tx->cookie;
1080 }
1081
1082 static int d40_start(struct d40_chan *d40c)
1083 {
1084         if (d40c->base->rev == 0) {
1085                 int err;
1086
1087                 if (chan_is_logical(d40c)) {
1088                         err = d40_channel_execute_command(d40c,
1089                                                           D40_DMA_SUSPEND_REQ);
1090                         if (err)
1091                                 return err;
1092                 }
1093         }
1094
1095         if (chan_is_logical(d40c))
1096                 d40_config_set_event(d40c, true);
1097
1098         return d40_channel_execute_command(d40c, D40_DMA_RUN);
1099 }
1100
1101 static struct d40_desc *d40_queue_start(struct d40_chan *d40c)
1102 {
1103         struct d40_desc *d40d;
1104         int err;
1105
1106         /* Start queued jobs, if any */
1107         d40d = d40_first_queued(d40c);
1108
1109         if (d40d != NULL) {
1110                 d40c->busy = true;
1111
1112                 /* Remove from queue */
1113                 d40_desc_remove(d40d);
1114
1115                 /* Add to active queue */
1116                 d40_desc_submit(d40c, d40d);
1117
1118                 /* Initiate DMA job */
1119                 d40_desc_load(d40c, d40d);
1120
1121                 /* Start dma job */
1122                 err = d40_start(d40c);
1123
1124                 if (err)
1125                         return NULL;
1126         }
1127
1128         return d40d;
1129 }
1130
1131 /* called from interrupt context */
1132 static void dma_tc_handle(struct d40_chan *d40c)
1133 {
1134         struct d40_desc *d40d;
1135
1136         /* Get first active entry from list */
1137         d40d = d40_first_active_get(d40c);
1138
1139         if (d40d == NULL)
1140                 return;
1141
1142         if (d40d->cyclic) {
1143                 /*
1144                  * If this was a paritially loaded list, we need to reloaded
1145                  * it, and only when the list is completed.  We need to check
1146                  * for done because the interrupt will hit for every link, and
1147                  * not just the last one.
1148                  */
1149                 if (d40d->lli_current < d40d->lli_len
1150                     && !d40_tx_is_linked(d40c)
1151                     && !d40_residue(d40c)) {
1152                         d40_lcla_free_all(d40c, d40d);
1153                         d40_desc_load(d40c, d40d);
1154                         (void) d40_start(d40c);
1155
1156                         if (d40d->lli_current == d40d->lli_len)
1157                                 d40d->lli_current = 0;
1158                 }
1159         } else {
1160                 d40_lcla_free_all(d40c, d40d);
1161
1162                 if (d40d->lli_current < d40d->lli_len) {
1163                         d40_desc_load(d40c, d40d);
1164                         /* Start dma job */
1165                         (void) d40_start(d40c);
1166                         return;
1167                 }
1168
1169                 if (d40_queue_start(d40c) == NULL)
1170                         d40c->busy = false;
1171         }
1172
1173         d40c->pending_tx++;
1174         tasklet_schedule(&d40c->tasklet);
1175
1176 }
1177
1178 static void dma_tasklet(unsigned long data)
1179 {
1180         struct d40_chan *d40c = (struct d40_chan *) data;
1181         struct d40_desc *d40d;
1182         unsigned long flags;
1183         dma_async_tx_callback callback;
1184         void *callback_param;
1185
1186         spin_lock_irqsave(&d40c->lock, flags);
1187
1188         /* Get first active entry from list */
1189         d40d = d40_first_active_get(d40c);
1190         if (d40d == NULL)
1191                 goto err;
1192
1193         if (!d40d->cyclic)
1194                 d40c->completed = d40d->txd.cookie;
1195
1196         /*
1197          * If terminating a channel pending_tx is set to zero.
1198          * This prevents any finished active jobs to return to the client.
1199          */
1200         if (d40c->pending_tx == 0) {
1201                 spin_unlock_irqrestore(&d40c->lock, flags);
1202                 return;
1203         }
1204
1205         /* Callback to client */
1206         callback = d40d->txd.callback;
1207         callback_param = d40d->txd.callback_param;
1208
1209         if (!d40d->cyclic) {
1210                 if (async_tx_test_ack(&d40d->txd)) {
1211                         d40_desc_remove(d40d);
1212                         d40_desc_free(d40c, d40d);
1213                 } else {
1214                         if (!d40d->is_in_client_list) {
1215                                 d40_desc_remove(d40d);
1216                                 d40_lcla_free_all(d40c, d40d);
1217                                 list_add_tail(&d40d->node, &d40c->client);
1218                                 d40d->is_in_client_list = true;
1219                         }
1220                 }
1221         }
1222
1223         d40c->pending_tx--;
1224
1225         if (d40c->pending_tx)
1226                 tasklet_schedule(&d40c->tasklet);
1227
1228         spin_unlock_irqrestore(&d40c->lock, flags);
1229
1230         if (callback && (d40d->txd.flags & DMA_PREP_INTERRUPT))
1231                 callback(callback_param);
1232
1233         return;
1234
1235  err:
1236         /* Rescue manoeuvre if receiving double interrupts */
1237         if (d40c->pending_tx > 0)
1238                 d40c->pending_tx--;
1239         spin_unlock_irqrestore(&d40c->lock, flags);
1240 }
1241
1242 static irqreturn_t d40_handle_interrupt(int irq, void *data)
1243 {
1244         static const struct d40_interrupt_lookup il[] = {
1245                 {D40_DREG_LCTIS0, D40_DREG_LCICR0, false,  0},
1246                 {D40_DREG_LCTIS1, D40_DREG_LCICR1, false, 32},
1247                 {D40_DREG_LCTIS2, D40_DREG_LCICR2, false, 64},
1248                 {D40_DREG_LCTIS3, D40_DREG_LCICR3, false, 96},
1249                 {D40_DREG_LCEIS0, D40_DREG_LCICR0, true,   0},
1250                 {D40_DREG_LCEIS1, D40_DREG_LCICR1, true,  32},
1251                 {D40_DREG_LCEIS2, D40_DREG_LCICR2, true,  64},
1252                 {D40_DREG_LCEIS3, D40_DREG_LCICR3, true,  96},
1253                 {D40_DREG_PCTIS,  D40_DREG_PCICR,  false, D40_PHY_CHAN},
1254                 {D40_DREG_PCEIS,  D40_DREG_PCICR,  true,  D40_PHY_CHAN},
1255         };
1256
1257         int i;
1258         u32 regs[ARRAY_SIZE(il)];
1259         u32 idx;
1260         u32 row;
1261         long chan = -1;
1262         struct d40_chan *d40c;
1263         unsigned long flags;
1264         struct d40_base *base = data;
1265
1266         spin_lock_irqsave(&base->interrupt_lock, flags);
1267
1268         /* Read interrupt status of both logical and physical channels */
1269         for (i = 0; i < ARRAY_SIZE(il); i++)
1270                 regs[i] = readl(base->virtbase + il[i].src);
1271
1272         for (;;) {
1273
1274                 chan = find_next_bit((unsigned long *)regs,
1275                                      BITS_PER_LONG * ARRAY_SIZE(il), chan + 1);
1276
1277                 /* No more set bits found? */
1278                 if (chan == BITS_PER_LONG * ARRAY_SIZE(il))
1279                         break;
1280
1281                 row = chan / BITS_PER_LONG;
1282                 idx = chan & (BITS_PER_LONG - 1);
1283
1284                 /* ACK interrupt */
1285                 writel(1 << idx, base->virtbase + il[row].clr);
1286
1287                 if (il[row].offset == D40_PHY_CHAN)
1288                         d40c = base->lookup_phy_chans[idx];
1289                 else
1290                         d40c = base->lookup_log_chans[il[row].offset + idx];
1291                 spin_lock(&d40c->lock);
1292
1293                 if (!il[row].is_error)
1294                         dma_tc_handle(d40c);
1295                 else
1296                         d40_err(base->dev, "IRQ chan: %ld offset %d idx %d\n",
1297                                 chan, il[row].offset, idx);
1298
1299                 spin_unlock(&d40c->lock);
1300         }
1301
1302         spin_unlock_irqrestore(&base->interrupt_lock, flags);
1303
1304         return IRQ_HANDLED;
1305 }
1306
1307 static int d40_validate_conf(struct d40_chan *d40c,
1308                              struct stedma40_chan_cfg *conf)
1309 {
1310         int res = 0;
1311         u32 dst_event_group = D40_TYPE_TO_GROUP(conf->dst_dev_type);
1312         u32 src_event_group = D40_TYPE_TO_GROUP(conf->src_dev_type);
1313         bool is_log = conf->mode == STEDMA40_MODE_LOGICAL;
1314
1315         if (!conf->dir) {
1316                 chan_err(d40c, "Invalid direction.\n");
1317                 res = -EINVAL;
1318         }
1319
1320         if (conf->dst_dev_type != STEDMA40_DEV_DST_MEMORY &&
1321             d40c->base->plat_data->dev_tx[conf->dst_dev_type] == 0 &&
1322             d40c->runtime_addr == 0) {
1323
1324                 chan_err(d40c, "Invalid TX channel address (%d)\n",
1325                          conf->dst_dev_type);
1326                 res = -EINVAL;
1327         }
1328
1329         if (conf->src_dev_type != STEDMA40_DEV_SRC_MEMORY &&
1330             d40c->base->plat_data->dev_rx[conf->src_dev_type] == 0 &&
1331             d40c->runtime_addr == 0) {
1332                 chan_err(d40c, "Invalid RX channel address (%d)\n",
1333                         conf->src_dev_type);
1334                 res = -EINVAL;
1335         }
1336
1337         if (conf->dir == STEDMA40_MEM_TO_PERIPH &&
1338             dst_event_group == STEDMA40_DEV_DST_MEMORY) {
1339                 chan_err(d40c, "Invalid dst\n");
1340                 res = -EINVAL;
1341         }
1342
1343         if (conf->dir == STEDMA40_PERIPH_TO_MEM &&
1344             src_event_group == STEDMA40_DEV_SRC_MEMORY) {
1345                 chan_err(d40c, "Invalid src\n");
1346                 res = -EINVAL;
1347         }
1348
1349         if (src_event_group == STEDMA40_DEV_SRC_MEMORY &&
1350             dst_event_group == STEDMA40_DEV_DST_MEMORY && is_log) {
1351                 chan_err(d40c, "No event line\n");
1352                 res = -EINVAL;
1353         }
1354
1355         if (conf->dir == STEDMA40_PERIPH_TO_PERIPH &&
1356             (src_event_group != dst_event_group)) {
1357                 chan_err(d40c, "Invalid event group\n");
1358                 res = -EINVAL;
1359         }
1360
1361         if (conf->dir == STEDMA40_PERIPH_TO_PERIPH) {
1362                 /*
1363                  * DMAC HW supports it. Will be added to this driver,
1364                  * in case any dma client requires it.
1365                  */
1366                 chan_err(d40c, "periph to periph not supported\n");
1367                 res = -EINVAL;
1368         }
1369
1370         if (d40_psize_2_burst_size(is_log, conf->src_info.psize) *
1371             (1 << conf->src_info.data_width) !=
1372             d40_psize_2_burst_size(is_log, conf->dst_info.psize) *
1373             (1 << conf->dst_info.data_width)) {
1374                 /*
1375                  * The DMAC hardware only supports
1376                  * src (burst x width) == dst (burst x width)
1377                  */
1378
1379                 chan_err(d40c, "src (burst x width) != dst (burst x width)\n");
1380                 res = -EINVAL;
1381         }
1382
1383         return res;
1384 }
1385
1386 static bool d40_alloc_mask_set(struct d40_phy_res *phy, bool is_src,
1387                                int log_event_line, bool is_log)
1388 {
1389         unsigned long flags;
1390         spin_lock_irqsave(&phy->lock, flags);
1391         if (!is_log) {
1392                 /* Physical interrupts are masked per physical full channel */
1393                 if (phy->allocated_src == D40_ALLOC_FREE &&
1394                     phy->allocated_dst == D40_ALLOC_FREE) {
1395                         phy->allocated_dst = D40_ALLOC_PHY;
1396                         phy->allocated_src = D40_ALLOC_PHY;
1397                         goto found;
1398                 } else
1399                         goto not_found;
1400         }
1401
1402         /* Logical channel */
1403         if (is_src) {
1404                 if (phy->allocated_src == D40_ALLOC_PHY)
1405                         goto not_found;
1406
1407                 if (phy->allocated_src == D40_ALLOC_FREE)
1408                         phy->allocated_src = D40_ALLOC_LOG_FREE;
1409
1410                 if (!(phy->allocated_src & (1 << log_event_line))) {
1411                         phy->allocated_src |= 1 << log_event_line;
1412                         goto found;
1413                 } else
1414                         goto not_found;
1415         } else {
1416                 if (phy->allocated_dst == D40_ALLOC_PHY)
1417                         goto not_found;
1418
1419                 if (phy->allocated_dst == D40_ALLOC_FREE)
1420                         phy->allocated_dst = D40_ALLOC_LOG_FREE;
1421
1422                 if (!(phy->allocated_dst & (1 << log_event_line))) {
1423                         phy->allocated_dst |= 1 << log_event_line;
1424                         goto found;
1425                 } else
1426                         goto not_found;
1427         }
1428
1429 not_found:
1430         spin_unlock_irqrestore(&phy->lock, flags);
1431         return false;
1432 found:
1433         spin_unlock_irqrestore(&phy->lock, flags);
1434         return true;
1435 }
1436
1437 static bool d40_alloc_mask_free(struct d40_phy_res *phy, bool is_src,
1438                                int log_event_line)
1439 {
1440         unsigned long flags;
1441         bool is_free = false;
1442
1443         spin_lock_irqsave(&phy->lock, flags);
1444         if (!log_event_line) {
1445                 phy->allocated_dst = D40_ALLOC_FREE;
1446                 phy->allocated_src = D40_ALLOC_FREE;
1447                 is_free = true;
1448                 goto out;
1449         }
1450
1451         /* Logical channel */
1452         if (is_src) {
1453                 phy->allocated_src &= ~(1 << log_event_line);
1454                 if (phy->allocated_src == D40_ALLOC_LOG_FREE)
1455                         phy->allocated_src = D40_ALLOC_FREE;
1456         } else {
1457                 phy->allocated_dst &= ~(1 << log_event_line);
1458                 if (phy->allocated_dst == D40_ALLOC_LOG_FREE)
1459                         phy->allocated_dst = D40_ALLOC_FREE;
1460         }
1461
1462         is_free = ((phy->allocated_src | phy->allocated_dst) ==
1463                    D40_ALLOC_FREE);
1464
1465 out:
1466         spin_unlock_irqrestore(&phy->lock, flags);
1467
1468         return is_free;
1469 }
1470
1471 static int d40_allocate_channel(struct d40_chan *d40c)
1472 {
1473         int dev_type;
1474         int event_group;
1475         int event_line;
1476         struct d40_phy_res *phys;
1477         int i;
1478         int j;
1479         int log_num;
1480         bool is_src;
1481         bool is_log = d40c->dma_cfg.mode == STEDMA40_MODE_LOGICAL;
1482
1483         phys = d40c->base->phy_res;
1484
1485         if (d40c->dma_cfg.dir == STEDMA40_PERIPH_TO_MEM) {
1486                 dev_type = d40c->dma_cfg.src_dev_type;
1487                 log_num = 2 * dev_type;
1488                 is_src = true;
1489         } else if (d40c->dma_cfg.dir == STEDMA40_MEM_TO_PERIPH ||
1490                    d40c->dma_cfg.dir == STEDMA40_MEM_TO_MEM) {
1491                 /* dst event lines are used for logical memcpy */
1492                 dev_type = d40c->dma_cfg.dst_dev_type;
1493                 log_num = 2 * dev_type + 1;
1494                 is_src = false;
1495         } else
1496                 return -EINVAL;
1497
1498         event_group = D40_TYPE_TO_GROUP(dev_type);
1499         event_line = D40_TYPE_TO_EVENT(dev_type);
1500
1501         if (!is_log) {
1502                 if (d40c->dma_cfg.dir == STEDMA40_MEM_TO_MEM) {
1503                         /* Find physical half channel */
1504                         for (i = 0; i < d40c->base->num_phy_chans; i++) {
1505
1506                                 if (d40_alloc_mask_set(&phys[i], is_src,
1507                                                        0, is_log))
1508                                         goto found_phy;
1509                         }
1510                 } else
1511                         for (j = 0; j < d40c->base->num_phy_chans; j += 8) {
1512                                 int phy_num = j  + event_group * 2;
1513                                 for (i = phy_num; i < phy_num + 2; i++) {
1514                                         if (d40_alloc_mask_set(&phys[i],
1515                                                                is_src,
1516                                                                0,
1517                                                                is_log))
1518                                                 goto found_phy;
1519                                 }
1520                         }
1521                 return -EINVAL;
1522 found_phy:
1523                 d40c->phy_chan = &phys[i];
1524                 d40c->log_num = D40_PHY_CHAN;
1525                 goto out;
1526         }
1527         if (dev_type == -1)
1528                 return -EINVAL;
1529
1530         /* Find logical channel */
1531         for (j = 0; j < d40c->base->num_phy_chans; j += 8) {
1532                 int phy_num = j + event_group * 2;
1533                 /*
1534                  * Spread logical channels across all available physical rather
1535                  * than pack every logical channel at the first available phy
1536                  * channels.
1537                  */
1538                 if (is_src) {
1539                         for (i = phy_num; i < phy_num + 2; i++) {
1540                                 if (d40_alloc_mask_set(&phys[i], is_src,
1541                                                        event_line, is_log))
1542                                         goto found_log;
1543                         }
1544                 } else {
1545                         for (i = phy_num + 1; i >= phy_num; i--) {
1546                                 if (d40_alloc_mask_set(&phys[i], is_src,
1547                                                        event_line, is_log))
1548                                         goto found_log;
1549                         }
1550                 }
1551         }
1552         return -EINVAL;
1553
1554 found_log:
1555         d40c->phy_chan = &phys[i];
1556         d40c->log_num = log_num;
1557 out:
1558
1559         if (is_log)
1560                 d40c->base->lookup_log_chans[d40c->log_num] = d40c;
1561         else
1562                 d40c->base->lookup_phy_chans[d40c->phy_chan->num] = d40c;
1563
1564         return 0;
1565
1566 }
1567
1568 static int d40_config_memcpy(struct d40_chan *d40c)
1569 {
1570         dma_cap_mask_t cap = d40c->chan.device->cap_mask;
1571
1572         if (dma_has_cap(DMA_MEMCPY, cap) && !dma_has_cap(DMA_SLAVE, cap)) {
1573                 d40c->dma_cfg = *d40c->base->plat_data->memcpy_conf_log;
1574                 d40c->dma_cfg.src_dev_type = STEDMA40_DEV_SRC_MEMORY;
1575                 d40c->dma_cfg.dst_dev_type = d40c->base->plat_data->
1576                         memcpy[d40c->chan.chan_id];
1577
1578         } else if (dma_has_cap(DMA_MEMCPY, cap) &&
1579                    dma_has_cap(DMA_SLAVE, cap)) {
1580                 d40c->dma_cfg = *d40c->base->plat_data->memcpy_conf_phy;
1581         } else {
1582                 chan_err(d40c, "No memcpy\n");
1583                 return -EINVAL;
1584         }
1585
1586         return 0;
1587 }
1588
1589
1590 static int d40_free_dma(struct d40_chan *d40c)
1591 {
1592
1593         int res = 0;
1594         u32 event;
1595         struct d40_phy_res *phy = d40c->phy_chan;
1596         bool is_src;
1597         struct d40_desc *d;
1598         struct d40_desc *_d;
1599
1600
1601         /* Terminate all queued and active transfers */
1602         d40_term_all(d40c);
1603
1604         /* Release client owned descriptors */
1605         if (!list_empty(&d40c->client))
1606                 list_for_each_entry_safe(d, _d, &d40c->client, node) {
1607                         d40_desc_remove(d);
1608                         d40_desc_free(d40c, d);
1609                 }
1610
1611         if (phy == NULL) {
1612                 chan_err(d40c, "phy == null\n");
1613                 return -EINVAL;
1614         }
1615
1616         if (phy->allocated_src == D40_ALLOC_FREE &&
1617             phy->allocated_dst == D40_ALLOC_FREE) {
1618                 chan_err(d40c, "channel already free\n");
1619                 return -EINVAL;
1620         }
1621
1622         if (d40c->dma_cfg.dir == STEDMA40_MEM_TO_PERIPH ||
1623             d40c->dma_cfg.dir == STEDMA40_MEM_TO_MEM) {
1624                 event = D40_TYPE_TO_EVENT(d40c->dma_cfg.dst_dev_type);
1625                 is_src = false;
1626         } else if (d40c->dma_cfg.dir == STEDMA40_PERIPH_TO_MEM) {
1627                 event = D40_TYPE_TO_EVENT(d40c->dma_cfg.src_dev_type);
1628                 is_src = true;
1629         } else {
1630                 chan_err(d40c, "Unknown direction\n");
1631                 return -EINVAL;
1632         }
1633
1634         res = d40_channel_execute_command(d40c, D40_DMA_SUSPEND_REQ);
1635         if (res) {
1636                 chan_err(d40c, "suspend failed\n");
1637                 return res;
1638         }
1639
1640         if (chan_is_logical(d40c)) {
1641                 /* Release logical channel, deactivate the event line */
1642
1643                 d40_config_set_event(d40c, false);
1644                 d40c->base->lookup_log_chans[d40c->log_num] = NULL;
1645
1646                 /*
1647                  * Check if there are more logical allocation
1648                  * on this phy channel.
1649                  */
1650                 if (!d40_alloc_mask_free(phy, is_src, event)) {
1651                         /* Resume the other logical channels if any */
1652                         if (d40_chan_has_events(d40c)) {
1653                                 res = d40_channel_execute_command(d40c,
1654                                                                   D40_DMA_RUN);
1655                                 if (res) {
1656                                         chan_err(d40c,
1657                                                 "Executing RUN command\n");
1658                                         return res;
1659                                 }
1660                         }
1661                         return 0;
1662                 }
1663         } else {
1664                 (void) d40_alloc_mask_free(phy, is_src, 0);
1665         }
1666
1667         /* Release physical channel */
1668         res = d40_channel_execute_command(d40c, D40_DMA_STOP);
1669         if (res) {
1670                 chan_err(d40c, "Failed to stop channel\n");
1671                 return res;
1672         }
1673         d40c->phy_chan = NULL;
1674         d40c->configured = false;
1675         d40c->base->lookup_phy_chans[phy->num] = NULL;
1676
1677         return 0;
1678 }
1679
1680 static bool d40_is_paused(struct d40_chan *d40c)
1681 {
1682         void __iomem *chanbase = chan_base(d40c);
1683         bool is_paused = false;
1684         unsigned long flags;
1685         void __iomem *active_reg;
1686         u32 status;
1687         u32 event;
1688
1689         spin_lock_irqsave(&d40c->lock, flags);
1690
1691         if (chan_is_physical(d40c)) {
1692                 if (d40c->phy_chan->num % 2 == 0)
1693                         active_reg = d40c->base->virtbase + D40_DREG_ACTIVE;
1694                 else
1695                         active_reg = d40c->base->virtbase + D40_DREG_ACTIVO;
1696
1697                 status = (readl(active_reg) &
1698                           D40_CHAN_POS_MASK(d40c->phy_chan->num)) >>
1699                         D40_CHAN_POS(d40c->phy_chan->num);
1700                 if (status == D40_DMA_SUSPENDED || status == D40_DMA_STOP)
1701                         is_paused = true;
1702
1703                 goto _exit;
1704         }
1705
1706         if (d40c->dma_cfg.dir == STEDMA40_MEM_TO_PERIPH ||
1707             d40c->dma_cfg.dir == STEDMA40_MEM_TO_MEM) {
1708                 event = D40_TYPE_TO_EVENT(d40c->dma_cfg.dst_dev_type);
1709                 status = readl(chanbase + D40_CHAN_REG_SDLNK);
1710         } else if (d40c->dma_cfg.dir == STEDMA40_PERIPH_TO_MEM) {
1711                 event = D40_TYPE_TO_EVENT(d40c->dma_cfg.src_dev_type);
1712                 status = readl(chanbase + D40_CHAN_REG_SSLNK);
1713         } else {
1714                 chan_err(d40c, "Unknown direction\n");
1715                 goto _exit;
1716         }
1717
1718         status = (status & D40_EVENTLINE_MASK(event)) >>
1719                 D40_EVENTLINE_POS(event);
1720
1721         if (status != D40_DMA_RUN)
1722                 is_paused = true;
1723 _exit:
1724         spin_unlock_irqrestore(&d40c->lock, flags);
1725         return is_paused;
1726
1727 }
1728
1729
1730 static u32 stedma40_residue(struct dma_chan *chan)
1731 {
1732         struct d40_chan *d40c =
1733                 container_of(chan, struct d40_chan, chan);
1734         u32 bytes_left;
1735         unsigned long flags;
1736
1737         spin_lock_irqsave(&d40c->lock, flags);
1738         bytes_left = d40_residue(d40c);
1739         spin_unlock_irqrestore(&d40c->lock, flags);
1740
1741         return bytes_left;
1742 }
1743
1744 static int
1745 d40_prep_sg_log(struct d40_chan *chan, struct d40_desc *desc,
1746                 struct scatterlist *sg_src, struct scatterlist *sg_dst,
1747                 unsigned int sg_len, dma_addr_t src_dev_addr,
1748                 dma_addr_t dst_dev_addr)
1749 {
1750         struct stedma40_chan_cfg *cfg = &chan->dma_cfg;
1751         struct stedma40_half_channel_info *src_info = &cfg->src_info;
1752         struct stedma40_half_channel_info *dst_info = &cfg->dst_info;
1753         int ret;
1754
1755         ret = d40_log_sg_to_lli(sg_src, sg_len,
1756                                 src_dev_addr,
1757                                 desc->lli_log.src,
1758                                 chan->log_def.lcsp1,
1759                                 src_info->data_width,
1760                                 dst_info->data_width);
1761
1762         ret = d40_log_sg_to_lli(sg_dst, sg_len,
1763                                 dst_dev_addr,
1764                                 desc->lli_log.dst,
1765                                 chan->log_def.lcsp3,
1766                                 dst_info->data_width,
1767                                 src_info->data_width);
1768
1769         return ret < 0 ? ret : 0;
1770 }
1771
1772 static int
1773 d40_prep_sg_phy(struct d40_chan *chan, struct d40_desc *desc,
1774                 struct scatterlist *sg_src, struct scatterlist *sg_dst,
1775                 unsigned int sg_len, dma_addr_t src_dev_addr,
1776                 dma_addr_t dst_dev_addr)
1777 {
1778         struct stedma40_chan_cfg *cfg = &chan->dma_cfg;
1779         struct stedma40_half_channel_info *src_info = &cfg->src_info;
1780         struct stedma40_half_channel_info *dst_info = &cfg->dst_info;
1781         unsigned long flags = 0;
1782         int ret;
1783
1784         if (desc->cyclic)
1785                 flags |= LLI_CYCLIC | LLI_TERM_INT;
1786
1787         ret = d40_phy_sg_to_lli(sg_src, sg_len, src_dev_addr,
1788                                 desc->lli_phy.src,
1789                                 virt_to_phys(desc->lli_phy.src),
1790                                 chan->src_def_cfg,
1791                                 src_info, dst_info, flags);
1792
1793         ret = d40_phy_sg_to_lli(sg_dst, sg_len, dst_dev_addr,
1794                                 desc->lli_phy.dst,
1795                                 virt_to_phys(desc->lli_phy.dst),
1796                                 chan->dst_def_cfg,
1797                                 dst_info, src_info, flags);
1798
1799         dma_sync_single_for_device(chan->base->dev, desc->lli_pool.dma_addr,
1800                                    desc->lli_pool.size, DMA_TO_DEVICE);
1801
1802         return ret < 0 ? ret : 0;
1803 }
1804
1805
1806 static struct d40_desc *
1807 d40_prep_desc(struct d40_chan *chan, struct scatterlist *sg,
1808               unsigned int sg_len, unsigned long dma_flags)
1809 {
1810         struct stedma40_chan_cfg *cfg = &chan->dma_cfg;
1811         struct d40_desc *desc;
1812         int ret;
1813
1814         desc = d40_desc_get(chan);
1815         if (!desc)
1816                 return NULL;
1817
1818         desc->lli_len = d40_sg_2_dmalen(sg, sg_len, cfg->src_info.data_width,
1819                                         cfg->dst_info.data_width);
1820         if (desc->lli_len < 0) {
1821                 chan_err(chan, "Unaligned size\n");
1822                 goto err;
1823         }
1824
1825         ret = d40_pool_lli_alloc(chan, desc, desc->lli_len);
1826         if (ret < 0) {
1827                 chan_err(chan, "Could not allocate lli\n");
1828                 goto err;
1829         }
1830
1831
1832         desc->lli_current = 0;
1833         desc->txd.flags = dma_flags;
1834         desc->txd.tx_submit = d40_tx_submit;
1835
1836         dma_async_tx_descriptor_init(&desc->txd, &chan->chan);
1837
1838         return desc;
1839
1840 err:
1841         d40_desc_free(chan, desc);
1842         return NULL;
1843 }
1844
1845 static dma_addr_t
1846 d40_get_dev_addr(struct d40_chan *chan, enum dma_data_direction direction)
1847 {
1848         struct stedma40_platform_data *plat = chan->base->plat_data;
1849         struct stedma40_chan_cfg *cfg = &chan->dma_cfg;
1850         dma_addr_t addr = 0;
1851
1852         if (chan->runtime_addr)
1853                 return chan->runtime_addr;
1854
1855         if (direction == DMA_FROM_DEVICE)
1856                 addr = plat->dev_rx[cfg->src_dev_type];
1857         else if (direction == DMA_TO_DEVICE)
1858                 addr = plat->dev_tx[cfg->dst_dev_type];
1859
1860         return addr;
1861 }
1862
1863 static struct dma_async_tx_descriptor *
1864 d40_prep_sg(struct dma_chan *dchan, struct scatterlist *sg_src,
1865             struct scatterlist *sg_dst, unsigned int sg_len,
1866             enum dma_data_direction direction, unsigned long dma_flags)
1867 {
1868         struct d40_chan *chan = container_of(dchan, struct d40_chan, chan);
1869         dma_addr_t src_dev_addr = 0;
1870         dma_addr_t dst_dev_addr = 0;
1871         struct d40_desc *desc;
1872         unsigned long flags;
1873         int ret;
1874
1875         if (!chan->phy_chan) {
1876                 chan_err(chan, "Cannot prepare unallocated channel\n");
1877                 return NULL;
1878         }
1879
1880
1881         spin_lock_irqsave(&chan->lock, flags);
1882
1883         desc = d40_prep_desc(chan, sg_src, sg_len, dma_flags);
1884         if (desc == NULL)
1885                 goto err;
1886
1887         if (sg_next(&sg_src[sg_len - 1]) == sg_src)
1888                 desc->cyclic = true;
1889
1890         if (direction != DMA_NONE) {
1891                 dma_addr_t dev_addr = d40_get_dev_addr(chan, direction);
1892
1893                 if (direction == DMA_FROM_DEVICE)
1894                         src_dev_addr = dev_addr;
1895                 else if (direction == DMA_TO_DEVICE)
1896                         dst_dev_addr = dev_addr;
1897         }
1898
1899         if (chan_is_logical(chan))
1900                 ret = d40_prep_sg_log(chan, desc, sg_src, sg_dst,
1901                                       sg_len, src_dev_addr, dst_dev_addr);
1902         else
1903                 ret = d40_prep_sg_phy(chan, desc, sg_src, sg_dst,
1904                                       sg_len, src_dev_addr, dst_dev_addr);
1905
1906         if (ret) {
1907                 chan_err(chan, "Failed to prepare %s sg job: %d\n",
1908                          chan_is_logical(chan) ? "log" : "phy", ret);
1909                 goto err;
1910         }
1911
1912         spin_unlock_irqrestore(&chan->lock, flags);
1913
1914         return &desc->txd;
1915
1916 err:
1917         if (desc)
1918                 d40_desc_free(chan, desc);
1919         spin_unlock_irqrestore(&chan->lock, flags);
1920         return NULL;
1921 }
1922
1923 bool stedma40_filter(struct dma_chan *chan, void *data)
1924 {
1925         struct stedma40_chan_cfg *info = data;
1926         struct d40_chan *d40c =
1927                 container_of(chan, struct d40_chan, chan);
1928         int err;
1929
1930         if (data) {
1931                 err = d40_validate_conf(d40c, info);
1932                 if (!err)
1933                         d40c->dma_cfg = *info;
1934         } else
1935                 err = d40_config_memcpy(d40c);
1936
1937         if (!err)
1938                 d40c->configured = true;
1939
1940         return err == 0;
1941 }
1942 EXPORT_SYMBOL(stedma40_filter);
1943
1944 static void __d40_set_prio_rt(struct d40_chan *d40c, int dev_type, bool src)
1945 {
1946         bool realtime = d40c->dma_cfg.realtime;
1947         bool highprio = d40c->dma_cfg.high_priority;
1948         u32 prioreg = highprio ? D40_DREG_PSEG1 : D40_DREG_PCEG1;
1949         u32 rtreg = realtime ? D40_DREG_RSEG1 : D40_DREG_RCEG1;
1950         u32 event = D40_TYPE_TO_EVENT(dev_type);
1951         u32 group = D40_TYPE_TO_GROUP(dev_type);
1952         u32 bit = 1 << event;
1953
1954         /* Destination event lines are stored in the upper halfword */
1955         if (!src)
1956                 bit <<= 16;
1957
1958         writel(bit, d40c->base->virtbase + prioreg + group * 4);
1959         writel(bit, d40c->base->virtbase + rtreg + group * 4);
1960 }
1961
1962 static void d40_set_prio_realtime(struct d40_chan *d40c)
1963 {
1964         if (d40c->base->rev < 3)
1965                 return;
1966
1967         if ((d40c->dma_cfg.dir ==  STEDMA40_PERIPH_TO_MEM) ||
1968             (d40c->dma_cfg.dir == STEDMA40_PERIPH_TO_PERIPH))
1969                 __d40_set_prio_rt(d40c, d40c->dma_cfg.src_dev_type, true);
1970
1971         if ((d40c->dma_cfg.dir ==  STEDMA40_MEM_TO_PERIPH) ||
1972             (d40c->dma_cfg.dir == STEDMA40_PERIPH_TO_PERIPH))
1973                 __d40_set_prio_rt(d40c, d40c->dma_cfg.dst_dev_type, false);
1974 }
1975
1976 /* DMA ENGINE functions */
1977 static int d40_alloc_chan_resources(struct dma_chan *chan)
1978 {
1979         int err;
1980         unsigned long flags;
1981         struct d40_chan *d40c =
1982                 container_of(chan, struct d40_chan, chan);
1983         bool is_free_phy;
1984         spin_lock_irqsave(&d40c->lock, flags);
1985
1986         d40c->completed = chan->cookie = 1;
1987
1988         /* If no dma configuration is set use default configuration (memcpy) */
1989         if (!d40c->configured) {
1990                 err = d40_config_memcpy(d40c);
1991                 if (err) {
1992                         chan_err(d40c, "Failed to configure memcpy channel\n");
1993                         goto fail;
1994                 }
1995         }
1996         is_free_phy = (d40c->phy_chan == NULL);
1997
1998         err = d40_allocate_channel(d40c);
1999         if (err) {
2000                 chan_err(d40c, "Failed to allocate channel\n");
2001                 goto fail;
2002         }
2003
2004         /* Fill in basic CFG register values */
2005         d40_phy_cfg(&d40c->dma_cfg, &d40c->src_def_cfg,
2006                     &d40c->dst_def_cfg, chan_is_logical(d40c));
2007
2008         d40_set_prio_realtime(d40c);
2009
2010         if (chan_is_logical(d40c)) {
2011                 d40_log_cfg(&d40c->dma_cfg,
2012                             &d40c->log_def.lcsp1, &d40c->log_def.lcsp3);
2013
2014                 if (d40c->dma_cfg.dir == STEDMA40_PERIPH_TO_MEM)
2015                         d40c->lcpa = d40c->base->lcpa_base +
2016                           d40c->dma_cfg.src_dev_type * D40_LCPA_CHAN_SIZE;
2017                 else
2018                         d40c->lcpa = d40c->base->lcpa_base +
2019                           d40c->dma_cfg.dst_dev_type *
2020                           D40_LCPA_CHAN_SIZE + D40_LCPA_CHAN_DST_DELTA;
2021         }
2022
2023         /*
2024          * Only write channel configuration to the DMA if the physical
2025          * resource is free. In case of multiple logical channels
2026          * on the same physical resource, only the first write is necessary.
2027          */
2028         if (is_free_phy)
2029                 d40_config_write(d40c);
2030 fail:
2031         spin_unlock_irqrestore(&d40c->lock, flags);
2032         return err;
2033 }
2034
2035 static void d40_free_chan_resources(struct dma_chan *chan)
2036 {
2037         struct d40_chan *d40c =
2038                 container_of(chan, struct d40_chan, chan);
2039         int err;
2040         unsigned long flags;
2041
2042         if (d40c->phy_chan == NULL) {
2043                 chan_err(d40c, "Cannot free unallocated channel\n");
2044                 return;
2045         }
2046
2047
2048         spin_lock_irqsave(&d40c->lock, flags);
2049
2050         err = d40_free_dma(d40c);
2051
2052         if (err)
2053                 chan_err(d40c, "Failed to free channel\n");
2054         spin_unlock_irqrestore(&d40c->lock, flags);
2055 }
2056
2057 static struct dma_async_tx_descriptor *d40_prep_memcpy(struct dma_chan *chan,
2058                                                        dma_addr_t dst,
2059                                                        dma_addr_t src,
2060                                                        size_t size,
2061                                                        unsigned long dma_flags)
2062 {
2063         struct scatterlist dst_sg;
2064         struct scatterlist src_sg;
2065
2066         sg_init_table(&dst_sg, 1);
2067         sg_init_table(&src_sg, 1);
2068
2069         sg_dma_address(&dst_sg) = dst;
2070         sg_dma_address(&src_sg) = src;
2071
2072         sg_dma_len(&dst_sg) = size;
2073         sg_dma_len(&src_sg) = size;
2074
2075         return d40_prep_sg(chan, &src_sg, &dst_sg, 1, DMA_NONE, dma_flags);
2076 }
2077
2078 static struct dma_async_tx_descriptor *
2079 d40_prep_memcpy_sg(struct dma_chan *chan,
2080                    struct scatterlist *dst_sg, unsigned int dst_nents,
2081                    struct scatterlist *src_sg, unsigned int src_nents,
2082                    unsigned long dma_flags)
2083 {
2084         if (dst_nents != src_nents)
2085                 return NULL;
2086
2087         return d40_prep_sg(chan, src_sg, dst_sg, src_nents, DMA_NONE, dma_flags);
2088 }
2089
2090 static struct dma_async_tx_descriptor *d40_prep_slave_sg(struct dma_chan *chan,
2091                                                          struct scatterlist *sgl,
2092                                                          unsigned int sg_len,
2093                                                          enum dma_data_direction direction,
2094                                                          unsigned long dma_flags)
2095 {
2096         if (direction != DMA_FROM_DEVICE && direction != DMA_TO_DEVICE)
2097                 return NULL;
2098
2099         return d40_prep_sg(chan, sgl, sgl, sg_len, direction, dma_flags);
2100 }
2101
2102 static struct dma_async_tx_descriptor *
2103 dma40_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t dma_addr,
2104                      size_t buf_len, size_t period_len,
2105                      enum dma_data_direction direction)
2106 {
2107         unsigned int periods = buf_len / period_len;
2108         struct dma_async_tx_descriptor *txd;
2109         struct scatterlist *sg;
2110         int i;
2111
2112         sg = kcalloc(periods + 1, sizeof(struct scatterlist), GFP_NOWAIT);
2113         for (i = 0; i < periods; i++) {
2114                 sg_dma_address(&sg[i]) = dma_addr;
2115                 sg_dma_len(&sg[i]) = period_len;
2116                 dma_addr += period_len;
2117         }
2118
2119         sg[periods].offset = 0;
2120         sg[periods].length = 0;
2121         sg[periods].page_link =
2122                 ((unsigned long)sg | 0x01) & ~0x02;
2123
2124         txd = d40_prep_sg(chan, sg, sg, periods, direction,
2125                           DMA_PREP_INTERRUPT);
2126
2127         kfree(sg);
2128
2129         return txd;
2130 }
2131
2132 static enum dma_status d40_tx_status(struct dma_chan *chan,
2133                                      dma_cookie_t cookie,
2134                                      struct dma_tx_state *txstate)
2135 {
2136         struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
2137         dma_cookie_t last_used;
2138         dma_cookie_t last_complete;
2139         int ret;
2140
2141         if (d40c->phy_chan == NULL) {
2142                 chan_err(d40c, "Cannot read status of unallocated channel\n");
2143                 return -EINVAL;
2144         }
2145
2146         last_complete = d40c->completed;
2147         last_used = chan->cookie;
2148
2149         if (d40_is_paused(d40c))
2150                 ret = DMA_PAUSED;
2151         else
2152                 ret = dma_async_is_complete(cookie, last_complete, last_used);
2153
2154         dma_set_tx_state(txstate, last_complete, last_used,
2155                          stedma40_residue(chan));
2156
2157         return ret;
2158 }
2159
2160 static void d40_issue_pending(struct dma_chan *chan)
2161 {
2162         struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
2163         unsigned long flags;
2164
2165         if (d40c->phy_chan == NULL) {
2166                 chan_err(d40c, "Channel is not allocated!\n");
2167                 return;
2168         }
2169
2170         spin_lock_irqsave(&d40c->lock, flags);
2171
2172         list_splice_tail_init(&d40c->pending_queue, &d40c->queue);
2173
2174         /* Busy means that queued jobs are already being processed */
2175         if (!d40c->busy)
2176                 (void) d40_queue_start(d40c);
2177
2178         spin_unlock_irqrestore(&d40c->lock, flags);
2179 }
2180
2181 static int
2182 dma40_config_to_halfchannel(struct d40_chan *d40c,
2183                             struct stedma40_half_channel_info *info,
2184                             enum dma_slave_buswidth width,
2185                             u32 maxburst)
2186 {
2187         enum stedma40_periph_data_width addr_width;
2188         int psize;
2189
2190         switch (width) {
2191         case DMA_SLAVE_BUSWIDTH_1_BYTE:
2192                 addr_width = STEDMA40_BYTE_WIDTH;
2193                 break;
2194         case DMA_SLAVE_BUSWIDTH_2_BYTES:
2195                 addr_width = STEDMA40_HALFWORD_WIDTH;
2196                 break;
2197         case DMA_SLAVE_BUSWIDTH_4_BYTES:
2198                 addr_width = STEDMA40_WORD_WIDTH;
2199                 break;
2200         case DMA_SLAVE_BUSWIDTH_8_BYTES:
2201                 addr_width = STEDMA40_DOUBLEWORD_WIDTH;
2202                 break;
2203         default:
2204                 dev_err(d40c->base->dev,
2205                         "illegal peripheral address width "
2206                         "requested (%d)\n",
2207                         width);
2208                 return -EINVAL;
2209         }
2210
2211         if (chan_is_logical(d40c)) {
2212                 if (maxburst >= 16)
2213                         psize = STEDMA40_PSIZE_LOG_16;
2214                 else if (maxburst >= 8)
2215                         psize = STEDMA40_PSIZE_LOG_8;
2216                 else if (maxburst >= 4)
2217                         psize = STEDMA40_PSIZE_LOG_4;
2218                 else
2219                         psize = STEDMA40_PSIZE_LOG_1;
2220         } else {
2221                 if (maxburst >= 16)
2222                         psize = STEDMA40_PSIZE_PHY_16;
2223                 else if (maxburst >= 8)
2224                         psize = STEDMA40_PSIZE_PHY_8;
2225                 else if (maxburst >= 4)
2226                         psize = STEDMA40_PSIZE_PHY_4;
2227                 else
2228                         psize = STEDMA40_PSIZE_PHY_1;
2229         }
2230
2231         info->data_width = addr_width;
2232         info->psize = psize;
2233         info->flow_ctrl = STEDMA40_NO_FLOW_CTRL;
2234
2235         return 0;
2236 }
2237
2238 /* Runtime reconfiguration extension */
2239 static int d40_set_runtime_config(struct dma_chan *chan,
2240                                   struct dma_slave_config *config)
2241 {
2242         struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
2243         struct stedma40_chan_cfg *cfg = &d40c->dma_cfg;
2244         enum dma_slave_buswidth src_addr_width, dst_addr_width;
2245         dma_addr_t config_addr;
2246         u32 src_maxburst, dst_maxburst;
2247         int ret;
2248
2249         src_addr_width = config->src_addr_width;
2250         src_maxburst = config->src_maxburst;
2251         dst_addr_width = config->dst_addr_width;
2252         dst_maxburst = config->dst_maxburst;
2253
2254         if (config->direction == DMA_FROM_DEVICE) {
2255                 dma_addr_t dev_addr_rx =
2256                         d40c->base->plat_data->dev_rx[cfg->src_dev_type];
2257
2258                 config_addr = config->src_addr;
2259                 if (dev_addr_rx)
2260                         dev_dbg(d40c->base->dev,
2261                                 "channel has a pre-wired RX address %08x "
2262                                 "overriding with %08x\n",
2263                                 dev_addr_rx, config_addr);
2264                 if (cfg->dir != STEDMA40_PERIPH_TO_MEM)
2265                         dev_dbg(d40c->base->dev,
2266                                 "channel was not configured for peripheral "
2267                                 "to memory transfer (%d) overriding\n",
2268                                 cfg->dir);
2269                 cfg->dir = STEDMA40_PERIPH_TO_MEM;
2270
2271                 /* Configure the memory side */
2272                 if (dst_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED)
2273                         dst_addr_width = src_addr_width;
2274                 if (dst_maxburst == 0)
2275                         dst_maxburst = src_maxburst;
2276
2277         } else if (config->direction == DMA_TO_DEVICE) {
2278                 dma_addr_t dev_addr_tx =
2279                         d40c->base->plat_data->dev_tx[cfg->dst_dev_type];
2280
2281                 config_addr = config->dst_addr;
2282                 if (dev_addr_tx)
2283                         dev_dbg(d40c->base->dev,
2284                                 "channel has a pre-wired TX address %08x "
2285                                 "overriding with %08x\n",
2286                                 dev_addr_tx, config_addr);
2287                 if (cfg->dir != STEDMA40_MEM_TO_PERIPH)
2288                         dev_dbg(d40c->base->dev,
2289                                 "channel was not configured for memory "
2290                                 "to peripheral transfer (%d) overriding\n",
2291                                 cfg->dir);
2292                 cfg->dir = STEDMA40_MEM_TO_PERIPH;
2293
2294                 /* Configure the memory side */
2295                 if (src_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED)
2296                         src_addr_width = dst_addr_width;
2297                 if (src_maxburst == 0)
2298                         src_maxburst = dst_maxburst;
2299         } else {
2300                 dev_err(d40c->base->dev,
2301                         "unrecognized channel direction %d\n",
2302                         config->direction);
2303                 return -EINVAL;
2304         }
2305
2306         if (src_maxburst * src_addr_width != dst_maxburst * dst_addr_width) {
2307                 dev_err(d40c->base->dev,
2308                         "src/dst width/maxburst mismatch: %d*%d != %d*%d\n",
2309                         src_maxburst,
2310                         src_addr_width,
2311                         dst_maxburst,
2312                         dst_addr_width);
2313                 return -EINVAL;
2314         }
2315
2316         ret = dma40_config_to_halfchannel(d40c, &cfg->src_info,
2317                                           src_addr_width,
2318                                           src_maxburst);
2319         if (ret)
2320                 return ret;
2321
2322         ret = dma40_config_to_halfchannel(d40c, &cfg->dst_info,
2323                                           dst_addr_width,
2324                                           dst_maxburst);
2325         if (ret)
2326                 return ret;
2327
2328         /* Fill in register values */
2329         if (chan_is_logical(d40c))
2330                 d40_log_cfg(cfg, &d40c->log_def.lcsp1, &d40c->log_def.lcsp3);
2331         else
2332                 d40_phy_cfg(cfg, &d40c->src_def_cfg,
2333                             &d40c->dst_def_cfg, false);
2334
2335         /* These settings will take precedence later */
2336         d40c->runtime_addr = config_addr;
2337         d40c->runtime_direction = config->direction;
2338         dev_dbg(d40c->base->dev,
2339                 "configured channel %s for %s, data width %d/%d, "
2340                 "maxburst %d/%d elements, LE, no flow control\n",
2341                 dma_chan_name(chan),
2342                 (config->direction == DMA_FROM_DEVICE) ? "RX" : "TX",
2343                 src_addr_width, dst_addr_width,
2344                 src_maxburst, dst_maxburst);
2345
2346         return 0;
2347 }
2348
2349 static int d40_control(struct dma_chan *chan, enum dma_ctrl_cmd cmd,
2350                        unsigned long arg)
2351 {
2352         struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
2353
2354         if (d40c->phy_chan == NULL) {
2355                 chan_err(d40c, "Channel is not allocated!\n");
2356                 return -EINVAL;
2357         }
2358
2359         switch (cmd) {
2360         case DMA_TERMINATE_ALL:
2361                 return d40_terminate_all(d40c);
2362         case DMA_PAUSE:
2363                 return d40_pause(d40c);
2364         case DMA_RESUME:
2365                 return d40_resume(d40c);
2366         case DMA_SLAVE_CONFIG:
2367                 return d40_set_runtime_config(chan,
2368                         (struct dma_slave_config *) arg);
2369         default:
2370                 break;
2371         }
2372
2373         /* Other commands are unimplemented */
2374         return -ENXIO;
2375 }
2376
2377 /* Initialization functions */
2378
2379 static void __init d40_chan_init(struct d40_base *base, struct dma_device *dma,
2380                                  struct d40_chan *chans, int offset,
2381                                  int num_chans)
2382 {
2383         int i = 0;
2384         struct d40_chan *d40c;
2385
2386         INIT_LIST_HEAD(&dma->channels);
2387
2388         for (i = offset; i < offset + num_chans; i++) {
2389                 d40c = &chans[i];
2390                 d40c->base = base;
2391                 d40c->chan.device = dma;
2392
2393                 spin_lock_init(&d40c->lock);
2394
2395                 d40c->log_num = D40_PHY_CHAN;
2396
2397                 INIT_LIST_HEAD(&d40c->active);
2398                 INIT_LIST_HEAD(&d40c->queue);
2399                 INIT_LIST_HEAD(&d40c->pending_queue);
2400                 INIT_LIST_HEAD(&d40c->client);
2401
2402                 tasklet_init(&d40c->tasklet, dma_tasklet,
2403                              (unsigned long) d40c);
2404
2405                 list_add_tail(&d40c->chan.device_node,
2406                               &dma->channels);
2407         }
2408 }
2409
2410 static void d40_ops_init(struct d40_base *base, struct dma_device *dev)
2411 {
2412         if (dma_has_cap(DMA_SLAVE, dev->cap_mask))
2413                 dev->device_prep_slave_sg = d40_prep_slave_sg;
2414
2415         if (dma_has_cap(DMA_MEMCPY, dev->cap_mask)) {
2416                 dev->device_prep_dma_memcpy = d40_prep_memcpy;
2417
2418                 /*
2419                  * This controller can only access address at even
2420                  * 32bit boundaries, i.e. 2^2
2421                  */
2422                 dev->copy_align = 2;
2423         }
2424
2425         if (dma_has_cap(DMA_SG, dev->cap_mask))
2426                 dev->device_prep_dma_sg = d40_prep_memcpy_sg;
2427
2428         if (dma_has_cap(DMA_CYCLIC, dev->cap_mask))
2429                 dev->device_prep_dma_cyclic = dma40_prep_dma_cyclic;
2430
2431         dev->device_alloc_chan_resources = d40_alloc_chan_resources;
2432         dev->device_free_chan_resources = d40_free_chan_resources;
2433         dev->device_issue_pending = d40_issue_pending;
2434         dev->device_tx_status = d40_tx_status;
2435         dev->device_control = d40_control;
2436         dev->dev = base->dev;
2437 }
2438
2439 static int __init d40_dmaengine_init(struct d40_base *base,
2440                                      int num_reserved_chans)
2441 {
2442         int err ;
2443
2444         d40_chan_init(base, &base->dma_slave, base->log_chans,
2445                       0, base->num_log_chans);
2446
2447         dma_cap_zero(base->dma_slave.cap_mask);
2448         dma_cap_set(DMA_SLAVE, base->dma_slave.cap_mask);
2449         dma_cap_set(DMA_CYCLIC, base->dma_slave.cap_mask);
2450
2451         d40_ops_init(base, &base->dma_slave);
2452
2453         err = dma_async_device_register(&base->dma_slave);
2454
2455         if (err) {
2456                 d40_err(base->dev, "Failed to register slave channels\n");
2457                 goto failure1;
2458         }
2459
2460         d40_chan_init(base, &base->dma_memcpy, base->log_chans,
2461                       base->num_log_chans, base->plat_data->memcpy_len);
2462
2463         dma_cap_zero(base->dma_memcpy.cap_mask);
2464         dma_cap_set(DMA_MEMCPY, base->dma_memcpy.cap_mask);
2465         dma_cap_set(DMA_SG, base->dma_memcpy.cap_mask);
2466
2467         d40_ops_init(base, &base->dma_memcpy);
2468
2469         err = dma_async_device_register(&base->dma_memcpy);
2470
2471         if (err) {
2472                 d40_err(base->dev,
2473                         "Failed to regsiter memcpy only channels\n");
2474                 goto failure2;
2475         }
2476
2477         d40_chan_init(base, &base->dma_both, base->phy_chans,
2478                       0, num_reserved_chans);
2479
2480         dma_cap_zero(base->dma_both.cap_mask);
2481         dma_cap_set(DMA_SLAVE, base->dma_both.cap_mask);
2482         dma_cap_set(DMA_MEMCPY, base->dma_both.cap_mask);
2483         dma_cap_set(DMA_SG, base->dma_both.cap_mask);
2484         dma_cap_set(DMA_CYCLIC, base->dma_slave.cap_mask);
2485
2486         d40_ops_init(base, &base->dma_both);
2487         err = dma_async_device_register(&base->dma_both);
2488
2489         if (err) {
2490                 d40_err(base->dev,
2491                         "Failed to register logical and physical capable channels\n");
2492                 goto failure3;
2493         }
2494         return 0;
2495 failure3:
2496         dma_async_device_unregister(&base->dma_memcpy);
2497 failure2:
2498         dma_async_device_unregister(&base->dma_slave);
2499 failure1:
2500         return err;
2501 }
2502
2503 /* Initialization functions. */
2504
2505 static int __init d40_phy_res_init(struct d40_base *base)
2506 {
2507         int i;
2508         int num_phy_chans_avail = 0;
2509         u32 val[2];
2510         int odd_even_bit = -2;
2511
2512         val[0] = readl(base->virtbase + D40_DREG_PRSME);
2513         val[1] = readl(base->virtbase + D40_DREG_PRSMO);
2514
2515         for (i = 0; i < base->num_phy_chans; i++) {
2516                 base->phy_res[i].num = i;
2517                 odd_even_bit += 2 * ((i % 2) == 0);
2518                 if (((val[i % 2] >> odd_even_bit) & 3) == 1) {
2519                         /* Mark security only channels as occupied */
2520                         base->phy_res[i].allocated_src = D40_ALLOC_PHY;
2521                         base->phy_res[i].allocated_dst = D40_ALLOC_PHY;
2522                 } else {
2523                         base->phy_res[i].allocated_src = D40_ALLOC_FREE;
2524                         base->phy_res[i].allocated_dst = D40_ALLOC_FREE;
2525                         num_phy_chans_avail++;
2526                 }
2527                 spin_lock_init(&base->phy_res[i].lock);
2528         }
2529
2530         /* Mark disabled channels as occupied */
2531         for (i = 0; base->plat_data->disabled_channels[i] != -1; i++) {
2532                 int chan = base->plat_data->disabled_channels[i];
2533
2534                 base->phy_res[chan].allocated_src = D40_ALLOC_PHY;
2535                 base->phy_res[chan].allocated_dst = D40_ALLOC_PHY;
2536                 num_phy_chans_avail--;
2537         }
2538
2539         dev_info(base->dev, "%d of %d physical DMA channels available\n",
2540                  num_phy_chans_avail, base->num_phy_chans);
2541
2542         /* Verify settings extended vs standard */
2543         val[0] = readl(base->virtbase + D40_DREG_PRTYP);
2544
2545         for (i = 0; i < base->num_phy_chans; i++) {
2546
2547                 if (base->phy_res[i].allocated_src == D40_ALLOC_FREE &&
2548                     (val[0] & 0x3) != 1)
2549                         dev_info(base->dev,
2550                                  "[%s] INFO: channel %d is misconfigured (%d)\n",
2551                                  __func__, i, val[0] & 0x3);
2552
2553                 val[0] = val[0] >> 2;
2554         }
2555
2556         return num_phy_chans_avail;
2557 }
2558
2559 static struct d40_base * __init d40_hw_detect_init(struct platform_device *pdev)
2560 {
2561         struct stedma40_platform_data *plat_data;
2562         struct clk *clk = NULL;
2563         void __iomem *virtbase = NULL;
2564         struct resource *res = NULL;
2565         struct d40_base *base = NULL;
2566         int num_log_chans = 0;
2567         int num_phy_chans;
2568         int i;
2569         u32 pid;
2570         u32 cid;
2571         u8 rev;
2572
2573         clk = clk_get(&pdev->dev, NULL);
2574
2575         if (IS_ERR(clk)) {
2576                 d40_err(&pdev->dev, "No matching clock found\n");
2577                 goto failure;
2578         }
2579
2580         clk_enable(clk);
2581
2582         /* Get IO for DMAC base address */
2583         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "base");
2584         if (!res)
2585                 goto failure;
2586
2587         if (request_mem_region(res->start, resource_size(res),
2588                                D40_NAME " I/O base") == NULL)
2589                 goto failure;
2590
2591         virtbase = ioremap(res->start, resource_size(res));
2592         if (!virtbase)
2593                 goto failure;
2594
2595         /* This is just a regular AMBA PrimeCell ID actually */
2596         for (pid = 0, i = 0; i < 4; i++)
2597                 pid |= (readl(virtbase + resource_size(res) - 0x20 + 4 * i)
2598                         & 255) << (i * 8);
2599         for (cid = 0, i = 0; i < 4; i++)
2600                 cid |= (readl(virtbase + resource_size(res) - 0x10 + 4 * i)
2601                         & 255) << (i * 8);
2602
2603         if (cid != AMBA_CID) {
2604                 d40_err(&pdev->dev, "Unknown hardware! No PrimeCell ID\n");
2605                 goto failure;
2606         }
2607         if (AMBA_MANF_BITS(pid) != AMBA_VENDOR_ST) {
2608                 d40_err(&pdev->dev, "Unknown designer! Got %x wanted %x\n",
2609                         AMBA_MANF_BITS(pid),
2610                         AMBA_VENDOR_ST);
2611                 goto failure;
2612         }
2613         /*
2614          * HW revision:
2615          * DB8500ed has revision 0
2616          * ? has revision 1
2617          * DB8500v1 has revision 2
2618          * DB8500v2 has revision 3
2619          */
2620         rev = AMBA_REV_BITS(pid);
2621
2622         /* The number of physical channels on this HW */
2623         num_phy_chans = 4 * (readl(virtbase + D40_DREG_ICFG) & 0x7) + 4;
2624
2625         dev_info(&pdev->dev, "hardware revision: %d @ 0x%x\n",
2626                  rev, res->start);
2627
2628         plat_data = pdev->dev.platform_data;
2629
2630         /* Count the number of logical channels in use */
2631         for (i = 0; i < plat_data->dev_len; i++)
2632                 if (plat_data->dev_rx[i] != 0)
2633                         num_log_chans++;
2634
2635         for (i = 0; i < plat_data->dev_len; i++)
2636                 if (plat_data->dev_tx[i] != 0)
2637                         num_log_chans++;
2638
2639         base = kzalloc(ALIGN(sizeof(struct d40_base), 4) +
2640                        (num_phy_chans + num_log_chans + plat_data->memcpy_len) *
2641                        sizeof(struct d40_chan), GFP_KERNEL);
2642
2643         if (base == NULL) {
2644                 d40_err(&pdev->dev, "Out of memory\n");
2645                 goto failure;
2646         }
2647
2648         base->rev = rev;
2649         base->clk = clk;
2650         base->num_phy_chans = num_phy_chans;
2651         base->num_log_chans = num_log_chans;
2652         base->phy_start = res->start;
2653         base->phy_size = resource_size(res);
2654         base->virtbase = virtbase;
2655         base->plat_data = plat_data;
2656         base->dev = &pdev->dev;
2657         base->phy_chans = ((void *)base) + ALIGN(sizeof(struct d40_base), 4);
2658         base->log_chans = &base->phy_chans[num_phy_chans];
2659
2660         base->phy_res = kzalloc(num_phy_chans * sizeof(struct d40_phy_res),
2661                                 GFP_KERNEL);
2662         if (!base->phy_res)
2663                 goto failure;
2664
2665         base->lookup_phy_chans = kzalloc(num_phy_chans *
2666                                          sizeof(struct d40_chan *),
2667                                          GFP_KERNEL);
2668         if (!base->lookup_phy_chans)
2669                 goto failure;
2670
2671         if (num_log_chans + plat_data->memcpy_len) {
2672                 /*
2673                  * The max number of logical channels are event lines for all
2674                  * src devices and dst devices
2675                  */
2676                 base->lookup_log_chans = kzalloc(plat_data->dev_len * 2 *
2677                                                  sizeof(struct d40_chan *),
2678                                                  GFP_KERNEL);
2679                 if (!base->lookup_log_chans)
2680                         goto failure;
2681         }
2682
2683         base->lcla_pool.alloc_map = kzalloc(num_phy_chans *
2684                                             sizeof(struct d40_desc *) *
2685                                             D40_LCLA_LINK_PER_EVENT_GRP,
2686                                             GFP_KERNEL);
2687         if (!base->lcla_pool.alloc_map)
2688                 goto failure;
2689
2690         base->desc_slab = kmem_cache_create(D40_NAME, sizeof(struct d40_desc),
2691                                             0, SLAB_HWCACHE_ALIGN,
2692                                             NULL);
2693         if (base->desc_slab == NULL)
2694                 goto failure;
2695
2696         return base;
2697
2698 failure:
2699         if (!IS_ERR(clk)) {
2700                 clk_disable(clk);
2701                 clk_put(clk);
2702         }
2703         if (virtbase)
2704                 iounmap(virtbase);
2705         if (res)
2706                 release_mem_region(res->start,
2707                                    resource_size(res));
2708         if (virtbase)
2709                 iounmap(virtbase);
2710
2711         if (base) {
2712                 kfree(base->lcla_pool.alloc_map);
2713                 kfree(base->lookup_log_chans);
2714                 kfree(base->lookup_phy_chans);
2715                 kfree(base->phy_res);
2716                 kfree(base);
2717         }
2718
2719         return NULL;
2720 }
2721
2722 static void __init d40_hw_init(struct d40_base *base)
2723 {
2724
2725         static const struct d40_reg_val dma_init_reg[] = {
2726                 /* Clock every part of the DMA block from start */
2727                 { .reg = D40_DREG_GCC,    .val = 0x0000ff01},
2728
2729                 /* Interrupts on all logical channels */
2730                 { .reg = D40_DREG_LCMIS0, .val = 0xFFFFFFFF},
2731                 { .reg = D40_DREG_LCMIS1, .val = 0xFFFFFFFF},
2732                 { .reg = D40_DREG_LCMIS2, .val = 0xFFFFFFFF},
2733                 { .reg = D40_DREG_LCMIS3, .val = 0xFFFFFFFF},
2734                 { .reg = D40_DREG_LCICR0, .val = 0xFFFFFFFF},
2735                 { .reg = D40_DREG_LCICR1, .val = 0xFFFFFFFF},
2736                 { .reg = D40_DREG_LCICR2, .val = 0xFFFFFFFF},
2737                 { .reg = D40_DREG_LCICR3, .val = 0xFFFFFFFF},
2738                 { .reg = D40_DREG_LCTIS0, .val = 0xFFFFFFFF},
2739                 { .reg = D40_DREG_LCTIS1, .val = 0xFFFFFFFF},
2740                 { .reg = D40_DREG_LCTIS2, .val = 0xFFFFFFFF},
2741                 { .reg = D40_DREG_LCTIS3, .val = 0xFFFFFFFF}
2742         };
2743         int i;
2744         u32 prmseo[2] = {0, 0};
2745         u32 activeo[2] = {0xFFFFFFFF, 0xFFFFFFFF};
2746         u32 pcmis = 0;
2747         u32 pcicr = 0;
2748
2749         for (i = 0; i < ARRAY_SIZE(dma_init_reg); i++)
2750                 writel(dma_init_reg[i].val,
2751                        base->virtbase + dma_init_reg[i].reg);
2752
2753         /* Configure all our dma channels to default settings */
2754         for (i = 0; i < base->num_phy_chans; i++) {
2755
2756                 activeo[i % 2] = activeo[i % 2] << 2;
2757
2758                 if (base->phy_res[base->num_phy_chans - i - 1].allocated_src
2759                     == D40_ALLOC_PHY) {
2760                         activeo[i % 2] |= 3;
2761                         continue;
2762                 }
2763
2764                 /* Enable interrupt # */
2765                 pcmis = (pcmis << 1) | 1;
2766
2767                 /* Clear interrupt # */
2768                 pcicr = (pcicr << 1) | 1;
2769
2770                 /* Set channel to physical mode */
2771                 prmseo[i % 2] = prmseo[i % 2] << 2;
2772                 prmseo[i % 2] |= 1;
2773
2774         }
2775
2776         writel(prmseo[1], base->virtbase + D40_DREG_PRMSE);
2777         writel(prmseo[0], base->virtbase + D40_DREG_PRMSO);
2778         writel(activeo[1], base->virtbase + D40_DREG_ACTIVE);
2779         writel(activeo[0], base->virtbase + D40_DREG_ACTIVO);
2780
2781         /* Write which interrupt to enable */
2782         writel(pcmis, base->virtbase + D40_DREG_PCMIS);
2783
2784         /* Write which interrupt to clear */
2785         writel(pcicr, base->virtbase + D40_DREG_PCICR);
2786
2787 }
2788
2789 static int __init d40_lcla_allocate(struct d40_base *base)
2790 {
2791         struct d40_lcla_pool *pool = &base->lcla_pool;
2792         unsigned long *page_list;
2793         int i, j;
2794         int ret = 0;
2795
2796         /*
2797          * This is somewhat ugly. We need 8192 bytes that are 18 bit aligned,
2798          * To full fill this hardware requirement without wasting 256 kb
2799          * we allocate pages until we get an aligned one.
2800          */
2801         page_list = kmalloc(sizeof(unsigned long) * MAX_LCLA_ALLOC_ATTEMPTS,
2802                             GFP_KERNEL);
2803
2804         if (!page_list) {
2805                 ret = -ENOMEM;
2806                 goto failure;
2807         }
2808
2809         /* Calculating how many pages that are required */
2810         base->lcla_pool.pages = SZ_1K * base->num_phy_chans / PAGE_SIZE;
2811
2812         for (i = 0; i < MAX_LCLA_ALLOC_ATTEMPTS; i++) {
2813                 page_list[i] = __get_free_pages(GFP_KERNEL,
2814                                                 base->lcla_pool.pages);
2815                 if (!page_list[i]) {
2816
2817                         d40_err(base->dev, "Failed to allocate %d pages.\n",
2818                                 base->lcla_pool.pages);
2819
2820                         for (j = 0; j < i; j++)
2821                                 free_pages(page_list[j], base->lcla_pool.pages);
2822                         goto failure;
2823                 }
2824
2825                 if ((virt_to_phys((void *)page_list[i]) &
2826                      (LCLA_ALIGNMENT - 1)) == 0)
2827                         break;
2828         }
2829
2830         for (j = 0; j < i; j++)
2831                 free_pages(page_list[j], base->lcla_pool.pages);
2832
2833         if (i < MAX_LCLA_ALLOC_ATTEMPTS) {
2834                 base->lcla_pool.base = (void *)page_list[i];
2835         } else {
2836                 /*
2837                  * After many attempts and no succees with finding the correct
2838                  * alignment, try with allocating a big buffer.
2839                  */
2840                 dev_warn(base->dev,
2841                          "[%s] Failed to get %d pages @ 18 bit align.\n",
2842                          __func__, base->lcla_pool.pages);
2843                 base->lcla_pool.base_unaligned = kmalloc(SZ_1K *
2844                                                          base->num_phy_chans +
2845                                                          LCLA_ALIGNMENT,
2846                                                          GFP_KERNEL);
2847                 if (!base->lcla_pool.base_unaligned) {
2848                         ret = -ENOMEM;
2849                         goto failure;
2850                 }
2851
2852                 base->lcla_pool.base = PTR_ALIGN(base->lcla_pool.base_unaligned,
2853                                                  LCLA_ALIGNMENT);
2854         }
2855
2856         pool->dma_addr = dma_map_single(base->dev, pool->base,
2857                                         SZ_1K * base->num_phy_chans,
2858                                         DMA_TO_DEVICE);
2859         if (dma_mapping_error(base->dev, pool->dma_addr)) {
2860                 pool->dma_addr = 0;
2861                 ret = -ENOMEM;
2862                 goto failure;
2863         }
2864
2865         writel(virt_to_phys(base->lcla_pool.base),
2866                base->virtbase + D40_DREG_LCLA);
2867 failure:
2868         kfree(page_list);
2869         return ret;
2870 }
2871
2872 static int __init d40_probe(struct platform_device *pdev)
2873 {
2874         int err;
2875         int ret = -ENOENT;
2876         struct d40_base *base;
2877         struct resource *res = NULL;
2878         int num_reserved_chans;
2879         u32 val;
2880
2881         base = d40_hw_detect_init(pdev);
2882
2883         if (!base)
2884                 goto failure;
2885
2886         num_reserved_chans = d40_phy_res_init(base);
2887
2888         platform_set_drvdata(pdev, base);
2889
2890         spin_lock_init(&base->interrupt_lock);
2891         spin_lock_init(&base->execmd_lock);
2892
2893         /* Get IO for logical channel parameter address */
2894         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "lcpa");
2895         if (!res) {
2896                 ret = -ENOENT;
2897                 d40_err(&pdev->dev, "No \"lcpa\" memory resource\n");
2898                 goto failure;
2899         }
2900         base->lcpa_size = resource_size(res);
2901         base->phy_lcpa = res->start;
2902
2903         if (request_mem_region(res->start, resource_size(res),
2904                                D40_NAME " I/O lcpa") == NULL) {
2905                 ret = -EBUSY;
2906                 d40_err(&pdev->dev,
2907                         "Failed to request LCPA region 0x%x-0x%x\n",
2908                         res->start, res->end);
2909                 goto failure;
2910         }
2911
2912         /* We make use of ESRAM memory for this. */
2913         val = readl(base->virtbase + D40_DREG_LCPA);
2914         if (res->start != val && val != 0) {
2915                 dev_warn(&pdev->dev,
2916                          "[%s] Mismatch LCPA dma 0x%x, def 0x%x\n",
2917                          __func__, val, res->start);
2918         } else
2919                 writel(res->start, base->virtbase + D40_DREG_LCPA);
2920
2921         base->lcpa_base = ioremap(res->start, resource_size(res));
2922         if (!base->lcpa_base) {
2923                 ret = -ENOMEM;
2924                 d40_err(&pdev->dev, "Failed to ioremap LCPA region\n");
2925                 goto failure;
2926         }
2927
2928         ret = d40_lcla_allocate(base);
2929         if (ret) {
2930                 d40_err(&pdev->dev, "Failed to allocate LCLA area\n");
2931                 goto failure;
2932         }
2933
2934         spin_lock_init(&base->lcla_pool.lock);
2935
2936         base->irq = platform_get_irq(pdev, 0);
2937
2938         ret = request_irq(base->irq, d40_handle_interrupt, 0, D40_NAME, base);
2939         if (ret) {
2940                 d40_err(&pdev->dev, "No IRQ defined\n");
2941                 goto failure;
2942         }
2943
2944         err = d40_dmaengine_init(base, num_reserved_chans);
2945         if (err)
2946                 goto failure;
2947
2948         d40_hw_init(base);
2949
2950         dev_info(base->dev, "initialized\n");
2951         return 0;
2952
2953 failure:
2954         if (base) {
2955                 if (base->desc_slab)
2956                         kmem_cache_destroy(base->desc_slab);
2957                 if (base->virtbase)
2958                         iounmap(base->virtbase);
2959
2960                 if (base->lcla_pool.dma_addr)
2961                         dma_unmap_single(base->dev, base->lcla_pool.dma_addr,
2962                                          SZ_1K * base->num_phy_chans,
2963                                          DMA_TO_DEVICE);
2964
2965                 if (!base->lcla_pool.base_unaligned && base->lcla_pool.base)
2966                         free_pages((unsigned long)base->lcla_pool.base,
2967                                    base->lcla_pool.pages);
2968
2969                 kfree(base->lcla_pool.base_unaligned);
2970
2971                 if (base->phy_lcpa)
2972                         release_mem_region(base->phy_lcpa,
2973                                            base->lcpa_size);
2974                 if (base->phy_start)
2975                         release_mem_region(base->phy_start,
2976                                            base->phy_size);
2977                 if (base->clk) {
2978                         clk_disable(base->clk);
2979                         clk_put(base->clk);
2980                 }
2981
2982                 kfree(base->lcla_pool.alloc_map);
2983                 kfree(base->lookup_log_chans);
2984                 kfree(base->lookup_phy_chans);
2985                 kfree(base->phy_res);
2986                 kfree(base);
2987         }
2988
2989         d40_err(&pdev->dev, "probe failed\n");
2990         return ret;
2991 }
2992
2993 static struct platform_driver d40_driver = {
2994         .driver = {
2995                 .owner = THIS_MODULE,
2996                 .name  = D40_NAME,
2997         },
2998 };
2999
3000 static int __init stedma40_init(void)
3001 {
3002         return platform_driver_probe(&d40_driver, d40_probe);
3003 }
3004 subsys_initcall(stedma40_init);