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