xref: /linux/drivers/dma/ste_dma40.c (revision 20bed0d6ff62d985fe8222958825504b8aad4e88)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) Ericsson AB 2007-2008
4  * Copyright (C) ST-Ericsson SA 2008-2010
5  * Author: Per Forlin <per.forlin@stericsson.com> for ST-Ericsson
6  * Author: Jonas Aaberg <jonas.aberg@stericsson.com> for ST-Ericsson
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/log2.h>
18 #include <linux/pm.h>
19 #include <linux/pm_runtime.h>
20 #include <linux/err.h>
21 #include <linux/of.h>
22 #include <linux/of_address.h>
23 #include <linux/of_dma.h>
24 #include <linux/amba/bus.h>
25 #include <linux/regulator/consumer.h>
26 
27 #include "dmaengine.h"
28 #include "ste_dma40.h"
29 #include "ste_dma40_ll.h"
30 
31 #define D40_MEMCPY_MAX_CHANS	8
32 
33 /**
34  * struct stedma40_platform_data - Configuration struct for the dma device.
35  *
36  * @disabled_channels: A vector, ending with -1, that marks physical channels
37  * that are for different reasons not available for the driver.
38  * @soft_lli_chans: A vector, that marks physical channels will use LLI by SW
39  * which avoids HW bug that exists in some versions of the controller.
40  * SoftLLI introduces relink overhead that could impact performance for
41  * certain use cases.
42  * @num_of_soft_lli_chans: The number of channels that needs to be configured
43  * to use SoftLLI.
44  * @use_esram_lcla: flag for mapping the lcla into esram region
45  * @num_of_memcpy_chans: The number of channels reserved for memcpy.
46  * @memcpy_channels: The event lines used for memcpy.
47  * @num_of_phy_chans: The number of physical channels implemented in HW.
48  * 0 means reading the number of channels from DMA HW but this is only valid
49  * for 'multiple of 4' channels, like 8.
50  */
51 struct stedma40_platform_data {
52 	int				 disabled_channels[STEDMA40_MAX_PHYS];
53 	int				*soft_lli_chans;
54 	int				 num_of_soft_lli_chans;
55 	bool				 use_esram_lcla;
56 	int				 num_of_memcpy_chans;
57 	u32				 memcpy_channels[D40_MEMCPY_MAX_CHANS];
58 	int				 num_of_phy_chans;
59 };
60 
61 #define D40_NAME "dma40"
62 
63 #define D40_PHY_CHAN -1
64 
65 /* For masking out/in 2 bit channel positions */
66 #define D40_CHAN_POS(chan)  (2 * (chan / 2))
67 #define D40_CHAN_POS_MASK(chan) (0x3 << D40_CHAN_POS(chan))
68 
69 /* Maximum iterations taken before giving up suspending a channel */
70 #define D40_SUSPEND_MAX_IT 500
71 
72 /* Maximum attempts to sample a stable cyclic residue position */
73 #define D40_RESIDUE_MAX_ATTEMPTS 3
74 
75 /* Milliseconds */
76 #define DMA40_AUTOSUSPEND_DELAY	100
77 
78 /* Hardware requirement on LCLA alignment */
79 #define LCLA_ALIGNMENT 0x40000
80 
81 /* Max number of links per event group */
82 #define D40_LCLA_LINK_PER_EVENT_GRP 128
83 #define D40_LCLA_END D40_LCLA_LINK_PER_EVENT_GRP
84 
85 /* Number of event groups per hardware register layout */
86 #define D40_EVENT_GROUPS_V4A 4
87 #define D40_EVENT_GROUPS_V4B 5
88 #define D40_PHYS_PER_EVENT_GROUP 2
89 
90 /* Max number of logical channels per physical channel */
91 #define D40_MAX_LOG_CHAN_PER_PHY 32
92 
93 /* Attempts before giving up to trying to get pages that are aligned */
94 #define MAX_LCLA_ALLOC_ATTEMPTS 256
95 
96 /* Bit markings for allocation map */
97 #define D40_ALLOC_FREE		BIT(31)
98 #define D40_ALLOC_PHY		BIT(30)
99 #define D40_ALLOC_LOG_FREE	0
100 
101 /* Default configuration for physical memcpy */
102 static const struct stedma40_chan_cfg dma40_memcpy_conf_phy = {
103 	.mode = STEDMA40_MODE_PHYSICAL,
104 	.dir = DMA_MEM_TO_MEM,
105 
106 	.src_info.data_width = DMA_SLAVE_BUSWIDTH_1_BYTE,
107 	.src_info.psize = STEDMA40_PSIZE_PHY_1,
108 	.src_info.flow_ctrl = STEDMA40_NO_FLOW_CTRL,
109 
110 	.dst_info.data_width = DMA_SLAVE_BUSWIDTH_1_BYTE,
111 	.dst_info.psize = STEDMA40_PSIZE_PHY_1,
112 	.dst_info.flow_ctrl = STEDMA40_NO_FLOW_CTRL,
113 };
114 
115 /* Default configuration for logical memcpy */
116 static const struct stedma40_chan_cfg dma40_memcpy_conf_log = {
117 	.mode = STEDMA40_MODE_LOGICAL,
118 	.dir = DMA_MEM_TO_MEM,
119 
120 	.src_info.data_width = DMA_SLAVE_BUSWIDTH_1_BYTE,
121 	.src_info.psize = STEDMA40_PSIZE_LOG_1,
122 	.src_info.flow_ctrl = STEDMA40_NO_FLOW_CTRL,
123 
124 	.dst_info.data_width = DMA_SLAVE_BUSWIDTH_1_BYTE,
125 	.dst_info.psize = STEDMA40_PSIZE_LOG_1,
126 	.dst_info.flow_ctrl = STEDMA40_NO_FLOW_CTRL,
127 };
128 
129 /**
130  * enum d40_command - The different commands and/or statuses.
131  *
132  * @D40_DMA_STOP: DMA channel command STOP or status STOPPED,
133  * @D40_DMA_RUN: The DMA channel is RUNNING of the command RUN.
134  * @D40_DMA_SUSPEND_REQ: Request the DMA to SUSPEND as soon as possible.
135  * @D40_DMA_SUSPENDED: The DMA channel is SUSPENDED.
136  */
137 enum d40_command {
138 	D40_DMA_STOP		= 0,
139 	D40_DMA_RUN		= 1,
140 	D40_DMA_SUSPEND_REQ	= 2,
141 	D40_DMA_SUSPENDED	= 3
142 };
143 
144 /*
145  * enum d40_events - The different Event Enables for the event lines.
146  *
147  * @D40_DEACTIVATE_EVENTLINE: De-activate Event line, stopping the logical chan.
148  * @D40_ACTIVATE_EVENTLINE: Activate the Event line, to start a logical chan.
149  * @D40_SUSPEND_REQ_EVENTLINE: Requesting for suspending a event line.
150  * @D40_ROUND_EVENTLINE: Status check for event line.
151  */
152 
153 enum d40_events {
154 	D40_DEACTIVATE_EVENTLINE	= 0,
155 	D40_ACTIVATE_EVENTLINE		= 1,
156 	D40_SUSPEND_REQ_EVENTLINE	= 2,
157 	D40_ROUND_EVENTLINE		= 3
158 };
159 
160 /*
161  * These are the registers that has to be saved and later restored
162  * when the DMA hw is powered off.
163  * TODO: Add save/restore of D40_DREG_GCC on dma40 v3 or later, if that works.
164  */
165 static __maybe_unused u32 d40_backup_regs[] = {
166 	D40_DREG_LCPA,
167 	D40_DREG_LCLA,
168 	D40_DREG_PRMSE,
169 	D40_DREG_PRMSO,
170 	D40_DREG_PRMOE,
171 	D40_DREG_PRMOO,
172 };
173 
174 #define BACKUP_REGS_SZ ARRAY_SIZE(d40_backup_regs)
175 
176 /*
177  * since 9540 and 8540 has the same HW revision
178  * use v4a for 9540 or earlier
179  * use v4b for 8540 or later
180  * HW revision:
181  * DB8500ed has revision 0
182  * DB8500v1 has revision 2
183  * DB8500v2 has revision 3
184  * AP9540v1 has revision 4
185  * DB8540v1 has revision 4
186  * TODO: Check if all these registers have to be saved/restored on dma40 v4a
187  */
188 static u32 d40_backup_regs_v4a[] = {
189 	D40_DREG_PSEG1,
190 	D40_DREG_PSEG2,
191 	D40_DREG_PSEG3,
192 	D40_DREG_PSEG4,
193 	D40_DREG_PCEG1,
194 	D40_DREG_PCEG2,
195 	D40_DREG_PCEG3,
196 	D40_DREG_PCEG4,
197 	D40_DREG_RSEG1,
198 	D40_DREG_RSEG2,
199 	D40_DREG_RSEG3,
200 	D40_DREG_RSEG4,
201 	D40_DREG_RCEG1,
202 	D40_DREG_RCEG2,
203 	D40_DREG_RCEG3,
204 	D40_DREG_RCEG4,
205 };
206 
207 #define BACKUP_REGS_SZ_V4A ARRAY_SIZE(d40_backup_regs_v4a)
208 
209 static u32 d40_backup_regs_v4b[] = {
210 	D40_DREG_CPSEG1,
211 	D40_DREG_CPSEG2,
212 	D40_DREG_CPSEG3,
213 	D40_DREG_CPSEG4,
214 	D40_DREG_CPSEG5,
215 	D40_DREG_CPCEG1,
216 	D40_DREG_CPCEG2,
217 	D40_DREG_CPCEG3,
218 	D40_DREG_CPCEG4,
219 	D40_DREG_CPCEG5,
220 	D40_DREG_CRSEG1,
221 	D40_DREG_CRSEG2,
222 	D40_DREG_CRSEG3,
223 	D40_DREG_CRSEG4,
224 	D40_DREG_CRSEG5,
225 	D40_DREG_CRCEG1,
226 	D40_DREG_CRCEG2,
227 	D40_DREG_CRCEG3,
228 	D40_DREG_CRCEG4,
229 	D40_DREG_CRCEG5,
230 };
231 
232 #define BACKUP_REGS_SZ_V4B ARRAY_SIZE(d40_backup_regs_v4b)
233 
234 static __maybe_unused u32 d40_backup_regs_chan[] = {
235 	D40_CHAN_REG_SSCFG,
236 	D40_CHAN_REG_SSELT,
237 	D40_CHAN_REG_SSPTR,
238 	D40_CHAN_REG_SSLNK,
239 	D40_CHAN_REG_SDCFG,
240 	D40_CHAN_REG_SDELT,
241 	D40_CHAN_REG_SDPTR,
242 	D40_CHAN_REG_SDLNK,
243 };
244 
245 #define BACKUP_REGS_SZ_MAX ((BACKUP_REGS_SZ_V4A > BACKUP_REGS_SZ_V4B) ? \
246 			     BACKUP_REGS_SZ_V4A : BACKUP_REGS_SZ_V4B)
247 
248 /**
249  * struct d40_interrupt_lookup - lookup table for interrupt handler
250  *
251  * @src: Interrupt mask register.
252  * @clr: Interrupt clear register.
253  * @is_error: true if this is an error interrupt.
254  * @offset: start delta in the lookup_log_chans in d40_base. If equals to
255  * D40_PHY_CHAN, the lookup_phy_chans shall be used instead.
256  */
257 struct d40_interrupt_lookup {
258 	u32 src;
259 	u32 clr;
260 	bool is_error;
261 	int offset;
262 };
263 
264 
265 static struct d40_interrupt_lookup il_v4a[] = {
266 	{D40_DREG_LCTIS0, D40_DREG_LCICR0, false,  0},
267 	{D40_DREG_LCTIS1, D40_DREG_LCICR1, false, 32},
268 	{D40_DREG_LCTIS2, D40_DREG_LCICR2, false, 64},
269 	{D40_DREG_LCTIS3, D40_DREG_LCICR3, false, 96},
270 	{D40_DREG_LCEIS0, D40_DREG_LCICR0, true,   0},
271 	{D40_DREG_LCEIS1, D40_DREG_LCICR1, true,  32},
272 	{D40_DREG_LCEIS2, D40_DREG_LCICR2, true,  64},
273 	{D40_DREG_LCEIS3, D40_DREG_LCICR3, true,  96},
274 	{D40_DREG_PCTIS,  D40_DREG_PCICR,  false, D40_PHY_CHAN},
275 	{D40_DREG_PCEIS,  D40_DREG_PCICR,  true,  D40_PHY_CHAN},
276 };
277 
278 static struct d40_interrupt_lookup il_v4b[] = {
279 	{D40_DREG_CLCTIS1, D40_DREG_CLCICR1, false,  0},
280 	{D40_DREG_CLCTIS2, D40_DREG_CLCICR2, false, 32},
281 	{D40_DREG_CLCTIS3, D40_DREG_CLCICR3, false, 64},
282 	{D40_DREG_CLCTIS4, D40_DREG_CLCICR4, false, 96},
283 	{D40_DREG_CLCTIS5, D40_DREG_CLCICR5, false, 128},
284 	{D40_DREG_CLCEIS1, D40_DREG_CLCICR1, true,   0},
285 	{D40_DREG_CLCEIS2, D40_DREG_CLCICR2, true,  32},
286 	{D40_DREG_CLCEIS3, D40_DREG_CLCICR3, true,  64},
287 	{D40_DREG_CLCEIS4, D40_DREG_CLCICR4, true,  96},
288 	{D40_DREG_CLCEIS5, D40_DREG_CLCICR5, true,  128},
289 	{D40_DREG_CPCTIS,  D40_DREG_CPCICR,  false, D40_PHY_CHAN},
290 	{D40_DREG_CPCEIS,  D40_DREG_CPCICR,  true,  D40_PHY_CHAN},
291 };
292 
293 /**
294  * struct d40_reg_val - simple lookup struct
295  *
296  * @reg: The register.
297  * @val: The value that belongs to the register in reg.
298  */
299 struct d40_reg_val {
300 	unsigned int reg;
301 	unsigned int val;
302 };
303 
304 static __initdata struct d40_reg_val dma_init_reg_v4a[] = {
305 	/* Clock every part of the DMA block from start */
306 	{ .reg = D40_DREG_GCC,    .val = D40_DREG_GCC_ENABLE_ALL},
307 
308 	/* Interrupts on all logical channels */
309 	{ .reg = D40_DREG_LCMIS0, .val = 0xFFFFFFFF},
310 	{ .reg = D40_DREG_LCMIS1, .val = 0xFFFFFFFF},
311 	{ .reg = D40_DREG_LCMIS2, .val = 0xFFFFFFFF},
312 	{ .reg = D40_DREG_LCMIS3, .val = 0xFFFFFFFF},
313 	{ .reg = D40_DREG_LCICR0, .val = 0xFFFFFFFF},
314 	{ .reg = D40_DREG_LCICR1, .val = 0xFFFFFFFF},
315 	{ .reg = D40_DREG_LCICR2, .val = 0xFFFFFFFF},
316 	{ .reg = D40_DREG_LCICR3, .val = 0xFFFFFFFF},
317 	{ .reg = D40_DREG_LCTIS0, .val = 0xFFFFFFFF},
318 	{ .reg = D40_DREG_LCTIS1, .val = 0xFFFFFFFF},
319 	{ .reg = D40_DREG_LCTIS2, .val = 0xFFFFFFFF},
320 	{ .reg = D40_DREG_LCTIS3, .val = 0xFFFFFFFF}
321 };
322 static __initdata struct d40_reg_val dma_init_reg_v4b[] = {
323 	/* Clock every part of the DMA block from start */
324 	{ .reg = D40_DREG_GCC,    .val = D40_DREG_GCC_ENABLE_ALL},
325 
326 	/* Interrupts on all logical channels */
327 	{ .reg = D40_DREG_CLCMIS1, .val = 0xFFFFFFFF},
328 	{ .reg = D40_DREG_CLCMIS2, .val = 0xFFFFFFFF},
329 	{ .reg = D40_DREG_CLCMIS3, .val = 0xFFFFFFFF},
330 	{ .reg = D40_DREG_CLCMIS4, .val = 0xFFFFFFFF},
331 	{ .reg = D40_DREG_CLCMIS5, .val = 0xFFFFFFFF},
332 	{ .reg = D40_DREG_CLCICR1, .val = 0xFFFFFFFF},
333 	{ .reg = D40_DREG_CLCICR2, .val = 0xFFFFFFFF},
334 	{ .reg = D40_DREG_CLCICR3, .val = 0xFFFFFFFF},
335 	{ .reg = D40_DREG_CLCICR4, .val = 0xFFFFFFFF},
336 	{ .reg = D40_DREG_CLCICR5, .val = 0xFFFFFFFF},
337 	{ .reg = D40_DREG_CLCTIS1, .val = 0xFFFFFFFF},
338 	{ .reg = D40_DREG_CLCTIS2, .val = 0xFFFFFFFF},
339 	{ .reg = D40_DREG_CLCTIS3, .val = 0xFFFFFFFF},
340 	{ .reg = D40_DREG_CLCTIS4, .val = 0xFFFFFFFF},
341 	{ .reg = D40_DREG_CLCTIS5, .val = 0xFFFFFFFF}
342 };
343 
344 /**
345  * struct d40_lli_pool - Structure for keeping LLIs in memory
346  *
347  * @base: Pointer to memory area when the pre_alloc_lli's are not large
348  * enough, IE bigger than the most common case, 1 dst and 1 src. NULL if
349  * pre_alloc_lli is used.
350  * @dma_addr: DMA address, if mapped
351  * @size: The size in bytes of the memory at base or the size of pre_alloc_lli.
352  * @pre_alloc_lli: Pre allocated area for the most common case of transfers,
353  * one buffer to one buffer.
354  */
355 struct d40_lli_pool {
356 	void	*base;
357 	int	 size;
358 	dma_addr_t	dma_addr;
359 	/* Space for dst and src, plus an extra for padding */
360 	u8	 pre_alloc_lli[3 * sizeof(struct d40_phy_lli)];
361 };
362 
363 /**
364  * struct d40_desc - A descriptor is one DMA job.
365  *
366  * @lli_phy: LLI settings for physical channel. Both src and dst=
367  * points into the lli_pool, to base if lli_len > 1 or to pre_alloc_lli if
368  * lli_len equals one.
369  * @lli_log: Same as above but for logical channels.
370  * @lli_pool: The pool with two entries pre-allocated.
371  * @lli_len: Number of llis of current descriptor.
372  * @lli_current: Number of transferred llis.
373  * @lcla_alloc: Number of LCLA entries allocated.
374  * @cyclic_dma_addr: Start address of the cyclic buffer.
375  * @cyclic_buf_len: Length of the cyclic buffer.
376  * @cyclic_residue: Last valid cyclic residue sample.
377  * @cyclic_period_len: Length of one cyclic period.
378  * @cyclic_callback_pos: Position after the callbacks already queued.
379  * @txd: DMA engine struct. Used for among other things for communication
380  * during a transfer.
381  * @node: List entry.
382  * @is_in_client_list: true if the client owns this descriptor.
383  * @cyclic: true if this is a cyclic job
384  * @cyclic_callback_pos_valid: Whether cyclic_callback_pos is reliable.
385  *
386  * This descriptor is used for both logical and physical transfers.
387  */
388 struct d40_desc {
389 	/* LLI physical */
390 	struct d40_phy_lli_bidir	 lli_phy;
391 	/* LLI logical */
392 	struct d40_log_lli_bidir	 lli_log;
393 
394 	struct d40_lli_pool		 lli_pool;
395 	int				 lli_len;
396 	int				 lli_current;
397 	int				 lcla_alloc;
398 	dma_addr_t			 cyclic_dma_addr;
399 	size_t				 cyclic_buf_len;
400 	size_t				 cyclic_residue;
401 	size_t				 cyclic_period_len;
402 	size_t				 cyclic_callback_pos;
403 
404 	struct dma_async_tx_descriptor	 txd;
405 	struct list_head		 node;
406 
407 	bool				 is_in_client_list;
408 	bool				 cyclic;
409 	bool				 cyclic_callback_pos_valid;
410 };
411 
412 /**
413  * struct d40_lcla_pool - LCLA pool settings and data.
414  *
415  * @base: The virtual address of LCLA. 18 bit aligned.
416  * @dma_addr: DMA address, if mapped
417  * @base_unaligned: The original kmalloc pointer, if kmalloc is used.
418  * This pointer is only there for clean-up on error.
419  * @alloc_order: Order used for the LCLA page allocation.
420  * Only used later for clean-up on error.
421  * @lock: Lock to protect the content in this struct.
422  * @alloc_map: big map over which LCLA entry is own by which job.
423  */
424 struct d40_lcla_pool {
425 	void		*base;
426 	dma_addr_t	dma_addr;
427 	void		*base_unaligned;
428 	unsigned int	 alloc_order;
429 	spinlock_t	 lock;
430 	struct d40_desc	**alloc_map;
431 };
432 
433 /**
434  * struct d40_phy_res - struct for handling eventlines mapped to physical
435  * channels.
436  *
437  * @lock: A lock protection this entity.
438  * @reserved: True if used by secure world or otherwise.
439  * @num: The physical channel number of this entity.
440  * @allocated_src: Bit mapped to show which src event line's are mapped to
441  * this physical channel. Can also be free or physically allocated.
442  * @allocated_dst: Same as for src but is dst.
443  * allocated_dst and allocated_src uses the D40_ALLOC* defines as well as
444  * event line number.
445  * @use_soft_lli: To mark if the linked lists of channel are managed by SW.
446  */
447 struct d40_phy_res {
448 	spinlock_t lock;
449 	bool	   reserved;
450 	int	   num;
451 	u32	   allocated_src;
452 	u32	   allocated_dst;
453 	bool	   use_soft_lli;
454 };
455 
456 struct d40_base;
457 
458 /**
459  * struct d40_chan - Struct that describes a channel.
460  *
461  * @lock: A spinlock to protect this struct.
462  * @log_num: The logical number, if any of this channel.
463  * @pending_tx: The number of pending transfers. Used between interrupt handler
464  * and tasklet.
465  * @busy: Set to true when transfer is ongoing on this channel.
466  * @phy_chan: Pointer to physical channel which this instance runs on. If this
467  * point is NULL, then the channel is not allocated.
468  * @chan: DMA engine handle.
469  * @tasklet: Tasklet that gets scheduled from interrupt context to complete a
470  * transfer and call client callback.
471  * @client: Cliented owned descriptor list.
472  * @pending_queue: Submitted jobs, to be issued by issue_pending()
473  * @active: Active descriptor.
474  * @done: Completed jobs
475  * @queue: Queued jobs.
476  * @prepare_queue: Prepared jobs.
477  * @dma_cfg: The client configuration of this dma channel.
478  * @slave_config: DMA slave configuration.
479  * @configured: whether the dma_cfg configuration is valid
480  * @base: Pointer to the device instance struct.
481  * @src_def_cfg: Default cfg register setting for src.
482  * @dst_def_cfg: Default cfg register setting for dst.
483  * @log_def: Default logical channel settings.
484  * @lcpa: Pointer to dst and src lcpa settings.
485  * @runtime_addr: runtime configured address.
486  * @runtime_direction: runtime configured direction.
487  *
488  * This struct can either "be" a logical or a physical channel.
489  */
490 struct d40_chan {
491 	spinlock_t			 lock;
492 	int				 log_num;
493 	int				 pending_tx;
494 	bool				 busy;
495 	struct d40_phy_res		*phy_chan;
496 	struct dma_chan			 chan;
497 	struct tasklet_struct		 tasklet;
498 	struct list_head		 client;
499 	struct list_head		 pending_queue;
500 	struct list_head		 active;
501 	struct list_head		 done;
502 	struct list_head		 queue;
503 	struct list_head		 prepare_queue;
504 	struct stedma40_chan_cfg	 dma_cfg;
505 	struct dma_slave_config		 slave_config;
506 	bool				 configured;
507 	struct d40_base			*base;
508 	/* Default register configurations */
509 	u32				 src_def_cfg;
510 	u32				 dst_def_cfg;
511 	struct d40_def_lcsp		 log_def;
512 	struct d40_log_lli_full __iomem	*lcpa;
513 	/* Runtime reconfiguration */
514 	dma_addr_t			runtime_addr;
515 	enum dma_transfer_direction	runtime_direction;
516 };
517 
518 /**
519  * struct d40_gen_dmac - generic values to represent u8500/u8540 DMA
520  * controller
521  *
522  * @backup: the pointer to the registers address array for backup
523  * @backup_size: the size of the registers address array for backup
524  * @realtime_en: the realtime enable register
525  * @realtime_clear: the realtime clear register
526  * @high_prio_en: the high priority enable register
527  * @high_prio_clear: the high priority clear register
528  * @interrupt_en: the interrupt enable register
529  * @interrupt_clear: the interrupt clear register
530  * @num_event_groups: number of supported event groups
531  * @il: the pointer to struct d40_interrupt_lookup
532  * @il_size: the size of d40_interrupt_lookup array
533  * @init_reg: the pointer to the struct d40_reg_val
534  * @init_reg_size: the size of d40_reg_val array
535  */
536 struct d40_gen_dmac {
537 	u32				*backup;
538 	u32				 backup_size;
539 	u32				 realtime_en;
540 	u32				 realtime_clear;
541 	u32				 high_prio_en;
542 	u32				 high_prio_clear;
543 	u32				 interrupt_en;
544 	u32				 interrupt_clear;
545 	u32				 num_event_groups;
546 	struct d40_interrupt_lookup	*il;
547 	u32				 il_size;
548 	struct d40_reg_val		*init_reg;
549 	u32				 init_reg_size;
550 };
551 
552 /**
553  * struct d40_base - The big global struct, one for each probe'd instance.
554  *
555  * @interrupt_lock: Lock used to make sure one interrupt is handle a time.
556  * @execmd_lock: Lock for execute command usage since several channels share
557  * the same physical register.
558  * @dev: The device structure.
559  * @virtbase: The virtual base address of the DMA's register.
560  * @rev: silicon revision detected.
561  * @clk: Pointer to the DMA clock structure.
562  * @irq: The IRQ number.
563  * @num_memcpy_chans: The number of channels used for memcpy (mem-to-mem
564  * transfers).
565  * @num_phy_chans: The number of physical channels. Read from HW. This
566  * is the number of available channels for this driver, not counting "Secure
567  * mode" allocated physical channels.
568  * @num_log_chans: The number of logical channels. Calculated from
569  * num_phy_chans.
570  * @dma_both: dma_device channels that can do both memcpy and slave transfers.
571  * @dma_slave: dma_device channels that can do only do slave transfers.
572  * @dma_memcpy: dma_device channels that can do only do memcpy transfers.
573  * @phy_chans: Room for all possible physical channels in system.
574  * @log_chans: Room for all possible logical channels in system.
575  * @lookup_log_chans: Used to map interrupt number to logical channel. Points
576  * to log_chans entries.
577  * @lookup_phy_chans: Used to map interrupt number to physical channel. Points
578  * to phy_chans entries.
579  * @plat_data: Pointer to provided platform_data which is the driver
580  * configuration.
581  * @lcpa_regulator: Pointer to hold the regulator for the esram bank for lcla.
582  * @phy_res: Vector containing all physical channels.
583  * @lcla_pool: lcla pool settings and data.
584  * @lcpa_base: The virtual mapped address of LCPA.
585  * @phy_lcpa: The physical address of the LCPA.
586  * @lcpa_size: The size of the LCPA area.
587  * @desc_slab: cache for descriptors.
588  * @reg_val_backup: Here the values of some hardware registers are stored
589  * before the DMA is powered off. They are restored when the power is back on.
590  * @reg_val_backup_v4: Backup of registers that only exits on dma40 v3 and
591  * later
592  * @reg_val_backup_chan: Backup data for standard channel parameter registers.
593  * @regs_interrupt: Scratch space for registers during interrupt.
594  * @gcc_pwr_off_mask: Mask to maintain the channels that can be turned off.
595  * @gen_dmac: the struct for generic registers values to represent u8500/8540
596  * DMA controller
597  */
598 struct d40_base {
599 	spinlock_t			 interrupt_lock;
600 	spinlock_t			 execmd_lock;
601 	struct device			 *dev;
602 	void __iomem			 *virtbase;
603 	u8				  rev:4;
604 	struct clk			 *clk;
605 	int				  irq;
606 	int				  num_memcpy_chans;
607 	int				  num_phy_chans;
608 	int				  num_log_chans;
609 	struct dma_device		  dma_both;
610 	struct dma_device		  dma_slave;
611 	struct dma_device		  dma_memcpy;
612 	struct d40_chan			 *log_chans;
613 	struct d40_chan			**lookup_log_chans;
614 	struct d40_chan			**lookup_phy_chans;
615 	struct stedma40_platform_data	 *plat_data;
616 	struct regulator		 *lcpa_regulator;
617 	/* Physical half channels */
618 	struct d40_phy_res		 *phy_res;
619 	struct d40_lcla_pool		  lcla_pool;
620 	void __iomem			 *lcpa_base;
621 	dma_addr_t			  phy_lcpa;
622 	resource_size_t			  lcpa_size;
623 	struct kmem_cache		 *desc_slab;
624 	u32				  reg_val_backup[BACKUP_REGS_SZ];
625 	u32				  reg_val_backup_v4[BACKUP_REGS_SZ_MAX];
626 	u32				 *reg_val_backup_chan;
627 	u32				 *regs_interrupt;
628 	u16				  gcc_pwr_off_mask;
629 	struct d40_gen_dmac		  gen_dmac;
630 	struct d40_chan			 phy_chans[];
631 };
632 
633 static bool chan_is_physical(struct d40_chan *chan)
634 {
635 	return chan->log_num == D40_PHY_CHAN;
636 }
637 
638 static bool chan_is_logical(struct d40_chan *chan)
639 {
640 	return !chan_is_physical(chan);
641 }
642 
643 static void __iomem *chan_base(struct d40_chan *chan)
644 {
645 	return chan->base->virtbase + D40_DREG_PCBASE +
646 	       chan->phy_chan->num * D40_DREG_PCDELTA;
647 }
648 
649 #define d40_err(dev, format, arg...)		\
650 	dev_err(dev, "[%s] " format, __func__, ## arg)
651 
652 #define chan_err(d40c, format, arg...)		\
653 	d40_err(dmaengine_chan_dev(&d40c->chan), format, ## arg)
654 
655 static int d40_set_runtime_config_write(struct dma_chan *chan,
656 				  struct dma_slave_config *config,
657 				  enum dma_transfer_direction direction);
658 
659 static int d40_pool_lli_alloc(struct d40_chan *d40c, struct d40_desc *d40d,
660 			      int lli_len)
661 {
662 	bool is_log = chan_is_logical(d40c);
663 	u32 align;
664 	void *base;
665 
666 	if (is_log)
667 		align = sizeof(struct d40_log_lli);
668 	else
669 		align = sizeof(struct d40_phy_lli);
670 
671 	if (lli_len == 1) {
672 		base = d40d->lli_pool.pre_alloc_lli;
673 		d40d->lli_pool.size = sizeof(d40d->lli_pool.pre_alloc_lli);
674 		d40d->lli_pool.base = NULL;
675 	} else {
676 		d40d->lli_pool.size = lli_len * 2 * align;
677 
678 		base = kmalloc(d40d->lli_pool.size + align, GFP_NOWAIT);
679 		d40d->lli_pool.base = base;
680 
681 		if (d40d->lli_pool.base == NULL)
682 			return -ENOMEM;
683 	}
684 
685 	if (is_log) {
686 		d40d->lli_log.src = PTR_ALIGN(base, align);
687 		d40d->lli_log.dst = d40d->lli_log.src + lli_len;
688 
689 		d40d->lli_pool.dma_addr = 0;
690 	} else {
691 		d40d->lli_phy.src = PTR_ALIGN(base, align);
692 		d40d->lli_phy.dst = d40d->lli_phy.src + lli_len;
693 
694 		d40d->lli_pool.dma_addr = dma_map_single(d40c->base->dev,
695 							 d40d->lli_phy.src,
696 							 d40d->lli_pool.size,
697 							 DMA_TO_DEVICE);
698 
699 		if (dma_mapping_error(d40c->base->dev,
700 				      d40d->lli_pool.dma_addr)) {
701 			kfree(d40d->lli_pool.base);
702 			d40d->lli_pool.base = NULL;
703 			d40d->lli_pool.dma_addr = 0;
704 			return -ENOMEM;
705 		}
706 	}
707 
708 	return 0;
709 }
710 
711 static void d40_pool_lli_free(struct d40_chan *d40c, struct d40_desc *d40d)
712 {
713 	if (d40d->lli_pool.dma_addr)
714 		dma_unmap_single(d40c->base->dev, d40d->lli_pool.dma_addr,
715 				 d40d->lli_pool.size, DMA_TO_DEVICE);
716 
717 	kfree(d40d->lli_pool.base);
718 	d40d->lli_pool.base = NULL;
719 	d40d->lli_pool.size = 0;
720 	d40d->lli_log.src = NULL;
721 	d40d->lli_log.dst = NULL;
722 	d40d->lli_phy.src = NULL;
723 	d40d->lli_phy.dst = NULL;
724 }
725 
726 static int d40_lcla_alloc_one(struct d40_chan *d40c,
727 			      struct d40_desc *d40d)
728 {
729 	unsigned long flags;
730 	int i;
731 	int ret = -EINVAL;
732 
733 	spin_lock_irqsave(&d40c->base->lcla_pool.lock, flags);
734 
735 	/*
736 	 * Allocate both src and dst at the same time, therefore the half
737 	 * start on 1 since 0 can't be used since zero is used as end marker.
738 	 */
739 	for (i = 1 ; i < D40_LCLA_LINK_PER_EVENT_GRP / 2; i++) {
740 		int idx = d40c->phy_chan->num * D40_LCLA_LINK_PER_EVENT_GRP + i;
741 
742 		if (!d40c->base->lcla_pool.alloc_map[idx]) {
743 			d40c->base->lcla_pool.alloc_map[idx] = d40d;
744 			d40d->lcla_alloc++;
745 			ret = i;
746 			break;
747 		}
748 	}
749 
750 	spin_unlock_irqrestore(&d40c->base->lcla_pool.lock, flags);
751 
752 	return ret;
753 }
754 
755 static int d40_lcla_free_all(struct d40_chan *d40c,
756 			     struct d40_desc *d40d)
757 {
758 	unsigned long flags;
759 	int i;
760 	int ret = -EINVAL;
761 
762 	if (chan_is_physical(d40c))
763 		return 0;
764 
765 	spin_lock_irqsave(&d40c->base->lcla_pool.lock, flags);
766 
767 	for (i = 1 ; i < D40_LCLA_LINK_PER_EVENT_GRP / 2; i++) {
768 		int idx = d40c->phy_chan->num * D40_LCLA_LINK_PER_EVENT_GRP + i;
769 
770 		if (d40c->base->lcla_pool.alloc_map[idx] == d40d) {
771 			d40c->base->lcla_pool.alloc_map[idx] = NULL;
772 			d40d->lcla_alloc--;
773 			if (d40d->lcla_alloc == 0) {
774 				ret = 0;
775 				break;
776 			}
777 		}
778 	}
779 
780 	spin_unlock_irqrestore(&d40c->base->lcla_pool.lock, flags);
781 
782 	return ret;
783 
784 }
785 
786 static void d40_desc_remove(struct d40_desc *d40d)
787 {
788 	list_del(&d40d->node);
789 }
790 
791 static struct d40_desc *d40_desc_get(struct d40_chan *d40c)
792 {
793 	struct d40_desc *desc = NULL;
794 
795 	if (!list_empty(&d40c->client)) {
796 		struct d40_desc *d;
797 		struct d40_desc *_d;
798 
799 		list_for_each_entry_safe(d, _d, &d40c->client, node) {
800 			if (async_tx_test_ack(&d->txd)) {
801 				d40_desc_remove(d);
802 				desc = d;
803 				memset(desc, 0, sizeof(*desc));
804 				break;
805 			}
806 		}
807 	}
808 
809 	if (!desc)
810 		desc = kmem_cache_zalloc(d40c->base->desc_slab, GFP_NOWAIT);
811 
812 	if (desc)
813 		INIT_LIST_HEAD(&desc->node);
814 
815 	return desc;
816 }
817 
818 static void d40_desc_free(struct d40_chan *d40c, struct d40_desc *d40d)
819 {
820 
821 	d40_pool_lli_free(d40c, d40d);
822 	d40_lcla_free_all(d40c, d40d);
823 	kmem_cache_free(d40c->base->desc_slab, d40d);
824 }
825 
826 static void d40_desc_submit(struct d40_chan *d40c, struct d40_desc *desc)
827 {
828 	list_add_tail(&desc->node, &d40c->active);
829 }
830 
831 static void d40_phy_lli_load(struct d40_chan *chan, struct d40_desc *desc)
832 {
833 	struct d40_phy_lli *lli_dst = desc->lli_phy.dst;
834 	struct d40_phy_lli *lli_src = desc->lli_phy.src;
835 	void __iomem *base = chan_base(chan);
836 
837 	writel(lli_src->reg_cfg, base + D40_CHAN_REG_SSCFG);
838 	writel(lli_src->reg_elt, base + D40_CHAN_REG_SSELT);
839 	writel(lli_src->reg_ptr, base + D40_CHAN_REG_SSPTR);
840 	writel(lli_src->reg_lnk, base + D40_CHAN_REG_SSLNK);
841 
842 	writel(lli_dst->reg_cfg, base + D40_CHAN_REG_SDCFG);
843 	writel(lli_dst->reg_elt, base + D40_CHAN_REG_SDELT);
844 	writel(lli_dst->reg_ptr, base + D40_CHAN_REG_SDPTR);
845 	writel(lli_dst->reg_lnk, base + D40_CHAN_REG_SDLNK);
846 }
847 
848 static void d40_desc_done(struct d40_chan *d40c, struct d40_desc *desc)
849 {
850 	list_add_tail(&desc->node, &d40c->done);
851 }
852 
853 static void d40_log_lli_to_lcxa(struct d40_chan *chan, struct d40_desc *desc)
854 {
855 	struct d40_lcla_pool *pool = &chan->base->lcla_pool;
856 	struct d40_log_lli_bidir *lli = &desc->lli_log;
857 	int lli_current = desc->lli_current;
858 	int lli_len = desc->lli_len;
859 	bool cyclic = desc->cyclic;
860 	int curr_lcla = -EINVAL;
861 	int first_lcla = 0;
862 	bool use_esram_lcla = chan->base->plat_data->use_esram_lcla;
863 	bool linkback;
864 
865 	/*
866 	 * We may have partially running cyclic transfers, in case we did't get
867 	 * enough LCLA entries.
868 	 */
869 	linkback = cyclic && lli_current == 0;
870 
871 	/*
872 	 * For linkback, we need one LCLA even with only one link, because we
873 	 * can't link back to the one in LCPA space
874 	 */
875 	if (linkback || (lli_len - lli_current > 1)) {
876 		/*
877 		 * If the channel is expected to use only soft_lli don't
878 		 * allocate a lcla. This is to avoid a HW issue that exists
879 		 * in some controller during a peripheral to memory transfer
880 		 * that uses linked lists.
881 		 */
882 		if (!(chan->phy_chan->use_soft_lli &&
883 			chan->dma_cfg.dir == DMA_DEV_TO_MEM))
884 			curr_lcla = d40_lcla_alloc_one(chan, desc);
885 
886 		first_lcla = curr_lcla;
887 	}
888 
889 	/*
890 	 * For linkback, we normally load the LCPA in the loop since we need to
891 	 * link it to the second LCLA and not the first.  However, if we
892 	 * couldn't even get a first LCLA, then we have to run in LCPA and
893 	 * reload manually.
894 	 */
895 	if (!linkback || curr_lcla == -EINVAL) {
896 		unsigned int flags = 0;
897 
898 		if (curr_lcla == -EINVAL)
899 			flags |= LLI_TERM_INT;
900 
901 		d40_log_lli_lcpa_write(chan->lcpa,
902 				       &lli->dst[lli_current],
903 				       &lli->src[lli_current],
904 				       curr_lcla,
905 				       flags);
906 		lli_current++;
907 	}
908 
909 	if (curr_lcla < 0)
910 		goto set_current;
911 
912 	for (; lli_current < lli_len; lli_current++) {
913 		unsigned int lcla_offset = chan->phy_chan->num * 1024 +
914 					   8 * curr_lcla * 2;
915 		struct d40_log_lli *lcla = pool->base + lcla_offset;
916 		unsigned int flags = 0;
917 		int next_lcla;
918 
919 		if (lli_current + 1 < lli_len)
920 			next_lcla = d40_lcla_alloc_one(chan, desc);
921 		else
922 			next_lcla = linkback ? first_lcla : -EINVAL;
923 
924 		if (cyclic || next_lcla == -EINVAL)
925 			flags |= LLI_TERM_INT;
926 
927 		if (linkback && curr_lcla == first_lcla) {
928 			/* First link goes in both LCPA and LCLA */
929 			d40_log_lli_lcpa_write(chan->lcpa,
930 					       &lli->dst[lli_current],
931 					       &lli->src[lli_current],
932 					       next_lcla, flags);
933 		}
934 
935 		/*
936 		 * One unused LCLA in the cyclic case if the very first
937 		 * next_lcla fails...
938 		 */
939 		d40_log_lli_lcla_write(lcla,
940 				       &lli->dst[lli_current],
941 				       &lli->src[lli_current],
942 				       next_lcla, flags);
943 
944 		/*
945 		 * Cache maintenance is not needed if lcla is
946 		 * mapped in esram
947 		 */
948 		if (!use_esram_lcla) {
949 			dma_sync_single_range_for_device(chan->base->dev,
950 						pool->dma_addr, lcla_offset,
951 						2 * sizeof(struct d40_log_lli),
952 						DMA_TO_DEVICE);
953 		}
954 		curr_lcla = next_lcla;
955 
956 		if (curr_lcla == -EINVAL || curr_lcla == first_lcla) {
957 			lli_current++;
958 			break;
959 		}
960 	}
961  set_current:
962 	desc->lli_current = lli_current;
963 }
964 
965 static void d40_desc_load(struct d40_chan *d40c, struct d40_desc *d40d)
966 {
967 	if (chan_is_physical(d40c)) {
968 		d40_phy_lli_load(d40c, d40d);
969 		d40d->lli_current = d40d->lli_len;
970 	} else
971 		d40_log_lli_to_lcxa(d40c, d40d);
972 }
973 
974 static struct d40_desc *d40_first_active_get(struct d40_chan *d40c)
975 {
976 	return list_first_entry_or_null(&d40c->active, struct d40_desc, node);
977 }
978 
979 /* remove desc from current queue and add it to the pending_queue */
980 static void d40_desc_queue(struct d40_chan *d40c, struct d40_desc *desc)
981 {
982 	d40_desc_remove(desc);
983 	desc->is_in_client_list = false;
984 	list_add_tail(&desc->node, &d40c->pending_queue);
985 }
986 
987 static struct d40_desc *d40_first_pending(struct d40_chan *d40c)
988 {
989 	return list_first_entry_or_null(&d40c->pending_queue, struct d40_desc,
990 					node);
991 }
992 
993 static struct d40_desc *d40_first_queued(struct d40_chan *d40c)
994 {
995 	return list_first_entry_or_null(&d40c->queue, struct d40_desc, node);
996 }
997 
998 static struct d40_desc *d40_first_done(struct d40_chan *d40c)
999 {
1000 	return list_first_entry_or_null(&d40c->done, struct d40_desc, node);
1001 }
1002 
1003 static int d40_psize_2_burst_size(bool is_log, int psize)
1004 {
1005 	if (is_log) {
1006 		if (psize == STEDMA40_PSIZE_LOG_1)
1007 			return 1;
1008 	} else {
1009 		if (psize == STEDMA40_PSIZE_PHY_1)
1010 			return 1;
1011 	}
1012 
1013 	return 2 << psize;
1014 }
1015 
1016 /*
1017  * The dma only supports transmitting packages up to
1018  * STEDMA40_MAX_SEG_SIZE * data_width, where data_width is stored in Bytes.
1019  *
1020  * Calculate the total number of dma elements required to send the entire sg list.
1021  */
1022 static int d40_size_2_dmalen(int size, u32 data_width1, u32 data_width2)
1023 {
1024 	int dmalen;
1025 	u32 max_w = max(data_width1, data_width2);
1026 	u32 min_w = min(data_width1, data_width2);
1027 	u32 seg_max = ALIGN(STEDMA40_MAX_SEG_SIZE * min_w, max_w);
1028 
1029 	if (seg_max > STEDMA40_MAX_SEG_SIZE)
1030 		seg_max -= max_w;
1031 
1032 	if (!IS_ALIGNED(size, max_w))
1033 		return -EINVAL;
1034 
1035 	if (size <= seg_max)
1036 		dmalen = 1;
1037 	else {
1038 		dmalen = size / seg_max;
1039 		if (dmalen * seg_max < size)
1040 			dmalen++;
1041 	}
1042 	return dmalen;
1043 }
1044 
1045 static int d40_sg_2_dmalen(struct scatterlist *sgl, int sg_len,
1046 			   u32 data_width1, u32 data_width2)
1047 {
1048 	struct scatterlist *sg;
1049 	int i;
1050 	int len = 0;
1051 	int ret;
1052 
1053 	for_each_sg(sgl, sg, sg_len, i) {
1054 		ret = d40_size_2_dmalen(sg_dma_len(sg),
1055 					data_width1, data_width2);
1056 		if (ret < 0)
1057 			return ret;
1058 		len += ret;
1059 	}
1060 	return len;
1061 }
1062 
1063 static int __d40_execute_command_phy(struct d40_chan *d40c,
1064 				     enum d40_command command)
1065 {
1066 	u32 status;
1067 	int i;
1068 	void __iomem *active_reg;
1069 	int ret = 0;
1070 	unsigned long flags;
1071 	u32 wmask;
1072 
1073 	if (command == D40_DMA_STOP) {
1074 		ret = __d40_execute_command_phy(d40c, D40_DMA_SUSPEND_REQ);
1075 		if (ret)
1076 			return ret;
1077 	}
1078 
1079 	spin_lock_irqsave(&d40c->base->execmd_lock, flags);
1080 
1081 	if (d40c->phy_chan->num % 2 == 0)
1082 		active_reg = d40c->base->virtbase + D40_DREG_ACTIVE;
1083 	else
1084 		active_reg = d40c->base->virtbase + D40_DREG_ACTIVO;
1085 
1086 	if (command == D40_DMA_SUSPEND_REQ) {
1087 		status = (readl(active_reg) &
1088 			  D40_CHAN_POS_MASK(d40c->phy_chan->num)) >>
1089 			D40_CHAN_POS(d40c->phy_chan->num);
1090 
1091 		if (status == D40_DMA_SUSPENDED || status == D40_DMA_STOP)
1092 			goto unlock;
1093 	}
1094 
1095 	wmask = 0xffffffff & ~(D40_CHAN_POS_MASK(d40c->phy_chan->num));
1096 	writel(wmask | (command << D40_CHAN_POS(d40c->phy_chan->num)),
1097 	       active_reg);
1098 
1099 	if (command == D40_DMA_SUSPEND_REQ) {
1100 
1101 		for (i = 0 ; i < D40_SUSPEND_MAX_IT; i++) {
1102 			status = (readl(active_reg) &
1103 				  D40_CHAN_POS_MASK(d40c->phy_chan->num)) >>
1104 				D40_CHAN_POS(d40c->phy_chan->num);
1105 
1106 			cpu_relax();
1107 			/*
1108 			 * Reduce the number of bus accesses while
1109 			 * waiting for the DMA to suspend.
1110 			 */
1111 			udelay(3);
1112 
1113 			if (status == D40_DMA_STOP ||
1114 			    status == D40_DMA_SUSPENDED)
1115 				break;
1116 		}
1117 
1118 		if (i == D40_SUSPEND_MAX_IT) {
1119 			chan_err(d40c,
1120 				"unable to suspend the chl %d (log: %d) status %x\n",
1121 				d40c->phy_chan->num, d40c->log_num,
1122 				status);
1123 			dump_stack();
1124 			ret = -EBUSY;
1125 		}
1126 
1127 	}
1128  unlock:
1129 	spin_unlock_irqrestore(&d40c->base->execmd_lock, flags);
1130 	return ret;
1131 }
1132 
1133 static void d40_term_all(struct d40_chan *d40c)
1134 {
1135 	struct d40_desc *d40d;
1136 	struct d40_desc *_d;
1137 
1138 	/* Release completed descriptors */
1139 	while ((d40d = d40_first_done(d40c))) {
1140 		d40_desc_remove(d40d);
1141 		d40_desc_free(d40c, d40d);
1142 	}
1143 
1144 	/* Release active descriptors */
1145 	while ((d40d = d40_first_active_get(d40c))) {
1146 		d40_desc_remove(d40d);
1147 		d40_desc_free(d40c, d40d);
1148 	}
1149 
1150 	/* Release queued descriptors waiting for transfer */
1151 	while ((d40d = d40_first_queued(d40c))) {
1152 		d40_desc_remove(d40d);
1153 		d40_desc_free(d40c, d40d);
1154 	}
1155 
1156 	/* Release pending descriptors */
1157 	while ((d40d = d40_first_pending(d40c))) {
1158 		d40_desc_remove(d40d);
1159 		d40_desc_free(d40c, d40d);
1160 	}
1161 
1162 	/* Release client owned descriptors */
1163 	if (!list_empty(&d40c->client))
1164 		list_for_each_entry_safe(d40d, _d, &d40c->client, node) {
1165 			d40_desc_remove(d40d);
1166 			d40_desc_free(d40c, d40d);
1167 		}
1168 
1169 	/* Release descriptors in prepare queue */
1170 	if (!list_empty(&d40c->prepare_queue))
1171 		list_for_each_entry_safe(d40d, _d,
1172 					 &d40c->prepare_queue, node) {
1173 			d40_desc_remove(d40d);
1174 			d40_desc_free(d40c, d40d);
1175 		}
1176 
1177 	d40c->pending_tx = 0;
1178 }
1179 
1180 static void __d40_config_set_event(struct d40_chan *d40c,
1181 				   enum d40_events event_type, u32 event,
1182 				   int reg)
1183 {
1184 	void __iomem *addr = chan_base(d40c) + reg;
1185 	int tries;
1186 	u32 status;
1187 
1188 	switch (event_type) {
1189 
1190 	case D40_DEACTIVATE_EVENTLINE:
1191 
1192 		writel((D40_DEACTIVATE_EVENTLINE << D40_EVENTLINE_POS(event))
1193 		       | ~D40_EVENTLINE_MASK(event), addr);
1194 		break;
1195 
1196 	case D40_SUSPEND_REQ_EVENTLINE:
1197 		status = (readl(addr) & D40_EVENTLINE_MASK(event)) >>
1198 			  D40_EVENTLINE_POS(event);
1199 
1200 		if (status == D40_DEACTIVATE_EVENTLINE ||
1201 		    status == D40_SUSPEND_REQ_EVENTLINE)
1202 			break;
1203 
1204 		writel((D40_SUSPEND_REQ_EVENTLINE << D40_EVENTLINE_POS(event))
1205 		       | ~D40_EVENTLINE_MASK(event), addr);
1206 
1207 		for (tries = 0 ; tries < D40_SUSPEND_MAX_IT; tries++) {
1208 
1209 			status = (readl(addr) & D40_EVENTLINE_MASK(event)) >>
1210 				  D40_EVENTLINE_POS(event);
1211 
1212 			cpu_relax();
1213 			/*
1214 			 * Reduce the number of bus accesses while
1215 			 * waiting for the DMA to suspend.
1216 			 */
1217 			udelay(3);
1218 
1219 			if (status == D40_DEACTIVATE_EVENTLINE)
1220 				break;
1221 		}
1222 
1223 		if (tries == D40_SUSPEND_MAX_IT) {
1224 			chan_err(d40c,
1225 				"unable to stop the event_line chl %d (log: %d)"
1226 				"status %x\n", d40c->phy_chan->num,
1227 				 d40c->log_num, status);
1228 		}
1229 		break;
1230 
1231 	case D40_ACTIVATE_EVENTLINE:
1232 	/*
1233 	 * The hardware sometimes doesn't register the enable when src and dst
1234 	 * event lines are active on the same logical channel.  Retry to ensure
1235 	 * it does.  Usually only one retry is sufficient.
1236 	 */
1237 		tries = 100;
1238 		while (--tries) {
1239 			writel((D40_ACTIVATE_EVENTLINE <<
1240 				D40_EVENTLINE_POS(event)) |
1241 				~D40_EVENTLINE_MASK(event), addr);
1242 
1243 			if (readl(addr) & D40_EVENTLINE_MASK(event))
1244 				break;
1245 		}
1246 
1247 		if (tries != 99)
1248 			dev_dbg(dmaengine_chan_dev(&d40c->chan),
1249 				"[%s] workaround enable S%cLNK (%d tries)\n",
1250 				__func__, reg == D40_CHAN_REG_SSLNK ? 'S' : 'D',
1251 				100 - tries);
1252 
1253 		WARN_ON(!tries);
1254 		break;
1255 
1256 	case D40_ROUND_EVENTLINE:
1257 		BUG();
1258 		break;
1259 
1260 	}
1261 }
1262 
1263 static void d40_config_set_event(struct d40_chan *d40c,
1264 				 enum d40_events event_type)
1265 {
1266 	u32 event = D40_TYPE_TO_EVENT(d40c->dma_cfg.dev_type);
1267 
1268 	/* Enable event line connected to device (or memcpy) */
1269 	if ((d40c->dma_cfg.dir == DMA_DEV_TO_MEM) ||
1270 	    (d40c->dma_cfg.dir == DMA_DEV_TO_DEV))
1271 		__d40_config_set_event(d40c, event_type, event,
1272 				       D40_CHAN_REG_SSLNK);
1273 
1274 	if (d40c->dma_cfg.dir !=  DMA_DEV_TO_MEM)
1275 		__d40_config_set_event(d40c, event_type, event,
1276 				       D40_CHAN_REG_SDLNK);
1277 }
1278 
1279 static u32 d40_chan_has_events(struct d40_chan *d40c)
1280 {
1281 	void __iomem *chanbase = chan_base(d40c);
1282 	u32 val;
1283 
1284 	val = readl(chanbase + D40_CHAN_REG_SSLNK);
1285 	val |= readl(chanbase + D40_CHAN_REG_SDLNK);
1286 
1287 	return val;
1288 }
1289 
1290 static int
1291 __d40_execute_command_log(struct d40_chan *d40c, enum d40_command command)
1292 {
1293 	unsigned long flags;
1294 	int ret = 0;
1295 	u32 active_status;
1296 	void __iomem *active_reg;
1297 
1298 	if (d40c->phy_chan->num % 2 == 0)
1299 		active_reg = d40c->base->virtbase + D40_DREG_ACTIVE;
1300 	else
1301 		active_reg = d40c->base->virtbase + D40_DREG_ACTIVO;
1302 
1303 
1304 	spin_lock_irqsave(&d40c->phy_chan->lock, flags);
1305 
1306 	switch (command) {
1307 	case D40_DMA_STOP:
1308 	case D40_DMA_SUSPEND_REQ:
1309 
1310 		active_status = (readl(active_reg) &
1311 				 D40_CHAN_POS_MASK(d40c->phy_chan->num)) >>
1312 				 D40_CHAN_POS(d40c->phy_chan->num);
1313 
1314 		if (active_status == D40_DMA_RUN)
1315 			d40_config_set_event(d40c, D40_SUSPEND_REQ_EVENTLINE);
1316 		else
1317 			d40_config_set_event(d40c, D40_DEACTIVATE_EVENTLINE);
1318 
1319 		if (!d40_chan_has_events(d40c) && (command == D40_DMA_STOP))
1320 			ret = __d40_execute_command_phy(d40c, command);
1321 
1322 		break;
1323 
1324 	case D40_DMA_RUN:
1325 
1326 		d40_config_set_event(d40c, D40_ACTIVATE_EVENTLINE);
1327 		ret = __d40_execute_command_phy(d40c, command);
1328 		break;
1329 
1330 	case D40_DMA_SUSPENDED:
1331 		BUG();
1332 		break;
1333 	}
1334 
1335 	spin_unlock_irqrestore(&d40c->phy_chan->lock, flags);
1336 	return ret;
1337 }
1338 
1339 static int d40_channel_execute_command(struct d40_chan *d40c,
1340 				       enum d40_command command)
1341 {
1342 	if (chan_is_logical(d40c))
1343 		return __d40_execute_command_log(d40c, command);
1344 	else
1345 		return __d40_execute_command_phy(d40c, command);
1346 }
1347 
1348 static u32 d40_get_prmo(struct d40_chan *d40c)
1349 {
1350 	static const unsigned int phy_map[] = {
1351 		[STEDMA40_PCHAN_BASIC_MODE]
1352 			= D40_DREG_PRMO_PCHAN_BASIC,
1353 		[STEDMA40_PCHAN_MODULO_MODE]
1354 			= D40_DREG_PRMO_PCHAN_MODULO,
1355 		[STEDMA40_PCHAN_DOUBLE_DST_MODE]
1356 			= D40_DREG_PRMO_PCHAN_DOUBLE_DST,
1357 	};
1358 	static const unsigned int log_map[] = {
1359 		[STEDMA40_LCHAN_SRC_PHY_DST_LOG]
1360 			= D40_DREG_PRMO_LCHAN_SRC_PHY_DST_LOG,
1361 		[STEDMA40_LCHAN_SRC_LOG_DST_PHY]
1362 			= D40_DREG_PRMO_LCHAN_SRC_LOG_DST_PHY,
1363 		[STEDMA40_LCHAN_SRC_LOG_DST_LOG]
1364 			= D40_DREG_PRMO_LCHAN_SRC_LOG_DST_LOG,
1365 	};
1366 
1367 	if (chan_is_physical(d40c))
1368 		return phy_map[d40c->dma_cfg.mode_opt];
1369 	else
1370 		return log_map[d40c->dma_cfg.mode_opt];
1371 }
1372 
1373 static void d40_config_write(struct d40_chan *d40c)
1374 {
1375 	u32 addr_base;
1376 	u32 var;
1377 
1378 	/* Odd addresses are even addresses + 4 */
1379 	addr_base = (d40c->phy_chan->num % 2) * 4;
1380 	/* Setup channel mode to logical or physical */
1381 	var = ((u32)(chan_is_logical(d40c)) + 1) <<
1382 		D40_CHAN_POS(d40c->phy_chan->num);
1383 	writel(var, d40c->base->virtbase + D40_DREG_PRMSE + addr_base);
1384 
1385 	/* Setup operational mode option register */
1386 	var = d40_get_prmo(d40c) << D40_CHAN_POS(d40c->phy_chan->num);
1387 
1388 	writel(var, d40c->base->virtbase + D40_DREG_PRMOE + addr_base);
1389 
1390 	if (chan_is_logical(d40c)) {
1391 		int lidx = (d40c->phy_chan->num << D40_SREG_ELEM_LOG_LIDX_POS)
1392 			   & D40_SREG_ELEM_LOG_LIDX_MASK;
1393 		void __iomem *chanbase = chan_base(d40c);
1394 
1395 		/* Set default config for CFG reg */
1396 		writel(d40c->src_def_cfg, chanbase + D40_CHAN_REG_SSCFG);
1397 		writel(d40c->dst_def_cfg, chanbase + D40_CHAN_REG_SDCFG);
1398 
1399 		/* Set LIDX for lcla */
1400 		writel(lidx, chanbase + D40_CHAN_REG_SSELT);
1401 		writel(lidx, chanbase + D40_CHAN_REG_SDELT);
1402 
1403 		/* Clear LNK which will be used by d40_chan_has_events() */
1404 		writel(0, chanbase + D40_CHAN_REG_SSLNK);
1405 		writel(0, chanbase + D40_CHAN_REG_SDLNK);
1406 	}
1407 }
1408 
1409 static u32 d40_residue(struct d40_chan *d40c)
1410 {
1411 	u32 num_elt;
1412 
1413 	if (chan_is_logical(d40c))
1414 		num_elt = (readl(&d40c->lcpa->lcsp2) & D40_MEM_LCSP2_ECNT_MASK)
1415 			>> D40_MEM_LCSP2_ECNT_POS;
1416 	else {
1417 		u32 val = readl(chan_base(d40c) + D40_CHAN_REG_SDELT);
1418 		num_elt = (val & D40_SREG_ELEM_PHY_ECNT_MASK)
1419 			  >> D40_SREG_ELEM_PHY_ECNT_POS;
1420 	}
1421 
1422 	return num_elt * d40c->dma_cfg.dst_info.data_width;
1423 }
1424 
1425 static bool d40_current_addr(struct d40_chan *d40c, dma_addr_t *addr)
1426 {
1427 	bool dst = d40c->dma_cfg.dir == DMA_DEV_TO_MEM;
1428 	void __iomem *high_reg;
1429 	void __iomem *low_reg;
1430 	u32 low;
1431 	u32 high;
1432 	u32 check;
1433 	int i;
1434 
1435 	if (chan_is_physical(d40c)) {
1436 		*addr = readl(chan_base(d40c) +
1437 			      (dst ? D40_CHAN_REG_SDPTR : D40_CHAN_REG_SSPTR));
1438 		return true;
1439 	}
1440 
1441 	if (dst) {
1442 		low_reg = &d40c->lcpa->lcsp2;
1443 		high_reg = &d40c->lcpa->lcsp3;
1444 	} else {
1445 		low_reg = &d40c->lcpa->lcsp0;
1446 		high_reg = &d40c->lcpa->lcsp1;
1447 	}
1448 
1449 	for (i = 0; i < D40_RESIDUE_MAX_ATTEMPTS; i++) {
1450 		high = readl(high_reg) & D40_MEM_LCSP1_SPTR_MASK;
1451 		low = readl(low_reg) & D40_MEM_LCSP0_SPTR_MASK;
1452 		check = readl(high_reg) & D40_MEM_LCSP1_SPTR_MASK;
1453 		if (high == check) {
1454 			*addr = low | high;
1455 			return true;
1456 		}
1457 	}
1458 
1459 	return false;
1460 }
1461 
1462 static bool d40_cyclic_offset(struct d40_chan *d40c, struct d40_desc *d40d,
1463 			      size_t *offset)
1464 {
1465 	dma_addr_t current_addr;
1466 	dma_addr_t current_offset;
1467 	int i;
1468 
1469 	for (i = 0; i < D40_RESIDUE_MAX_ATTEMPTS; i++) {
1470 		if (!d40_current_addr(d40c, &current_addr))
1471 			continue;
1472 
1473 		current_offset = current_addr - d40d->cyclic_dma_addr;
1474 		if (current_offset <= d40d->cyclic_buf_len) {
1475 			*offset = current_offset;
1476 			return true;
1477 		}
1478 	}
1479 
1480 	return false;
1481 }
1482 
1483 static unsigned int d40_cyclic_periods_elapsed(struct d40_chan *d40c,
1484 					       struct d40_desc *d40d)
1485 {
1486 	size_t current_pos;
1487 	size_t delta;
1488 	size_t offset;
1489 	unsigned int periods;
1490 
1491 	if (!d40d->cyclic_period_len)
1492 		return 1;
1493 
1494 	if (!d40_cyclic_offset(d40c, d40d, &offset)) {
1495 		d40d->cyclic_callback_pos_valid = false;
1496 		return 1;
1497 	}
1498 
1499 	current_pos = rounddown(offset, d40d->cyclic_period_len);
1500 	if (!d40_residue(d40c) && current_pos != offset)
1501 		current_pos += d40d->cyclic_period_len;
1502 	if (current_pos == d40d->cyclic_buf_len)
1503 		current_pos = 0;
1504 
1505 	if (!d40d->cyclic_callback_pos_valid) {
1506 		/*
1507 		 * The previous interrupt was reported without a pointer
1508 		 * sample. Resynchronize without using the stale position,
1509 		 * which would count that callback again.
1510 		 */
1511 		d40d->cyclic_callback_pos = current_pos;
1512 		d40d->cyclic_callback_pos_valid = true;
1513 		return 1;
1514 	}
1515 
1516 	/*
1517 	 * The pointer wraps with the cyclic buffer, so its displacement is
1518 	 * only the minimum number of elapsed periods. Complete buffer laps
1519 	 * are not observable.
1520 	 */
1521 	delta = (current_pos + d40d->cyclic_buf_len -
1522 		 d40d->cyclic_callback_pos) % d40d->cyclic_buf_len;
1523 	periods = delta / d40d->cyclic_period_len;
1524 	if (!periods) {
1525 		/*
1526 		 * The TC status is a single latched bit. An unchanged pointer
1527 		 * cannot distinguish a complete lap from a repeated interrupt,
1528 		 * so do not amplify it into a buffer's worth of callbacks.
1529 		 */
1530 		periods = 1;
1531 	}
1532 
1533 	d40d->cyclic_callback_pos = current_pos;
1534 
1535 	return periods;
1536 }
1537 
1538 static bool d40_tx_is_linked(struct d40_chan *d40c)
1539 {
1540 	bool is_link;
1541 
1542 	if (chan_is_logical(d40c))
1543 		is_link = readl(&d40c->lcpa->lcsp3) &  D40_MEM_LCSP3_DLOS_MASK;
1544 	else
1545 		is_link = readl(chan_base(d40c) + D40_CHAN_REG_SDLNK)
1546 			  & D40_SREG_LNK_PHYS_LNK_MASK;
1547 
1548 	return is_link;
1549 }
1550 
1551 static int d40_pause(struct dma_chan *chan)
1552 {
1553 	struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
1554 	int res = 0;
1555 	unsigned long flags;
1556 
1557 	if (d40c->phy_chan == NULL) {
1558 		chan_err(d40c, "Channel is not allocated!\n");
1559 		return -EINVAL;
1560 	}
1561 
1562 	if (!d40c->busy)
1563 		return 0;
1564 
1565 	spin_lock_irqsave(&d40c->lock, flags);
1566 	res = pm_runtime_resume_and_get(d40c->base->dev);
1567 	if (res < 0)
1568 		goto unlock;
1569 
1570 	res = d40_channel_execute_command(d40c, D40_DMA_SUSPEND_REQ);
1571 
1572 	pm_runtime_put_autosuspend(d40c->base->dev);
1573  unlock:
1574 	spin_unlock_irqrestore(&d40c->lock, flags);
1575 	return res;
1576 }
1577 
1578 static int d40_resume(struct dma_chan *chan)
1579 {
1580 	struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
1581 	int res = 0;
1582 	unsigned long flags;
1583 
1584 	if (d40c->phy_chan == NULL) {
1585 		chan_err(d40c, "Channel is not allocated!\n");
1586 		return -EINVAL;
1587 	}
1588 
1589 	if (!d40c->busy)
1590 		return 0;
1591 
1592 	spin_lock_irqsave(&d40c->lock, flags);
1593 	res = pm_runtime_resume_and_get(d40c->base->dev);
1594 	if (res < 0)
1595 		goto unlock;
1596 
1597 	/* If bytes left to transfer or linked tx resume job */
1598 	if (d40_residue(d40c) || d40_tx_is_linked(d40c))
1599 		res = d40_channel_execute_command(d40c, D40_DMA_RUN);
1600 
1601 	pm_runtime_put_autosuspend(d40c->base->dev);
1602  unlock:
1603 	spin_unlock_irqrestore(&d40c->lock, flags);
1604 	return res;
1605 }
1606 
1607 static dma_cookie_t d40_tx_submit(struct dma_async_tx_descriptor *tx)
1608 {
1609 	struct d40_chan *d40c = container_of(tx->chan,
1610 					     struct d40_chan,
1611 					     chan);
1612 	struct d40_desc *d40d = container_of(tx, struct d40_desc, txd);
1613 	unsigned long flags;
1614 	dma_cookie_t cookie;
1615 
1616 	spin_lock_irqsave(&d40c->lock, flags);
1617 	cookie = dma_cookie_assign(tx);
1618 	d40_desc_queue(d40c, d40d);
1619 	spin_unlock_irqrestore(&d40c->lock, flags);
1620 
1621 	return cookie;
1622 }
1623 
1624 static int d40_start(struct d40_chan *d40c)
1625 {
1626 	return d40_channel_execute_command(d40c, D40_DMA_RUN);
1627 }
1628 
1629 static struct d40_desc *d40_queue_start(struct d40_chan *d40c)
1630 {
1631 	struct d40_desc *d40d;
1632 	int err;
1633 
1634 	/* Start queued jobs, if any */
1635 	d40d = d40_first_queued(d40c);
1636 
1637 	if (d40d != NULL) {
1638 		if (!d40c->busy) {
1639 			err = pm_runtime_resume_and_get(d40c->base->dev);
1640 			if (err < 0) {
1641 				chan_err(d40c, "Failed to resume DMA: %d\n",
1642 					 err);
1643 				do {
1644 					d40_desc_remove(d40d);
1645 					d40_desc_done(d40c, d40d);
1646 					d40c->pending_tx++;
1647 					d40d = d40_first_queued(d40c);
1648 				} while (d40d);
1649 				tasklet_schedule(&d40c->tasklet);
1650 				return ERR_PTR(err);
1651 			}
1652 			d40c->busy = true;
1653 		}
1654 
1655 		/* Remove from queue */
1656 		d40_desc_remove(d40d);
1657 
1658 		/* Add to active queue */
1659 		d40_desc_submit(d40c, d40d);
1660 
1661 		/* Initiate DMA job */
1662 		d40_desc_load(d40c, d40d);
1663 
1664 		/* Start dma job */
1665 		err = d40_start(d40c);
1666 
1667 		if (err) {
1668 			d40_desc_remove(d40d);
1669 			d40_desc_done(d40c, d40d);
1670 			d40c->pending_tx++;
1671 			d40c->busy = false;
1672 			pm_runtime_put_autosuspend(d40c->base->dev);
1673 			tasklet_schedule(&d40c->tasklet);
1674 			return ERR_PTR(err);
1675 		}
1676 	}
1677 
1678 	return d40d;
1679 }
1680 
1681 /* called from interrupt context */
1682 static void dma_tc_handle(struct d40_chan *d40c)
1683 {
1684 	struct d40_desc *d40d;
1685 	unsigned int callbacks = 1;
1686 
1687 	/* Get first active entry from list */
1688 	d40d = d40_first_active_get(d40c);
1689 
1690 	if (d40d == NULL)
1691 		return;
1692 
1693 	if (d40d->cyclic) {
1694 		/*
1695 		 * If this was a paritially loaded list, we need to reloaded
1696 		 * it, and only when the list is completed.  We need to check
1697 		 * for done because the interrupt will hit for every link, and
1698 		 * not just the last one.
1699 		 */
1700 		if (d40d->lli_current < d40d->lli_len
1701 		    && !d40_tx_is_linked(d40c)
1702 		    && !d40_residue(d40c)) {
1703 			d40_lcla_free_all(d40c, d40d);
1704 			d40_desc_load(d40c, d40d);
1705 			(void) d40_start(d40c);
1706 
1707 			if (d40d->lli_current == d40d->lli_len)
1708 				d40d->lli_current = 0;
1709 		}
1710 
1711 		callbacks = d40_cyclic_periods_elapsed(d40c, d40d);
1712 	} else {
1713 		d40_lcla_free_all(d40c, d40d);
1714 
1715 		if (d40d->lli_current < d40d->lli_len) {
1716 			d40_desc_load(d40c, d40d);
1717 			/* Start dma job */
1718 			(void) d40_start(d40c);
1719 			return;
1720 		}
1721 
1722 		d40_desc_remove(d40d);
1723 		d40_desc_done(d40c, d40d);
1724 
1725 		if (d40_queue_start(d40c) == NULL) {
1726 			d40c->busy = false;
1727 
1728 			pm_runtime_put_autosuspend(d40c->base->dev);
1729 		}
1730 	}
1731 
1732 	d40c->pending_tx += callbacks;
1733 	tasklet_schedule(&d40c->tasklet);
1734 
1735 }
1736 
1737 static void dma_tasklet(struct tasklet_struct *t)
1738 {
1739 	struct d40_chan *d40c = from_tasklet(d40c, t, tasklet);
1740 	struct d40_desc *d40d;
1741 	unsigned long flags;
1742 	bool callback_active;
1743 	bool from_done;
1744 	struct dmaengine_desc_callback cb;
1745 
1746 	spin_lock_irqsave(&d40c->lock, flags);
1747 
1748 	/* Get first entry from the done list */
1749 	d40d = d40_first_done(d40c);
1750 	from_done = !!d40d;
1751 	if (!from_done) {
1752 		/* Check if we have reached here for cyclic job */
1753 		d40d = d40_first_active_get(d40c);
1754 		if (d40d == NULL || !d40d->cyclic)
1755 			goto check_pending_tx;
1756 	}
1757 
1758 	if (from_done)
1759 		dma_cookie_complete(&d40d->txd);
1760 
1761 	/*
1762 	 * If terminating a channel pending_tx is set to zero.
1763 	 * This prevents any finished active jobs to return to the client.
1764 	 */
1765 	if (d40c->pending_tx == 0) {
1766 		spin_unlock_irqrestore(&d40c->lock, flags);
1767 		return;
1768 	}
1769 
1770 	/* Callback to client */
1771 	callback_active = !!(d40d->txd.flags & DMA_PREP_INTERRUPT);
1772 	dmaengine_desc_get_callback(&d40d->txd, &cb);
1773 
1774 	if (from_done) {
1775 		if (async_tx_test_ack(&d40d->txd)) {
1776 			d40_desc_remove(d40d);
1777 			d40_desc_free(d40c, d40d);
1778 		} else if (!d40d->is_in_client_list) {
1779 			d40_desc_remove(d40d);
1780 			d40_lcla_free_all(d40c, d40d);
1781 			list_add_tail(&d40d->node, &d40c->client);
1782 			d40d->is_in_client_list = true;
1783 		}
1784 	}
1785 
1786 	d40c->pending_tx--;
1787 
1788 	if (d40c->pending_tx)
1789 		tasklet_schedule(&d40c->tasklet);
1790 
1791 	spin_unlock_irqrestore(&d40c->lock, flags);
1792 
1793 	if (callback_active)
1794 		dmaengine_desc_callback_invoke(&cb, NULL);
1795 
1796 	return;
1797  check_pending_tx:
1798 	/* Rescue maneuver if receiving double interrupts */
1799 	if (d40c->pending_tx > 0)
1800 		d40c->pending_tx--;
1801 	spin_unlock_irqrestore(&d40c->lock, flags);
1802 }
1803 
1804 static irqreturn_t d40_handle_interrupt(int irq, void *data)
1805 {
1806 	irqreturn_t handled = IRQ_NONE;
1807 	int i;
1808 	u32 idx;
1809 	u32 row;
1810 	long chan = -1;
1811 	struct d40_chan *d40c;
1812 	struct d40_base *base = data;
1813 	u32 *regs = base->regs_interrupt;
1814 	struct d40_interrupt_lookup *il = base->gen_dmac.il;
1815 	u32 il_size = base->gen_dmac.il_size;
1816 	int ret;
1817 
1818 	ret = pm_runtime_get_if_active(base->dev);
1819 	if (IS_ENABLED(CONFIG_PM) && ret <= 0)
1820 		return IRQ_NONE;
1821 
1822 	spin_lock(&base->interrupt_lock);
1823 
1824 	/* Read interrupt status of both logical and physical channels */
1825 	for (i = 0; i < il_size; i++)
1826 		regs[i] = readl(base->virtbase + il[i].src);
1827 
1828 	for (;;) {
1829 
1830 		chan = find_next_bit((unsigned long *)regs,
1831 				     BITS_PER_LONG * il_size, chan + 1);
1832 
1833 		/* No more set bits found? */
1834 		if (chan == BITS_PER_LONG * il_size)
1835 			break;
1836 
1837 		row = chan / BITS_PER_LONG;
1838 		idx = chan & (BITS_PER_LONG - 1);
1839 
1840 		/*
1841 		 * Status for a channel owned by another core still explains
1842 		 * the interrupt, but only ACK Linux-owned channels below.
1843 		 */
1844 		handled = IRQ_HANDLED;
1845 
1846 		if (il[row].offset == D40_PHY_CHAN)
1847 			d40c = base->lookup_phy_chans[idx];
1848 		else
1849 			d40c = base->lookup_log_chans[il[row].offset + idx];
1850 
1851 		if (!d40c) {
1852 			/*
1853 			 * No error because this can happen if something else
1854 			 * in the system is using the channel.
1855 			 */
1856 			continue;
1857 		}
1858 
1859 		/* ACK interrupt */
1860 		writel(BIT(idx), base->virtbase + il[row].clr);
1861 
1862 		spin_lock(&d40c->lock);
1863 
1864 		if (!il[row].is_error)
1865 			dma_tc_handle(d40c);
1866 		else
1867 			d40_err(base->dev, "IRQ chan: %ld offset %d idx %d\n",
1868 				chan, il[row].offset, idx);
1869 
1870 		spin_unlock(&d40c->lock);
1871 	}
1872 
1873 	spin_unlock(&base->interrupt_lock);
1874 
1875 	if (ret > 0)
1876 		pm_runtime_put_autosuspend(base->dev);
1877 
1878 	return handled;
1879 }
1880 
1881 static int d40_validate_conf(struct d40_chan *d40c,
1882 			     struct stedma40_chan_cfg *conf)
1883 {
1884 	int res = 0;
1885 	bool is_log = conf->mode == STEDMA40_MODE_LOGICAL;
1886 	bool invalid_dev_type = conf->dev_type < 0;
1887 
1888 	if (!invalid_dev_type &&
1889 	    D40_TYPE_TO_GROUP(conf->dev_type) >=
1890 	    d40c->base->gen_dmac.num_event_groups)
1891 		invalid_dev_type = true;
1892 
1893 	if (conf->dir != DMA_MEM_TO_MEM &&
1894 	    !is_slave_direction(conf->dir)) {
1895 		chan_err(d40c, "Invalid direction.\n");
1896 		res = -EINVAL;
1897 	}
1898 
1899 	if (!invalid_dev_type && is_log) {
1900 		int max_dev_type;
1901 
1902 		if (conf->dir == DMA_DEV_TO_MEM)
1903 			max_dev_type = DIV_ROUND_UP(d40c->base->num_log_chans, 2);
1904 		else
1905 			max_dev_type = d40c->base->num_log_chans / 2;
1906 
1907 		invalid_dev_type = conf->dev_type >= max_dev_type;
1908 	}
1909 
1910 	if (invalid_dev_type) {
1911 		chan_err(d40c, "Invalid device type (%d)\n", conf->dev_type);
1912 		res = -EINVAL;
1913 	}
1914 
1915 	if (conf->use_fixed_channel &&
1916 	    (conf->phy_channel < 0 ||
1917 	     conf->phy_channel >= d40c->base->num_phy_chans)) {
1918 		chan_err(d40c, "Invalid physical channel (%d)\n",
1919 			 conf->phy_channel);
1920 		res = -EINVAL;
1921 	}
1922 
1923 	if (conf->dir == DMA_DEV_TO_DEV) {
1924 		/*
1925 		 * DMAC HW supports it. Will be added to this driver,
1926 		 * in case any dma client requires it.
1927 		 */
1928 		chan_err(d40c, "periph to periph not supported\n");
1929 		res = -EINVAL;
1930 	}
1931 
1932 	if (d40_psize_2_burst_size(is_log, conf->src_info.psize) *
1933 	    conf->src_info.data_width !=
1934 	    d40_psize_2_burst_size(is_log, conf->dst_info.psize) *
1935 	    conf->dst_info.data_width) {
1936 		/*
1937 		 * The DMAC hardware only supports
1938 		 * src (burst x width) == dst (burst x width)
1939 		 */
1940 
1941 		chan_err(d40c, "src (burst x width) != dst (burst x width)\n");
1942 		res = -EINVAL;
1943 	}
1944 
1945 	return res;
1946 }
1947 
1948 static bool d40_alloc_mask_set(struct d40_phy_res *phy,
1949 			       bool is_src, int log_event_line, bool is_log,
1950 			       bool *first_user)
1951 {
1952 	unsigned long flags;
1953 	spin_lock_irqsave(&phy->lock, flags);
1954 
1955 	*first_user = ((phy->allocated_src | phy->allocated_dst)
1956 			== D40_ALLOC_FREE);
1957 
1958 	if (!is_log) {
1959 		/* Physical interrupts are masked per physical full channel */
1960 		if (phy->allocated_src == D40_ALLOC_FREE &&
1961 		    phy->allocated_dst == D40_ALLOC_FREE) {
1962 			phy->allocated_dst = D40_ALLOC_PHY;
1963 			phy->allocated_src = D40_ALLOC_PHY;
1964 			goto found_unlock;
1965 		} else
1966 			goto not_found_unlock;
1967 	}
1968 
1969 	/* Logical channel */
1970 	if (is_src) {
1971 		if (phy->allocated_src == D40_ALLOC_PHY)
1972 			goto not_found_unlock;
1973 
1974 		if (phy->allocated_src == D40_ALLOC_FREE)
1975 			phy->allocated_src = D40_ALLOC_LOG_FREE;
1976 
1977 		if (!(phy->allocated_src & BIT(log_event_line))) {
1978 			phy->allocated_src |= BIT(log_event_line);
1979 			goto found_unlock;
1980 		} else
1981 			goto not_found_unlock;
1982 	} else {
1983 		if (phy->allocated_dst == D40_ALLOC_PHY)
1984 			goto not_found_unlock;
1985 
1986 		if (phy->allocated_dst == D40_ALLOC_FREE)
1987 			phy->allocated_dst = D40_ALLOC_LOG_FREE;
1988 
1989 		if (!(phy->allocated_dst & BIT(log_event_line))) {
1990 			phy->allocated_dst |= BIT(log_event_line);
1991 			goto found_unlock;
1992 		}
1993 	}
1994  not_found_unlock:
1995 	spin_unlock_irqrestore(&phy->lock, flags);
1996 	return false;
1997  found_unlock:
1998 	spin_unlock_irqrestore(&phy->lock, flags);
1999 	return true;
2000 }
2001 
2002 static bool d40_alloc_mask_free(struct d40_phy_res *phy, bool is_src,
2003 			       int log_event_line)
2004 {
2005 	unsigned long flags;
2006 	bool is_free = false;
2007 
2008 	spin_lock_irqsave(&phy->lock, flags);
2009 	if (!log_event_line) {
2010 		phy->allocated_dst = D40_ALLOC_FREE;
2011 		phy->allocated_src = D40_ALLOC_FREE;
2012 		is_free = true;
2013 		goto unlock;
2014 	}
2015 
2016 	/* Logical channel */
2017 	if (is_src) {
2018 		phy->allocated_src &= ~BIT(log_event_line);
2019 		if (phy->allocated_src == D40_ALLOC_LOG_FREE)
2020 			phy->allocated_src = D40_ALLOC_FREE;
2021 	} else {
2022 		phy->allocated_dst &= ~BIT(log_event_line);
2023 		if (phy->allocated_dst == D40_ALLOC_LOG_FREE)
2024 			phy->allocated_dst = D40_ALLOC_FREE;
2025 	}
2026 
2027 	is_free = ((phy->allocated_src | phy->allocated_dst) ==
2028 		   D40_ALLOC_FREE);
2029  unlock:
2030 	spin_unlock_irqrestore(&phy->lock, flags);
2031 
2032 	return is_free;
2033 }
2034 
2035 static int d40_phy_to_group(struct d40_base *base, int phy)
2036 {
2037 	return (phy / D40_PHYS_PER_EVENT_GROUP) %
2038 	       base->gen_dmac.num_event_groups;
2039 }
2040 
2041 static int d40_allocate_channel(struct d40_chan *d40c, bool *first_phy_user)
2042 {
2043 	int dev_type = d40c->dma_cfg.dev_type;
2044 	int event_group;
2045 	int event_line;
2046 	struct d40_phy_res *phys;
2047 	int i;
2048 	int j;
2049 	int log_num;
2050 	int num_phy_chans;
2051 	int phy_group_stride;
2052 	bool is_src;
2053 	bool is_log = d40c->dma_cfg.mode == STEDMA40_MODE_LOGICAL;
2054 
2055 	phys = d40c->base->phy_res;
2056 	num_phy_chans = d40c->base->num_phy_chans;
2057 	phy_group_stride = D40_PHYS_PER_EVENT_GROUP *
2058 			   d40c->base->gen_dmac.num_event_groups;
2059 
2060 	if (d40c->dma_cfg.dir == DMA_DEV_TO_MEM) {
2061 		log_num = 2 * dev_type;
2062 		is_src = true;
2063 	} else if (d40c->dma_cfg.dir == DMA_MEM_TO_DEV ||
2064 		   d40c->dma_cfg.dir == DMA_MEM_TO_MEM) {
2065 		/* dst event lines are used for logical memcpy */
2066 		log_num = 2 * dev_type + 1;
2067 		is_src = false;
2068 	} else
2069 		return -EINVAL;
2070 
2071 	event_group = D40_TYPE_TO_GROUP(dev_type);
2072 	event_line = D40_TYPE_TO_EVENT(dev_type);
2073 
2074 	if (!is_log) {
2075 		if (d40c->dma_cfg.dir == DMA_MEM_TO_MEM) {
2076 			/* Find physical half channel */
2077 			if (d40c->dma_cfg.use_fixed_channel) {
2078 				i = d40c->dma_cfg.phy_channel;
2079 				if (d40_alloc_mask_set(&phys[i], is_src,
2080 						       0, is_log,
2081 						       first_phy_user))
2082 					goto found_phy;
2083 			} else {
2084 				for (i = 0; i < num_phy_chans; i++) {
2085 					if (d40_alloc_mask_set(&phys[i], is_src,
2086 						       0, is_log,
2087 						       first_phy_user))
2088 						goto found_phy;
2089 				}
2090 			}
2091 		} else
2092 			for (j = 0; j < num_phy_chans;
2093 			     j += phy_group_stride) {
2094 				int phy_num = j + event_group *
2095 					      D40_PHYS_PER_EVENT_GROUP;
2096 
2097 				if (phy_num + D40_PHYS_PER_EVENT_GROUP >
2098 				    num_phy_chans)
2099 					break;
2100 
2101 				for (i = phy_num;
2102 				     i < phy_num + D40_PHYS_PER_EVENT_GROUP;
2103 				     i++) {
2104 					if (d40_alloc_mask_set(&phys[i],
2105 							       is_src,
2106 							       0,
2107 							       is_log,
2108 							       first_phy_user))
2109 						goto found_phy;
2110 				}
2111 			}
2112 		return -EINVAL;
2113 found_phy:
2114 		d40c->phy_chan = &phys[i];
2115 		d40c->log_num = D40_PHY_CHAN;
2116 		goto out;
2117 	}
2118 	if (dev_type == -1)
2119 		return -EINVAL;
2120 
2121 	/* Find logical channel */
2122 	for (j = 0; j < num_phy_chans; j += phy_group_stride) {
2123 		int phy_num = j + event_group * D40_PHYS_PER_EVENT_GROUP;
2124 
2125 		if (phy_num + D40_PHYS_PER_EVENT_GROUP > num_phy_chans)
2126 			break;
2127 
2128 		if (d40c->dma_cfg.use_fixed_channel) {
2129 			i = d40c->dma_cfg.phy_channel;
2130 
2131 			if (i != phy_num && i != phy_num + 1)
2132 				continue;
2133 
2134 			if (d40_alloc_mask_set(&phys[i], is_src, event_line,
2135 					       is_log, first_phy_user))
2136 				goto found_log;
2137 
2138 			dev_err(dmaengine_chan_dev(&d40c->chan),
2139 				"could not allocate fixed phy channel %d\n", i);
2140 			return -EINVAL;
2141 		}
2142 
2143 		/*
2144 		 * Spread logical channels across all available physical rather
2145 		 * than pack every logical channel at the first available phy
2146 		 * channels.
2147 		 */
2148 		if (is_src) {
2149 			for (i = phy_num;
2150 			     i < phy_num + D40_PHYS_PER_EVENT_GROUP;
2151 			     i++) {
2152 				if (d40_alloc_mask_set(&phys[i], is_src,
2153 						       event_line, is_log,
2154 						       first_phy_user))
2155 					goto found_log;
2156 			}
2157 		} else {
2158 			for (i = phy_num + D40_PHYS_PER_EVENT_GROUP - 1;
2159 			     i >= phy_num; i--) {
2160 				if (d40_alloc_mask_set(&phys[i], is_src,
2161 						       event_line, is_log,
2162 						       first_phy_user))
2163 					goto found_log;
2164 			}
2165 		}
2166 	}
2167 	return -EINVAL;
2168 
2169 found_log:
2170 	d40c->phy_chan = &phys[i];
2171 	d40c->log_num = log_num;
2172 out:
2173 
2174 	if (is_log)
2175 		d40c->base->lookup_log_chans[d40c->log_num] = d40c;
2176 	else
2177 		d40c->base->lookup_phy_chans[d40c->phy_chan->num] = d40c;
2178 
2179 	return 0;
2180 
2181 }
2182 
2183 static int d40_config_memcpy(struct d40_chan *d40c)
2184 {
2185 	dma_cap_mask_t cap = d40c->chan.device->cap_mask;
2186 	int ret;
2187 
2188 	if (dma_has_cap(DMA_MEMCPY, cap) && !dma_has_cap(DMA_SLAVE, cap)) {
2189 		d40c->dma_cfg = dma40_memcpy_conf_log;
2190 		d40c->dma_cfg.dev_type =
2191 			d40c->base->plat_data->memcpy_channels[d40c->chan.chan_id];
2192 
2193 		ret = d40_validate_conf(d40c, &d40c->dma_cfg);
2194 		if (ret)
2195 			return ret;
2196 
2197 		d40_log_cfg(&d40c->dma_cfg,
2198 			    &d40c->log_def.lcsp1, &d40c->log_def.lcsp3);
2199 
2200 	} else if (dma_has_cap(DMA_MEMCPY, cap) &&
2201 		   dma_has_cap(DMA_SLAVE, cap)) {
2202 		d40c->dma_cfg = dma40_memcpy_conf_phy;
2203 
2204 		ret = d40_validate_conf(d40c, &d40c->dma_cfg);
2205 		if (ret)
2206 			return ret;
2207 
2208 		/* Generate interrupt at end of transfer or relink. */
2209 		d40c->dst_def_cfg |= BIT(D40_SREG_CFG_TIM_POS);
2210 
2211 		/* Generate interrupt on error. */
2212 		d40c->src_def_cfg |= BIT(D40_SREG_CFG_EIM_POS);
2213 		d40c->dst_def_cfg |= BIT(D40_SREG_CFG_EIM_POS);
2214 
2215 	} else {
2216 		chan_err(d40c, "No memcpy\n");
2217 		return -EINVAL;
2218 	}
2219 
2220 	return 0;
2221 }
2222 
2223 static int d40_free_dma(struct d40_chan *d40c)
2224 {
2225 
2226 	int res = 0;
2227 	u32 event = D40_TYPE_TO_EVENT(d40c->dma_cfg.dev_type);
2228 	struct d40_phy_res *phy = d40c->phy_chan;
2229 	bool is_src;
2230 
2231 	if (phy == NULL) {
2232 		chan_err(d40c, "phy == null\n");
2233 		return -EINVAL;
2234 	}
2235 
2236 	if (phy->allocated_src == D40_ALLOC_FREE &&
2237 	    phy->allocated_dst == D40_ALLOC_FREE) {
2238 		chan_err(d40c, "channel already free\n");
2239 		return -EINVAL;
2240 	}
2241 
2242 	if (d40c->dma_cfg.dir == DMA_MEM_TO_DEV ||
2243 	    d40c->dma_cfg.dir == DMA_MEM_TO_MEM)
2244 		is_src = false;
2245 	else if (d40c->dma_cfg.dir == DMA_DEV_TO_MEM)
2246 		is_src = true;
2247 	else {
2248 		chan_err(d40c, "Unknown direction\n");
2249 		return -EINVAL;
2250 	}
2251 
2252 	/* Release descriptor state; this does not access DMA40 registers. */
2253 	d40_term_all(d40c);
2254 
2255 	res = pm_runtime_resume_and_get(d40c->base->dev);
2256 	if (res >= 0) {
2257 		res = d40_channel_execute_command(d40c, D40_DMA_STOP);
2258 		if (res)
2259 			chan_err(d40c, "stop failed\n");
2260 
2261 		pm_runtime_put_autosuspend(d40c->base->dev);
2262 		if (res)
2263 			return res;
2264 	}
2265 
2266 	d40_alloc_mask_free(phy, is_src, chan_is_logical(d40c) ? event : 0);
2267 
2268 	if (chan_is_logical(d40c))
2269 		d40c->base->lookup_log_chans[d40c->log_num] = NULL;
2270 	else
2271 		d40c->base->lookup_phy_chans[phy->num] = NULL;
2272 
2273 	if (d40c->busy)
2274 		pm_runtime_put_autosuspend(d40c->base->dev);
2275 
2276 	d40c->busy = false;
2277 	d40c->phy_chan = NULL;
2278 	d40c->configured = false;
2279 	return res;
2280 }
2281 
2282 static bool d40_is_paused(struct d40_chan *d40c)
2283 {
2284 	void __iomem *chanbase = chan_base(d40c);
2285 	bool is_paused = false;
2286 	unsigned long flags;
2287 	void __iomem *active_reg;
2288 	u32 status;
2289 	u32 event = D40_TYPE_TO_EVENT(d40c->dma_cfg.dev_type);
2290 
2291 	spin_lock_irqsave(&d40c->lock, flags);
2292 
2293 	if (chan_is_physical(d40c)) {
2294 		if (d40c->phy_chan->num % 2 == 0)
2295 			active_reg = d40c->base->virtbase + D40_DREG_ACTIVE;
2296 		else
2297 			active_reg = d40c->base->virtbase + D40_DREG_ACTIVO;
2298 
2299 		status = (readl(active_reg) &
2300 			  D40_CHAN_POS_MASK(d40c->phy_chan->num)) >>
2301 			D40_CHAN_POS(d40c->phy_chan->num);
2302 		if (status == D40_DMA_SUSPENDED || status == D40_DMA_STOP)
2303 			is_paused = true;
2304 		goto unlock;
2305 	}
2306 
2307 	if (d40c->dma_cfg.dir == DMA_MEM_TO_DEV ||
2308 	    d40c->dma_cfg.dir == DMA_MEM_TO_MEM) {
2309 		status = readl(chanbase + D40_CHAN_REG_SDLNK);
2310 	} else if (d40c->dma_cfg.dir == DMA_DEV_TO_MEM) {
2311 		status = readl(chanbase + D40_CHAN_REG_SSLNK);
2312 	} else {
2313 		chan_err(d40c, "Unknown direction\n");
2314 		goto unlock;
2315 	}
2316 
2317 	status = (status & D40_EVENTLINE_MASK(event)) >>
2318 		D40_EVENTLINE_POS(event);
2319 
2320 	if (status != D40_DMA_RUN)
2321 		is_paused = true;
2322  unlock:
2323 	spin_unlock_irqrestore(&d40c->lock, flags);
2324 	return is_paused;
2325 
2326 }
2327 
2328 static u32 stedma40_residue(struct dma_chan *chan, dma_cookie_t cookie)
2329 {
2330 	struct d40_chan *d40c =
2331 		container_of(chan, struct d40_chan, chan);
2332 	struct d40_desc *d40d;
2333 	size_t offset;
2334 	u32 bytes_left;
2335 	unsigned long flags;
2336 
2337 	spin_lock_irqsave(&d40c->lock, flags);
2338 	d40d = d40_first_active_get(d40c);
2339 	if (d40d && d40d->txd.cookie == cookie && d40d->cyclic &&
2340 	    d40d->cyclic_buf_len) {
2341 		if (d40_cyclic_offset(d40c, d40d, &offset))
2342 			d40d->cyclic_residue = d40d->cyclic_buf_len - offset;
2343 		bytes_left = d40d->cyclic_residue;
2344 	} else {
2345 		bytes_left = d40_residue(d40c);
2346 	}
2347 
2348 	spin_unlock_irqrestore(&d40c->lock, flags);
2349 
2350 	return bytes_left;
2351 }
2352 
2353 static int
2354 d40_prep_sg_log(struct d40_chan *chan, struct d40_desc *desc,
2355 		struct scatterlist *sg_src, struct scatterlist *sg_dst,
2356 		unsigned int sg_len, dma_addr_t src_dev_addr,
2357 		dma_addr_t dst_dev_addr)
2358 {
2359 	struct stedma40_chan_cfg *cfg = &chan->dma_cfg;
2360 	struct stedma40_half_channel_info *src_info = &cfg->src_info;
2361 	struct stedma40_half_channel_info *dst_info = &cfg->dst_info;
2362 	int ret;
2363 
2364 	ret = d40_log_sg_to_lli(sg_src, sg_len,
2365 				src_dev_addr,
2366 				desc->lli_log.src,
2367 				chan->log_def.lcsp1,
2368 				src_info->data_width,
2369 				dst_info->data_width);
2370 
2371 	ret = d40_log_sg_to_lli(sg_dst, sg_len,
2372 				dst_dev_addr,
2373 				desc->lli_log.dst,
2374 				chan->log_def.lcsp3,
2375 				dst_info->data_width,
2376 				src_info->data_width);
2377 
2378 	return ret < 0 ? ret : 0;
2379 }
2380 
2381 static int
2382 d40_prep_sg_phy(struct d40_chan *chan, struct d40_desc *desc,
2383 		struct scatterlist *sg_src, struct scatterlist *sg_dst,
2384 		unsigned int sg_len, dma_addr_t src_dev_addr,
2385 		dma_addr_t dst_dev_addr)
2386 {
2387 	struct stedma40_chan_cfg *cfg = &chan->dma_cfg;
2388 	struct stedma40_half_channel_info *src_info = &cfg->src_info;
2389 	struct stedma40_half_channel_info *dst_info = &cfg->dst_info;
2390 	unsigned long flags = 0;
2391 	int ret;
2392 
2393 	if (desc->cyclic)
2394 		flags |= LLI_CYCLIC | LLI_TERM_INT;
2395 
2396 	ret = d40_phy_sg_to_lli(sg_src, sg_len, src_dev_addr,
2397 				desc->lli_phy.src,
2398 				virt_to_phys(desc->lli_phy.src),
2399 				chan->src_def_cfg,
2400 				src_info, dst_info, flags);
2401 
2402 	ret = d40_phy_sg_to_lli(sg_dst, sg_len, dst_dev_addr,
2403 				desc->lli_phy.dst,
2404 				virt_to_phys(desc->lli_phy.dst),
2405 				chan->dst_def_cfg,
2406 				dst_info, src_info, flags);
2407 
2408 	dma_sync_single_for_device(chan->base->dev, desc->lli_pool.dma_addr,
2409 				   desc->lli_pool.size, DMA_TO_DEVICE);
2410 
2411 	return ret < 0 ? ret : 0;
2412 }
2413 
2414 static struct d40_desc *
2415 d40_prep_desc(struct d40_chan *chan, struct scatterlist *sg,
2416 	      unsigned int sg_len, unsigned long dma_flags)
2417 {
2418 	struct stedma40_chan_cfg *cfg;
2419 	struct d40_desc *desc;
2420 	int ret;
2421 
2422 	desc = d40_desc_get(chan);
2423 	if (!desc)
2424 		return NULL;
2425 
2426 	cfg = &chan->dma_cfg;
2427 	desc->lli_len = d40_sg_2_dmalen(sg, sg_len, cfg->src_info.data_width,
2428 					cfg->dst_info.data_width);
2429 	if (desc->lli_len < 0) {
2430 		chan_err(chan, "Unaligned size\n");
2431 		goto free_desc;
2432 	}
2433 
2434 	ret = d40_pool_lli_alloc(chan, desc, desc->lli_len);
2435 	if (ret < 0) {
2436 		chan_err(chan, "Could not allocate lli\n");
2437 		goto free_desc;
2438 	}
2439 
2440 	desc->lli_current = 0;
2441 	desc->txd.flags = dma_flags;
2442 	desc->txd.tx_submit = d40_tx_submit;
2443 
2444 	dma_async_tx_descriptor_init(&desc->txd, &chan->chan);
2445 
2446 	return desc;
2447  free_desc:
2448 	d40_desc_free(chan, desc);
2449 	return NULL;
2450 }
2451 
2452 static struct dma_async_tx_descriptor *
2453 d40_prep_sg(struct dma_chan *dchan, struct scatterlist *sg_src,
2454 	    struct scatterlist *sg_dst, unsigned int sg_len,
2455 	    enum dma_transfer_direction direction, unsigned long dma_flags)
2456 {
2457 	struct d40_chan *chan = container_of(dchan, struct d40_chan, chan);
2458 	dma_addr_t src_dev_addr;
2459 	dma_addr_t dst_dev_addr;
2460 	struct d40_desc *desc;
2461 	unsigned long flags;
2462 	int ret;
2463 
2464 	if (!chan->phy_chan) {
2465 		chan_err(chan, "Cannot prepare unallocated channel\n");
2466 		return NULL;
2467 	}
2468 
2469 	if (direction != DMA_MEM_TO_MEM) {
2470 		ret = d40_set_runtime_config_write(dchan,
2471 						   &chan->slave_config,
2472 						   direction);
2473 		if (ret)
2474 			return NULL;
2475 	}
2476 
2477 	spin_lock_irqsave(&chan->lock, flags);
2478 
2479 	desc = d40_prep_desc(chan, sg_src, sg_len, dma_flags);
2480 	if (desc == NULL)
2481 		goto unlock;
2482 
2483 	if (sg_next(&sg_src[sg_len - 1]) == sg_src) {
2484 		desc->cyclic = true;
2485 		if (desc->lli_len != sg_len) {
2486 			chan_err(chan, "Cyclic periods must fit in one LLI\n");
2487 			goto free_desc;
2488 		}
2489 	}
2490 
2491 	src_dev_addr = 0;
2492 	dst_dev_addr = 0;
2493 	if (direction == DMA_DEV_TO_MEM)
2494 		src_dev_addr = chan->runtime_addr;
2495 	else if (direction == DMA_MEM_TO_DEV)
2496 		dst_dev_addr = chan->runtime_addr;
2497 
2498 	if (chan_is_logical(chan))
2499 		ret = d40_prep_sg_log(chan, desc, sg_src, sg_dst,
2500 				      sg_len, src_dev_addr, dst_dev_addr);
2501 	else
2502 		ret = d40_prep_sg_phy(chan, desc, sg_src, sg_dst,
2503 				      sg_len, src_dev_addr, dst_dev_addr);
2504 
2505 	if (ret) {
2506 		chan_err(chan, "Failed to prepare %s sg job: %d\n",
2507 			 chan_is_logical(chan) ? "log" : "phy", ret);
2508 		goto free_desc;
2509 	}
2510 
2511 	/*
2512 	 * add descriptor to the prepare queue in order to be able
2513 	 * to free them later in terminate_all
2514 	 */
2515 	list_add_tail(&desc->node, &chan->prepare_queue);
2516 
2517 	spin_unlock_irqrestore(&chan->lock, flags);
2518 
2519 	return &desc->txd;
2520  free_desc:
2521 	d40_desc_free(chan, desc);
2522  unlock:
2523 	spin_unlock_irqrestore(&chan->lock, flags);
2524 	return NULL;
2525 }
2526 
2527 static bool stedma40_filter(struct dma_chan *chan, void *data)
2528 {
2529 	struct stedma40_chan_cfg *info = data;
2530 	struct d40_chan *d40c =
2531 		container_of(chan, struct d40_chan, chan);
2532 	int err;
2533 
2534 	if (data) {
2535 		err = d40_validate_conf(d40c, info);
2536 		if (!err)
2537 			d40c->dma_cfg = *info;
2538 	} else
2539 		err = d40_config_memcpy(d40c);
2540 
2541 	if (!err)
2542 		d40c->configured = true;
2543 
2544 	return err == 0;
2545 }
2546 
2547 static void __d40_set_prio_rt(struct d40_chan *d40c, int dev_type, bool src)
2548 {
2549 	bool realtime = d40c->dma_cfg.realtime;
2550 	bool highprio = d40c->dma_cfg.high_priority;
2551 	u32 rtreg;
2552 	u32 event = D40_TYPE_TO_EVENT(dev_type);
2553 	u32 group = D40_TYPE_TO_GROUP(dev_type);
2554 	u32 bit = BIT(event);
2555 	u32 prioreg;
2556 	struct d40_gen_dmac *dmac = &d40c->base->gen_dmac;
2557 
2558 	rtreg = realtime ? dmac->realtime_en : dmac->realtime_clear;
2559 	/*
2560 	 * Due to a hardware bug, in some cases a logical channel triggered by
2561 	 * a high priority destination event line can generate extra packet
2562 	 * transactions.
2563 	 *
2564 	 * The workaround is to not set the high priority level for the
2565 	 * destination event lines that trigger logical channels.
2566 	 */
2567 	if (!src && chan_is_logical(d40c))
2568 		highprio = false;
2569 
2570 	prioreg = highprio ? dmac->high_prio_en : dmac->high_prio_clear;
2571 
2572 	/* Destination event lines are stored in the upper halfword */
2573 	if (!src)
2574 		bit <<= 16;
2575 
2576 	writel(bit, d40c->base->virtbase + prioreg + group * 4);
2577 	writel(bit, d40c->base->virtbase + rtreg + group * 4);
2578 }
2579 
2580 static void d40_set_prio_realtime(struct d40_chan *d40c)
2581 {
2582 	if (d40c->base->rev < 3)
2583 		return;
2584 
2585 	if ((d40c->dma_cfg.dir ==  DMA_DEV_TO_MEM) ||
2586 	    (d40c->dma_cfg.dir == DMA_DEV_TO_DEV))
2587 		__d40_set_prio_rt(d40c, d40c->dma_cfg.dev_type, true);
2588 
2589 	if ((d40c->dma_cfg.dir ==  DMA_MEM_TO_DEV) ||
2590 	    (d40c->dma_cfg.dir == DMA_DEV_TO_DEV))
2591 		__d40_set_prio_rt(d40c, d40c->dma_cfg.dev_type, false);
2592 }
2593 
2594 #define D40_DT_FLAGS_MODE(flags)       ((flags >> 0) & 0x1)
2595 #define D40_DT_FLAGS_DIR(flags)        ((flags >> 1) & 0x1)
2596 #define D40_DT_FLAGS_BIG_ENDIAN(flags) ((flags >> 2) & 0x1)
2597 #define D40_DT_FLAGS_FIXED_CHAN(flags) ((flags >> 3) & 0x1)
2598 #define D40_DT_FLAGS_HIGH_PRIO(flags)  ((flags >> 4) & 0x1)
2599 
2600 static struct dma_chan *d40_xlate(struct of_phandle_args *dma_spec,
2601 				  struct of_dma *ofdma)
2602 {
2603 	struct stedma40_chan_cfg cfg;
2604 	dma_cap_mask_t cap;
2605 	u32 flags;
2606 
2607 	if (dma_spec->args_count != 3)
2608 		return NULL;
2609 
2610 	memset(&cfg, 0, sizeof(struct stedma40_chan_cfg));
2611 
2612 	dma_cap_zero(cap);
2613 	dma_cap_set(DMA_SLAVE, cap);
2614 
2615 	cfg.dev_type = dma_spec->args[0];
2616 	flags = dma_spec->args[2];
2617 
2618 	switch (D40_DT_FLAGS_MODE(flags)) {
2619 	case 0: cfg.mode = STEDMA40_MODE_LOGICAL; break;
2620 	case 1: cfg.mode = STEDMA40_MODE_PHYSICAL; break;
2621 	}
2622 
2623 	switch (D40_DT_FLAGS_DIR(flags)) {
2624 	case 0:
2625 		cfg.dir = DMA_MEM_TO_DEV;
2626 		cfg.dst_info.big_endian = D40_DT_FLAGS_BIG_ENDIAN(flags);
2627 		break;
2628 	case 1:
2629 		cfg.dir = DMA_DEV_TO_MEM;
2630 		cfg.src_info.big_endian = D40_DT_FLAGS_BIG_ENDIAN(flags);
2631 		break;
2632 	}
2633 
2634 	if (D40_DT_FLAGS_FIXED_CHAN(flags)) {
2635 		cfg.phy_channel = dma_spec->args[1];
2636 		cfg.use_fixed_channel = true;
2637 	}
2638 
2639 	if (D40_DT_FLAGS_HIGH_PRIO(flags))
2640 		cfg.high_priority = true;
2641 
2642 	return dma_request_channel(cap, stedma40_filter, &cfg);
2643 }
2644 
2645 /* DMA ENGINE functions */
2646 static int d40_alloc_chan_resources(struct dma_chan *chan)
2647 {
2648 	int err;
2649 	unsigned long flags;
2650 	struct d40_chan *d40c =
2651 		container_of(chan, struct d40_chan, chan);
2652 	bool is_free_phy;
2653 	spin_lock_irqsave(&d40c->lock, flags);
2654 
2655 	dma_cookie_init(chan);
2656 
2657 	/* If no dma configuration is set use default configuration (memcpy) */
2658 	if (!d40c->configured) {
2659 		err = d40_config_memcpy(d40c);
2660 		if (err) {
2661 			chan_err(d40c, "Failed to configure memcpy channel\n");
2662 			goto unlock;
2663 		}
2664 	}
2665 
2666 	err = pm_runtime_resume_and_get(d40c->base->dev);
2667 	if (err < 0)
2668 		goto unlock;
2669 
2670 	err = d40_allocate_channel(d40c, &is_free_phy);
2671 	if (err) {
2672 		chan_err(d40c, "Failed to allocate channel\n");
2673 		d40c->configured = false;
2674 		goto mark_last_busy;
2675 	}
2676 
2677 	d40_set_prio_realtime(d40c);
2678 
2679 	if (chan_is_logical(d40c)) {
2680 		if (d40c->dma_cfg.dir == DMA_DEV_TO_MEM)
2681 			d40c->lcpa = d40c->base->lcpa_base +
2682 				d40c->dma_cfg.dev_type * D40_LCPA_CHAN_SIZE;
2683 		else
2684 			d40c->lcpa = d40c->base->lcpa_base +
2685 				d40c->dma_cfg.dev_type *
2686 				D40_LCPA_CHAN_SIZE + D40_LCPA_CHAN_DST_DELTA;
2687 
2688 		/* Unmask the Global Interrupt Mask. */
2689 		d40c->src_def_cfg |= BIT(D40_SREG_CFG_LOG_GIM_POS);
2690 		d40c->dst_def_cfg |= BIT(D40_SREG_CFG_LOG_GIM_POS);
2691 	}
2692 
2693 	dev_dbg(dmaengine_chan_dev(&d40c->chan), "allocated %s channel (phy %d%s)\n",
2694 		 chan_is_logical(d40c) ? "logical" : "physical",
2695 		 d40c->phy_chan->num,
2696 		 d40c->dma_cfg.use_fixed_channel ? ", fixed" : "");
2697 
2698 
2699 	/*
2700 	 * Only write channel configuration to the DMA if the physical
2701 	 * resource is free. In case of multiple logical channels
2702 	 * on the same physical resource, only the first write is necessary.
2703 	 */
2704 	if (is_free_phy)
2705 		d40_config_write(d40c);
2706  mark_last_busy:
2707 	pm_runtime_put_autosuspend(d40c->base->dev);
2708  unlock:
2709 	spin_unlock_irqrestore(&d40c->lock, flags);
2710 	return err;
2711 }
2712 
2713 static void d40_free_chan_resources(struct dma_chan *chan)
2714 {
2715 	struct d40_chan *d40c =
2716 		container_of(chan, struct d40_chan, chan);
2717 	int err;
2718 	unsigned long flags;
2719 
2720 	if (d40c->phy_chan == NULL) {
2721 		chan_err(d40c, "Cannot free unallocated channel\n");
2722 		return;
2723 	}
2724 
2725 	spin_lock_irqsave(&d40c->lock, flags);
2726 
2727 	err = d40_free_dma(d40c);
2728 
2729 	if (err)
2730 		chan_err(d40c, "Failed to free channel\n");
2731 	spin_unlock_irqrestore(&d40c->lock, flags);
2732 }
2733 
2734 static struct dma_async_tx_descriptor *d40_prep_memcpy(struct dma_chan *chan,
2735 						       dma_addr_t dst,
2736 						       dma_addr_t src,
2737 						       size_t size,
2738 						       unsigned long dma_flags)
2739 {
2740 	struct scatterlist dst_sg;
2741 	struct scatterlist src_sg;
2742 
2743 	sg_init_table(&dst_sg, 1);
2744 	sg_init_table(&src_sg, 1);
2745 
2746 	sg_dma_address(&dst_sg) = dst;
2747 	sg_dma_address(&src_sg) = src;
2748 
2749 	sg_dma_len(&dst_sg) = size;
2750 	sg_dma_len(&src_sg) = size;
2751 
2752 	return d40_prep_sg(chan, &src_sg, &dst_sg, 1,
2753 			   DMA_MEM_TO_MEM, dma_flags);
2754 }
2755 
2756 static struct dma_async_tx_descriptor *
2757 d40_prep_slave_sg(struct dma_chan *chan, struct scatterlist *sgl,
2758 		  unsigned int sg_len, enum dma_transfer_direction direction,
2759 		  unsigned long dma_flags, void *context)
2760 {
2761 	if (!is_slave_direction(direction))
2762 		return NULL;
2763 
2764 	return d40_prep_sg(chan, sgl, sgl, sg_len, direction, dma_flags);
2765 }
2766 
2767 static struct dma_async_tx_descriptor *
2768 dma40_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t dma_addr,
2769 		     size_t buf_len, size_t period_len,
2770 		     enum dma_transfer_direction direction, unsigned long flags)
2771 {
2772 	unsigned int periods;
2773 	struct dma_async_tx_descriptor *txd;
2774 	struct d40_desc *desc;
2775 	struct scatterlist *sg;
2776 	dma_addr_t buf_addr = dma_addr;
2777 	int i;
2778 
2779 	if (!buf_len || !period_len || buf_len % period_len)
2780 		return NULL;
2781 
2782 	periods = buf_len / period_len;
2783 
2784 	sg = kzalloc_objs(struct scatterlist, periods + 1, GFP_NOWAIT);
2785 	if (!sg)
2786 		return NULL;
2787 
2788 	for (i = 0; i < periods; i++) {
2789 		sg_dma_address(&sg[i]) = dma_addr;
2790 		sg_dma_len(&sg[i]) = period_len;
2791 		dma_addr += period_len;
2792 	}
2793 
2794 	sg_chain(sg, periods + 1, sg);
2795 
2796 	txd = d40_prep_sg(chan, sg, sg, periods, direction,
2797 			  DMA_PREP_INTERRUPT);
2798 	if (txd) {
2799 		desc = container_of(txd, struct d40_desc, txd);
2800 		desc->cyclic_dma_addr = buf_addr;
2801 		desc->cyclic_buf_len = buf_len;
2802 		desc->cyclic_residue = buf_len;
2803 		desc->cyclic_period_len = period_len;
2804 		desc->cyclic_callback_pos = 0;
2805 		desc->cyclic_callback_pos_valid = true;
2806 	}
2807 
2808 	kfree(sg);
2809 
2810 	return txd;
2811 }
2812 
2813 static enum dma_status d40_tx_status(struct dma_chan *chan,
2814 				     dma_cookie_t cookie,
2815 				     struct dma_tx_state *txstate)
2816 {
2817 	struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
2818 	enum dma_status ret;
2819 
2820 	if (d40c->phy_chan == NULL) {
2821 		chan_err(d40c, "Cannot read status of unallocated channel\n");
2822 		return -EINVAL;
2823 	}
2824 
2825 	ret = dma_cookie_status(chan, cookie, txstate);
2826 	if (ret != DMA_COMPLETE && txstate)
2827 		dma_set_residue(txstate, stedma40_residue(chan, cookie));
2828 
2829 	if (d40_is_paused(d40c))
2830 		ret = DMA_PAUSED;
2831 
2832 	return ret;
2833 }
2834 
2835 static void d40_issue_pending(struct dma_chan *chan)
2836 {
2837 	struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
2838 	unsigned long flags;
2839 
2840 	if (d40c->phy_chan == NULL) {
2841 		chan_err(d40c, "Channel is not allocated!\n");
2842 		return;
2843 	}
2844 
2845 	spin_lock_irqsave(&d40c->lock, flags);
2846 
2847 	list_splice_tail_init(&d40c->pending_queue, &d40c->queue);
2848 
2849 	/* Busy means that queued jobs are already being processed */
2850 	if (!d40c->busy)
2851 		(void) d40_queue_start(d40c);
2852 
2853 	spin_unlock_irqrestore(&d40c->lock, flags);
2854 }
2855 
2856 static int d40_terminate_all(struct dma_chan *chan)
2857 {
2858 	unsigned long flags;
2859 	struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
2860 	int ret;
2861 
2862 	if (d40c->phy_chan == NULL) {
2863 		chan_err(d40c, "Channel is not allocated!\n");
2864 		return -EINVAL;
2865 	}
2866 
2867 	spin_lock_irqsave(&d40c->lock, flags);
2868 
2869 	ret = pm_runtime_resume_and_get(d40c->base->dev);
2870 	if (ret >= 0) {
2871 		ret = d40_channel_execute_command(d40c, D40_DMA_STOP);
2872 		if (ret)
2873 			chan_err(d40c, "Failed to stop channel\n");
2874 
2875 		pm_runtime_put_autosuspend(d40c->base->dev);
2876 	}
2877 
2878 	/*
2879 	 * Always release software state, even when the controller cannot
2880 	 * resume. d40_term_all() does not access DMA40 registers.
2881 	 */
2882 	d40_term_all(d40c);
2883 	if (d40c->busy)
2884 		pm_runtime_put_autosuspend(d40c->base->dev);
2885 	d40c->busy = false;
2886 
2887 	spin_unlock_irqrestore(&d40c->lock, flags);
2888 	return ret;
2889 }
2890 
2891 static int
2892 dma40_config_to_halfchannel(struct d40_chan *d40c,
2893 			    struct stedma40_half_channel_info *info,
2894 			    u32 maxburst)
2895 {
2896 	int psize;
2897 
2898 	if (chan_is_logical(d40c)) {
2899 		if (maxburst >= 16)
2900 			psize = STEDMA40_PSIZE_LOG_16;
2901 		else if (maxburst >= 8)
2902 			psize = STEDMA40_PSIZE_LOG_8;
2903 		else if (maxburst >= 4)
2904 			psize = STEDMA40_PSIZE_LOG_4;
2905 		else
2906 			psize = STEDMA40_PSIZE_LOG_1;
2907 	} else {
2908 		if (maxburst >= 16)
2909 			psize = STEDMA40_PSIZE_PHY_16;
2910 		else if (maxburst >= 8)
2911 			psize = STEDMA40_PSIZE_PHY_8;
2912 		else if (maxburst >= 4)
2913 			psize = STEDMA40_PSIZE_PHY_4;
2914 		else
2915 			psize = STEDMA40_PSIZE_PHY_1;
2916 	}
2917 
2918 	info->psize = psize;
2919 	info->flow_ctrl = STEDMA40_NO_FLOW_CTRL;
2920 
2921 	return 0;
2922 }
2923 
2924 static int d40_set_runtime_config(struct dma_chan *chan,
2925 				  struct dma_slave_config *config)
2926 {
2927 	struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
2928 
2929 	memcpy(&d40c->slave_config, config, sizeof(*config));
2930 
2931 	return 0;
2932 }
2933 
2934 /* Runtime reconfiguration extension */
2935 static int d40_set_runtime_config_write(struct dma_chan *chan,
2936 				  struct dma_slave_config *config,
2937 				  enum dma_transfer_direction direction)
2938 {
2939 	struct d40_chan *d40c = container_of(chan, struct d40_chan, chan);
2940 	struct stedma40_chan_cfg *cfg = &d40c->dma_cfg;
2941 	enum dma_slave_buswidth src_addr_width, dst_addr_width;
2942 	dma_addr_t config_addr;
2943 	u32 src_maxburst, dst_maxburst;
2944 	int ret;
2945 
2946 	if (d40c->phy_chan == NULL) {
2947 		chan_err(d40c, "Channel is not allocated!\n");
2948 		return -EINVAL;
2949 	}
2950 
2951 	if (direction != cfg->dir) {
2952 		chan_err(d40c,
2953 			 "transfer direction %d differs from allocated direction %d\n",
2954 			 direction, cfg->dir);
2955 		return -EINVAL;
2956 	}
2957 
2958 	src_addr_width = config->src_addr_width;
2959 	src_maxburst = config->src_maxburst;
2960 	dst_addr_width = config->dst_addr_width;
2961 	dst_maxburst = config->dst_maxburst;
2962 
2963 	if (direction == DMA_DEV_TO_MEM) {
2964 		config_addr = config->src_addr;
2965 
2966 		/* Configure the memory side */
2967 		if (dst_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED)
2968 			dst_addr_width = src_addr_width;
2969 		if (dst_maxburst == 0)
2970 			dst_maxburst = src_maxburst;
2971 
2972 	} else if (direction == DMA_MEM_TO_DEV) {
2973 		config_addr = config->dst_addr;
2974 
2975 		/* Configure the memory side */
2976 		if (src_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED)
2977 			src_addr_width = dst_addr_width;
2978 		if (src_maxburst == 0)
2979 			src_maxburst = dst_maxburst;
2980 	} else {
2981 		dev_err(d40c->base->dev,
2982 			"unrecognized channel direction %d\n",
2983 			direction);
2984 		return -EINVAL;
2985 	}
2986 
2987 	if (config_addr <= 0) {
2988 		dev_err(d40c->base->dev, "no address supplied\n");
2989 		return -EINVAL;
2990 	}
2991 
2992 	if (src_maxburst * src_addr_width != dst_maxburst * dst_addr_width) {
2993 		dev_err(d40c->base->dev,
2994 			"src/dst width/maxburst mismatch: %d*%d != %d*%d\n",
2995 			src_maxburst,
2996 			src_addr_width,
2997 			dst_maxburst,
2998 			dst_addr_width);
2999 		return -EINVAL;
3000 	}
3001 
3002 	if (src_maxburst > 16) {
3003 		src_maxburst = 16;
3004 		dst_maxburst = src_maxburst * src_addr_width / dst_addr_width;
3005 	} else if (dst_maxburst > 16) {
3006 		dst_maxburst = 16;
3007 		src_maxburst = dst_maxburst * dst_addr_width / src_addr_width;
3008 	}
3009 
3010 	/* Only valid widths are; 1, 2, 4 and 8. */
3011 	if (src_addr_width <= DMA_SLAVE_BUSWIDTH_UNDEFINED ||
3012 	    src_addr_width >  DMA_SLAVE_BUSWIDTH_8_BYTES   ||
3013 	    dst_addr_width <= DMA_SLAVE_BUSWIDTH_UNDEFINED ||
3014 	    dst_addr_width >  DMA_SLAVE_BUSWIDTH_8_BYTES   ||
3015 	    !is_power_of_2(src_addr_width) ||
3016 	    !is_power_of_2(dst_addr_width))
3017 		return -EINVAL;
3018 
3019 	cfg->src_info.data_width = src_addr_width;
3020 	cfg->dst_info.data_width = dst_addr_width;
3021 
3022 	ret = dma40_config_to_halfchannel(d40c, &cfg->src_info,
3023 					  src_maxburst);
3024 	if (ret)
3025 		return ret;
3026 
3027 	ret = dma40_config_to_halfchannel(d40c, &cfg->dst_info,
3028 					  dst_maxburst);
3029 	if (ret)
3030 		return ret;
3031 
3032 	/* Fill in register values */
3033 	if (chan_is_logical(d40c))
3034 		d40_log_cfg(cfg, &d40c->log_def.lcsp1, &d40c->log_def.lcsp3);
3035 	else
3036 		d40_phy_cfg(cfg, &d40c->src_def_cfg, &d40c->dst_def_cfg);
3037 
3038 	/* These settings will take precedence later */
3039 	d40c->runtime_addr = config_addr;
3040 	d40c->runtime_direction = direction;
3041 	dev_dbg(d40c->base->dev,
3042 		"configured channel %s for %s, data width %d/%d, "
3043 		"maxburst %d/%d elements, LE, no flow control\n",
3044 		dma_chan_name(chan),
3045 		(direction == DMA_DEV_TO_MEM) ? "RX" : "TX",
3046 		src_addr_width, dst_addr_width,
3047 		src_maxburst, dst_maxburst);
3048 
3049 	return 0;
3050 }
3051 
3052 /* Initialization functions */
3053 
3054 static void __init d40_chan_init(struct d40_base *base, struct dma_device *dma,
3055 				 struct d40_chan *chans, int offset,
3056 				 int num_chans)
3057 {
3058 	int i = 0;
3059 	struct d40_chan *d40c;
3060 
3061 	INIT_LIST_HEAD(&dma->channels);
3062 
3063 	for (i = offset; i < offset + num_chans; i++) {
3064 		d40c = &chans[i];
3065 		d40c->base = base;
3066 		d40c->chan.device = dma;
3067 
3068 		spin_lock_init(&d40c->lock);
3069 
3070 		d40c->log_num = D40_PHY_CHAN;
3071 
3072 		INIT_LIST_HEAD(&d40c->done);
3073 		INIT_LIST_HEAD(&d40c->active);
3074 		INIT_LIST_HEAD(&d40c->queue);
3075 		INIT_LIST_HEAD(&d40c->pending_queue);
3076 		INIT_LIST_HEAD(&d40c->client);
3077 		INIT_LIST_HEAD(&d40c->prepare_queue);
3078 
3079 		tasklet_setup(&d40c->tasklet, dma_tasklet);
3080 
3081 		list_add_tail(&d40c->chan.device_node,
3082 			      &dma->channels);
3083 	}
3084 }
3085 
3086 static void d40_kill_tasklets(void *data)
3087 {
3088 	struct dma_device *dma = data;
3089 	struct d40_chan *d40c;
3090 	struct dma_chan *chan;
3091 
3092 	list_for_each_entry(chan, &dma->channels, device_node) {
3093 		d40c = container_of(chan, struct d40_chan, chan);
3094 		tasklet_kill(&d40c->tasklet);
3095 	}
3096 }
3097 
3098 static void d40_ops_init(struct d40_base *base, struct dma_device *dev)
3099 {
3100 	if (dma_has_cap(DMA_SLAVE, dev->cap_mask)) {
3101 		dev->device_prep_slave_sg = d40_prep_slave_sg;
3102 		dev->directions = BIT(DMA_DEV_TO_MEM) | BIT(DMA_MEM_TO_DEV);
3103 	}
3104 
3105 	if (dma_has_cap(DMA_MEMCPY, dev->cap_mask)) {
3106 		dev->device_prep_dma_memcpy = d40_prep_memcpy;
3107 		dev->directions = BIT(DMA_MEM_TO_MEM);
3108 		/*
3109 		 * This controller can only access address at even
3110 		 * 32bit boundaries, i.e. 2^2
3111 		 */
3112 		dev->copy_align = DMAENGINE_ALIGN_4_BYTES;
3113 	}
3114 
3115 	if (dma_has_cap(DMA_CYCLIC, dev->cap_mask))
3116 		dev->device_prep_dma_cyclic = dma40_prep_dma_cyclic;
3117 
3118 	dev->device_alloc_chan_resources = d40_alloc_chan_resources;
3119 	dev->device_free_chan_resources = d40_free_chan_resources;
3120 	dev->device_issue_pending = d40_issue_pending;
3121 	dev->device_tx_status = d40_tx_status;
3122 	dev->device_config = d40_set_runtime_config;
3123 	dev->device_pause = d40_pause;
3124 	dev->device_resume = d40_resume;
3125 	dev->device_terminate_all = d40_terminate_all;
3126 	dev->residue_granularity = DMA_RESIDUE_GRANULARITY_BURST;
3127 	dev->dev = base->dev;
3128 }
3129 
3130 static int __init d40_dmaengine_init(struct d40_base *base,
3131 				     int num_reserved_chans)
3132 {
3133 	int err ;
3134 
3135 	d40_chan_init(base, &base->dma_slave, base->log_chans,
3136 		      0, base->num_log_chans);
3137 
3138 	dma_cap_zero(base->dma_slave.cap_mask);
3139 	dma_cap_set(DMA_SLAVE, base->dma_slave.cap_mask);
3140 	dma_cap_set(DMA_CYCLIC, base->dma_slave.cap_mask);
3141 
3142 	d40_ops_init(base, &base->dma_slave);
3143 
3144 	err = devm_add_action(base->dev, d40_kill_tasklets,
3145 			      &base->dma_slave);
3146 	if (err)
3147 		goto exit;
3148 
3149 	err = dmaenginem_async_device_register(&base->dma_slave);
3150 
3151 	if (err) {
3152 		d40_err(base->dev, "Failed to register slave channels\n");
3153 		goto exit;
3154 	}
3155 
3156 	d40_chan_init(base, &base->dma_memcpy, base->log_chans,
3157 		      base->num_log_chans, base->num_memcpy_chans);
3158 
3159 	dma_cap_zero(base->dma_memcpy.cap_mask);
3160 	dma_cap_set(DMA_MEMCPY, base->dma_memcpy.cap_mask);
3161 
3162 	d40_ops_init(base, &base->dma_memcpy);
3163 
3164 	err = devm_add_action(base->dev, d40_kill_tasklets,
3165 			      &base->dma_memcpy);
3166 	if (err)
3167 		goto exit;
3168 
3169 	err = dmaenginem_async_device_register(&base->dma_memcpy);
3170 
3171 	if (err) {
3172 		d40_err(base->dev,
3173 			"Failed to register memcpy only channels\n");
3174 		goto exit;
3175 	}
3176 
3177 	d40_chan_init(base, &base->dma_both, base->phy_chans,
3178 		      0, num_reserved_chans);
3179 
3180 	dma_cap_zero(base->dma_both.cap_mask);
3181 	dma_cap_set(DMA_SLAVE, base->dma_both.cap_mask);
3182 	dma_cap_set(DMA_MEMCPY, base->dma_both.cap_mask);
3183 	dma_cap_set(DMA_CYCLIC, base->dma_both.cap_mask);
3184 
3185 	d40_ops_init(base, &base->dma_both);
3186 
3187 	err = devm_add_action(base->dev, d40_kill_tasklets,
3188 			      &base->dma_both);
3189 	if (err)
3190 		goto exit;
3191 
3192 	err = dmaenginem_async_device_register(&base->dma_both);
3193 
3194 	if (err) {
3195 		d40_err(base->dev,
3196 			"Failed to register logical and physical capable channels\n");
3197 		goto exit;
3198 	}
3199 	return 0;
3200  exit:
3201 	return err;
3202 }
3203 
3204 /* Suspend resume functionality */
3205 #ifdef CONFIG_PM_SLEEP
3206 static int dma40_suspend(struct device *dev)
3207 {
3208 	struct d40_base *base = dev_get_drvdata(dev);
3209 	int ret;
3210 
3211 	ret = pm_runtime_force_suspend(dev);
3212 	if (ret)
3213 		return ret;
3214 
3215 	if (base->lcpa_regulator)
3216 		ret = regulator_disable(base->lcpa_regulator);
3217 	return ret;
3218 }
3219 
3220 static int dma40_resume(struct device *dev)
3221 {
3222 	struct d40_base *base = dev_get_drvdata(dev);
3223 	int ret = 0;
3224 
3225 	if (base->lcpa_regulator) {
3226 		ret = regulator_enable(base->lcpa_regulator);
3227 		if (ret)
3228 			return ret;
3229 	}
3230 
3231 	return pm_runtime_force_resume(dev);
3232 }
3233 #endif
3234 
3235 #ifdef CONFIG_PM
3236 static void dma40_backup(void __iomem *baseaddr, u32 *backup,
3237 			 u32 *regaddr, int num, bool save)
3238 {
3239 	int i;
3240 
3241 	for (i = 0; i < num; i++) {
3242 		void __iomem *addr = baseaddr + regaddr[i];
3243 
3244 		if (save)
3245 			backup[i] = readl_relaxed(addr);
3246 		else
3247 			writel_relaxed(backup[i], addr);
3248 	}
3249 }
3250 
3251 static void d40_save_restore_registers(struct d40_base *base, bool save)
3252 {
3253 	int i;
3254 
3255 	/* Save/Restore channel specific registers */
3256 	for (i = 0; i < base->num_phy_chans; i++) {
3257 		void __iomem *addr;
3258 		int idx;
3259 
3260 		if (base->phy_res[i].reserved)
3261 			continue;
3262 
3263 		addr = base->virtbase + D40_DREG_PCBASE + i * D40_DREG_PCDELTA;
3264 		idx = i * ARRAY_SIZE(d40_backup_regs_chan);
3265 
3266 		dma40_backup(addr, &base->reg_val_backup_chan[idx],
3267 			     d40_backup_regs_chan,
3268 			     ARRAY_SIZE(d40_backup_regs_chan),
3269 			     save);
3270 	}
3271 
3272 	/* Save/Restore global registers */
3273 	dma40_backup(base->virtbase, base->reg_val_backup,
3274 		     d40_backup_regs, ARRAY_SIZE(d40_backup_regs),
3275 		     save);
3276 
3277 	/* Save/Restore registers only existing on dma40 v3 and later */
3278 	if (base->gen_dmac.backup)
3279 		dma40_backup(base->virtbase, base->reg_val_backup_v4,
3280 			     base->gen_dmac.backup,
3281 			base->gen_dmac.backup_size,
3282 			save);
3283 }
3284 
3285 static int dma40_runtime_suspend(struct device *dev)
3286 {
3287 	struct d40_base *base = dev_get_drvdata(dev);
3288 
3289 	d40_save_restore_registers(base, true);
3290 
3291 	/* Don't disable/enable clocks for v1 due to HW bugs */
3292 	if (base->rev != 1)
3293 		writel_relaxed(base->gcc_pwr_off_mask,
3294 			       base->virtbase + D40_DREG_GCC);
3295 
3296 	return 0;
3297 }
3298 
3299 static int dma40_runtime_resume(struct device *dev)
3300 {
3301 	struct d40_base *base = dev_get_drvdata(dev);
3302 
3303 	d40_save_restore_registers(base, false);
3304 
3305 	writel_relaxed(D40_DREG_GCC_ENABLE_ALL,
3306 		       base->virtbase + D40_DREG_GCC);
3307 	return 0;
3308 }
3309 #endif
3310 
3311 static const struct dev_pm_ops dma40_pm_ops = {
3312 	SET_LATE_SYSTEM_SLEEP_PM_OPS(dma40_suspend, dma40_resume)
3313 	SET_RUNTIME_PM_OPS(dma40_runtime_suspend,
3314 				dma40_runtime_resume,
3315 				NULL)
3316 };
3317 
3318 /* Initialization functions. */
3319 
3320 static int __init d40_phy_res_init(struct d40_base *base)
3321 {
3322 	int i;
3323 	int num_phy_chans_avail = 0;
3324 	u32 val[2];
3325 	int odd_even_bit = -2;
3326 	int gcc = D40_DREG_GCC_ENA;
3327 
3328 	val[0] = readl(base->virtbase + D40_DREG_PRSME);
3329 	val[1] = readl(base->virtbase + D40_DREG_PRSMO);
3330 
3331 	for (i = 0; i < base->num_phy_chans; i++) {
3332 		base->phy_res[i].num = i;
3333 		odd_even_bit += 2 * ((i % 2) == 0);
3334 		if (((val[i % 2] >> odd_even_bit) & 3) == 1) {
3335 			/* Mark security only channels as occupied */
3336 			base->phy_res[i].allocated_src = D40_ALLOC_PHY;
3337 			base->phy_res[i].allocated_dst = D40_ALLOC_PHY;
3338 			base->phy_res[i].reserved = true;
3339 			gcc |= D40_DREG_GCC_EVTGRP_ENA(d40_phy_to_group(base, i),
3340 						       D40_DREG_GCC_SRC);
3341 			gcc |= D40_DREG_GCC_EVTGRP_ENA(d40_phy_to_group(base, i),
3342 						       D40_DREG_GCC_DST);
3343 
3344 
3345 		} else {
3346 			base->phy_res[i].allocated_src = D40_ALLOC_FREE;
3347 			base->phy_res[i].allocated_dst = D40_ALLOC_FREE;
3348 			base->phy_res[i].reserved = false;
3349 			num_phy_chans_avail++;
3350 		}
3351 		spin_lock_init(&base->phy_res[i].lock);
3352 	}
3353 
3354 	/* Mark disabled channels as occupied */
3355 	for (i = 0; base->plat_data->disabled_channels[i] != -1; i++) {
3356 		int chan = base->plat_data->disabled_channels[i];
3357 
3358 		base->phy_res[chan].allocated_src = D40_ALLOC_PHY;
3359 		base->phy_res[chan].allocated_dst = D40_ALLOC_PHY;
3360 		base->phy_res[chan].reserved = true;
3361 		gcc |= D40_DREG_GCC_EVTGRP_ENA(d40_phy_to_group(base, chan),
3362 					       D40_DREG_GCC_SRC);
3363 		gcc |= D40_DREG_GCC_EVTGRP_ENA(d40_phy_to_group(base, chan),
3364 					       D40_DREG_GCC_DST);
3365 		num_phy_chans_avail--;
3366 	}
3367 
3368 	/* Mark soft_lli channels */
3369 	for (i = 0; i < base->plat_data->num_of_soft_lli_chans; i++) {
3370 		int chan = base->plat_data->soft_lli_chans[i];
3371 
3372 		base->phy_res[chan].use_soft_lli = true;
3373 	}
3374 
3375 	dev_info(base->dev, "%d of %d physical DMA channels available\n",
3376 		 num_phy_chans_avail, base->num_phy_chans);
3377 
3378 	/* Verify settings extended vs standard */
3379 	val[0] = readl(base->virtbase + D40_DREG_PRTYP);
3380 
3381 	for (i = 0; i < base->num_phy_chans; i++) {
3382 
3383 		if (base->phy_res[i].allocated_src == D40_ALLOC_FREE &&
3384 		    (val[0] & 0x3) != 1)
3385 			dev_info(base->dev,
3386 				 "[%s] INFO: channel %d is misconfigured (%d)\n",
3387 				 __func__, i, val[0] & 0x3);
3388 
3389 		val[0] = val[0] >> 2;
3390 	}
3391 
3392 	/*
3393 	 * To keep things simple, Enable all clocks initially.
3394 	 * The clocks will get managed later post channel allocation.
3395 	 * The clocks for the event lines on which reserved channels exists
3396 	 * are not managed here.
3397 	 */
3398 	writel(D40_DREG_GCC_ENABLE_ALL, base->virtbase + D40_DREG_GCC);
3399 	base->gcc_pwr_off_mask = gcc;
3400 
3401 	return num_phy_chans_avail;
3402 }
3403 
3404 /* Called from the registered devm action */
3405 static void d40_drop_kmem_cache_action(void *d)
3406 {
3407 	struct kmem_cache *desc_slab = d;
3408 
3409 	kmem_cache_destroy(desc_slab);
3410 }
3411 
3412 static int __init d40_hw_detect_init(struct platform_device *pdev,
3413 				     struct d40_base **retbase)
3414 {
3415 	struct stedma40_platform_data *plat_data = dev_get_platdata(&pdev->dev);
3416 	struct device *dev = &pdev->dev;
3417 	struct clk *clk;
3418 	void __iomem *virtbase;
3419 	struct d40_base *base;
3420 	size_t alloc_size;
3421 	int num_log_chans;
3422 	int num_phy_chans;
3423 	int num_memcpy_chans;
3424 	int i;
3425 	u32 pid;
3426 	u32 cid;
3427 	u8 rev;
3428 	int ret;
3429 
3430 	clk = devm_clk_get_enabled(dev, NULL);
3431 	if (IS_ERR(clk))
3432 		return PTR_ERR(clk);
3433 
3434 	/* Get IO for DMAC base address */
3435 	virtbase = devm_platform_ioremap_resource_byname(pdev, "base");
3436 	if (IS_ERR(virtbase))
3437 		return PTR_ERR(virtbase);
3438 
3439 	/* This is just a regular AMBA PrimeCell ID actually */
3440 	for (pid = 0, i = 0; i < 4; i++)
3441 		pid |= (readl(virtbase + SZ_4K - 0x20 + 4 * i)
3442 			& 255) << (i * 8);
3443 	for (cid = 0, i = 0; i < 4; i++)
3444 		cid |= (readl(virtbase + SZ_4K - 0x10 + 4 * i)
3445 			& 255) << (i * 8);
3446 
3447 	if (cid != AMBA_CID) {
3448 		d40_err(dev, "Unknown hardware! No PrimeCell ID\n");
3449 		return -EINVAL;
3450 	}
3451 	if (AMBA_MANF_BITS(pid) != AMBA_VENDOR_ST) {
3452 		d40_err(dev, "Unknown designer! Got %x wanted %x\n",
3453 			AMBA_MANF_BITS(pid),
3454 			AMBA_VENDOR_ST);
3455 		return -EINVAL;
3456 	}
3457 	/*
3458 	 * HW revision:
3459 	 * DB8500ed has revision 0
3460 	 * ? has revision 1
3461 	 * DB8500v1 has revision 2
3462 	 * DB8500v2 has revision 3
3463 	 * AP9540v1 has revision 4
3464 	 * DB8540v1 has revision 4
3465 	 */
3466 	rev = AMBA_REV_BITS(pid);
3467 	if (rev < 2) {
3468 		d40_err(dev, "hardware revision: %d is not supported", rev);
3469 		return -EINVAL;
3470 	}
3471 
3472 	/* The number of physical channels on this HW */
3473 	if (plat_data->num_of_phy_chans)
3474 		num_phy_chans = plat_data->num_of_phy_chans;
3475 	else
3476 		num_phy_chans = 4 * (readl(virtbase + D40_DREG_ICFG) & 0x7) + 4;
3477 
3478 	num_phy_chans = min(num_phy_chans, STEDMA40_MAX_PHYS);
3479 
3480 	for (i = 0; plat_data->disabled_channels[i] != -1; i++) {
3481 		int chan = plat_data->disabled_channels[i];
3482 
3483 		if (chan < 0 || chan >= num_phy_chans) {
3484 			dev_err(dev, "Invalid disabled channel %d\n", chan);
3485 			return -EINVAL;
3486 		}
3487 	}
3488 
3489 	/* The number of channels used for memcpy */
3490 	num_memcpy_chans = plat_data->num_of_memcpy_chans;
3491 	num_log_chans = num_phy_chans * D40_MAX_LOG_CHAN_PER_PHY;
3492 
3493 	dev_info(dev,
3494 		 "hardware rev: %d with %d physical and %d logical channels\n",
3495 		 rev, num_phy_chans, num_log_chans);
3496 
3497 	alloc_size = struct_size(base, phy_chans, num_phy_chans);
3498 	alloc_size += sizeof(*base->log_chans) * (num_log_chans + num_memcpy_chans);
3499 	base = devm_kzalloc(dev, alloc_size, GFP_KERNEL);
3500 
3501 	if (!base)
3502 		return -ENOMEM;
3503 
3504 	base->rev = rev;
3505 	base->clk = clk;
3506 	base->num_memcpy_chans = num_memcpy_chans;
3507 	base->num_phy_chans = num_phy_chans;
3508 	base->num_log_chans = num_log_chans;
3509 	base->virtbase = virtbase;
3510 	base->plat_data = plat_data;
3511 	base->dev = dev;
3512 	base->log_chans = &base->phy_chans[num_phy_chans];
3513 
3514 	if (base->plat_data->num_of_phy_chans == 14) {
3515 		base->gen_dmac.num_event_groups = D40_EVENT_GROUPS_V4B;
3516 		base->gen_dmac.backup = d40_backup_regs_v4b;
3517 		base->gen_dmac.backup_size = BACKUP_REGS_SZ_V4B;
3518 		base->gen_dmac.interrupt_en = D40_DREG_CPCMIS;
3519 		base->gen_dmac.interrupt_clear = D40_DREG_CPCICR;
3520 		base->gen_dmac.realtime_en = D40_DREG_CRSEG1;
3521 		base->gen_dmac.realtime_clear = D40_DREG_CRCEG1;
3522 		base->gen_dmac.high_prio_en = D40_DREG_CPSEG1;
3523 		base->gen_dmac.high_prio_clear = D40_DREG_CPCEG1;
3524 		base->gen_dmac.il = il_v4b;
3525 		base->gen_dmac.il_size = ARRAY_SIZE(il_v4b);
3526 		base->gen_dmac.init_reg = dma_init_reg_v4b;
3527 		base->gen_dmac.init_reg_size = ARRAY_SIZE(dma_init_reg_v4b);
3528 	} else {
3529 		base->gen_dmac.num_event_groups = D40_EVENT_GROUPS_V4A;
3530 		if (base->rev >= 3) {
3531 			base->gen_dmac.backup = d40_backup_regs_v4a;
3532 			base->gen_dmac.backup_size = BACKUP_REGS_SZ_V4A;
3533 		}
3534 		base->gen_dmac.interrupt_en = D40_DREG_PCMIS;
3535 		base->gen_dmac.interrupt_clear = D40_DREG_PCICR;
3536 		base->gen_dmac.realtime_en = D40_DREG_RSEG1;
3537 		base->gen_dmac.realtime_clear = D40_DREG_RCEG1;
3538 		base->gen_dmac.high_prio_en = D40_DREG_PSEG1;
3539 		base->gen_dmac.high_prio_clear = D40_DREG_PCEG1;
3540 		base->gen_dmac.il = il_v4a;
3541 		base->gen_dmac.il_size = ARRAY_SIZE(il_v4a);
3542 		base->gen_dmac.init_reg = dma_init_reg_v4a;
3543 		base->gen_dmac.init_reg_size = ARRAY_SIZE(dma_init_reg_v4a);
3544 	}
3545 
3546 	base->phy_res = devm_kcalloc(dev, num_phy_chans,
3547 				     sizeof(*base->phy_res),
3548 				     GFP_KERNEL);
3549 	if (!base->phy_res)
3550 		return -ENOMEM;
3551 
3552 	base->lookup_phy_chans = devm_kcalloc(dev, num_phy_chans,
3553 					      sizeof(*base->lookup_phy_chans),
3554 					      GFP_KERNEL);
3555 	if (!base->lookup_phy_chans)
3556 		return -ENOMEM;
3557 
3558 	base->lookup_log_chans = devm_kcalloc(dev, num_log_chans,
3559 					      sizeof(*base->lookup_log_chans),
3560 					      GFP_KERNEL);
3561 	if (!base->lookup_log_chans)
3562 		return -ENOMEM;
3563 
3564 	base->reg_val_backup_chan = devm_kmalloc_array(dev, base->num_phy_chans,
3565 						  sizeof(d40_backup_regs_chan),
3566 						  GFP_KERNEL);
3567 	if (!base->reg_val_backup_chan)
3568 		return -ENOMEM;
3569 
3570 	base->lcla_pool.alloc_map = devm_kcalloc(dev, num_phy_chans
3571 					    * D40_LCLA_LINK_PER_EVENT_GRP,
3572 					    sizeof(*base->lcla_pool.alloc_map),
3573 					    GFP_KERNEL);
3574 	if (!base->lcla_pool.alloc_map)
3575 		return -ENOMEM;
3576 
3577 	base->regs_interrupt = devm_kmalloc_array(dev, base->gen_dmac.il_size,
3578 					     sizeof(*base->regs_interrupt),
3579 					     GFP_KERNEL);
3580 	if (!base->regs_interrupt)
3581 		return -ENOMEM;
3582 
3583 	base->desc_slab = kmem_cache_create(D40_NAME, sizeof(struct d40_desc),
3584 					    0, SLAB_HWCACHE_ALIGN,
3585 					    NULL);
3586 	if (!base->desc_slab)
3587 		return -ENOMEM;
3588 
3589 	ret = devm_add_action_or_reset(dev, d40_drop_kmem_cache_action,
3590 				       base->desc_slab);
3591 	if (ret)
3592 		return ret;
3593 
3594 	*retbase = base;
3595 
3596 	return 0;
3597 }
3598 
3599 static void __init d40_hw_init(struct d40_base *base)
3600 {
3601 
3602 	int i;
3603 	u32 prmseo[2] = {0, 0};
3604 	u32 activeo[2] = {0xFFFFFFFF, 0xFFFFFFFF};
3605 	u32 pcmis = 0;
3606 	u32 pcicr = 0;
3607 	struct d40_reg_val *dma_init_reg = base->gen_dmac.init_reg;
3608 	u32 reg_size = base->gen_dmac.init_reg_size;
3609 
3610 	for (i = 0; i < reg_size; i++)
3611 		writel(dma_init_reg[i].val,
3612 		       base->virtbase + dma_init_reg[i].reg);
3613 
3614 	/* Configure all our dma channels to default settings */
3615 	for (i = 0; i < base->num_phy_chans; i++) {
3616 
3617 		activeo[i % 2] = activeo[i % 2] << 2;
3618 
3619 		if (base->phy_res[base->num_phy_chans - i - 1].allocated_src
3620 		    == D40_ALLOC_PHY) {
3621 			activeo[i % 2] |= 3;
3622 			continue;
3623 		}
3624 
3625 		/* Enable interrupt # */
3626 		pcmis = (pcmis << 1) | 1;
3627 
3628 		/* Clear interrupt # */
3629 		pcicr = (pcicr << 1) | 1;
3630 
3631 		/* Set channel to physical mode */
3632 		prmseo[i % 2] = prmseo[i % 2] << 2;
3633 		prmseo[i % 2] |= 1;
3634 
3635 	}
3636 
3637 	writel(prmseo[1], base->virtbase + D40_DREG_PRMSE);
3638 	writel(prmseo[0], base->virtbase + D40_DREG_PRMSO);
3639 	writel(activeo[1], base->virtbase + D40_DREG_ACTIVE);
3640 	writel(activeo[0], base->virtbase + D40_DREG_ACTIVO);
3641 
3642 	/* Write which interrupt to enable */
3643 	writel(pcmis, base->virtbase + base->gen_dmac.interrupt_en);
3644 
3645 	/* Write which interrupt to clear */
3646 	writel(pcicr, base->virtbase + base->gen_dmac.interrupt_clear);
3647 
3648 	/* These are __initdata and cannot be accessed after init */
3649 	base->gen_dmac.init_reg = NULL;
3650 	base->gen_dmac.init_reg_size = 0;
3651 }
3652 
3653 static int __init d40_lcla_allocate(struct d40_base *base)
3654 {
3655 	struct d40_lcla_pool *pool = &base->lcla_pool;
3656 	size_t lcla_size = SZ_1K * base->num_phy_chans;
3657 	unsigned long *page_list;
3658 	int i, j;
3659 	int ret;
3660 
3661 	/*
3662 	 * This is somewhat ugly. We need 8192 bytes that are 18 bit aligned,
3663 	 * To full fill this hardware requirement without wasting 256 kb
3664 	 * we allocate pages until we get an aligned one.
3665 	 */
3666 	page_list = kmalloc_array(MAX_LCLA_ALLOC_ATTEMPTS,
3667 				  sizeof(*page_list),
3668 				  GFP_KERNEL);
3669 	if (!page_list)
3670 		return -ENOMEM;
3671 
3672 	base->lcla_pool.alloc_order = get_order(lcla_size);
3673 
3674 	for (i = 0; i < MAX_LCLA_ALLOC_ATTEMPTS; i++) {
3675 		page_list[i] = __get_free_pages(GFP_KERNEL,
3676 						base->lcla_pool.alloc_order);
3677 		if (!page_list[i]) {
3678 
3679 			d40_err(base->dev, "Failed to allocate %zu bytes.\n",
3680 				lcla_size);
3681 			ret = -ENOMEM;
3682 
3683 			for (j = 0; j < i; j++)
3684 				free_pages(page_list[j],
3685 					   base->lcla_pool.alloc_order);
3686 			goto free_page_list;
3687 		}
3688 
3689 		if ((virt_to_phys((void *)page_list[i]) &
3690 		     (LCLA_ALIGNMENT - 1)) == 0)
3691 			break;
3692 	}
3693 
3694 	for (j = 0; j < i; j++)
3695 		free_pages(page_list[j], base->lcla_pool.alloc_order);
3696 
3697 	if (i < MAX_LCLA_ALLOC_ATTEMPTS) {
3698 		base->lcla_pool.base = (void *)page_list[i];
3699 	} else {
3700 		/*
3701 		 * After many attempts and no success with finding the correct
3702 		 * alignment, try with allocating a big buffer.
3703 		 */
3704 		dev_warn(base->dev,
3705 			 "[%s] Failed to get %zu bytes @ 18 bit align.\n",
3706 			 __func__, lcla_size);
3707 		base->lcla_pool.base_unaligned = kmalloc(lcla_size +
3708 							 LCLA_ALIGNMENT,
3709 							 GFP_KERNEL);
3710 		if (!base->lcla_pool.base_unaligned) {
3711 			ret = -ENOMEM;
3712 			goto free_page_list;
3713 		}
3714 
3715 		base->lcla_pool.base = PTR_ALIGN(base->lcla_pool.base_unaligned,
3716 						 LCLA_ALIGNMENT);
3717 	}
3718 
3719 	pool->dma_addr = dma_map_single(base->dev, pool->base, lcla_size,
3720 					DMA_TO_DEVICE);
3721 	if (dma_mapping_error(base->dev, pool->dma_addr)) {
3722 		pool->dma_addr = 0;
3723 		ret = -ENOMEM;
3724 		goto free_page_list;
3725 	}
3726 
3727 	writel(virt_to_phys(base->lcla_pool.base),
3728 	       base->virtbase + D40_DREG_LCLA);
3729 	ret = 0;
3730  free_page_list:
3731 	kfree(page_list);
3732 	return ret;
3733 }
3734 
3735 static int __init d40_of_probe(struct device *dev,
3736 			       struct device_node *np)
3737 {
3738 	struct stedma40_platform_data *pdata;
3739 	int num_phy = 0, num_memcpy = 0, num_disabled = 0;
3740 	const __be32 *list;
3741 	int ret;
3742 
3743 	pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
3744 	if (!pdata)
3745 		return -ENOMEM;
3746 
3747 	/* If absent this value will be obtained from h/w. */
3748 	of_property_read_u32(np, "dma-channels", &num_phy);
3749 	if (num_phy > 0)
3750 		pdata->num_of_phy_chans = num_phy;
3751 
3752 	list = of_get_property(np, "memcpy-channels", &num_memcpy);
3753 	num_memcpy /= sizeof(*list);
3754 
3755 	if (num_memcpy > ARRAY_SIZE(pdata->memcpy_channels) ||
3756 	    num_memcpy <= 0) {
3757 		d40_err(dev,
3758 			"Invalid number of memcpy channels specified (%d)\n",
3759 			num_memcpy);
3760 		return -EINVAL;
3761 	}
3762 	ret = of_property_read_u32_array(np, "memcpy-channels",
3763 					 pdata->memcpy_channels, num_memcpy);
3764 	if (ret)
3765 		return ret;
3766 	pdata->num_of_memcpy_chans = num_memcpy;
3767 
3768 	list = of_get_property(np, "disabled-channels", &num_disabled);
3769 	num_disabled /= sizeof(*list);
3770 
3771 	if (num_disabled >= STEDMA40_MAX_PHYS || num_disabled < 0) {
3772 		d40_err(dev,
3773 			"Invalid number of disabled channels specified (%d)\n",
3774 			num_disabled);
3775 		return -EINVAL;
3776 	}
3777 
3778 	of_property_read_u32_array(np, "disabled-channels",
3779 				   pdata->disabled_channels,
3780 				   num_disabled);
3781 	pdata->disabled_channels[num_disabled] = -1;
3782 
3783 	dev->platform_data = pdata;
3784 
3785 	return 0;
3786 }
3787 
3788 static int __init d40_probe(struct platform_device *pdev)
3789 {
3790 	struct device *dev = &pdev->dev;
3791 	struct device_node *np = pdev->dev.of_node;
3792 	struct device_node *np_lcpa;
3793 	struct d40_base *base;
3794 	struct resource *res;
3795 	struct resource res_lcpa;
3796 	void *dmaenginem_reg_group;
3797 	int num_reserved_chans;
3798 	u32 val;
3799 	int ret;
3800 
3801 	if (d40_of_probe(dev, np)) {
3802 		ret = -ENOMEM;
3803 		goto report_failure;
3804 	}
3805 
3806 	ret = d40_hw_detect_init(pdev, &base);
3807 	if (ret)
3808 		goto report_failure;
3809 
3810 	num_reserved_chans = d40_phy_res_init(base);
3811 
3812 	platform_set_drvdata(pdev, base);
3813 
3814 	spin_lock_init(&base->interrupt_lock);
3815 	spin_lock_init(&base->execmd_lock);
3816 
3817 	/* Get IO for logical channel parameter address (LCPA) */
3818 	np_lcpa = of_parse_phandle(np, "sram", 0);
3819 	if (!np_lcpa) {
3820 		dev_err(dev, "no LCPA SRAM node\n");
3821 		ret = -EINVAL;
3822 		goto report_failure;
3823 	}
3824 	/* This is no device so read the address directly from the node */
3825 	ret = of_address_to_resource(np_lcpa, 0, &res_lcpa);
3826 	of_node_put(np_lcpa);
3827 	if (ret) {
3828 		dev_err(dev, "no LCPA SRAM resource\n");
3829 		goto report_failure;
3830 	}
3831 	base->lcpa_size = resource_size(&res_lcpa);
3832 	base->phy_lcpa = res_lcpa.start;
3833 	dev_info(dev, "found LCPA SRAM at %pad, size %pa\n",
3834 		 &base->phy_lcpa, &base->lcpa_size);
3835 
3836 	/* We make use of ESRAM memory for this. */
3837 	val = readl(base->virtbase + D40_DREG_LCPA);
3838 	if (base->phy_lcpa != val && val != 0) {
3839 		dev_warn(dev,
3840 			 "[%s] Mismatch LCPA dma 0x%x, def %08x\n",
3841 			 __func__, val, (u32)base->phy_lcpa);
3842 	} else
3843 		writel(base->phy_lcpa, base->virtbase + D40_DREG_LCPA);
3844 
3845 	base->lcpa_base = devm_ioremap(dev, base->phy_lcpa, base->lcpa_size);
3846 	if (!base->lcpa_base) {
3847 		ret = -ENOMEM;
3848 		d40_err(dev, "Failed to ioremap LCPA region\n");
3849 		goto report_failure;
3850 	}
3851 	/* If lcla has to be located in ESRAM we don't need to allocate */
3852 	if (base->plat_data->use_esram_lcla) {
3853 		res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
3854 							"lcla_esram");
3855 		if (!res) {
3856 			ret = -ENOENT;
3857 			d40_err(dev,
3858 				"No \"lcla_esram\" memory resource\n");
3859 			goto report_failure;
3860 		}
3861 		base->lcla_pool.base = devm_ioremap(dev, res->start,
3862 						    resource_size(res));
3863 		if (!base->lcla_pool.base) {
3864 			ret = -ENOMEM;
3865 			d40_err(dev, "Failed to ioremap LCLA region\n");
3866 			goto report_failure;
3867 		}
3868 		writel(res->start, base->virtbase + D40_DREG_LCLA);
3869 
3870 	} else {
3871 		ret = d40_lcla_allocate(base);
3872 		if (ret) {
3873 			d40_err(dev, "Failed to allocate LCLA area\n");
3874 			goto destroy_cache;
3875 		}
3876 	}
3877 
3878 	spin_lock_init(&base->lcla_pool.lock);
3879 
3880 	base->irq = platform_get_irq(pdev, 0);
3881 	if (base->irq < 0) {
3882 		ret = base->irq;
3883 		goto destroy_cache;
3884 	}
3885 
3886 	if (base->plat_data->use_esram_lcla) {
3887 
3888 		base->lcpa_regulator = regulator_get(base->dev, "lcla_esram");
3889 		if (IS_ERR(base->lcpa_regulator)) {
3890 			d40_err(dev, "Failed to get lcpa_regulator\n");
3891 			ret = PTR_ERR(base->lcpa_regulator);
3892 			base->lcpa_regulator = NULL;
3893 			goto destroy_cache;
3894 		}
3895 
3896 		ret = regulator_enable(base->lcpa_regulator);
3897 		if (ret) {
3898 			d40_err(dev,
3899 				"Failed to enable lcpa_regulator\n");
3900 			regulator_put(base->lcpa_regulator);
3901 			base->lcpa_regulator = NULL;
3902 			goto destroy_cache;
3903 		}
3904 	}
3905 
3906 	writel_relaxed(D40_DREG_GCC_ENABLE_ALL, base->virtbase + D40_DREG_GCC);
3907 
3908 	pm_runtime_irq_safe(base->dev);
3909 	pm_runtime_set_autosuspend_delay(base->dev, DMA40_AUTOSUSPEND_DELAY);
3910 	pm_runtime_mark_last_busy(base->dev);
3911 
3912 	ret = devm_pm_runtime_set_active_enabled(base->dev);
3913 	if (ret) {
3914 		d40_err(dev, "Failed to enable runtime PM: %d\n", ret);
3915 		goto destroy_cache;
3916 	}
3917 	pm_runtime_use_autosuspend(base->dev);
3918 
3919 	dma_set_max_seg_size(base->dev, STEDMA40_MAX_SEG_SIZE);
3920 
3921 	d40_hw_init(base);
3922 
3923 	ret = request_irq(base->irq, d40_handle_interrupt, 0, D40_NAME, base);
3924 	if (ret) {
3925 		d40_err(dev, "No IRQ defined\n");
3926 		goto destroy_cache;
3927 	}
3928 
3929 	dmaenginem_reg_group = devres_open_group(dev, NULL, GFP_KERNEL);
3930 	if (!dmaenginem_reg_group) {
3931 		ret = -ENOMEM;
3932 		goto release_irq;
3933 	}
3934 
3935 	ret = d40_dmaengine_init(base, num_reserved_chans);
3936 	if (ret)
3937 		goto release_dmaenginem;
3938 
3939 	ret = of_dma_controller_register(np, d40_xlate, NULL);
3940 	if (ret) {
3941 		dev_err(dev,
3942 			"could not register of_dma_controller\n");
3943 		goto release_dmaenginem;
3944 	}
3945 	devres_remove_group(dev, dmaenginem_reg_group);
3946 
3947 	dev_info(base->dev, "initialized\n");
3948 	return 0;
3949 
3950  release_dmaenginem:
3951 	free_irq(base->irq, base);
3952 	devres_release_group(dev, dmaenginem_reg_group);
3953 	goto destroy_cache;
3954  release_irq:
3955 	free_irq(base->irq, base);
3956  destroy_cache:
3957 	if (base->lcla_pool.dma_addr)
3958 		dma_unmap_single(base->dev, base->lcla_pool.dma_addr,
3959 				 SZ_1K * base->num_phy_chans,
3960 				 DMA_TO_DEVICE);
3961 
3962 	if (!base->plat_data->use_esram_lcla &&
3963 	    !base->lcla_pool.base_unaligned && base->lcla_pool.base)
3964 		free_pages((unsigned long)base->lcla_pool.base,
3965 			   base->lcla_pool.alloc_order);
3966 
3967 	kfree(base->lcla_pool.base_unaligned);
3968 
3969 	if (base->lcpa_regulator) {
3970 		regulator_disable(base->lcpa_regulator);
3971 		regulator_put(base->lcpa_regulator);
3972 	}
3973 
3974  report_failure:
3975 	d40_err(dev, "probe failed\n");
3976 	return ret;
3977 }
3978 
3979 static const struct of_device_id d40_match[] = {
3980         { .compatible = "stericsson,dma40", },
3981         {}
3982 };
3983 
3984 static struct platform_driver d40_driver = {
3985 	.driver = {
3986 		.name  = D40_NAME,
3987 		.pm = &dma40_pm_ops,
3988 		.of_match_table = d40_match,
3989 	},
3990 };
3991 
3992 static int __init stedma40_init(void)
3993 {
3994 	return platform_driver_probe(&d40_driver, d40_probe);
3995 }
3996 subsys_initcall(stedma40_init);
3997