x86/aperfmperf: Restructure arch_scale_freq_tick()
[platform/kernel/linux-starfive.git] / drivers / dma / imx-sdma.c
1 // SPDX-License-Identifier: GPL-2.0+
2 //
3 // drivers/dma/imx-sdma.c
4 //
5 // This file contains a driver for the Freescale Smart DMA engine
6 //
7 // Copyright 2010 Sascha Hauer, Pengutronix <s.hauer@pengutronix.de>
8 //
9 // Based on code from Freescale:
10 //
11 // Copyright 2004-2009 Freescale Semiconductor, Inc. All Rights Reserved.
12
13 #include <linux/init.h>
14 #include <linux/iopoll.h>
15 #include <linux/module.h>
16 #include <linux/types.h>
17 #include <linux/bitops.h>
18 #include <linux/mm.h>
19 #include <linux/interrupt.h>
20 #include <linux/clk.h>
21 #include <linux/delay.h>
22 #include <linux/sched.h>
23 #include <linux/semaphore.h>
24 #include <linux/spinlock.h>
25 #include <linux/device.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/firmware.h>
28 #include <linux/slab.h>
29 #include <linux/platform_device.h>
30 #include <linux/dmaengine.h>
31 #include <linux/of.h>
32 #include <linux/of_address.h>
33 #include <linux/of_device.h>
34 #include <linux/of_dma.h>
35 #include <linux/workqueue.h>
36
37 #include <asm/irq.h>
38 #include <linux/platform_data/dma-imx.h>
39 #include <linux/regmap.h>
40 #include <linux/mfd/syscon.h>
41 #include <linux/mfd/syscon/imx6q-iomuxc-gpr.h>
42
43 #include "dmaengine.h"
44 #include "virt-dma.h"
45
46 /* SDMA registers */
47 #define SDMA_H_C0PTR            0x000
48 #define SDMA_H_INTR             0x004
49 #define SDMA_H_STATSTOP         0x008
50 #define SDMA_H_START            0x00c
51 #define SDMA_H_EVTOVR           0x010
52 #define SDMA_H_DSPOVR           0x014
53 #define SDMA_H_HOSTOVR          0x018
54 #define SDMA_H_EVTPEND          0x01c
55 #define SDMA_H_DSPENBL          0x020
56 #define SDMA_H_RESET            0x024
57 #define SDMA_H_EVTERR           0x028
58 #define SDMA_H_INTRMSK          0x02c
59 #define SDMA_H_PSW              0x030
60 #define SDMA_H_EVTERRDBG        0x034
61 #define SDMA_H_CONFIG           0x038
62 #define SDMA_ONCE_ENB           0x040
63 #define SDMA_ONCE_DATA          0x044
64 #define SDMA_ONCE_INSTR         0x048
65 #define SDMA_ONCE_STAT          0x04c
66 #define SDMA_ONCE_CMD           0x050
67 #define SDMA_EVT_MIRROR         0x054
68 #define SDMA_ILLINSTADDR        0x058
69 #define SDMA_CHN0ADDR           0x05c
70 #define SDMA_ONCE_RTB           0x060
71 #define SDMA_XTRIG_CONF1        0x070
72 #define SDMA_XTRIG_CONF2        0x074
73 #define SDMA_CHNENBL0_IMX35     0x200
74 #define SDMA_CHNENBL0_IMX31     0x080
75 #define SDMA_CHNPRI_0           0x100
76
77 /*
78  * Buffer descriptor status values.
79  */
80 #define BD_DONE  0x01
81 #define BD_WRAP  0x02
82 #define BD_CONT  0x04
83 #define BD_INTR  0x08
84 #define BD_RROR  0x10
85 #define BD_LAST  0x20
86 #define BD_EXTD  0x80
87
88 /*
89  * Data Node descriptor status values.
90  */
91 #define DND_END_OF_FRAME  0x80
92 #define DND_END_OF_XFER   0x40
93 #define DND_DONE          0x20
94 #define DND_UNUSED        0x01
95
96 /*
97  * IPCV2 descriptor status values.
98  */
99 #define BD_IPCV2_END_OF_FRAME  0x40
100
101 #define IPCV2_MAX_NODES        50
102 /*
103  * Error bit set in the CCB status field by the SDMA,
104  * in setbd routine, in case of a transfer error
105  */
106 #define DATA_ERROR  0x10000000
107
108 /*
109  * Buffer descriptor commands.
110  */
111 #define C0_ADDR             0x01
112 #define C0_LOAD             0x02
113 #define C0_DUMP             0x03
114 #define C0_SETCTX           0x07
115 #define C0_GETCTX           0x03
116 #define C0_SETDM            0x01
117 #define C0_SETPM            0x04
118 #define C0_GETDM            0x02
119 #define C0_GETPM            0x08
120 /*
121  * Change endianness indicator in the BD command field
122  */
123 #define CHANGE_ENDIANNESS   0x80
124
125 /*
126  *  p_2_p watermark_level description
127  *      Bits            Name                    Description
128  *      0-7             Lower WML               Lower watermark level
129  *      8               PS                      1: Pad Swallowing
130  *                                              0: No Pad Swallowing
131  *      9               PA                      1: Pad Adding
132  *                                              0: No Pad Adding
133  *      10              SPDIF                   If this bit is set both source
134  *                                              and destination are on SPBA
135  *      11              Source Bit(SP)          1: Source on SPBA
136  *                                              0: Source on AIPS
137  *      12              Destination Bit(DP)     1: Destination on SPBA
138  *                                              0: Destination on AIPS
139  *      13-15           ---------               MUST BE 0
140  *      16-23           Higher WML              HWML
141  *      24-27           N                       Total number of samples after
142  *                                              which Pad adding/Swallowing
143  *                                              must be done. It must be odd.
144  *      28              Lower WML Event(LWE)    SDMA events reg to check for
145  *                                              LWML event mask
146  *                                              0: LWE in EVENTS register
147  *                                              1: LWE in EVENTS2 register
148  *      29              Higher WML Event(HWE)   SDMA events reg to check for
149  *                                              HWML event mask
150  *                                              0: HWE in EVENTS register
151  *                                              1: HWE in EVENTS2 register
152  *      30              ---------               MUST BE 0
153  *      31              CONT                    1: Amount of samples to be
154  *                                              transferred is unknown and
155  *                                              script will keep on
156  *                                              transferring samples as long as
157  *                                              both events are detected and
158  *                                              script must be manually stopped
159  *                                              by the application
160  *                                              0: The amount of samples to be
161  *                                              transferred is equal to the
162  *                                              count field of mode word
163  */
164 #define SDMA_WATERMARK_LEVEL_LWML       0xFF
165 #define SDMA_WATERMARK_LEVEL_PS         BIT(8)
166 #define SDMA_WATERMARK_LEVEL_PA         BIT(9)
167 #define SDMA_WATERMARK_LEVEL_SPDIF      BIT(10)
168 #define SDMA_WATERMARK_LEVEL_SP         BIT(11)
169 #define SDMA_WATERMARK_LEVEL_DP         BIT(12)
170 #define SDMA_WATERMARK_LEVEL_HWML       (0xFF << 16)
171 #define SDMA_WATERMARK_LEVEL_LWE        BIT(28)
172 #define SDMA_WATERMARK_LEVEL_HWE        BIT(29)
173 #define SDMA_WATERMARK_LEVEL_CONT       BIT(31)
174
175 #define SDMA_DMA_BUSWIDTHS      (BIT(DMA_SLAVE_BUSWIDTH_1_BYTE) | \
176                                  BIT(DMA_SLAVE_BUSWIDTH_2_BYTES) | \
177                                  BIT(DMA_SLAVE_BUSWIDTH_4_BYTES))
178
179 #define SDMA_DMA_DIRECTIONS     (BIT(DMA_DEV_TO_MEM) | \
180                                  BIT(DMA_MEM_TO_DEV) | \
181                                  BIT(DMA_DEV_TO_DEV))
182
183 /**
184  * struct sdma_script_start_addrs - SDMA script start pointers
185  *
186  * start addresses of the different functions in the physical
187  * address space of the SDMA engine.
188  */
189 struct sdma_script_start_addrs {
190         s32 ap_2_ap_addr;
191         s32 ap_2_bp_addr;
192         s32 ap_2_ap_fixed_addr;
193         s32 bp_2_ap_addr;
194         s32 loopback_on_dsp_side_addr;
195         s32 mcu_interrupt_only_addr;
196         s32 firi_2_per_addr;
197         s32 firi_2_mcu_addr;
198         s32 per_2_firi_addr;
199         s32 mcu_2_firi_addr;
200         s32 uart_2_per_addr;
201         s32 uart_2_mcu_ram_addr;
202         s32 per_2_app_addr;
203         s32 mcu_2_app_addr;
204         s32 per_2_per_addr;
205         s32 uartsh_2_per_addr;
206         s32 uartsh_2_mcu_ram_addr;
207         s32 per_2_shp_addr;
208         s32 mcu_2_shp_addr;
209         s32 ata_2_mcu_addr;
210         s32 mcu_2_ata_addr;
211         s32 app_2_per_addr;
212         s32 app_2_mcu_addr;
213         s32 shp_2_per_addr;
214         s32 shp_2_mcu_addr;
215         s32 mshc_2_mcu_addr;
216         s32 mcu_2_mshc_addr;
217         s32 spdif_2_mcu_addr;
218         s32 mcu_2_spdif_addr;
219         s32 asrc_2_mcu_addr;
220         s32 ext_mem_2_ipu_addr;
221         s32 descrambler_addr;
222         s32 dptc_dvfs_addr;
223         s32 utra_addr;
224         s32 ram_code_start_addr;
225         /* End of v1 array */
226         s32 mcu_2_ssish_addr;
227         s32 ssish_2_mcu_addr;
228         s32 hdmi_dma_addr;
229         /* End of v2 array */
230         s32 zcanfd_2_mcu_addr;
231         s32 zqspi_2_mcu_addr;
232         s32 mcu_2_ecspi_addr;
233         s32 mcu_2_sai_addr;
234         s32 sai_2_mcu_addr;
235         s32 uart_2_mcu_addr;
236         s32 uartsh_2_mcu_addr;
237         /* End of v3 array */
238         s32 mcu_2_zqspi_addr;
239         /* End of v4 array */
240 };
241
242 /*
243  * Mode/Count of data node descriptors - IPCv2
244  */
245 struct sdma_mode_count {
246 #define SDMA_BD_MAX_CNT 0xffff
247         u32 count   : 16; /* size of the buffer pointed by this BD */
248         u32 status  :  8; /* E,R,I,C,W,D status bits stored here */
249         u32 command :  8; /* command mostly used for channel 0 */
250 };
251
252 /*
253  * Buffer descriptor
254  */
255 struct sdma_buffer_descriptor {
256         struct sdma_mode_count  mode;
257         u32 buffer_addr;        /* address of the buffer described */
258         u32 ext_buffer_addr;    /* extended buffer address */
259 } __attribute__ ((packed));
260
261 /**
262  * struct sdma_channel_control - Channel control Block
263  *
264  * @current_bd_ptr:     current buffer descriptor processed
265  * @base_bd_ptr:        first element of buffer descriptor array
266  * @unused:             padding. The SDMA engine expects an array of 128 byte
267  *                      control blocks
268  */
269 struct sdma_channel_control {
270         u32 current_bd_ptr;
271         u32 base_bd_ptr;
272         u32 unused[2];
273 } __attribute__ ((packed));
274
275 /**
276  * struct sdma_state_registers - SDMA context for a channel
277  *
278  * @pc:         program counter
279  * @unused1:    unused
280  * @t:          test bit: status of arithmetic & test instruction
281  * @rpc:        return program counter
282  * @unused0:    unused
283  * @sf:         source fault while loading data
284  * @spc:        loop start program counter
285  * @unused2:    unused
286  * @df:         destination fault while storing data
287  * @epc:        loop end program counter
288  * @lm:         loop mode
289  */
290 struct sdma_state_registers {
291         u32 pc     :14;
292         u32 unused1: 1;
293         u32 t      : 1;
294         u32 rpc    :14;
295         u32 unused0: 1;
296         u32 sf     : 1;
297         u32 spc    :14;
298         u32 unused2: 1;
299         u32 df     : 1;
300         u32 epc    :14;
301         u32 lm     : 2;
302 } __attribute__ ((packed));
303
304 /**
305  * struct sdma_context_data - sdma context specific to a channel
306  *
307  * @channel_state:      channel state bits
308  * @gReg:               general registers
309  * @mda:                burst dma destination address register
310  * @msa:                burst dma source address register
311  * @ms:                 burst dma status register
312  * @md:                 burst dma data register
313  * @pda:                peripheral dma destination address register
314  * @psa:                peripheral dma source address register
315  * @ps:                 peripheral dma status register
316  * @pd:                 peripheral dma data register
317  * @ca:                 CRC polynomial register
318  * @cs:                 CRC accumulator register
319  * @dda:                dedicated core destination address register
320  * @dsa:                dedicated core source address register
321  * @ds:                 dedicated core status register
322  * @dd:                 dedicated core data register
323  * @scratch0:           1st word of dedicated ram for context switch
324  * @scratch1:           2nd word of dedicated ram for context switch
325  * @scratch2:           3rd word of dedicated ram for context switch
326  * @scratch3:           4th word of dedicated ram for context switch
327  * @scratch4:           5th word of dedicated ram for context switch
328  * @scratch5:           6th word of dedicated ram for context switch
329  * @scratch6:           7th word of dedicated ram for context switch
330  * @scratch7:           8th word of dedicated ram for context switch
331  */
332 struct sdma_context_data {
333         struct sdma_state_registers  channel_state;
334         u32  gReg[8];
335         u32  mda;
336         u32  msa;
337         u32  ms;
338         u32  md;
339         u32  pda;
340         u32  psa;
341         u32  ps;
342         u32  pd;
343         u32  ca;
344         u32  cs;
345         u32  dda;
346         u32  dsa;
347         u32  ds;
348         u32  dd;
349         u32  scratch0;
350         u32  scratch1;
351         u32  scratch2;
352         u32  scratch3;
353         u32  scratch4;
354         u32  scratch5;
355         u32  scratch6;
356         u32  scratch7;
357 } __attribute__ ((packed));
358
359
360 struct sdma_engine;
361
362 /**
363  * struct sdma_desc - descriptor structor for one transfer
364  * @vd:                 descriptor for virt dma
365  * @num_bd:             number of descriptors currently handling
366  * @bd_phys:            physical address of bd
367  * @buf_tail:           ID of the buffer that was processed
368  * @buf_ptail:          ID of the previous buffer that was processed
369  * @period_len:         period length, used in cyclic.
370  * @chn_real_count:     the real count updated from bd->mode.count
371  * @chn_count:          the transfer count set
372  * @sdmac:              sdma_channel pointer
373  * @bd:                 pointer of allocate bd
374  */
375 struct sdma_desc {
376         struct virt_dma_desc    vd;
377         unsigned int            num_bd;
378         dma_addr_t              bd_phys;
379         unsigned int            buf_tail;
380         unsigned int            buf_ptail;
381         unsigned int            period_len;
382         unsigned int            chn_real_count;
383         unsigned int            chn_count;
384         struct sdma_channel     *sdmac;
385         struct sdma_buffer_descriptor *bd;
386 };
387
388 /**
389  * struct sdma_channel - housekeeping for a SDMA channel
390  *
391  * @vc:                 virt_dma base structure
392  * @desc:               sdma description including vd and other special member
393  * @sdma:               pointer to the SDMA engine for this channel
394  * @channel:            the channel number, matches dmaengine chan_id + 1
395  * @direction:          transfer type. Needed for setting SDMA script
396  * @slave_config:       Slave configuration
397  * @peripheral_type:    Peripheral type. Needed for setting SDMA script
398  * @event_id0:          aka dma request line
399  * @event_id1:          for channels that use 2 events
400  * @word_size:          peripheral access size
401  * @pc_from_device:     script address for those device_2_memory
402  * @pc_to_device:       script address for those memory_2_device
403  * @device_to_device:   script address for those device_2_device
404  * @pc_to_pc:           script address for those memory_2_memory
405  * @flags:              loop mode or not
406  * @per_address:        peripheral source or destination address in common case
407  *                      destination address in p_2_p case
408  * @per_address2:       peripheral source address in p_2_p case
409  * @event_mask:         event mask used in p_2_p script
410  * @watermark_level:    value for gReg[7], some script will extend it from
411  *                      basic watermark such as p_2_p
412  * @shp_addr:           value for gReg[6]
413  * @per_addr:           value for gReg[2]
414  * @status:             status of dma channel
415  * @context_loaded:     ensure context is only loaded once
416  * @data:               specific sdma interface structure
417  * @bd_pool:            dma_pool for bd
418  * @terminate_worker:   used to call back into terminate work function
419  */
420 struct sdma_channel {
421         struct virt_dma_chan            vc;
422         struct sdma_desc                *desc;
423         struct sdma_engine              *sdma;
424         unsigned int                    channel;
425         enum dma_transfer_direction             direction;
426         struct dma_slave_config         slave_config;
427         enum sdma_peripheral_type       peripheral_type;
428         unsigned int                    event_id0;
429         unsigned int                    event_id1;
430         enum dma_slave_buswidth         word_size;
431         unsigned int                    pc_from_device, pc_to_device;
432         unsigned int                    device_to_device;
433         unsigned int                    pc_to_pc;
434         unsigned long                   flags;
435         dma_addr_t                      per_address, per_address2;
436         unsigned long                   event_mask[2];
437         unsigned long                   watermark_level;
438         u32                             shp_addr, per_addr;
439         enum dma_status                 status;
440         struct imx_dma_data             data;
441         struct work_struct              terminate_worker;
442         struct list_head                terminated;
443         bool                            is_ram_script;
444 };
445
446 #define IMX_DMA_SG_LOOP         BIT(0)
447
448 #define MAX_DMA_CHANNELS 32
449 #define MXC_SDMA_DEFAULT_PRIORITY 1
450 #define MXC_SDMA_MIN_PRIORITY 1
451 #define MXC_SDMA_MAX_PRIORITY 7
452
453 #define SDMA_FIRMWARE_MAGIC 0x414d4453
454
455 /**
456  * struct sdma_firmware_header - Layout of the firmware image
457  *
458  * @magic:              "SDMA"
459  * @version_major:      increased whenever layout of struct
460  *                      sdma_script_start_addrs changes.
461  * @version_minor:      firmware minor version (for binary compatible changes)
462  * @script_addrs_start: offset of struct sdma_script_start_addrs in this image
463  * @num_script_addrs:   Number of script addresses in this image
464  * @ram_code_start:     offset of SDMA ram image in this firmware image
465  * @ram_code_size:      size of SDMA ram image
466  * @script_addrs:       Stores the start address of the SDMA scripts
467  *                      (in SDMA memory space)
468  */
469 struct sdma_firmware_header {
470         u32     magic;
471         u32     version_major;
472         u32     version_minor;
473         u32     script_addrs_start;
474         u32     num_script_addrs;
475         u32     ram_code_start;
476         u32     ram_code_size;
477 };
478
479 struct sdma_driver_data {
480         int chnenbl0;
481         int num_events;
482         struct sdma_script_start_addrs  *script_addrs;
483         bool check_ratio;
484         /*
485          * ecspi ERR009165 fixed should be done in sdma script
486          * and it has been fixed in soc from i.mx6ul.
487          * please get more information from the below link:
488          * https://www.nxp.com/docs/en/errata/IMX6DQCE.pdf
489          */
490         bool ecspi_fixed;
491 };
492
493 struct sdma_engine {
494         struct device                   *dev;
495         struct sdma_channel             channel[MAX_DMA_CHANNELS];
496         struct sdma_channel_control     *channel_control;
497         void __iomem                    *regs;
498         struct sdma_context_data        *context;
499         dma_addr_t                      context_phys;
500         struct dma_device               dma_device;
501         struct clk                      *clk_ipg;
502         struct clk                      *clk_ahb;
503         spinlock_t                      channel_0_lock;
504         u32                             script_number;
505         struct sdma_script_start_addrs  *script_addrs;
506         const struct sdma_driver_data   *drvdata;
507         u32                             spba_start_addr;
508         u32                             spba_end_addr;
509         unsigned int                    irq;
510         dma_addr_t                      bd0_phys;
511         struct sdma_buffer_descriptor   *bd0;
512         /* clock ratio for AHB:SDMA core. 1:1 is 1, 2:1 is 0*/
513         bool                            clk_ratio;
514         bool                            fw_loaded;
515 };
516
517 static int sdma_config_write(struct dma_chan *chan,
518                        struct dma_slave_config *dmaengine_cfg,
519                        enum dma_transfer_direction direction);
520
521 static struct sdma_driver_data sdma_imx31 = {
522         .chnenbl0 = SDMA_CHNENBL0_IMX31,
523         .num_events = 32,
524 };
525
526 static struct sdma_script_start_addrs sdma_script_imx25 = {
527         .ap_2_ap_addr = 729,
528         .uart_2_mcu_addr = 904,
529         .per_2_app_addr = 1255,
530         .mcu_2_app_addr = 834,
531         .uartsh_2_mcu_addr = 1120,
532         .per_2_shp_addr = 1329,
533         .mcu_2_shp_addr = 1048,
534         .ata_2_mcu_addr = 1560,
535         .mcu_2_ata_addr = 1479,
536         .app_2_per_addr = 1189,
537         .app_2_mcu_addr = 770,
538         .shp_2_per_addr = 1407,
539         .shp_2_mcu_addr = 979,
540 };
541
542 static struct sdma_driver_data sdma_imx25 = {
543         .chnenbl0 = SDMA_CHNENBL0_IMX35,
544         .num_events = 48,
545         .script_addrs = &sdma_script_imx25,
546 };
547
548 static struct sdma_driver_data sdma_imx35 = {
549         .chnenbl0 = SDMA_CHNENBL0_IMX35,
550         .num_events = 48,
551 };
552
553 static struct sdma_script_start_addrs sdma_script_imx51 = {
554         .ap_2_ap_addr = 642,
555         .uart_2_mcu_addr = 817,
556         .mcu_2_app_addr = 747,
557         .mcu_2_shp_addr = 961,
558         .ata_2_mcu_addr = 1473,
559         .mcu_2_ata_addr = 1392,
560         .app_2_per_addr = 1033,
561         .app_2_mcu_addr = 683,
562         .shp_2_per_addr = 1251,
563         .shp_2_mcu_addr = 892,
564 };
565
566 static struct sdma_driver_data sdma_imx51 = {
567         .chnenbl0 = SDMA_CHNENBL0_IMX35,
568         .num_events = 48,
569         .script_addrs = &sdma_script_imx51,
570 };
571
572 static struct sdma_script_start_addrs sdma_script_imx53 = {
573         .ap_2_ap_addr = 642,
574         .app_2_mcu_addr = 683,
575         .mcu_2_app_addr = 747,
576         .uart_2_mcu_addr = 817,
577         .shp_2_mcu_addr = 891,
578         .mcu_2_shp_addr = 960,
579         .uartsh_2_mcu_addr = 1032,
580         .spdif_2_mcu_addr = 1100,
581         .mcu_2_spdif_addr = 1134,
582         .firi_2_mcu_addr = 1193,
583         .mcu_2_firi_addr = 1290,
584 };
585
586 static struct sdma_driver_data sdma_imx53 = {
587         .chnenbl0 = SDMA_CHNENBL0_IMX35,
588         .num_events = 48,
589         .script_addrs = &sdma_script_imx53,
590 };
591
592 static struct sdma_script_start_addrs sdma_script_imx6q = {
593         .ap_2_ap_addr = 642,
594         .uart_2_mcu_addr = 817,
595         .mcu_2_app_addr = 747,
596         .per_2_per_addr = 6331,
597         .uartsh_2_mcu_addr = 1032,
598         .mcu_2_shp_addr = 960,
599         .app_2_mcu_addr = 683,
600         .shp_2_mcu_addr = 891,
601         .spdif_2_mcu_addr = 1100,
602         .mcu_2_spdif_addr = 1134,
603 };
604
605 static struct sdma_driver_data sdma_imx6q = {
606         .chnenbl0 = SDMA_CHNENBL0_IMX35,
607         .num_events = 48,
608         .script_addrs = &sdma_script_imx6q,
609 };
610
611 static struct sdma_driver_data sdma_imx6ul = {
612         .chnenbl0 = SDMA_CHNENBL0_IMX35,
613         .num_events = 48,
614         .script_addrs = &sdma_script_imx6q,
615         .ecspi_fixed = true,
616 };
617
618 static struct sdma_script_start_addrs sdma_script_imx7d = {
619         .ap_2_ap_addr = 644,
620         .uart_2_mcu_addr = 819,
621         .mcu_2_app_addr = 749,
622         .uartsh_2_mcu_addr = 1034,
623         .mcu_2_shp_addr = 962,
624         .app_2_mcu_addr = 685,
625         .shp_2_mcu_addr = 893,
626         .spdif_2_mcu_addr = 1102,
627         .mcu_2_spdif_addr = 1136,
628 };
629
630 static struct sdma_driver_data sdma_imx7d = {
631         .chnenbl0 = SDMA_CHNENBL0_IMX35,
632         .num_events = 48,
633         .script_addrs = &sdma_script_imx7d,
634 };
635
636 static struct sdma_driver_data sdma_imx8mq = {
637         .chnenbl0 = SDMA_CHNENBL0_IMX35,
638         .num_events = 48,
639         .script_addrs = &sdma_script_imx7d,
640         .check_ratio = 1,
641 };
642
643 static const struct of_device_id sdma_dt_ids[] = {
644         { .compatible = "fsl,imx6q-sdma", .data = &sdma_imx6q, },
645         { .compatible = "fsl,imx53-sdma", .data = &sdma_imx53, },
646         { .compatible = "fsl,imx51-sdma", .data = &sdma_imx51, },
647         { .compatible = "fsl,imx35-sdma", .data = &sdma_imx35, },
648         { .compatible = "fsl,imx31-sdma", .data = &sdma_imx31, },
649         { .compatible = "fsl,imx25-sdma", .data = &sdma_imx25, },
650         { .compatible = "fsl,imx7d-sdma", .data = &sdma_imx7d, },
651         { .compatible = "fsl,imx6ul-sdma", .data = &sdma_imx6ul, },
652         { .compatible = "fsl,imx8mq-sdma", .data = &sdma_imx8mq, },
653         { /* sentinel */ }
654 };
655 MODULE_DEVICE_TABLE(of, sdma_dt_ids);
656
657 #define SDMA_H_CONFIG_DSPDMA    BIT(12) /* indicates if the DSPDMA is used */
658 #define SDMA_H_CONFIG_RTD_PINS  BIT(11) /* indicates if Real-Time Debug pins are enabled */
659 #define SDMA_H_CONFIG_ACR       BIT(4)  /* indicates if AHB freq /core freq = 2 or 1 */
660 #define SDMA_H_CONFIG_CSM       (3)       /* indicates which context switch mode is selected*/
661
662 static inline u32 chnenbl_ofs(struct sdma_engine *sdma, unsigned int event)
663 {
664         u32 chnenbl0 = sdma->drvdata->chnenbl0;
665         return chnenbl0 + event * 4;
666 }
667
668 static int sdma_config_ownership(struct sdma_channel *sdmac,
669                 bool event_override, bool mcu_override, bool dsp_override)
670 {
671         struct sdma_engine *sdma = sdmac->sdma;
672         int channel = sdmac->channel;
673         unsigned long evt, mcu, dsp;
674
675         if (event_override && mcu_override && dsp_override)
676                 return -EINVAL;
677
678         evt = readl_relaxed(sdma->regs + SDMA_H_EVTOVR);
679         mcu = readl_relaxed(sdma->regs + SDMA_H_HOSTOVR);
680         dsp = readl_relaxed(sdma->regs + SDMA_H_DSPOVR);
681
682         if (dsp_override)
683                 __clear_bit(channel, &dsp);
684         else
685                 __set_bit(channel, &dsp);
686
687         if (event_override)
688                 __clear_bit(channel, &evt);
689         else
690                 __set_bit(channel, &evt);
691
692         if (mcu_override)
693                 __clear_bit(channel, &mcu);
694         else
695                 __set_bit(channel, &mcu);
696
697         writel_relaxed(evt, sdma->regs + SDMA_H_EVTOVR);
698         writel_relaxed(mcu, sdma->regs + SDMA_H_HOSTOVR);
699         writel_relaxed(dsp, sdma->regs + SDMA_H_DSPOVR);
700
701         return 0;
702 }
703
704 static int is_sdma_channel_enabled(struct sdma_engine *sdma, int channel)
705 {
706         return !!(readl(sdma->regs + SDMA_H_STATSTOP) & BIT(channel));
707 }
708
709 static void sdma_enable_channel(struct sdma_engine *sdma, int channel)
710 {
711         writel(BIT(channel), sdma->regs + SDMA_H_START);
712 }
713
714 /*
715  * sdma_run_channel0 - run a channel and wait till it's done
716  */
717 static int sdma_run_channel0(struct sdma_engine *sdma)
718 {
719         int ret;
720         u32 reg;
721
722         sdma_enable_channel(sdma, 0);
723
724         ret = readl_relaxed_poll_timeout_atomic(sdma->regs + SDMA_H_STATSTOP,
725                                                 reg, !(reg & 1), 1, 500);
726         if (ret)
727                 dev_err(sdma->dev, "Timeout waiting for CH0 ready\n");
728
729         /* Set bits of CONFIG register with dynamic context switching */
730         reg = readl(sdma->regs + SDMA_H_CONFIG);
731         if ((reg & SDMA_H_CONFIG_CSM) == 0) {
732                 reg |= SDMA_H_CONFIG_CSM;
733                 writel_relaxed(reg, sdma->regs + SDMA_H_CONFIG);
734         }
735
736         return ret;
737 }
738
739 static int sdma_load_script(struct sdma_engine *sdma, void *buf, int size,
740                 u32 address)
741 {
742         struct sdma_buffer_descriptor *bd0 = sdma->bd0;
743         void *buf_virt;
744         dma_addr_t buf_phys;
745         int ret;
746         unsigned long flags;
747
748         buf_virt = dma_alloc_coherent(sdma->dev, size, &buf_phys, GFP_KERNEL);
749         if (!buf_virt)
750                 return -ENOMEM;
751
752         spin_lock_irqsave(&sdma->channel_0_lock, flags);
753
754         bd0->mode.command = C0_SETPM;
755         bd0->mode.status = BD_DONE | BD_WRAP | BD_EXTD;
756         bd0->mode.count = size / 2;
757         bd0->buffer_addr = buf_phys;
758         bd0->ext_buffer_addr = address;
759
760         memcpy(buf_virt, buf, size);
761
762         ret = sdma_run_channel0(sdma);
763
764         spin_unlock_irqrestore(&sdma->channel_0_lock, flags);
765
766         dma_free_coherent(sdma->dev, size, buf_virt, buf_phys);
767
768         return ret;
769 }
770
771 static void sdma_event_enable(struct sdma_channel *sdmac, unsigned int event)
772 {
773         struct sdma_engine *sdma = sdmac->sdma;
774         int channel = sdmac->channel;
775         unsigned long val;
776         u32 chnenbl = chnenbl_ofs(sdma, event);
777
778         val = readl_relaxed(sdma->regs + chnenbl);
779         __set_bit(channel, &val);
780         writel_relaxed(val, sdma->regs + chnenbl);
781 }
782
783 static void sdma_event_disable(struct sdma_channel *sdmac, unsigned int event)
784 {
785         struct sdma_engine *sdma = sdmac->sdma;
786         int channel = sdmac->channel;
787         u32 chnenbl = chnenbl_ofs(sdma, event);
788         unsigned long val;
789
790         val = readl_relaxed(sdma->regs + chnenbl);
791         __clear_bit(channel, &val);
792         writel_relaxed(val, sdma->regs + chnenbl);
793 }
794
795 static struct sdma_desc *to_sdma_desc(struct dma_async_tx_descriptor *t)
796 {
797         return container_of(t, struct sdma_desc, vd.tx);
798 }
799
800 static void sdma_start_desc(struct sdma_channel *sdmac)
801 {
802         struct virt_dma_desc *vd = vchan_next_desc(&sdmac->vc);
803         struct sdma_desc *desc;
804         struct sdma_engine *sdma = sdmac->sdma;
805         int channel = sdmac->channel;
806
807         if (!vd) {
808                 sdmac->desc = NULL;
809                 return;
810         }
811         sdmac->desc = desc = to_sdma_desc(&vd->tx);
812
813         list_del(&vd->node);
814
815         sdma->channel_control[channel].base_bd_ptr = desc->bd_phys;
816         sdma->channel_control[channel].current_bd_ptr = desc->bd_phys;
817         sdma_enable_channel(sdma, sdmac->channel);
818 }
819
820 static void sdma_update_channel_loop(struct sdma_channel *sdmac)
821 {
822         struct sdma_buffer_descriptor *bd;
823         int error = 0;
824         enum dma_status old_status = sdmac->status;
825
826         /*
827          * loop mode. Iterate over descriptors, re-setup them and
828          * call callback function.
829          */
830         while (sdmac->desc) {
831                 struct sdma_desc *desc = sdmac->desc;
832
833                 bd = &desc->bd[desc->buf_tail];
834
835                 if (bd->mode.status & BD_DONE)
836                         break;
837
838                 if (bd->mode.status & BD_RROR) {
839                         bd->mode.status &= ~BD_RROR;
840                         sdmac->status = DMA_ERROR;
841                         error = -EIO;
842                 }
843
844                /*
845                 * We use bd->mode.count to calculate the residue, since contains
846                 * the number of bytes present in the current buffer descriptor.
847                 */
848
849                 desc->chn_real_count = bd->mode.count;
850                 bd->mode.count = desc->period_len;
851                 desc->buf_ptail = desc->buf_tail;
852                 desc->buf_tail = (desc->buf_tail + 1) % desc->num_bd;
853
854                 /*
855                  * The callback is called from the interrupt context in order
856                  * to reduce latency and to avoid the risk of altering the
857                  * SDMA transaction status by the time the client tasklet is
858                  * executed.
859                  */
860                 spin_unlock(&sdmac->vc.lock);
861                 dmaengine_desc_get_callback_invoke(&desc->vd.tx, NULL);
862                 spin_lock(&sdmac->vc.lock);
863
864                 /* Assign buffer ownership to SDMA */
865                 bd->mode.status |= BD_DONE;
866
867                 if (error)
868                         sdmac->status = old_status;
869         }
870
871         /*
872          * SDMA stops cyclic channel when DMA request triggers a channel and no SDMA
873          * owned buffer is available (i.e. BD_DONE was set too late).
874          */
875         if (!is_sdma_channel_enabled(sdmac->sdma, sdmac->channel)) {
876                 dev_warn(sdmac->sdma->dev, "restart cyclic channel %d\n", sdmac->channel);
877                 sdma_enable_channel(sdmac->sdma, sdmac->channel);
878         }
879 }
880
881 static void mxc_sdma_handle_channel_normal(struct sdma_channel *data)
882 {
883         struct sdma_channel *sdmac = (struct sdma_channel *) data;
884         struct sdma_buffer_descriptor *bd;
885         int i, error = 0;
886
887         sdmac->desc->chn_real_count = 0;
888         /*
889          * non loop mode. Iterate over all descriptors, collect
890          * errors and call callback function
891          */
892         for (i = 0; i < sdmac->desc->num_bd; i++) {
893                 bd = &sdmac->desc->bd[i];
894
895                 if (bd->mode.status & (BD_DONE | BD_RROR))
896                         error = -EIO;
897                 sdmac->desc->chn_real_count += bd->mode.count;
898         }
899
900         if (error)
901                 sdmac->status = DMA_ERROR;
902         else
903                 sdmac->status = DMA_COMPLETE;
904 }
905
906 static irqreturn_t sdma_int_handler(int irq, void *dev_id)
907 {
908         struct sdma_engine *sdma = dev_id;
909         unsigned long stat;
910
911         stat = readl_relaxed(sdma->regs + SDMA_H_INTR);
912         writel_relaxed(stat, sdma->regs + SDMA_H_INTR);
913         /* channel 0 is special and not handled here, see run_channel0() */
914         stat &= ~1;
915
916         while (stat) {
917                 int channel = fls(stat) - 1;
918                 struct sdma_channel *sdmac = &sdma->channel[channel];
919                 struct sdma_desc *desc;
920
921                 spin_lock(&sdmac->vc.lock);
922                 desc = sdmac->desc;
923                 if (desc) {
924                         if (sdmac->flags & IMX_DMA_SG_LOOP) {
925                                 sdma_update_channel_loop(sdmac);
926                         } else {
927                                 mxc_sdma_handle_channel_normal(sdmac);
928                                 vchan_cookie_complete(&desc->vd);
929                                 sdma_start_desc(sdmac);
930                         }
931                 }
932
933                 spin_unlock(&sdmac->vc.lock);
934                 __clear_bit(channel, &stat);
935         }
936
937         return IRQ_HANDLED;
938 }
939
940 /*
941  * sets the pc of SDMA script according to the peripheral type
942  */
943 static void sdma_get_pc(struct sdma_channel *sdmac,
944                 enum sdma_peripheral_type peripheral_type)
945 {
946         struct sdma_engine *sdma = sdmac->sdma;
947         int per_2_emi = 0, emi_2_per = 0;
948         /*
949          * These are needed once we start to support transfers between
950          * two peripherals or memory-to-memory transfers
951          */
952         int per_2_per = 0, emi_2_emi = 0;
953
954         sdmac->pc_from_device = 0;
955         sdmac->pc_to_device = 0;
956         sdmac->device_to_device = 0;
957         sdmac->pc_to_pc = 0;
958         sdmac->is_ram_script = false;
959
960         switch (peripheral_type) {
961         case IMX_DMATYPE_MEMORY:
962                 emi_2_emi = sdma->script_addrs->ap_2_ap_addr;
963                 break;
964         case IMX_DMATYPE_DSP:
965                 emi_2_per = sdma->script_addrs->bp_2_ap_addr;
966                 per_2_emi = sdma->script_addrs->ap_2_bp_addr;
967                 break;
968         case IMX_DMATYPE_FIRI:
969                 per_2_emi = sdma->script_addrs->firi_2_mcu_addr;
970                 emi_2_per = sdma->script_addrs->mcu_2_firi_addr;
971                 break;
972         case IMX_DMATYPE_UART:
973                 per_2_emi = sdma->script_addrs->uart_2_mcu_addr;
974                 emi_2_per = sdma->script_addrs->mcu_2_app_addr;
975                 break;
976         case IMX_DMATYPE_UART_SP:
977                 per_2_emi = sdma->script_addrs->uartsh_2_mcu_addr;
978                 emi_2_per = sdma->script_addrs->mcu_2_shp_addr;
979                 break;
980         case IMX_DMATYPE_ATA:
981                 per_2_emi = sdma->script_addrs->ata_2_mcu_addr;
982                 emi_2_per = sdma->script_addrs->mcu_2_ata_addr;
983                 break;
984         case IMX_DMATYPE_CSPI:
985                 per_2_emi = sdma->script_addrs->app_2_mcu_addr;
986
987                 /* Use rom script mcu_2_app if ERR009165 fixed */
988                 if (sdmac->sdma->drvdata->ecspi_fixed) {
989                         emi_2_per = sdma->script_addrs->mcu_2_app_addr;
990                 } else {
991                         emi_2_per = sdma->script_addrs->mcu_2_ecspi_addr;
992                         sdmac->is_ram_script = true;
993                 }
994
995                 break;
996         case IMX_DMATYPE_EXT:
997         case IMX_DMATYPE_SSI:
998         case IMX_DMATYPE_SAI:
999                 per_2_emi = sdma->script_addrs->app_2_mcu_addr;
1000                 emi_2_per = sdma->script_addrs->mcu_2_app_addr;
1001                 break;
1002         case IMX_DMATYPE_SSI_DUAL:
1003                 per_2_emi = sdma->script_addrs->ssish_2_mcu_addr;
1004                 emi_2_per = sdma->script_addrs->mcu_2_ssish_addr;
1005                 sdmac->is_ram_script = true;
1006                 break;
1007         case IMX_DMATYPE_SSI_SP:
1008         case IMX_DMATYPE_MMC:
1009         case IMX_DMATYPE_SDHC:
1010         case IMX_DMATYPE_CSPI_SP:
1011         case IMX_DMATYPE_ESAI:
1012         case IMX_DMATYPE_MSHC_SP:
1013                 per_2_emi = sdma->script_addrs->shp_2_mcu_addr;
1014                 emi_2_per = sdma->script_addrs->mcu_2_shp_addr;
1015                 break;
1016         case IMX_DMATYPE_ASRC:
1017                 per_2_emi = sdma->script_addrs->asrc_2_mcu_addr;
1018                 emi_2_per = sdma->script_addrs->asrc_2_mcu_addr;
1019                 per_2_per = sdma->script_addrs->per_2_per_addr;
1020                 sdmac->is_ram_script = true;
1021                 break;
1022         case IMX_DMATYPE_ASRC_SP:
1023                 per_2_emi = sdma->script_addrs->shp_2_mcu_addr;
1024                 emi_2_per = sdma->script_addrs->mcu_2_shp_addr;
1025                 per_2_per = sdma->script_addrs->per_2_per_addr;
1026                 break;
1027         case IMX_DMATYPE_MSHC:
1028                 per_2_emi = sdma->script_addrs->mshc_2_mcu_addr;
1029                 emi_2_per = sdma->script_addrs->mcu_2_mshc_addr;
1030                 break;
1031         case IMX_DMATYPE_CCM:
1032                 per_2_emi = sdma->script_addrs->dptc_dvfs_addr;
1033                 break;
1034         case IMX_DMATYPE_SPDIF:
1035                 per_2_emi = sdma->script_addrs->spdif_2_mcu_addr;
1036                 emi_2_per = sdma->script_addrs->mcu_2_spdif_addr;
1037                 break;
1038         case IMX_DMATYPE_IPU_MEMORY:
1039                 emi_2_per = sdma->script_addrs->ext_mem_2_ipu_addr;
1040                 break;
1041         default:
1042                 break;
1043         }
1044
1045         sdmac->pc_from_device = per_2_emi;
1046         sdmac->pc_to_device = emi_2_per;
1047         sdmac->device_to_device = per_2_per;
1048         sdmac->pc_to_pc = emi_2_emi;
1049 }
1050
1051 static int sdma_load_context(struct sdma_channel *sdmac)
1052 {
1053         struct sdma_engine *sdma = sdmac->sdma;
1054         int channel = sdmac->channel;
1055         int load_address;
1056         struct sdma_context_data *context = sdma->context;
1057         struct sdma_buffer_descriptor *bd0 = sdma->bd0;
1058         int ret;
1059         unsigned long flags;
1060
1061         if (sdmac->direction == DMA_DEV_TO_MEM)
1062                 load_address = sdmac->pc_from_device;
1063         else if (sdmac->direction == DMA_DEV_TO_DEV)
1064                 load_address = sdmac->device_to_device;
1065         else if (sdmac->direction == DMA_MEM_TO_MEM)
1066                 load_address = sdmac->pc_to_pc;
1067         else
1068                 load_address = sdmac->pc_to_device;
1069
1070         if (load_address < 0)
1071                 return load_address;
1072
1073         dev_dbg(sdma->dev, "load_address = %d\n", load_address);
1074         dev_dbg(sdma->dev, "wml = 0x%08x\n", (u32)sdmac->watermark_level);
1075         dev_dbg(sdma->dev, "shp_addr = 0x%08x\n", sdmac->shp_addr);
1076         dev_dbg(sdma->dev, "per_addr = 0x%08x\n", sdmac->per_addr);
1077         dev_dbg(sdma->dev, "event_mask0 = 0x%08x\n", (u32)sdmac->event_mask[0]);
1078         dev_dbg(sdma->dev, "event_mask1 = 0x%08x\n", (u32)sdmac->event_mask[1]);
1079
1080         spin_lock_irqsave(&sdma->channel_0_lock, flags);
1081
1082         memset(context, 0, sizeof(*context));
1083         context->channel_state.pc = load_address;
1084
1085         /* Send by context the event mask,base address for peripheral
1086          * and watermark level
1087          */
1088         context->gReg[0] = sdmac->event_mask[1];
1089         context->gReg[1] = sdmac->event_mask[0];
1090         context->gReg[2] = sdmac->per_addr;
1091         context->gReg[6] = sdmac->shp_addr;
1092         context->gReg[7] = sdmac->watermark_level;
1093
1094         bd0->mode.command = C0_SETDM;
1095         bd0->mode.status = BD_DONE | BD_WRAP | BD_EXTD;
1096         bd0->mode.count = sizeof(*context) / 4;
1097         bd0->buffer_addr = sdma->context_phys;
1098         bd0->ext_buffer_addr = 2048 + (sizeof(*context) / 4) * channel;
1099         ret = sdma_run_channel0(sdma);
1100
1101         spin_unlock_irqrestore(&sdma->channel_0_lock, flags);
1102
1103         return ret;
1104 }
1105
1106 static struct sdma_channel *to_sdma_chan(struct dma_chan *chan)
1107 {
1108         return container_of(chan, struct sdma_channel, vc.chan);
1109 }
1110
1111 static int sdma_disable_channel(struct dma_chan *chan)
1112 {
1113         struct sdma_channel *sdmac = to_sdma_chan(chan);
1114         struct sdma_engine *sdma = sdmac->sdma;
1115         int channel = sdmac->channel;
1116
1117         writel_relaxed(BIT(channel), sdma->regs + SDMA_H_STATSTOP);
1118         sdmac->status = DMA_ERROR;
1119
1120         return 0;
1121 }
1122 static void sdma_channel_terminate_work(struct work_struct *work)
1123 {
1124         struct sdma_channel *sdmac = container_of(work, struct sdma_channel,
1125                                                   terminate_worker);
1126         /*
1127          * According to NXP R&D team a delay of one BD SDMA cost time
1128          * (maximum is 1ms) should be added after disable of the channel
1129          * bit, to ensure SDMA core has really been stopped after SDMA
1130          * clients call .device_terminate_all.
1131          */
1132         usleep_range(1000, 2000);
1133
1134         vchan_dma_desc_free_list(&sdmac->vc, &sdmac->terminated);
1135 }
1136
1137 static int sdma_terminate_all(struct dma_chan *chan)
1138 {
1139         struct sdma_channel *sdmac = to_sdma_chan(chan);
1140         unsigned long flags;
1141
1142         spin_lock_irqsave(&sdmac->vc.lock, flags);
1143
1144         sdma_disable_channel(chan);
1145
1146         if (sdmac->desc) {
1147                 vchan_terminate_vdesc(&sdmac->desc->vd);
1148                 /*
1149                  * move out current descriptor into terminated list so that
1150                  * it could be free in sdma_channel_terminate_work alone
1151                  * later without potential involving next descriptor raised
1152                  * up before the last descriptor terminated.
1153                  */
1154                 vchan_get_all_descriptors(&sdmac->vc, &sdmac->terminated);
1155                 sdmac->desc = NULL;
1156                 schedule_work(&sdmac->terminate_worker);
1157         }
1158
1159         spin_unlock_irqrestore(&sdmac->vc.lock, flags);
1160
1161         return 0;
1162 }
1163
1164 static void sdma_channel_synchronize(struct dma_chan *chan)
1165 {
1166         struct sdma_channel *sdmac = to_sdma_chan(chan);
1167
1168         vchan_synchronize(&sdmac->vc);
1169
1170         flush_work(&sdmac->terminate_worker);
1171 }
1172
1173 static void sdma_set_watermarklevel_for_p2p(struct sdma_channel *sdmac)
1174 {
1175         struct sdma_engine *sdma = sdmac->sdma;
1176
1177         int lwml = sdmac->watermark_level & SDMA_WATERMARK_LEVEL_LWML;
1178         int hwml = (sdmac->watermark_level & SDMA_WATERMARK_LEVEL_HWML) >> 16;
1179
1180         set_bit(sdmac->event_id0 % 32, &sdmac->event_mask[1]);
1181         set_bit(sdmac->event_id1 % 32, &sdmac->event_mask[0]);
1182
1183         if (sdmac->event_id0 > 31)
1184                 sdmac->watermark_level |= SDMA_WATERMARK_LEVEL_LWE;
1185
1186         if (sdmac->event_id1 > 31)
1187                 sdmac->watermark_level |= SDMA_WATERMARK_LEVEL_HWE;
1188
1189         /*
1190          * If LWML(src_maxburst) > HWML(dst_maxburst), we need
1191          * swap LWML and HWML of INFO(A.3.2.5.1), also need swap
1192          * r0(event_mask[1]) and r1(event_mask[0]).
1193          */
1194         if (lwml > hwml) {
1195                 sdmac->watermark_level &= ~(SDMA_WATERMARK_LEVEL_LWML |
1196                                                 SDMA_WATERMARK_LEVEL_HWML);
1197                 sdmac->watermark_level |= hwml;
1198                 sdmac->watermark_level |= lwml << 16;
1199                 swap(sdmac->event_mask[0], sdmac->event_mask[1]);
1200         }
1201
1202         if (sdmac->per_address2 >= sdma->spba_start_addr &&
1203                         sdmac->per_address2 <= sdma->spba_end_addr)
1204                 sdmac->watermark_level |= SDMA_WATERMARK_LEVEL_SP;
1205
1206         if (sdmac->per_address >= sdma->spba_start_addr &&
1207                         sdmac->per_address <= sdma->spba_end_addr)
1208                 sdmac->watermark_level |= SDMA_WATERMARK_LEVEL_DP;
1209
1210         sdmac->watermark_level |= SDMA_WATERMARK_LEVEL_CONT;
1211 }
1212
1213 static int sdma_config_channel(struct dma_chan *chan)
1214 {
1215         struct sdma_channel *sdmac = to_sdma_chan(chan);
1216
1217         sdma_disable_channel(chan);
1218
1219         sdmac->event_mask[0] = 0;
1220         sdmac->event_mask[1] = 0;
1221         sdmac->shp_addr = 0;
1222         sdmac->per_addr = 0;
1223
1224         switch (sdmac->peripheral_type) {
1225         case IMX_DMATYPE_DSP:
1226                 sdma_config_ownership(sdmac, false, true, true);
1227                 break;
1228         case IMX_DMATYPE_MEMORY:
1229                 sdma_config_ownership(sdmac, false, true, false);
1230                 break;
1231         default:
1232                 sdma_config_ownership(sdmac, true, true, false);
1233                 break;
1234         }
1235
1236         sdma_get_pc(sdmac, sdmac->peripheral_type);
1237
1238         if ((sdmac->peripheral_type != IMX_DMATYPE_MEMORY) &&
1239                         (sdmac->peripheral_type != IMX_DMATYPE_DSP)) {
1240                 /* Handle multiple event channels differently */
1241                 if (sdmac->event_id1) {
1242                         if (sdmac->peripheral_type == IMX_DMATYPE_ASRC_SP ||
1243                             sdmac->peripheral_type == IMX_DMATYPE_ASRC)
1244                                 sdma_set_watermarklevel_for_p2p(sdmac);
1245                 } else {
1246                         __set_bit(sdmac->event_id0, sdmac->event_mask);
1247                 }
1248
1249                 /* Address */
1250                 sdmac->shp_addr = sdmac->per_address;
1251                 sdmac->per_addr = sdmac->per_address2;
1252         } else {
1253                 sdmac->watermark_level = 0; /* FIXME: M3_BASE_ADDRESS */
1254         }
1255
1256         return 0;
1257 }
1258
1259 static int sdma_set_channel_priority(struct sdma_channel *sdmac,
1260                                      unsigned int priority)
1261 {
1262         struct sdma_engine *sdma = sdmac->sdma;
1263         int channel = sdmac->channel;
1264
1265         if (priority < MXC_SDMA_MIN_PRIORITY
1266             || priority > MXC_SDMA_MAX_PRIORITY) {
1267                 return -EINVAL;
1268         }
1269
1270         writel_relaxed(priority, sdma->regs + SDMA_CHNPRI_0 + 4 * channel);
1271
1272         return 0;
1273 }
1274
1275 static int sdma_request_channel0(struct sdma_engine *sdma)
1276 {
1277         int ret = -EBUSY;
1278
1279         sdma->bd0 = dma_alloc_coherent(sdma->dev, PAGE_SIZE, &sdma->bd0_phys,
1280                                        GFP_NOWAIT);
1281         if (!sdma->bd0) {
1282                 ret = -ENOMEM;
1283                 goto out;
1284         }
1285
1286         sdma->channel_control[0].base_bd_ptr = sdma->bd0_phys;
1287         sdma->channel_control[0].current_bd_ptr = sdma->bd0_phys;
1288
1289         sdma_set_channel_priority(&sdma->channel[0], MXC_SDMA_DEFAULT_PRIORITY);
1290         return 0;
1291 out:
1292
1293         return ret;
1294 }
1295
1296
1297 static int sdma_alloc_bd(struct sdma_desc *desc)
1298 {
1299         u32 bd_size = desc->num_bd * sizeof(struct sdma_buffer_descriptor);
1300         int ret = 0;
1301
1302         desc->bd = dma_alloc_coherent(desc->sdmac->sdma->dev, bd_size,
1303                                       &desc->bd_phys, GFP_NOWAIT);
1304         if (!desc->bd) {
1305                 ret = -ENOMEM;
1306                 goto out;
1307         }
1308 out:
1309         return ret;
1310 }
1311
1312 static void sdma_free_bd(struct sdma_desc *desc)
1313 {
1314         u32 bd_size = desc->num_bd * sizeof(struct sdma_buffer_descriptor);
1315
1316         dma_free_coherent(desc->sdmac->sdma->dev, bd_size, desc->bd,
1317                           desc->bd_phys);
1318 }
1319
1320 static void sdma_desc_free(struct virt_dma_desc *vd)
1321 {
1322         struct sdma_desc *desc = container_of(vd, struct sdma_desc, vd);
1323
1324         sdma_free_bd(desc);
1325         kfree(desc);
1326 }
1327
1328 static int sdma_alloc_chan_resources(struct dma_chan *chan)
1329 {
1330         struct sdma_channel *sdmac = to_sdma_chan(chan);
1331         struct imx_dma_data *data = chan->private;
1332         struct imx_dma_data mem_data;
1333         int prio, ret;
1334
1335         /*
1336          * MEMCPY may never setup chan->private by filter function such as
1337          * dmatest, thus create 'struct imx_dma_data mem_data' for this case.
1338          * Please note in any other slave case, you have to setup chan->private
1339          * with 'struct imx_dma_data' in your own filter function if you want to
1340          * request dma channel by dma_request_channel() rather than
1341          * dma_request_slave_channel(). Othwise, 'MEMCPY in case?' will appear
1342          * to warn you to correct your filter function.
1343          */
1344         if (!data) {
1345                 dev_dbg(sdmac->sdma->dev, "MEMCPY in case?\n");
1346                 mem_data.priority = 2;
1347                 mem_data.peripheral_type = IMX_DMATYPE_MEMORY;
1348                 mem_data.dma_request = 0;
1349                 mem_data.dma_request2 = 0;
1350                 data = &mem_data;
1351
1352                 sdma_get_pc(sdmac, IMX_DMATYPE_MEMORY);
1353         }
1354
1355         switch (data->priority) {
1356         case DMA_PRIO_HIGH:
1357                 prio = 3;
1358                 break;
1359         case DMA_PRIO_MEDIUM:
1360                 prio = 2;
1361                 break;
1362         case DMA_PRIO_LOW:
1363         default:
1364                 prio = 1;
1365                 break;
1366         }
1367
1368         sdmac->peripheral_type = data->peripheral_type;
1369         sdmac->event_id0 = data->dma_request;
1370         sdmac->event_id1 = data->dma_request2;
1371
1372         ret = clk_enable(sdmac->sdma->clk_ipg);
1373         if (ret)
1374                 return ret;
1375         ret = clk_enable(sdmac->sdma->clk_ahb);
1376         if (ret)
1377                 goto disable_clk_ipg;
1378
1379         ret = sdma_set_channel_priority(sdmac, prio);
1380         if (ret)
1381                 goto disable_clk_ahb;
1382
1383         return 0;
1384
1385 disable_clk_ahb:
1386         clk_disable(sdmac->sdma->clk_ahb);
1387 disable_clk_ipg:
1388         clk_disable(sdmac->sdma->clk_ipg);
1389         return ret;
1390 }
1391
1392 static void sdma_free_chan_resources(struct dma_chan *chan)
1393 {
1394         struct sdma_channel *sdmac = to_sdma_chan(chan);
1395         struct sdma_engine *sdma = sdmac->sdma;
1396
1397         sdma_terminate_all(chan);
1398
1399         sdma_channel_synchronize(chan);
1400
1401         sdma_event_disable(sdmac, sdmac->event_id0);
1402         if (sdmac->event_id1)
1403                 sdma_event_disable(sdmac, sdmac->event_id1);
1404
1405         sdmac->event_id0 = 0;
1406         sdmac->event_id1 = 0;
1407
1408         sdma_set_channel_priority(sdmac, 0);
1409
1410         clk_disable(sdma->clk_ipg);
1411         clk_disable(sdma->clk_ahb);
1412 }
1413
1414 static struct sdma_desc *sdma_transfer_init(struct sdma_channel *sdmac,
1415                                 enum dma_transfer_direction direction, u32 bds)
1416 {
1417         struct sdma_desc *desc;
1418
1419         if (!sdmac->sdma->fw_loaded && sdmac->is_ram_script) {
1420                 dev_warn_once(sdmac->sdma->dev, "sdma firmware not ready!\n");
1421                 goto err_out;
1422         }
1423
1424         desc = kzalloc((sizeof(*desc)), GFP_NOWAIT);
1425         if (!desc)
1426                 goto err_out;
1427
1428         sdmac->status = DMA_IN_PROGRESS;
1429         sdmac->direction = direction;
1430         sdmac->flags = 0;
1431
1432         desc->chn_count = 0;
1433         desc->chn_real_count = 0;
1434         desc->buf_tail = 0;
1435         desc->buf_ptail = 0;
1436         desc->sdmac = sdmac;
1437         desc->num_bd = bds;
1438
1439         if (sdma_alloc_bd(desc))
1440                 goto err_desc_out;
1441
1442         /* No slave_config called in MEMCPY case, so do here */
1443         if (direction == DMA_MEM_TO_MEM)
1444                 sdma_config_ownership(sdmac, false, true, false);
1445
1446         if (sdma_load_context(sdmac))
1447                 goto err_desc_out;
1448
1449         return desc;
1450
1451 err_desc_out:
1452         kfree(desc);
1453 err_out:
1454         return NULL;
1455 }
1456
1457 static struct dma_async_tx_descriptor *sdma_prep_memcpy(
1458                 struct dma_chan *chan, dma_addr_t dma_dst,
1459                 dma_addr_t dma_src, size_t len, unsigned long flags)
1460 {
1461         struct sdma_channel *sdmac = to_sdma_chan(chan);
1462         struct sdma_engine *sdma = sdmac->sdma;
1463         int channel = sdmac->channel;
1464         size_t count;
1465         int i = 0, param;
1466         struct sdma_buffer_descriptor *bd;
1467         struct sdma_desc *desc;
1468
1469         if (!chan || !len)
1470                 return NULL;
1471
1472         dev_dbg(sdma->dev, "memcpy: %pad->%pad, len=%zu, channel=%d.\n",
1473                 &dma_src, &dma_dst, len, channel);
1474
1475         desc = sdma_transfer_init(sdmac, DMA_MEM_TO_MEM,
1476                                         len / SDMA_BD_MAX_CNT + 1);
1477         if (!desc)
1478                 return NULL;
1479
1480         do {
1481                 count = min_t(size_t, len, SDMA_BD_MAX_CNT);
1482                 bd = &desc->bd[i];
1483                 bd->buffer_addr = dma_src;
1484                 bd->ext_buffer_addr = dma_dst;
1485                 bd->mode.count = count;
1486                 desc->chn_count += count;
1487                 bd->mode.command = 0;
1488
1489                 dma_src += count;
1490                 dma_dst += count;
1491                 len -= count;
1492                 i++;
1493
1494                 param = BD_DONE | BD_EXTD | BD_CONT;
1495                 /* last bd */
1496                 if (!len) {
1497                         param |= BD_INTR;
1498                         param |= BD_LAST;
1499                         param &= ~BD_CONT;
1500                 }
1501
1502                 dev_dbg(sdma->dev, "entry %d: count: %zd dma: 0x%x %s%s\n",
1503                                 i, count, bd->buffer_addr,
1504                                 param & BD_WRAP ? "wrap" : "",
1505                                 param & BD_INTR ? " intr" : "");
1506
1507                 bd->mode.status = param;
1508         } while (len);
1509
1510         return vchan_tx_prep(&sdmac->vc, &desc->vd, flags);
1511 }
1512
1513 static struct dma_async_tx_descriptor *sdma_prep_slave_sg(
1514                 struct dma_chan *chan, struct scatterlist *sgl,
1515                 unsigned int sg_len, enum dma_transfer_direction direction,
1516                 unsigned long flags, void *context)
1517 {
1518         struct sdma_channel *sdmac = to_sdma_chan(chan);
1519         struct sdma_engine *sdma = sdmac->sdma;
1520         int i, count;
1521         int channel = sdmac->channel;
1522         struct scatterlist *sg;
1523         struct sdma_desc *desc;
1524
1525         sdma_config_write(chan, &sdmac->slave_config, direction);
1526
1527         desc = sdma_transfer_init(sdmac, direction, sg_len);
1528         if (!desc)
1529                 goto err_out;
1530
1531         dev_dbg(sdma->dev, "setting up %d entries for channel %d.\n",
1532                         sg_len, channel);
1533
1534         for_each_sg(sgl, sg, sg_len, i) {
1535                 struct sdma_buffer_descriptor *bd = &desc->bd[i];
1536                 int param;
1537
1538                 bd->buffer_addr = sg->dma_address;
1539
1540                 count = sg_dma_len(sg);
1541
1542                 if (count > SDMA_BD_MAX_CNT) {
1543                         dev_err(sdma->dev, "SDMA channel %d: maximum bytes for sg entry exceeded: %d > %d\n",
1544                                         channel, count, SDMA_BD_MAX_CNT);
1545                         goto err_bd_out;
1546                 }
1547
1548                 bd->mode.count = count;
1549                 desc->chn_count += count;
1550
1551                 if (sdmac->word_size > DMA_SLAVE_BUSWIDTH_4_BYTES)
1552                         goto err_bd_out;
1553
1554                 switch (sdmac->word_size) {
1555                 case DMA_SLAVE_BUSWIDTH_4_BYTES:
1556                         bd->mode.command = 0;
1557                         if (count & 3 || sg->dma_address & 3)
1558                                 goto err_bd_out;
1559                         break;
1560                 case DMA_SLAVE_BUSWIDTH_2_BYTES:
1561                         bd->mode.command = 2;
1562                         if (count & 1 || sg->dma_address & 1)
1563                                 goto err_bd_out;
1564                         break;
1565                 case DMA_SLAVE_BUSWIDTH_1_BYTE:
1566                         bd->mode.command = 1;
1567                         break;
1568                 default:
1569                         goto err_bd_out;
1570                 }
1571
1572                 param = BD_DONE | BD_EXTD | BD_CONT;
1573
1574                 if (i + 1 == sg_len) {
1575                         param |= BD_INTR;
1576                         param |= BD_LAST;
1577                         param &= ~BD_CONT;
1578                 }
1579
1580                 dev_dbg(sdma->dev, "entry %d: count: %d dma: %#llx %s%s\n",
1581                                 i, count, (u64)sg->dma_address,
1582                                 param & BD_WRAP ? "wrap" : "",
1583                                 param & BD_INTR ? " intr" : "");
1584
1585                 bd->mode.status = param;
1586         }
1587
1588         return vchan_tx_prep(&sdmac->vc, &desc->vd, flags);
1589 err_bd_out:
1590         sdma_free_bd(desc);
1591         kfree(desc);
1592 err_out:
1593         sdmac->status = DMA_ERROR;
1594         return NULL;
1595 }
1596
1597 static struct dma_async_tx_descriptor *sdma_prep_dma_cyclic(
1598                 struct dma_chan *chan, dma_addr_t dma_addr, size_t buf_len,
1599                 size_t period_len, enum dma_transfer_direction direction,
1600                 unsigned long flags)
1601 {
1602         struct sdma_channel *sdmac = to_sdma_chan(chan);
1603         struct sdma_engine *sdma = sdmac->sdma;
1604         int num_periods = buf_len / period_len;
1605         int channel = sdmac->channel;
1606         int i = 0, buf = 0;
1607         struct sdma_desc *desc;
1608
1609         dev_dbg(sdma->dev, "%s channel: %d\n", __func__, channel);
1610
1611         sdma_config_write(chan, &sdmac->slave_config, direction);
1612
1613         desc = sdma_transfer_init(sdmac, direction, num_periods);
1614         if (!desc)
1615                 goto err_out;
1616
1617         desc->period_len = period_len;
1618
1619         sdmac->flags |= IMX_DMA_SG_LOOP;
1620
1621         if (period_len > SDMA_BD_MAX_CNT) {
1622                 dev_err(sdma->dev, "SDMA channel %d: maximum period size exceeded: %zu > %d\n",
1623                                 channel, period_len, SDMA_BD_MAX_CNT);
1624                 goto err_bd_out;
1625         }
1626
1627         while (buf < buf_len) {
1628                 struct sdma_buffer_descriptor *bd = &desc->bd[i];
1629                 int param;
1630
1631                 bd->buffer_addr = dma_addr;
1632
1633                 bd->mode.count = period_len;
1634
1635                 if (sdmac->word_size > DMA_SLAVE_BUSWIDTH_4_BYTES)
1636                         goto err_bd_out;
1637                 if (sdmac->word_size == DMA_SLAVE_BUSWIDTH_4_BYTES)
1638                         bd->mode.command = 0;
1639                 else
1640                         bd->mode.command = sdmac->word_size;
1641
1642                 param = BD_DONE | BD_EXTD | BD_CONT | BD_INTR;
1643                 if (i + 1 == num_periods)
1644                         param |= BD_WRAP;
1645
1646                 dev_dbg(sdma->dev, "entry %d: count: %zu dma: %#llx %s%s\n",
1647                                 i, period_len, (u64)dma_addr,
1648                                 param & BD_WRAP ? "wrap" : "",
1649                                 param & BD_INTR ? " intr" : "");
1650
1651                 bd->mode.status = param;
1652
1653                 dma_addr += period_len;
1654                 buf += period_len;
1655
1656                 i++;
1657         }
1658
1659         return vchan_tx_prep(&sdmac->vc, &desc->vd, flags);
1660 err_bd_out:
1661         sdma_free_bd(desc);
1662         kfree(desc);
1663 err_out:
1664         sdmac->status = DMA_ERROR;
1665         return NULL;
1666 }
1667
1668 static int sdma_config_write(struct dma_chan *chan,
1669                        struct dma_slave_config *dmaengine_cfg,
1670                        enum dma_transfer_direction direction)
1671 {
1672         struct sdma_channel *sdmac = to_sdma_chan(chan);
1673
1674         if (direction == DMA_DEV_TO_MEM) {
1675                 sdmac->per_address = dmaengine_cfg->src_addr;
1676                 sdmac->watermark_level = dmaengine_cfg->src_maxburst *
1677                         dmaengine_cfg->src_addr_width;
1678                 sdmac->word_size = dmaengine_cfg->src_addr_width;
1679         } else if (direction == DMA_DEV_TO_DEV) {
1680                 sdmac->per_address2 = dmaengine_cfg->src_addr;
1681                 sdmac->per_address = dmaengine_cfg->dst_addr;
1682                 sdmac->watermark_level = dmaengine_cfg->src_maxburst &
1683                         SDMA_WATERMARK_LEVEL_LWML;
1684                 sdmac->watermark_level |= (dmaengine_cfg->dst_maxburst << 16) &
1685                         SDMA_WATERMARK_LEVEL_HWML;
1686                 sdmac->word_size = dmaengine_cfg->dst_addr_width;
1687         } else {
1688                 sdmac->per_address = dmaengine_cfg->dst_addr;
1689                 sdmac->watermark_level = dmaengine_cfg->dst_maxburst *
1690                         dmaengine_cfg->dst_addr_width;
1691                 sdmac->word_size = dmaengine_cfg->dst_addr_width;
1692         }
1693         sdmac->direction = direction;
1694         return sdma_config_channel(chan);
1695 }
1696
1697 static int sdma_config(struct dma_chan *chan,
1698                        struct dma_slave_config *dmaengine_cfg)
1699 {
1700         struct sdma_channel *sdmac = to_sdma_chan(chan);
1701
1702         memcpy(&sdmac->slave_config, dmaengine_cfg, sizeof(*dmaengine_cfg));
1703
1704         /* Set ENBLn earlier to make sure dma request triggered after that */
1705         if (sdmac->event_id0 >= sdmac->sdma->drvdata->num_events)
1706                 return -EINVAL;
1707         sdma_event_enable(sdmac, sdmac->event_id0);
1708
1709         if (sdmac->event_id1) {
1710                 if (sdmac->event_id1 >= sdmac->sdma->drvdata->num_events)
1711                         return -EINVAL;
1712                 sdma_event_enable(sdmac, sdmac->event_id1);
1713         }
1714
1715         return 0;
1716 }
1717
1718 static enum dma_status sdma_tx_status(struct dma_chan *chan,
1719                                       dma_cookie_t cookie,
1720                                       struct dma_tx_state *txstate)
1721 {
1722         struct sdma_channel *sdmac = to_sdma_chan(chan);
1723         struct sdma_desc *desc = NULL;
1724         u32 residue;
1725         struct virt_dma_desc *vd;
1726         enum dma_status ret;
1727         unsigned long flags;
1728
1729         ret = dma_cookie_status(chan, cookie, txstate);
1730         if (ret == DMA_COMPLETE || !txstate)
1731                 return ret;
1732
1733         spin_lock_irqsave(&sdmac->vc.lock, flags);
1734
1735         vd = vchan_find_desc(&sdmac->vc, cookie);
1736         if (vd)
1737                 desc = to_sdma_desc(&vd->tx);
1738         else if (sdmac->desc && sdmac->desc->vd.tx.cookie == cookie)
1739                 desc = sdmac->desc;
1740
1741         if (desc) {
1742                 if (sdmac->flags & IMX_DMA_SG_LOOP)
1743                         residue = (desc->num_bd - desc->buf_ptail) *
1744                                 desc->period_len - desc->chn_real_count;
1745                 else
1746                         residue = desc->chn_count - desc->chn_real_count;
1747         } else {
1748                 residue = 0;
1749         }
1750
1751         spin_unlock_irqrestore(&sdmac->vc.lock, flags);
1752
1753         dma_set_tx_state(txstate, chan->completed_cookie, chan->cookie,
1754                          residue);
1755
1756         return sdmac->status;
1757 }
1758
1759 static void sdma_issue_pending(struct dma_chan *chan)
1760 {
1761         struct sdma_channel *sdmac = to_sdma_chan(chan);
1762         unsigned long flags;
1763
1764         spin_lock_irqsave(&sdmac->vc.lock, flags);
1765         if (vchan_issue_pending(&sdmac->vc) && !sdmac->desc)
1766                 sdma_start_desc(sdmac);
1767         spin_unlock_irqrestore(&sdmac->vc.lock, flags);
1768 }
1769
1770 #define SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V1 34
1771 #define SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V2 38
1772 #define SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V3 45
1773 #define SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V4 46
1774
1775 static void sdma_add_scripts(struct sdma_engine *sdma,
1776                              const struct sdma_script_start_addrs *addr)
1777 {
1778         s32 *addr_arr = (u32 *)addr;
1779         s32 *saddr_arr = (u32 *)sdma->script_addrs;
1780         int i;
1781
1782         /* use the default firmware in ROM if missing external firmware */
1783         if (!sdma->script_number)
1784                 sdma->script_number = SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V1;
1785
1786         if (sdma->script_number > sizeof(struct sdma_script_start_addrs)
1787                                   / sizeof(s32)) {
1788                 dev_err(sdma->dev,
1789                         "SDMA script number %d not match with firmware.\n",
1790                         sdma->script_number);
1791                 return;
1792         }
1793
1794         for (i = 0; i < sdma->script_number; i++)
1795                 if (addr_arr[i] > 0)
1796                         saddr_arr[i] = addr_arr[i];
1797
1798         /*
1799          * get uart_2_mcu_addr/uartsh_2_mcu_addr rom script specially because
1800          * they are now replaced by uart_2_mcu_ram_addr/uartsh_2_mcu_ram_addr
1801          * to be compatible with legacy freescale/nxp sdma firmware, and they
1802          * are located in the bottom part of sdma_script_start_addrs which are
1803          * beyond the SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V1.
1804          */
1805         if (addr->uart_2_mcu_addr)
1806                 sdma->script_addrs->uart_2_mcu_addr = addr->uart_2_mcu_addr;
1807         if (addr->uartsh_2_mcu_addr)
1808                 sdma->script_addrs->uartsh_2_mcu_addr = addr->uartsh_2_mcu_addr;
1809
1810 }
1811
1812 static void sdma_load_firmware(const struct firmware *fw, void *context)
1813 {
1814         struct sdma_engine *sdma = context;
1815         const struct sdma_firmware_header *header;
1816         const struct sdma_script_start_addrs *addr;
1817         unsigned short *ram_code;
1818
1819         if (!fw) {
1820                 dev_info(sdma->dev, "external firmware not found, using ROM firmware\n");
1821                 /* In this case we just use the ROM firmware. */
1822                 return;
1823         }
1824
1825         if (fw->size < sizeof(*header))
1826                 goto err_firmware;
1827
1828         header = (struct sdma_firmware_header *)fw->data;
1829
1830         if (header->magic != SDMA_FIRMWARE_MAGIC)
1831                 goto err_firmware;
1832         if (header->ram_code_start + header->ram_code_size > fw->size)
1833                 goto err_firmware;
1834         switch (header->version_major) {
1835         case 1:
1836                 sdma->script_number = SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V1;
1837                 break;
1838         case 2:
1839                 sdma->script_number = SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V2;
1840                 break;
1841         case 3:
1842                 sdma->script_number = SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V3;
1843                 break;
1844         case 4:
1845                 sdma->script_number = SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V4;
1846                 break;
1847         default:
1848                 dev_err(sdma->dev, "unknown firmware version\n");
1849                 goto err_firmware;
1850         }
1851
1852         addr = (void *)header + header->script_addrs_start;
1853         ram_code = (void *)header + header->ram_code_start;
1854
1855         clk_enable(sdma->clk_ipg);
1856         clk_enable(sdma->clk_ahb);
1857         /* download the RAM image for SDMA */
1858         sdma_load_script(sdma, ram_code,
1859                          header->ram_code_size,
1860                          addr->ram_code_start_addr);
1861         clk_disable(sdma->clk_ipg);
1862         clk_disable(sdma->clk_ahb);
1863
1864         sdma_add_scripts(sdma, addr);
1865
1866         sdma->fw_loaded = true;
1867
1868         dev_info(sdma->dev, "loaded firmware %d.%d\n",
1869                  header->version_major,
1870                  header->version_minor);
1871
1872 err_firmware:
1873         release_firmware(fw);
1874 }
1875
1876 #define EVENT_REMAP_CELLS 3
1877
1878 static int sdma_event_remap(struct sdma_engine *sdma)
1879 {
1880         struct device_node *np = sdma->dev->of_node;
1881         struct device_node *gpr_np = of_parse_phandle(np, "gpr", 0);
1882         struct property *event_remap;
1883         struct regmap *gpr;
1884         char propname[] = "fsl,sdma-event-remap";
1885         u32 reg, val, shift, num_map, i;
1886         int ret = 0;
1887
1888         if (IS_ERR(np) || IS_ERR(gpr_np))
1889                 goto out;
1890
1891         event_remap = of_find_property(np, propname, NULL);
1892         num_map = event_remap ? (event_remap->length / sizeof(u32)) : 0;
1893         if (!num_map) {
1894                 dev_dbg(sdma->dev, "no event needs to be remapped\n");
1895                 goto out;
1896         } else if (num_map % EVENT_REMAP_CELLS) {
1897                 dev_err(sdma->dev, "the property %s must modulo %d\n",
1898                                 propname, EVENT_REMAP_CELLS);
1899                 ret = -EINVAL;
1900                 goto out;
1901         }
1902
1903         gpr = syscon_node_to_regmap(gpr_np);
1904         if (IS_ERR(gpr)) {
1905                 dev_err(sdma->dev, "failed to get gpr regmap\n");
1906                 ret = PTR_ERR(gpr);
1907                 goto out;
1908         }
1909
1910         for (i = 0; i < num_map; i += EVENT_REMAP_CELLS) {
1911                 ret = of_property_read_u32_index(np, propname, i, &reg);
1912                 if (ret) {
1913                         dev_err(sdma->dev, "failed to read property %s index %d\n",
1914                                         propname, i);
1915                         goto out;
1916                 }
1917
1918                 ret = of_property_read_u32_index(np, propname, i + 1, &shift);
1919                 if (ret) {
1920                         dev_err(sdma->dev, "failed to read property %s index %d\n",
1921                                         propname, i + 1);
1922                         goto out;
1923                 }
1924
1925                 ret = of_property_read_u32_index(np, propname, i + 2, &val);
1926                 if (ret) {
1927                         dev_err(sdma->dev, "failed to read property %s index %d\n",
1928                                         propname, i + 2);
1929                         goto out;
1930                 }
1931
1932                 regmap_update_bits(gpr, reg, BIT(shift), val << shift);
1933         }
1934
1935 out:
1936         if (!IS_ERR(gpr_np))
1937                 of_node_put(gpr_np);
1938
1939         return ret;
1940 }
1941
1942 static int sdma_get_firmware(struct sdma_engine *sdma,
1943                 const char *fw_name)
1944 {
1945         int ret;
1946
1947         ret = request_firmware_nowait(THIS_MODULE,
1948                         FW_ACTION_UEVENT, fw_name, sdma->dev,
1949                         GFP_KERNEL, sdma, sdma_load_firmware);
1950
1951         return ret;
1952 }
1953
1954 static int sdma_init(struct sdma_engine *sdma)
1955 {
1956         int i, ret;
1957         dma_addr_t ccb_phys;
1958
1959         ret = clk_enable(sdma->clk_ipg);
1960         if (ret)
1961                 return ret;
1962         ret = clk_enable(sdma->clk_ahb);
1963         if (ret)
1964                 goto disable_clk_ipg;
1965
1966         if (sdma->drvdata->check_ratio &&
1967             (clk_get_rate(sdma->clk_ahb) == clk_get_rate(sdma->clk_ipg)))
1968                 sdma->clk_ratio = 1;
1969
1970         /* Be sure SDMA has not started yet */
1971         writel_relaxed(0, sdma->regs + SDMA_H_C0PTR);
1972
1973         sdma->channel_control = dma_alloc_coherent(sdma->dev,
1974                         MAX_DMA_CHANNELS * sizeof(struct sdma_channel_control) +
1975                         sizeof(struct sdma_context_data),
1976                         &ccb_phys, GFP_KERNEL);
1977
1978         if (!sdma->channel_control) {
1979                 ret = -ENOMEM;
1980                 goto err_dma_alloc;
1981         }
1982
1983         sdma->context = (void *)sdma->channel_control +
1984                 MAX_DMA_CHANNELS * sizeof(struct sdma_channel_control);
1985         sdma->context_phys = ccb_phys +
1986                 MAX_DMA_CHANNELS * sizeof(struct sdma_channel_control);
1987
1988         /* disable all channels */
1989         for (i = 0; i < sdma->drvdata->num_events; i++)
1990                 writel_relaxed(0, sdma->regs + chnenbl_ofs(sdma, i));
1991
1992         /* All channels have priority 0 */
1993         for (i = 0; i < MAX_DMA_CHANNELS; i++)
1994                 writel_relaxed(0, sdma->regs + SDMA_CHNPRI_0 + i * 4);
1995
1996         ret = sdma_request_channel0(sdma);
1997         if (ret)
1998                 goto err_dma_alloc;
1999
2000         sdma_config_ownership(&sdma->channel[0], false, true, false);
2001
2002         /* Set Command Channel (Channel Zero) */
2003         writel_relaxed(0x4050, sdma->regs + SDMA_CHN0ADDR);
2004
2005         /* Set bits of CONFIG register but with static context switching */
2006         if (sdma->clk_ratio)
2007                 writel_relaxed(SDMA_H_CONFIG_ACR, sdma->regs + SDMA_H_CONFIG);
2008         else
2009                 writel_relaxed(0, sdma->regs + SDMA_H_CONFIG);
2010
2011         writel_relaxed(ccb_phys, sdma->regs + SDMA_H_C0PTR);
2012
2013         /* Initializes channel's priorities */
2014         sdma_set_channel_priority(&sdma->channel[0], 7);
2015
2016         clk_disable(sdma->clk_ipg);
2017         clk_disable(sdma->clk_ahb);
2018
2019         return 0;
2020
2021 err_dma_alloc:
2022         clk_disable(sdma->clk_ahb);
2023 disable_clk_ipg:
2024         clk_disable(sdma->clk_ipg);
2025         dev_err(sdma->dev, "initialisation failed with %d\n", ret);
2026         return ret;
2027 }
2028
2029 static bool sdma_filter_fn(struct dma_chan *chan, void *fn_param)
2030 {
2031         struct sdma_channel *sdmac = to_sdma_chan(chan);
2032         struct imx_dma_data *data = fn_param;
2033
2034         if (!imx_dma_is_general_purpose(chan))
2035                 return false;
2036
2037         sdmac->data = *data;
2038         chan->private = &sdmac->data;
2039
2040         return true;
2041 }
2042
2043 static struct dma_chan *sdma_xlate(struct of_phandle_args *dma_spec,
2044                                    struct of_dma *ofdma)
2045 {
2046         struct sdma_engine *sdma = ofdma->of_dma_data;
2047         dma_cap_mask_t mask = sdma->dma_device.cap_mask;
2048         struct imx_dma_data data;
2049
2050         if (dma_spec->args_count != 3)
2051                 return NULL;
2052
2053         data.dma_request = dma_spec->args[0];
2054         data.peripheral_type = dma_spec->args[1];
2055         data.priority = dma_spec->args[2];
2056         /*
2057          * init dma_request2 to zero, which is not used by the dts.
2058          * For P2P, dma_request2 is init from dma_request_channel(),
2059          * chan->private will point to the imx_dma_data, and in
2060          * device_alloc_chan_resources(), imx_dma_data.dma_request2 will
2061          * be set to sdmac->event_id1.
2062          */
2063         data.dma_request2 = 0;
2064
2065         return __dma_request_channel(&mask, sdma_filter_fn, &data,
2066                                      ofdma->of_node);
2067 }
2068
2069 static int sdma_probe(struct platform_device *pdev)
2070 {
2071         struct device_node *np = pdev->dev.of_node;
2072         struct device_node *spba_bus;
2073         const char *fw_name;
2074         int ret;
2075         int irq;
2076         struct resource *iores;
2077         struct resource spba_res;
2078         int i;
2079         struct sdma_engine *sdma;
2080         s32 *saddr_arr;
2081
2082         ret = dma_coerce_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
2083         if (ret)
2084                 return ret;
2085
2086         sdma = devm_kzalloc(&pdev->dev, sizeof(*sdma), GFP_KERNEL);
2087         if (!sdma)
2088                 return -ENOMEM;
2089
2090         spin_lock_init(&sdma->channel_0_lock);
2091
2092         sdma->dev = &pdev->dev;
2093         sdma->drvdata = of_device_get_match_data(sdma->dev);
2094
2095         irq = platform_get_irq(pdev, 0);
2096         if (irq < 0)
2097                 return irq;
2098
2099         iores = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2100         sdma->regs = devm_ioremap_resource(&pdev->dev, iores);
2101         if (IS_ERR(sdma->regs))
2102                 return PTR_ERR(sdma->regs);
2103
2104         sdma->clk_ipg = devm_clk_get(&pdev->dev, "ipg");
2105         if (IS_ERR(sdma->clk_ipg))
2106                 return PTR_ERR(sdma->clk_ipg);
2107
2108         sdma->clk_ahb = devm_clk_get(&pdev->dev, "ahb");
2109         if (IS_ERR(sdma->clk_ahb))
2110                 return PTR_ERR(sdma->clk_ahb);
2111
2112         ret = clk_prepare(sdma->clk_ipg);
2113         if (ret)
2114                 return ret;
2115
2116         ret = clk_prepare(sdma->clk_ahb);
2117         if (ret)
2118                 goto err_clk;
2119
2120         ret = devm_request_irq(&pdev->dev, irq, sdma_int_handler, 0, "sdma",
2121                                sdma);
2122         if (ret)
2123                 goto err_irq;
2124
2125         sdma->irq = irq;
2126
2127         sdma->script_addrs = kzalloc(sizeof(*sdma->script_addrs), GFP_KERNEL);
2128         if (!sdma->script_addrs) {
2129                 ret = -ENOMEM;
2130                 goto err_irq;
2131         }
2132
2133         /* initially no scripts available */
2134         saddr_arr = (s32 *)sdma->script_addrs;
2135         for (i = 0; i < sizeof(*sdma->script_addrs) / sizeof(s32); i++)
2136                 saddr_arr[i] = -EINVAL;
2137
2138         dma_cap_set(DMA_SLAVE, sdma->dma_device.cap_mask);
2139         dma_cap_set(DMA_CYCLIC, sdma->dma_device.cap_mask);
2140         dma_cap_set(DMA_MEMCPY, sdma->dma_device.cap_mask);
2141
2142         INIT_LIST_HEAD(&sdma->dma_device.channels);
2143         /* Initialize channel parameters */
2144         for (i = 0; i < MAX_DMA_CHANNELS; i++) {
2145                 struct sdma_channel *sdmac = &sdma->channel[i];
2146
2147                 sdmac->sdma = sdma;
2148
2149                 sdmac->channel = i;
2150                 sdmac->vc.desc_free = sdma_desc_free;
2151                 INIT_LIST_HEAD(&sdmac->terminated);
2152                 INIT_WORK(&sdmac->terminate_worker,
2153                                 sdma_channel_terminate_work);
2154                 /*
2155                  * Add the channel to the DMAC list. Do not add channel 0 though
2156                  * because we need it internally in the SDMA driver. This also means
2157                  * that channel 0 in dmaengine counting matches sdma channel 1.
2158                  */
2159                 if (i)
2160                         vchan_init(&sdmac->vc, &sdma->dma_device);
2161         }
2162
2163         ret = sdma_init(sdma);
2164         if (ret)
2165                 goto err_init;
2166
2167         ret = sdma_event_remap(sdma);
2168         if (ret)
2169                 goto err_init;
2170
2171         if (sdma->drvdata->script_addrs)
2172                 sdma_add_scripts(sdma, sdma->drvdata->script_addrs);
2173
2174         sdma->dma_device.dev = &pdev->dev;
2175
2176         sdma->dma_device.device_alloc_chan_resources = sdma_alloc_chan_resources;
2177         sdma->dma_device.device_free_chan_resources = sdma_free_chan_resources;
2178         sdma->dma_device.device_tx_status = sdma_tx_status;
2179         sdma->dma_device.device_prep_slave_sg = sdma_prep_slave_sg;
2180         sdma->dma_device.device_prep_dma_cyclic = sdma_prep_dma_cyclic;
2181         sdma->dma_device.device_config = sdma_config;
2182         sdma->dma_device.device_terminate_all = sdma_terminate_all;
2183         sdma->dma_device.device_synchronize = sdma_channel_synchronize;
2184         sdma->dma_device.src_addr_widths = SDMA_DMA_BUSWIDTHS;
2185         sdma->dma_device.dst_addr_widths = SDMA_DMA_BUSWIDTHS;
2186         sdma->dma_device.directions = SDMA_DMA_DIRECTIONS;
2187         sdma->dma_device.residue_granularity = DMA_RESIDUE_GRANULARITY_SEGMENT;
2188         sdma->dma_device.device_prep_dma_memcpy = sdma_prep_memcpy;
2189         sdma->dma_device.device_issue_pending = sdma_issue_pending;
2190         sdma->dma_device.copy_align = 2;
2191         dma_set_max_seg_size(sdma->dma_device.dev, SDMA_BD_MAX_CNT);
2192
2193         platform_set_drvdata(pdev, sdma);
2194
2195         ret = dma_async_device_register(&sdma->dma_device);
2196         if (ret) {
2197                 dev_err(&pdev->dev, "unable to register\n");
2198                 goto err_init;
2199         }
2200
2201         if (np) {
2202                 ret = of_dma_controller_register(np, sdma_xlate, sdma);
2203                 if (ret) {
2204                         dev_err(&pdev->dev, "failed to register controller\n");
2205                         goto err_register;
2206                 }
2207
2208                 spba_bus = of_find_compatible_node(NULL, NULL, "fsl,spba-bus");
2209                 ret = of_address_to_resource(spba_bus, 0, &spba_res);
2210                 if (!ret) {
2211                         sdma->spba_start_addr = spba_res.start;
2212                         sdma->spba_end_addr = spba_res.end;
2213                 }
2214                 of_node_put(spba_bus);
2215         }
2216
2217         /*
2218          * Because that device tree does not encode ROM script address,
2219          * the RAM script in firmware is mandatory for device tree
2220          * probe, otherwise it fails.
2221          */
2222         ret = of_property_read_string(np, "fsl,sdma-ram-script-name",
2223                                       &fw_name);
2224         if (ret) {
2225                 dev_warn(&pdev->dev, "failed to get firmware name\n");
2226         } else {
2227                 ret = sdma_get_firmware(sdma, fw_name);
2228                 if (ret)
2229                         dev_warn(&pdev->dev, "failed to get firmware from device tree\n");
2230         }
2231
2232         return 0;
2233
2234 err_register:
2235         dma_async_device_unregister(&sdma->dma_device);
2236 err_init:
2237         kfree(sdma->script_addrs);
2238 err_irq:
2239         clk_unprepare(sdma->clk_ahb);
2240 err_clk:
2241         clk_unprepare(sdma->clk_ipg);
2242         return ret;
2243 }
2244
2245 static int sdma_remove(struct platform_device *pdev)
2246 {
2247         struct sdma_engine *sdma = platform_get_drvdata(pdev);
2248         int i;
2249
2250         devm_free_irq(&pdev->dev, sdma->irq, sdma);
2251         dma_async_device_unregister(&sdma->dma_device);
2252         kfree(sdma->script_addrs);
2253         clk_unprepare(sdma->clk_ahb);
2254         clk_unprepare(sdma->clk_ipg);
2255         /* Kill the tasklet */
2256         for (i = 0; i < MAX_DMA_CHANNELS; i++) {
2257                 struct sdma_channel *sdmac = &sdma->channel[i];
2258
2259                 tasklet_kill(&sdmac->vc.task);
2260                 sdma_free_chan_resources(&sdmac->vc.chan);
2261         }
2262
2263         platform_set_drvdata(pdev, NULL);
2264         return 0;
2265 }
2266
2267 static struct platform_driver sdma_driver = {
2268         .driver         = {
2269                 .name   = "imx-sdma",
2270                 .of_match_table = sdma_dt_ids,
2271         },
2272         .remove         = sdma_remove,
2273         .probe          = sdma_probe,
2274 };
2275
2276 module_platform_driver(sdma_driver);
2277
2278 MODULE_AUTHOR("Sascha Hauer, Pengutronix <s.hauer@pengutronix.de>");
2279 MODULE_DESCRIPTION("i.MX SDMA driver");
2280 #if IS_ENABLED(CONFIG_SOC_IMX6Q)
2281 MODULE_FIRMWARE("imx/sdma/sdma-imx6q.bin");
2282 #endif
2283 #if IS_ENABLED(CONFIG_SOC_IMX7D)
2284 MODULE_FIRMWARE("imx/sdma/sdma-imx7d.bin");
2285 #endif
2286 MODULE_LICENSE("GPL");