]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/spi/spi-atmel.c
spi: imx: Use dma_request_chan() directly for channel request
[linux.git] / drivers / spi / spi-atmel.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Driver for Atmel AT32 and AT91 SPI Controllers
4  *
5  * Copyright (C) 2006 Atmel Corporation
6  */
7
8 #include <linux/kernel.h>
9 #include <linux/clk.h>
10 #include <linux/module.h>
11 #include <linux/platform_device.h>
12 #include <linux/delay.h>
13 #include <linux/dma-mapping.h>
14 #include <linux/dmaengine.h>
15 #include <linux/err.h>
16 #include <linux/interrupt.h>
17 #include <linux/spi/spi.h>
18 #include <linux/slab.h>
19 #include <linux/platform_data/dma-atmel.h>
20 #include <linux/of.h>
21
22 #include <linux/io.h>
23 #include <linux/gpio/consumer.h>
24 #include <linux/pinctrl/consumer.h>
25 #include <linux/pm_runtime.h>
26 #include <trace/events/spi.h>
27
28 /* SPI register offsets */
29 #define SPI_CR                                  0x0000
30 #define SPI_MR                                  0x0004
31 #define SPI_RDR                                 0x0008
32 #define SPI_TDR                                 0x000c
33 #define SPI_SR                                  0x0010
34 #define SPI_IER                                 0x0014
35 #define SPI_IDR                                 0x0018
36 #define SPI_IMR                                 0x001c
37 #define SPI_CSR0                                0x0030
38 #define SPI_CSR1                                0x0034
39 #define SPI_CSR2                                0x0038
40 #define SPI_CSR3                                0x003c
41 #define SPI_FMR                                 0x0040
42 #define SPI_FLR                                 0x0044
43 #define SPI_VERSION                             0x00fc
44 #define SPI_RPR                                 0x0100
45 #define SPI_RCR                                 0x0104
46 #define SPI_TPR                                 0x0108
47 #define SPI_TCR                                 0x010c
48 #define SPI_RNPR                                0x0110
49 #define SPI_RNCR                                0x0114
50 #define SPI_TNPR                                0x0118
51 #define SPI_TNCR                                0x011c
52 #define SPI_PTCR                                0x0120
53 #define SPI_PTSR                                0x0124
54
55 /* Bitfields in CR */
56 #define SPI_SPIEN_OFFSET                        0
57 #define SPI_SPIEN_SIZE                          1
58 #define SPI_SPIDIS_OFFSET                       1
59 #define SPI_SPIDIS_SIZE                         1
60 #define SPI_SWRST_OFFSET                        7
61 #define SPI_SWRST_SIZE                          1
62 #define SPI_LASTXFER_OFFSET                     24
63 #define SPI_LASTXFER_SIZE                       1
64 #define SPI_TXFCLR_OFFSET                       16
65 #define SPI_TXFCLR_SIZE                         1
66 #define SPI_RXFCLR_OFFSET                       17
67 #define SPI_RXFCLR_SIZE                         1
68 #define SPI_FIFOEN_OFFSET                       30
69 #define SPI_FIFOEN_SIZE                         1
70 #define SPI_FIFODIS_OFFSET                      31
71 #define SPI_FIFODIS_SIZE                        1
72
73 /* Bitfields in MR */
74 #define SPI_MSTR_OFFSET                         0
75 #define SPI_MSTR_SIZE                           1
76 #define SPI_PS_OFFSET                           1
77 #define SPI_PS_SIZE                             1
78 #define SPI_PCSDEC_OFFSET                       2
79 #define SPI_PCSDEC_SIZE                         1
80 #define SPI_FDIV_OFFSET                         3
81 #define SPI_FDIV_SIZE                           1
82 #define SPI_MODFDIS_OFFSET                      4
83 #define SPI_MODFDIS_SIZE                        1
84 #define SPI_WDRBT_OFFSET                        5
85 #define SPI_WDRBT_SIZE                          1
86 #define SPI_LLB_OFFSET                          7
87 #define SPI_LLB_SIZE                            1
88 #define SPI_PCS_OFFSET                          16
89 #define SPI_PCS_SIZE                            4
90 #define SPI_DLYBCS_OFFSET                       24
91 #define SPI_DLYBCS_SIZE                         8
92
93 /* Bitfields in RDR */
94 #define SPI_RD_OFFSET                           0
95 #define SPI_RD_SIZE                             16
96
97 /* Bitfields in TDR */
98 #define SPI_TD_OFFSET                           0
99 #define SPI_TD_SIZE                             16
100
101 /* Bitfields in SR */
102 #define SPI_RDRF_OFFSET                         0
103 #define SPI_RDRF_SIZE                           1
104 #define SPI_TDRE_OFFSET                         1
105 #define SPI_TDRE_SIZE                           1
106 #define SPI_MODF_OFFSET                         2
107 #define SPI_MODF_SIZE                           1
108 #define SPI_OVRES_OFFSET                        3
109 #define SPI_OVRES_SIZE                          1
110 #define SPI_ENDRX_OFFSET                        4
111 #define SPI_ENDRX_SIZE                          1
112 #define SPI_ENDTX_OFFSET                        5
113 #define SPI_ENDTX_SIZE                          1
114 #define SPI_RXBUFF_OFFSET                       6
115 #define SPI_RXBUFF_SIZE                         1
116 #define SPI_TXBUFE_OFFSET                       7
117 #define SPI_TXBUFE_SIZE                         1
118 #define SPI_NSSR_OFFSET                         8
119 #define SPI_NSSR_SIZE                           1
120 #define SPI_TXEMPTY_OFFSET                      9
121 #define SPI_TXEMPTY_SIZE                        1
122 #define SPI_SPIENS_OFFSET                       16
123 #define SPI_SPIENS_SIZE                         1
124 #define SPI_TXFEF_OFFSET                        24
125 #define SPI_TXFEF_SIZE                          1
126 #define SPI_TXFFF_OFFSET                        25
127 #define SPI_TXFFF_SIZE                          1
128 #define SPI_TXFTHF_OFFSET                       26
129 #define SPI_TXFTHF_SIZE                         1
130 #define SPI_RXFEF_OFFSET                        27
131 #define SPI_RXFEF_SIZE                          1
132 #define SPI_RXFFF_OFFSET                        28
133 #define SPI_RXFFF_SIZE                          1
134 #define SPI_RXFTHF_OFFSET                       29
135 #define SPI_RXFTHF_SIZE                         1
136 #define SPI_TXFPTEF_OFFSET                      30
137 #define SPI_TXFPTEF_SIZE                        1
138 #define SPI_RXFPTEF_OFFSET                      31
139 #define SPI_RXFPTEF_SIZE                        1
140
141 /* Bitfields in CSR0 */
142 #define SPI_CPOL_OFFSET                         0
143 #define SPI_CPOL_SIZE                           1
144 #define SPI_NCPHA_OFFSET                        1
145 #define SPI_NCPHA_SIZE                          1
146 #define SPI_CSAAT_OFFSET                        3
147 #define SPI_CSAAT_SIZE                          1
148 #define SPI_BITS_OFFSET                         4
149 #define SPI_BITS_SIZE                           4
150 #define SPI_SCBR_OFFSET                         8
151 #define SPI_SCBR_SIZE                           8
152 #define SPI_DLYBS_OFFSET                        16
153 #define SPI_DLYBS_SIZE                          8
154 #define SPI_DLYBCT_OFFSET                       24
155 #define SPI_DLYBCT_SIZE                         8
156
157 /* Bitfields in RCR */
158 #define SPI_RXCTR_OFFSET                        0
159 #define SPI_RXCTR_SIZE                          16
160
161 /* Bitfields in TCR */
162 #define SPI_TXCTR_OFFSET                        0
163 #define SPI_TXCTR_SIZE                          16
164
165 /* Bitfields in RNCR */
166 #define SPI_RXNCR_OFFSET                        0
167 #define SPI_RXNCR_SIZE                          16
168
169 /* Bitfields in TNCR */
170 #define SPI_TXNCR_OFFSET                        0
171 #define SPI_TXNCR_SIZE                          16
172
173 /* Bitfields in PTCR */
174 #define SPI_RXTEN_OFFSET                        0
175 #define SPI_RXTEN_SIZE                          1
176 #define SPI_RXTDIS_OFFSET                       1
177 #define SPI_RXTDIS_SIZE                         1
178 #define SPI_TXTEN_OFFSET                        8
179 #define SPI_TXTEN_SIZE                          1
180 #define SPI_TXTDIS_OFFSET                       9
181 #define SPI_TXTDIS_SIZE                         1
182
183 /* Bitfields in FMR */
184 #define SPI_TXRDYM_OFFSET                       0
185 #define SPI_TXRDYM_SIZE                         2
186 #define SPI_RXRDYM_OFFSET                       4
187 #define SPI_RXRDYM_SIZE                         2
188 #define SPI_TXFTHRES_OFFSET                     16
189 #define SPI_TXFTHRES_SIZE                       6
190 #define SPI_RXFTHRES_OFFSET                     24
191 #define SPI_RXFTHRES_SIZE                       6
192
193 /* Bitfields in FLR */
194 #define SPI_TXFL_OFFSET                         0
195 #define SPI_TXFL_SIZE                           6
196 #define SPI_RXFL_OFFSET                         16
197 #define SPI_RXFL_SIZE                           6
198
199 /* Constants for BITS */
200 #define SPI_BITS_8_BPT                          0
201 #define SPI_BITS_9_BPT                          1
202 #define SPI_BITS_10_BPT                         2
203 #define SPI_BITS_11_BPT                         3
204 #define SPI_BITS_12_BPT                         4
205 #define SPI_BITS_13_BPT                         5
206 #define SPI_BITS_14_BPT                         6
207 #define SPI_BITS_15_BPT                         7
208 #define SPI_BITS_16_BPT                         8
209 #define SPI_ONE_DATA                            0
210 #define SPI_TWO_DATA                            1
211 #define SPI_FOUR_DATA                           2
212
213 /* Bit manipulation macros */
214 #define SPI_BIT(name) \
215         (1 << SPI_##name##_OFFSET)
216 #define SPI_BF(name, value) \
217         (((value) & ((1 << SPI_##name##_SIZE) - 1)) << SPI_##name##_OFFSET)
218 #define SPI_BFEXT(name, value) \
219         (((value) >> SPI_##name##_OFFSET) & ((1 << SPI_##name##_SIZE) - 1))
220 #define SPI_BFINS(name, value, old) \
221         (((old) & ~(((1 << SPI_##name##_SIZE) - 1) << SPI_##name##_OFFSET)) \
222           | SPI_BF(name, value))
223
224 /* Register access macros */
225 #define spi_readl(port, reg) \
226         readl_relaxed((port)->regs + SPI_##reg)
227 #define spi_writel(port, reg, value) \
228         writel_relaxed((value), (port)->regs + SPI_##reg)
229 #define spi_writew(port, reg, value) \
230         writew_relaxed((value), (port)->regs + SPI_##reg)
231
232 /* use PIO for small transfers, avoiding DMA setup/teardown overhead and
233  * cache operations; better heuristics consider wordsize and bitrate.
234  */
235 #define DMA_MIN_BYTES   16
236
237 #define SPI_DMA_TIMEOUT         (msecs_to_jiffies(1000))
238
239 #define AUTOSUSPEND_TIMEOUT     2000
240
241 struct atmel_spi_caps {
242         bool    is_spi2;
243         bool    has_wdrbt;
244         bool    has_dma_support;
245         bool    has_pdc_support;
246 };
247
248 /*
249  * The core SPI transfer engine just talks to a register bank to set up
250  * DMA transfers; transfer queue progress is driven by IRQs.  The clock
251  * framework provides the base clock, subdivided for each spi_device.
252  */
253 struct atmel_spi {
254         spinlock_t              lock;
255         unsigned long           flags;
256
257         phys_addr_t             phybase;
258         void __iomem            *regs;
259         int                     irq;
260         struct clk              *clk;
261         struct platform_device  *pdev;
262         unsigned long           spi_clk;
263
264         struct spi_transfer     *current_transfer;
265         int                     current_remaining_bytes;
266         int                     done_status;
267         dma_addr_t              dma_addr_rx_bbuf;
268         dma_addr_t              dma_addr_tx_bbuf;
269         void                    *addr_rx_bbuf;
270         void                    *addr_tx_bbuf;
271
272         struct completion       xfer_completion;
273
274         struct atmel_spi_caps   caps;
275
276         bool                    use_dma;
277         bool                    use_pdc;
278
279         bool                    keep_cs;
280         bool                    cs_active;
281
282         u32                     fifo_size;
283         u8                      native_cs_free;
284         u8                      native_cs_for_gpio;
285 };
286
287 /* Controller-specific per-slave state */
288 struct atmel_spi_device {
289         u32                     csr;
290 };
291
292 #define SPI_MAX_DMA_XFER        65535 /* true for both PDC and DMA */
293 #define INVALID_DMA_ADDRESS     0xffffffff
294
295 /*
296  * Version 2 of the SPI controller has
297  *  - CR.LASTXFER
298  *  - SPI_MR.DIV32 may become FDIV or must-be-zero (here: always zero)
299  *  - SPI_SR.TXEMPTY, SPI_SR.NSSR (and corresponding irqs)
300  *  - SPI_CSRx.CSAAT
301  *  - SPI_CSRx.SBCR allows faster clocking
302  */
303 static bool atmel_spi_is_v2(struct atmel_spi *as)
304 {
305         return as->caps.is_spi2;
306 }
307
308 /*
309  * Earlier SPI controllers (e.g. on at91rm9200) have a design bug whereby
310  * they assume that spi slave device state will not change on deselect, so
311  * that automagic deselection is OK.  ("NPCSx rises if no data is to be
312  * transmitted")  Not so!  Workaround uses nCSx pins as GPIOs; or newer
313  * controllers have CSAAT and friends.
314  *
315  * Even controller newer than ar91rm9200, using GPIOs can make sens as
316  * it lets us support active-high chipselects despite the controller's
317  * belief that only active-low devices/systems exists.
318  *
319  * However, at91rm9200 has a second erratum whereby nCS0 doesn't work
320  * right when driven with GPIO.  ("Mode Fault does not allow more than one
321  * Master on Chip Select 0.")  No workaround exists for that ... so for
322  * nCS0 on that chip, we (a) don't use the GPIO, (b) can't support CS_HIGH,
323  * and (c) will trigger that first erratum in some cases.
324  */
325
326 static void cs_activate(struct atmel_spi *as, struct spi_device *spi)
327 {
328         struct atmel_spi_device *asd = spi->controller_state;
329         int chip_select;
330         u32 mr;
331
332         if (spi->cs_gpiod)
333                 chip_select = as->native_cs_for_gpio;
334         else
335                 chip_select = spi->chip_select;
336
337         if (atmel_spi_is_v2(as)) {
338                 spi_writel(as, CSR0 + 4 * chip_select, asd->csr);
339                 /* For the low SPI version, there is a issue that PDC transfer
340                  * on CS1,2,3 needs SPI_CSR0.BITS config as SPI_CSR1,2,3.BITS
341                  */
342                 spi_writel(as, CSR0, asd->csr);
343                 if (as->caps.has_wdrbt) {
344                         spi_writel(as, MR,
345                                         SPI_BF(PCS, ~(0x01 << chip_select))
346                                         | SPI_BIT(WDRBT)
347                                         | SPI_BIT(MODFDIS)
348                                         | SPI_BIT(MSTR));
349                 } else {
350                         spi_writel(as, MR,
351                                         SPI_BF(PCS, ~(0x01 << chip_select))
352                                         | SPI_BIT(MODFDIS)
353                                         | SPI_BIT(MSTR));
354                 }
355
356                 mr = spi_readl(as, MR);
357                 if (spi->cs_gpiod)
358                         gpiod_set_value(spi->cs_gpiod, 1);
359         } else {
360                 u32 cpol = (spi->mode & SPI_CPOL) ? SPI_BIT(CPOL) : 0;
361                 int i;
362                 u32 csr;
363
364                 /* Make sure clock polarity is correct */
365                 for (i = 0; i < spi->master->num_chipselect; i++) {
366                         csr = spi_readl(as, CSR0 + 4 * i);
367                         if ((csr ^ cpol) & SPI_BIT(CPOL))
368                                 spi_writel(as, CSR0 + 4 * i,
369                                                 csr ^ SPI_BIT(CPOL));
370                 }
371
372                 mr = spi_readl(as, MR);
373                 mr = SPI_BFINS(PCS, ~(1 << chip_select), mr);
374                 if (spi->cs_gpiod)
375                         gpiod_set_value(spi->cs_gpiod, 1);
376                 spi_writel(as, MR, mr);
377         }
378
379         dev_dbg(&spi->dev, "activate NPCS, mr %08x\n", mr);
380 }
381
382 static void cs_deactivate(struct atmel_spi *as, struct spi_device *spi)
383 {
384         int chip_select;
385         u32 mr;
386
387         if (spi->cs_gpiod)
388                 chip_select = as->native_cs_for_gpio;
389         else
390                 chip_select = spi->chip_select;
391
392         /* only deactivate *this* device; sometimes transfers to
393          * another device may be active when this routine is called.
394          */
395         mr = spi_readl(as, MR);
396         if (~SPI_BFEXT(PCS, mr) & (1 << chip_select)) {
397                 mr = SPI_BFINS(PCS, 0xf, mr);
398                 spi_writel(as, MR, mr);
399         }
400
401         dev_dbg(&spi->dev, "DEactivate NPCS, mr %08x\n", mr);
402
403         if (!spi->cs_gpiod)
404                 spi_writel(as, CR, SPI_BIT(LASTXFER));
405         else
406                 gpiod_set_value(spi->cs_gpiod, 0);
407 }
408
409 static void atmel_spi_lock(struct atmel_spi *as) __acquires(&as->lock)
410 {
411         spin_lock_irqsave(&as->lock, as->flags);
412 }
413
414 static void atmel_spi_unlock(struct atmel_spi *as) __releases(&as->lock)
415 {
416         spin_unlock_irqrestore(&as->lock, as->flags);
417 }
418
419 static inline bool atmel_spi_is_vmalloc_xfer(struct spi_transfer *xfer)
420 {
421         return is_vmalloc_addr(xfer->tx_buf) || is_vmalloc_addr(xfer->rx_buf);
422 }
423
424 static inline bool atmel_spi_use_dma(struct atmel_spi *as,
425                                 struct spi_transfer *xfer)
426 {
427         return as->use_dma && xfer->len >= DMA_MIN_BYTES;
428 }
429
430 static bool atmel_spi_can_dma(struct spi_master *master,
431                               struct spi_device *spi,
432                               struct spi_transfer *xfer)
433 {
434         struct atmel_spi *as = spi_master_get_devdata(master);
435
436         if (IS_ENABLED(CONFIG_SOC_SAM_V4_V5))
437                 return atmel_spi_use_dma(as, xfer) &&
438                         !atmel_spi_is_vmalloc_xfer(xfer);
439         else
440                 return atmel_spi_use_dma(as, xfer);
441
442 }
443
444 static int atmel_spi_dma_slave_config(struct atmel_spi *as,
445                                 struct dma_slave_config *slave_config,
446                                 u8 bits_per_word)
447 {
448         struct spi_master *master = platform_get_drvdata(as->pdev);
449         int err = 0;
450
451         if (bits_per_word > 8) {
452                 slave_config->dst_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
453                 slave_config->src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
454         } else {
455                 slave_config->dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
456                 slave_config->src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
457         }
458
459         slave_config->dst_addr = (dma_addr_t)as->phybase + SPI_TDR;
460         slave_config->src_addr = (dma_addr_t)as->phybase + SPI_RDR;
461         slave_config->src_maxburst = 1;
462         slave_config->dst_maxburst = 1;
463         slave_config->device_fc = false;
464
465         /*
466          * This driver uses fixed peripheral select mode (PS bit set to '0' in
467          * the Mode Register).
468          * So according to the datasheet, when FIFOs are available (and
469          * enabled), the Transmit FIFO operates in Multiple Data Mode.
470          * In this mode, up to 2 data, not 4, can be written into the Transmit
471          * Data Register in a single access.
472          * However, the first data has to be written into the lowest 16 bits and
473          * the second data into the highest 16 bits of the Transmit
474          * Data Register. For 8bit data (the most frequent case), it would
475          * require to rework tx_buf so each data would actualy fit 16 bits.
476          * So we'd rather write only one data at the time. Hence the transmit
477          * path works the same whether FIFOs are available (and enabled) or not.
478          */
479         slave_config->direction = DMA_MEM_TO_DEV;
480         if (dmaengine_slave_config(master->dma_tx, slave_config)) {
481                 dev_err(&as->pdev->dev,
482                         "failed to configure tx dma channel\n");
483                 err = -EINVAL;
484         }
485
486         /*
487          * This driver configures the spi controller for master mode (MSTR bit
488          * set to '1' in the Mode Register).
489          * So according to the datasheet, when FIFOs are available (and
490          * enabled), the Receive FIFO operates in Single Data Mode.
491          * So the receive path works the same whether FIFOs are available (and
492          * enabled) or not.
493          */
494         slave_config->direction = DMA_DEV_TO_MEM;
495         if (dmaengine_slave_config(master->dma_rx, slave_config)) {
496                 dev_err(&as->pdev->dev,
497                         "failed to configure rx dma channel\n");
498                 err = -EINVAL;
499         }
500
501         return err;
502 }
503
504 static int atmel_spi_configure_dma(struct spi_master *master,
505                                    struct atmel_spi *as)
506 {
507         struct dma_slave_config slave_config;
508         struct device *dev = &as->pdev->dev;
509         int err;
510
511         dma_cap_mask_t mask;
512         dma_cap_zero(mask);
513         dma_cap_set(DMA_SLAVE, mask);
514
515         master->dma_tx = dma_request_chan(dev, "tx");
516         if (IS_ERR(master->dma_tx)) {
517                 err = PTR_ERR(master->dma_tx);
518                 if (err == -EPROBE_DEFER) {
519                         dev_warn(dev, "no DMA channel available at the moment\n");
520                         goto error_clear;
521                 }
522                 dev_err(dev,
523                         "DMA TX channel not available, SPI unable to use DMA\n");
524                 err = -EBUSY;
525                 goto error_clear;
526         }
527
528         /*
529          * No reason to check EPROBE_DEFER here since we have already requested
530          * tx channel. If it fails here, it's for another reason.
531          */
532         master->dma_rx = dma_request_slave_channel(dev, "rx");
533
534         if (!master->dma_rx) {
535                 dev_err(dev,
536                         "DMA RX channel not available, SPI unable to use DMA\n");
537                 err = -EBUSY;
538                 goto error;
539         }
540
541         err = atmel_spi_dma_slave_config(as, &slave_config, 8);
542         if (err)
543                 goto error;
544
545         dev_info(&as->pdev->dev,
546                         "Using %s (tx) and %s (rx) for DMA transfers\n",
547                         dma_chan_name(master->dma_tx),
548                         dma_chan_name(master->dma_rx));
549
550         return 0;
551 error:
552         if (master->dma_rx)
553                 dma_release_channel(master->dma_rx);
554         if (!IS_ERR(master->dma_tx))
555                 dma_release_channel(master->dma_tx);
556 error_clear:
557         master->dma_tx = master->dma_rx = NULL;
558         return err;
559 }
560
561 static void atmel_spi_stop_dma(struct spi_master *master)
562 {
563         if (master->dma_rx)
564                 dmaengine_terminate_all(master->dma_rx);
565         if (master->dma_tx)
566                 dmaengine_terminate_all(master->dma_tx);
567 }
568
569 static void atmel_spi_release_dma(struct spi_master *master)
570 {
571         if (master->dma_rx) {
572                 dma_release_channel(master->dma_rx);
573                 master->dma_rx = NULL;
574         }
575         if (master->dma_tx) {
576                 dma_release_channel(master->dma_tx);
577                 master->dma_tx = NULL;
578         }
579 }
580
581 /* This function is called by the DMA driver from tasklet context */
582 static void dma_callback(void *data)
583 {
584         struct spi_master       *master = data;
585         struct atmel_spi        *as = spi_master_get_devdata(master);
586
587         if (is_vmalloc_addr(as->current_transfer->rx_buf) &&
588             IS_ENABLED(CONFIG_SOC_SAM_V4_V5)) {
589                 memcpy(as->current_transfer->rx_buf, as->addr_rx_bbuf,
590                        as->current_transfer->len);
591         }
592         complete(&as->xfer_completion);
593 }
594
595 /*
596  * Next transfer using PIO without FIFO.
597  */
598 static void atmel_spi_next_xfer_single(struct spi_master *master,
599                                        struct spi_transfer *xfer)
600 {
601         struct atmel_spi        *as = spi_master_get_devdata(master);
602         unsigned long xfer_pos = xfer->len - as->current_remaining_bytes;
603
604         dev_vdbg(master->dev.parent, "atmel_spi_next_xfer_pio\n");
605
606         /* Make sure data is not remaining in RDR */
607         spi_readl(as, RDR);
608         while (spi_readl(as, SR) & SPI_BIT(RDRF)) {
609                 spi_readl(as, RDR);
610                 cpu_relax();
611         }
612
613         if (xfer->bits_per_word > 8)
614                 spi_writel(as, TDR, *(u16 *)(xfer->tx_buf + xfer_pos));
615         else
616                 spi_writel(as, TDR, *(u8 *)(xfer->tx_buf + xfer_pos));
617
618         dev_dbg(master->dev.parent,
619                 "  start pio xfer %p: len %u tx %p rx %p bitpw %d\n",
620                 xfer, xfer->len, xfer->tx_buf, xfer->rx_buf,
621                 xfer->bits_per_word);
622
623         /* Enable relevant interrupts */
624         spi_writel(as, IER, SPI_BIT(RDRF) | SPI_BIT(OVRES));
625 }
626
627 /*
628  * Next transfer using PIO with FIFO.
629  */
630 static void atmel_spi_next_xfer_fifo(struct spi_master *master,
631                                      struct spi_transfer *xfer)
632 {
633         struct atmel_spi *as = spi_master_get_devdata(master);
634         u32 current_remaining_data, num_data;
635         u32 offset = xfer->len - as->current_remaining_bytes;
636         const u16 *words = (const u16 *)((u8 *)xfer->tx_buf + offset);
637         const u8  *bytes = (const u8  *)((u8 *)xfer->tx_buf + offset);
638         u16 td0, td1;
639         u32 fifomr;
640
641         dev_vdbg(master->dev.parent, "atmel_spi_next_xfer_fifo\n");
642
643         /* Compute the number of data to transfer in the current iteration */
644         current_remaining_data = ((xfer->bits_per_word > 8) ?
645                                   ((u32)as->current_remaining_bytes >> 1) :
646                                   (u32)as->current_remaining_bytes);
647         num_data = min(current_remaining_data, as->fifo_size);
648
649         /* Flush RX and TX FIFOs */
650         spi_writel(as, CR, SPI_BIT(RXFCLR) | SPI_BIT(TXFCLR));
651         while (spi_readl(as, FLR))
652                 cpu_relax();
653
654         /* Set RX FIFO Threshold to the number of data to transfer */
655         fifomr = spi_readl(as, FMR);
656         spi_writel(as, FMR, SPI_BFINS(RXFTHRES, num_data, fifomr));
657
658         /* Clear FIFO flags in the Status Register, especially RXFTHF */
659         (void)spi_readl(as, SR);
660
661         /* Fill TX FIFO */
662         while (num_data >= 2) {
663                 if (xfer->bits_per_word > 8) {
664                         td0 = *words++;
665                         td1 = *words++;
666                 } else {
667                         td0 = *bytes++;
668                         td1 = *bytes++;
669                 }
670
671                 spi_writel(as, TDR, (td1 << 16) | td0);
672                 num_data -= 2;
673         }
674
675         if (num_data) {
676                 if (xfer->bits_per_word > 8)
677                         td0 = *words++;
678                 else
679                         td0 = *bytes++;
680
681                 spi_writew(as, TDR, td0);
682                 num_data--;
683         }
684
685         dev_dbg(master->dev.parent,
686                 "  start fifo xfer %p: len %u tx %p rx %p bitpw %d\n",
687                 xfer, xfer->len, xfer->tx_buf, xfer->rx_buf,
688                 xfer->bits_per_word);
689
690         /*
691          * Enable RX FIFO Threshold Flag interrupt to be notified about
692          * transfer completion.
693          */
694         spi_writel(as, IER, SPI_BIT(RXFTHF) | SPI_BIT(OVRES));
695 }
696
697 /*
698  * Next transfer using PIO.
699  */
700 static void atmel_spi_next_xfer_pio(struct spi_master *master,
701                                     struct spi_transfer *xfer)
702 {
703         struct atmel_spi *as = spi_master_get_devdata(master);
704
705         if (as->fifo_size)
706                 atmel_spi_next_xfer_fifo(master, xfer);
707         else
708                 atmel_spi_next_xfer_single(master, xfer);
709 }
710
711 /*
712  * Submit next transfer for DMA.
713  */
714 static int atmel_spi_next_xfer_dma_submit(struct spi_master *master,
715                                 struct spi_transfer *xfer,
716                                 u32 *plen)
717 {
718         struct atmel_spi        *as = spi_master_get_devdata(master);
719         struct dma_chan         *rxchan = master->dma_rx;
720         struct dma_chan         *txchan = master->dma_tx;
721         struct dma_async_tx_descriptor *rxdesc;
722         struct dma_async_tx_descriptor *txdesc;
723         struct dma_slave_config slave_config;
724         dma_cookie_t            cookie;
725
726         dev_vdbg(master->dev.parent, "atmel_spi_next_xfer_dma_submit\n");
727
728         /* Check that the channels are available */
729         if (!rxchan || !txchan)
730                 return -ENODEV;
731
732         /* release lock for DMA operations */
733         atmel_spi_unlock(as);
734
735         *plen = xfer->len;
736
737         if (atmel_spi_dma_slave_config(as, &slave_config,
738                                        xfer->bits_per_word))
739                 goto err_exit;
740
741         /* Send both scatterlists */
742         if (atmel_spi_is_vmalloc_xfer(xfer) &&
743             IS_ENABLED(CONFIG_SOC_SAM_V4_V5)) {
744                 rxdesc = dmaengine_prep_slave_single(rxchan,
745                                                      as->dma_addr_rx_bbuf,
746                                                      xfer->len,
747                                                      DMA_DEV_TO_MEM,
748                                                      DMA_PREP_INTERRUPT |
749                                                      DMA_CTRL_ACK);
750         } else {
751                 rxdesc = dmaengine_prep_slave_sg(rxchan,
752                                                  xfer->rx_sg.sgl,
753                                                  xfer->rx_sg.nents,
754                                                  DMA_DEV_TO_MEM,
755                                                  DMA_PREP_INTERRUPT |
756                                                  DMA_CTRL_ACK);
757         }
758         if (!rxdesc)
759                 goto err_dma;
760
761         if (atmel_spi_is_vmalloc_xfer(xfer) &&
762             IS_ENABLED(CONFIG_SOC_SAM_V4_V5)) {
763                 memcpy(as->addr_tx_bbuf, xfer->tx_buf, xfer->len);
764                 txdesc = dmaengine_prep_slave_single(txchan,
765                                                      as->dma_addr_tx_bbuf,
766                                                      xfer->len, DMA_MEM_TO_DEV,
767                                                      DMA_PREP_INTERRUPT |
768                                                      DMA_CTRL_ACK);
769         } else {
770                 txdesc = dmaengine_prep_slave_sg(txchan,
771                                                  xfer->tx_sg.sgl,
772                                                  xfer->tx_sg.nents,
773                                                  DMA_MEM_TO_DEV,
774                                                  DMA_PREP_INTERRUPT |
775                                                  DMA_CTRL_ACK);
776         }
777         if (!txdesc)
778                 goto err_dma;
779
780         dev_dbg(master->dev.parent,
781                 "  start dma xfer %p: len %u tx %p/%08llx rx %p/%08llx\n",
782                 xfer, xfer->len, xfer->tx_buf, (unsigned long long)xfer->tx_dma,
783                 xfer->rx_buf, (unsigned long long)xfer->rx_dma);
784
785         /* Enable relevant interrupts */
786         spi_writel(as, IER, SPI_BIT(OVRES));
787
788         /* Put the callback on the RX transfer only, that should finish last */
789         rxdesc->callback = dma_callback;
790         rxdesc->callback_param = master;
791
792         /* Submit and fire RX and TX with TX last so we're ready to read! */
793         cookie = rxdesc->tx_submit(rxdesc);
794         if (dma_submit_error(cookie))
795                 goto err_dma;
796         cookie = txdesc->tx_submit(txdesc);
797         if (dma_submit_error(cookie))
798                 goto err_dma;
799         rxchan->device->device_issue_pending(rxchan);
800         txchan->device->device_issue_pending(txchan);
801
802         /* take back lock */
803         atmel_spi_lock(as);
804         return 0;
805
806 err_dma:
807         spi_writel(as, IDR, SPI_BIT(OVRES));
808         atmel_spi_stop_dma(master);
809 err_exit:
810         atmel_spi_lock(as);
811         return -ENOMEM;
812 }
813
814 static void atmel_spi_next_xfer_data(struct spi_master *master,
815                                 struct spi_transfer *xfer,
816                                 dma_addr_t *tx_dma,
817                                 dma_addr_t *rx_dma,
818                                 u32 *plen)
819 {
820         *rx_dma = xfer->rx_dma + xfer->len - *plen;
821         *tx_dma = xfer->tx_dma + xfer->len - *plen;
822         if (*plen > master->max_dma_len)
823                 *plen = master->max_dma_len;
824 }
825
826 static int atmel_spi_set_xfer_speed(struct atmel_spi *as,
827                                     struct spi_device *spi,
828                                     struct spi_transfer *xfer)
829 {
830         u32                     scbr, csr;
831         unsigned long           bus_hz;
832         int chip_select;
833
834         if (spi->cs_gpiod)
835                 chip_select = as->native_cs_for_gpio;
836         else
837                 chip_select = spi->chip_select;
838
839         /* v1 chips start out at half the peripheral bus speed. */
840         bus_hz = as->spi_clk;
841         if (!atmel_spi_is_v2(as))
842                 bus_hz /= 2;
843
844         /*
845          * Calculate the lowest divider that satisfies the
846          * constraint, assuming div32/fdiv/mbz == 0.
847          */
848         scbr = DIV_ROUND_UP(bus_hz, xfer->speed_hz);
849
850         /*
851          * If the resulting divider doesn't fit into the
852          * register bitfield, we can't satisfy the constraint.
853          */
854         if (scbr >= (1 << SPI_SCBR_SIZE)) {
855                 dev_err(&spi->dev,
856                         "setup: %d Hz too slow, scbr %u; min %ld Hz\n",
857                         xfer->speed_hz, scbr, bus_hz/255);
858                 return -EINVAL;
859         }
860         if (scbr == 0) {
861                 dev_err(&spi->dev,
862                         "setup: %d Hz too high, scbr %u; max %ld Hz\n",
863                         xfer->speed_hz, scbr, bus_hz);
864                 return -EINVAL;
865         }
866         csr = spi_readl(as, CSR0 + 4 * chip_select);
867         csr = SPI_BFINS(SCBR, scbr, csr);
868         spi_writel(as, CSR0 + 4 * chip_select, csr);
869
870         return 0;
871 }
872
873 /*
874  * Submit next transfer for PDC.
875  * lock is held, spi irq is blocked
876  */
877 static void atmel_spi_pdc_next_xfer(struct spi_master *master,
878                                         struct spi_message *msg,
879                                         struct spi_transfer *xfer)
880 {
881         struct atmel_spi        *as = spi_master_get_devdata(master);
882         u32                     len;
883         dma_addr_t              tx_dma, rx_dma;
884
885         spi_writel(as, PTCR, SPI_BIT(RXTDIS) | SPI_BIT(TXTDIS));
886
887         len = as->current_remaining_bytes;
888         atmel_spi_next_xfer_data(master, xfer, &tx_dma, &rx_dma, &len);
889         as->current_remaining_bytes -= len;
890
891         spi_writel(as, RPR, rx_dma);
892         spi_writel(as, TPR, tx_dma);
893
894         if (msg->spi->bits_per_word > 8)
895                 len >>= 1;
896         spi_writel(as, RCR, len);
897         spi_writel(as, TCR, len);
898
899         dev_dbg(&msg->spi->dev,
900                 "  start xfer %p: len %u tx %p/%08llx rx %p/%08llx\n",
901                 xfer, xfer->len, xfer->tx_buf,
902                 (unsigned long long)xfer->tx_dma, xfer->rx_buf,
903                 (unsigned long long)xfer->rx_dma);
904
905         if (as->current_remaining_bytes) {
906                 len = as->current_remaining_bytes;
907                 atmel_spi_next_xfer_data(master, xfer, &tx_dma, &rx_dma, &len);
908                 as->current_remaining_bytes -= len;
909
910                 spi_writel(as, RNPR, rx_dma);
911                 spi_writel(as, TNPR, tx_dma);
912
913                 if (msg->spi->bits_per_word > 8)
914                         len >>= 1;
915                 spi_writel(as, RNCR, len);
916                 spi_writel(as, TNCR, len);
917
918                 dev_dbg(&msg->spi->dev,
919                         "  next xfer %p: len %u tx %p/%08llx rx %p/%08llx\n",
920                         xfer, xfer->len, xfer->tx_buf,
921                         (unsigned long long)xfer->tx_dma, xfer->rx_buf,
922                         (unsigned long long)xfer->rx_dma);
923         }
924
925         /* REVISIT: We're waiting for RXBUFF before we start the next
926          * transfer because we need to handle some difficult timing
927          * issues otherwise. If we wait for TXBUFE in one transfer and
928          * then starts waiting for RXBUFF in the next, it's difficult
929          * to tell the difference between the RXBUFF interrupt we're
930          * actually waiting for and the RXBUFF interrupt of the
931          * previous transfer.
932          *
933          * It should be doable, though. Just not now...
934          */
935         spi_writel(as, IER, SPI_BIT(RXBUFF) | SPI_BIT(OVRES));
936         spi_writel(as, PTCR, SPI_BIT(TXTEN) | SPI_BIT(RXTEN));
937 }
938
939 /*
940  * For DMA, tx_buf/tx_dma have the same relationship as rx_buf/rx_dma:
941  *  - The buffer is either valid for CPU access, else NULL
942  *  - If the buffer is valid, so is its DMA address
943  *
944  * This driver manages the dma address unless message->is_dma_mapped.
945  */
946 static int
947 atmel_spi_dma_map_xfer(struct atmel_spi *as, struct spi_transfer *xfer)
948 {
949         struct device   *dev = &as->pdev->dev;
950
951         xfer->tx_dma = xfer->rx_dma = INVALID_DMA_ADDRESS;
952         if (xfer->tx_buf) {
953                 /* tx_buf is a const void* where we need a void * for the dma
954                  * mapping */
955                 void *nonconst_tx = (void *)xfer->tx_buf;
956
957                 xfer->tx_dma = dma_map_single(dev,
958                                 nonconst_tx, xfer->len,
959                                 DMA_TO_DEVICE);
960                 if (dma_mapping_error(dev, xfer->tx_dma))
961                         return -ENOMEM;
962         }
963         if (xfer->rx_buf) {
964                 xfer->rx_dma = dma_map_single(dev,
965                                 xfer->rx_buf, xfer->len,
966                                 DMA_FROM_DEVICE);
967                 if (dma_mapping_error(dev, xfer->rx_dma)) {
968                         if (xfer->tx_buf)
969                                 dma_unmap_single(dev,
970                                                 xfer->tx_dma, xfer->len,
971                                                 DMA_TO_DEVICE);
972                         return -ENOMEM;
973                 }
974         }
975         return 0;
976 }
977
978 static void atmel_spi_dma_unmap_xfer(struct spi_master *master,
979                                      struct spi_transfer *xfer)
980 {
981         if (xfer->tx_dma != INVALID_DMA_ADDRESS)
982                 dma_unmap_single(master->dev.parent, xfer->tx_dma,
983                                  xfer->len, DMA_TO_DEVICE);
984         if (xfer->rx_dma != INVALID_DMA_ADDRESS)
985                 dma_unmap_single(master->dev.parent, xfer->rx_dma,
986                                  xfer->len, DMA_FROM_DEVICE);
987 }
988
989 static void atmel_spi_disable_pdc_transfer(struct atmel_spi *as)
990 {
991         spi_writel(as, PTCR, SPI_BIT(RXTDIS) | SPI_BIT(TXTDIS));
992 }
993
994 static void
995 atmel_spi_pump_single_data(struct atmel_spi *as, struct spi_transfer *xfer)
996 {
997         u8              *rxp;
998         u16             *rxp16;
999         unsigned long   xfer_pos = xfer->len - as->current_remaining_bytes;
1000
1001         if (xfer->bits_per_word > 8) {
1002                 rxp16 = (u16 *)(((u8 *)xfer->rx_buf) + xfer_pos);
1003                 *rxp16 = spi_readl(as, RDR);
1004         } else {
1005                 rxp = ((u8 *)xfer->rx_buf) + xfer_pos;
1006                 *rxp = spi_readl(as, RDR);
1007         }
1008         if (xfer->bits_per_word > 8) {
1009                 if (as->current_remaining_bytes > 2)
1010                         as->current_remaining_bytes -= 2;
1011                 else
1012                         as->current_remaining_bytes = 0;
1013         } else {
1014                 as->current_remaining_bytes--;
1015         }
1016 }
1017
1018 static void
1019 atmel_spi_pump_fifo_data(struct atmel_spi *as, struct spi_transfer *xfer)
1020 {
1021         u32 fifolr = spi_readl(as, FLR);
1022         u32 num_bytes, num_data = SPI_BFEXT(RXFL, fifolr);
1023         u32 offset = xfer->len - as->current_remaining_bytes;
1024         u16 *words = (u16 *)((u8 *)xfer->rx_buf + offset);
1025         u8  *bytes = (u8  *)((u8 *)xfer->rx_buf + offset);
1026         u16 rd; /* RD field is the lowest 16 bits of RDR */
1027
1028         /* Update the number of remaining bytes to transfer */
1029         num_bytes = ((xfer->bits_per_word > 8) ?
1030                      (num_data << 1) :
1031                      num_data);
1032
1033         if (as->current_remaining_bytes > num_bytes)
1034                 as->current_remaining_bytes -= num_bytes;
1035         else
1036                 as->current_remaining_bytes = 0;
1037
1038         /* Handle odd number of bytes when data are more than 8bit width */
1039         if (xfer->bits_per_word > 8)
1040                 as->current_remaining_bytes &= ~0x1;
1041
1042         /* Read data */
1043         while (num_data) {
1044                 rd = spi_readl(as, RDR);
1045                 if (xfer->bits_per_word > 8)
1046                         *words++ = rd;
1047                 else
1048                         *bytes++ = rd;
1049                 num_data--;
1050         }
1051 }
1052
1053 /* Called from IRQ
1054  *
1055  * Must update "current_remaining_bytes" to keep track of data
1056  * to transfer.
1057  */
1058 static void
1059 atmel_spi_pump_pio_data(struct atmel_spi *as, struct spi_transfer *xfer)
1060 {
1061         if (as->fifo_size)
1062                 atmel_spi_pump_fifo_data(as, xfer);
1063         else
1064                 atmel_spi_pump_single_data(as, xfer);
1065 }
1066
1067 /* Interrupt
1068  *
1069  * No need for locking in this Interrupt handler: done_status is the
1070  * only information modified.
1071  */
1072 static irqreturn_t
1073 atmel_spi_pio_interrupt(int irq, void *dev_id)
1074 {
1075         struct spi_master       *master = dev_id;
1076         struct atmel_spi        *as = spi_master_get_devdata(master);
1077         u32                     status, pending, imr;
1078         struct spi_transfer     *xfer;
1079         int                     ret = IRQ_NONE;
1080
1081         imr = spi_readl(as, IMR);
1082         status = spi_readl(as, SR);
1083         pending = status & imr;
1084
1085         if (pending & SPI_BIT(OVRES)) {
1086                 ret = IRQ_HANDLED;
1087                 spi_writel(as, IDR, SPI_BIT(OVRES));
1088                 dev_warn(master->dev.parent, "overrun\n");
1089
1090                 /*
1091                  * When we get an overrun, we disregard the current
1092                  * transfer. Data will not be copied back from any
1093                  * bounce buffer and msg->actual_len will not be
1094                  * updated with the last xfer.
1095                  *
1096                  * We will also not process any remaning transfers in
1097                  * the message.
1098                  */
1099                 as->done_status = -EIO;
1100                 smp_wmb();
1101
1102                 /* Clear any overrun happening while cleaning up */
1103                 spi_readl(as, SR);
1104
1105                 complete(&as->xfer_completion);
1106
1107         } else if (pending & (SPI_BIT(RDRF) | SPI_BIT(RXFTHF))) {
1108                 atmel_spi_lock(as);
1109
1110                 if (as->current_remaining_bytes) {
1111                         ret = IRQ_HANDLED;
1112                         xfer = as->current_transfer;
1113                         atmel_spi_pump_pio_data(as, xfer);
1114                         if (!as->current_remaining_bytes)
1115                                 spi_writel(as, IDR, pending);
1116
1117                         complete(&as->xfer_completion);
1118                 }
1119
1120                 atmel_spi_unlock(as);
1121         } else {
1122                 WARN_ONCE(pending, "IRQ not handled, pending = %x\n", pending);
1123                 ret = IRQ_HANDLED;
1124                 spi_writel(as, IDR, pending);
1125         }
1126
1127         return ret;
1128 }
1129
1130 static irqreturn_t
1131 atmel_spi_pdc_interrupt(int irq, void *dev_id)
1132 {
1133         struct spi_master       *master = dev_id;
1134         struct atmel_spi        *as = spi_master_get_devdata(master);
1135         u32                     status, pending, imr;
1136         int                     ret = IRQ_NONE;
1137
1138         imr = spi_readl(as, IMR);
1139         status = spi_readl(as, SR);
1140         pending = status & imr;
1141
1142         if (pending & SPI_BIT(OVRES)) {
1143
1144                 ret = IRQ_HANDLED;
1145
1146                 spi_writel(as, IDR, (SPI_BIT(RXBUFF) | SPI_BIT(ENDRX)
1147                                      | SPI_BIT(OVRES)));
1148
1149                 /* Clear any overrun happening while cleaning up */
1150                 spi_readl(as, SR);
1151
1152                 as->done_status = -EIO;
1153
1154                 complete(&as->xfer_completion);
1155
1156         } else if (pending & (SPI_BIT(RXBUFF) | SPI_BIT(ENDRX))) {
1157                 ret = IRQ_HANDLED;
1158
1159                 spi_writel(as, IDR, pending);
1160
1161                 complete(&as->xfer_completion);
1162         }
1163
1164         return ret;
1165 }
1166
1167 static int atmel_word_delay_csr(struct spi_device *spi, struct atmel_spi *as)
1168 {
1169         struct spi_delay *delay = &spi->word_delay;
1170         u32 value = delay->value;
1171
1172         switch (delay->unit) {
1173         case SPI_DELAY_UNIT_NSECS:
1174                 value /= 1000;
1175                 break;
1176         case SPI_DELAY_UNIT_USECS:
1177                 break;
1178         default:
1179                 return -EINVAL;
1180         }
1181
1182         return (as->spi_clk / 1000000 * value) >> 5;
1183 }
1184
1185 static void initialize_native_cs_for_gpio(struct atmel_spi *as)
1186 {
1187         int i;
1188         struct spi_master *master = platform_get_drvdata(as->pdev);
1189
1190         if (!as->native_cs_free)
1191                 return; /* already initialized */
1192
1193         if (!master->cs_gpiods)
1194                 return; /* No CS GPIO */
1195
1196         /*
1197          * On the first version of the controller (AT91RM9200), CS0
1198          * can't be used associated with GPIO
1199          */
1200         if (atmel_spi_is_v2(as))
1201                 i = 0;
1202         else
1203                 i = 1;
1204
1205         for (; i < 4; i++)
1206                 if (master->cs_gpiods[i])
1207                         as->native_cs_free |= BIT(i);
1208
1209         if (as->native_cs_free)
1210                 as->native_cs_for_gpio = ffs(as->native_cs_free);
1211 }
1212
1213 static int atmel_spi_setup(struct spi_device *spi)
1214 {
1215         struct atmel_spi        *as;
1216         struct atmel_spi_device *asd;
1217         u32                     csr;
1218         unsigned int            bits = spi->bits_per_word;
1219         int chip_select;
1220         int                     word_delay_csr;
1221
1222         as = spi_master_get_devdata(spi->master);
1223
1224         /* see notes above re chipselect */
1225         if (!spi->cs_gpiod && (spi->mode & SPI_CS_HIGH)) {
1226                 dev_warn(&spi->dev, "setup: non GPIO CS can't be active-high\n");
1227                 return -EINVAL;
1228         }
1229
1230         /* Setup() is called during spi_register_controller(aka
1231          * spi_register_master) but after all membmers of the cs_gpiod
1232          * array have been filled, so we can looked for which native
1233          * CS will be free for using with GPIO
1234          */
1235         initialize_native_cs_for_gpio(as);
1236
1237         if (spi->cs_gpiod && as->native_cs_free) {
1238                 dev_err(&spi->dev,
1239                         "No native CS available to support this GPIO CS\n");
1240                 return -EBUSY;
1241         }
1242
1243         if (spi->cs_gpiod)
1244                 chip_select = as->native_cs_for_gpio;
1245         else
1246                 chip_select = spi->chip_select;
1247
1248         csr = SPI_BF(BITS, bits - 8);
1249         if (spi->mode & SPI_CPOL)
1250                 csr |= SPI_BIT(CPOL);
1251         if (!(spi->mode & SPI_CPHA))
1252                 csr |= SPI_BIT(NCPHA);
1253
1254         if (!spi->cs_gpiod)
1255                 csr |= SPI_BIT(CSAAT);
1256         csr |= SPI_BF(DLYBS, 0);
1257
1258         word_delay_csr = atmel_word_delay_csr(spi, as);
1259         if (word_delay_csr < 0)
1260                 return word_delay_csr;
1261
1262         /* DLYBCT adds delays between words.  This is useful for slow devices
1263          * that need a bit of time to setup the next transfer.
1264          */
1265         csr |= SPI_BF(DLYBCT, word_delay_csr);
1266
1267         asd = spi->controller_state;
1268         if (!asd) {
1269                 asd = kzalloc(sizeof(struct atmel_spi_device), GFP_KERNEL);
1270                 if (!asd)
1271                         return -ENOMEM;
1272
1273                 spi->controller_state = asd;
1274         }
1275
1276         asd->csr = csr;
1277
1278         dev_dbg(&spi->dev,
1279                 "setup: bpw %u mode 0x%x -> csr%d %08x\n",
1280                 bits, spi->mode, spi->chip_select, csr);
1281
1282         if (!atmel_spi_is_v2(as))
1283                 spi_writel(as, CSR0 + 4 * chip_select, csr);
1284
1285         return 0;
1286 }
1287
1288 static int atmel_spi_one_transfer(struct spi_master *master,
1289                                         struct spi_message *msg,
1290                                         struct spi_transfer *xfer)
1291 {
1292         struct atmel_spi        *as;
1293         struct spi_device       *spi = msg->spi;
1294         u8                      bits;
1295         u32                     len;
1296         struct atmel_spi_device *asd;
1297         int                     timeout;
1298         int                     ret;
1299         unsigned long           dma_timeout;
1300
1301         as = spi_master_get_devdata(master);
1302
1303         if (!(xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1304                 dev_dbg(&spi->dev, "missing rx or tx buf\n");
1305                 return -EINVAL;
1306         }
1307
1308         asd = spi->controller_state;
1309         bits = (asd->csr >> 4) & 0xf;
1310         if (bits != xfer->bits_per_word - 8) {
1311                 dev_dbg(&spi->dev,
1312                         "you can't yet change bits_per_word in transfers\n");
1313                 return -ENOPROTOOPT;
1314         }
1315
1316         /*
1317          * DMA map early, for performance (empties dcache ASAP) and
1318          * better fault reporting.
1319          */
1320         if ((!msg->is_dma_mapped)
1321                 && as->use_pdc) {
1322                 if (atmel_spi_dma_map_xfer(as, xfer) < 0)
1323                         return -ENOMEM;
1324         }
1325
1326         atmel_spi_set_xfer_speed(as, msg->spi, xfer);
1327
1328         as->done_status = 0;
1329         as->current_transfer = xfer;
1330         as->current_remaining_bytes = xfer->len;
1331         while (as->current_remaining_bytes) {
1332                 reinit_completion(&as->xfer_completion);
1333
1334                 if (as->use_pdc) {
1335                         atmel_spi_pdc_next_xfer(master, msg, xfer);
1336                 } else if (atmel_spi_use_dma(as, xfer)) {
1337                         len = as->current_remaining_bytes;
1338                         ret = atmel_spi_next_xfer_dma_submit(master,
1339                                                                 xfer, &len);
1340                         if (ret) {
1341                                 dev_err(&spi->dev,
1342                                         "unable to use DMA, fallback to PIO\n");
1343                                 atmel_spi_next_xfer_pio(master, xfer);
1344                         } else {
1345                                 as->current_remaining_bytes -= len;
1346                                 if (as->current_remaining_bytes < 0)
1347                                         as->current_remaining_bytes = 0;
1348                         }
1349                 } else {
1350                         atmel_spi_next_xfer_pio(master, xfer);
1351                 }
1352
1353                 /* interrupts are disabled, so free the lock for schedule */
1354                 atmel_spi_unlock(as);
1355                 dma_timeout = wait_for_completion_timeout(&as->xfer_completion,
1356                                                           SPI_DMA_TIMEOUT);
1357                 atmel_spi_lock(as);
1358                 if (WARN_ON(dma_timeout == 0)) {
1359                         dev_err(&spi->dev, "spi transfer timeout\n");
1360                         as->done_status = -EIO;
1361                 }
1362
1363                 if (as->done_status)
1364                         break;
1365         }
1366
1367         if (as->done_status) {
1368                 if (as->use_pdc) {
1369                         dev_warn(master->dev.parent,
1370                                 "overrun (%u/%u remaining)\n",
1371                                 spi_readl(as, TCR), spi_readl(as, RCR));
1372
1373                         /*
1374                          * Clean up DMA registers and make sure the data
1375                          * registers are empty.
1376                          */
1377                         spi_writel(as, RNCR, 0);
1378                         spi_writel(as, TNCR, 0);
1379                         spi_writel(as, RCR, 0);
1380                         spi_writel(as, TCR, 0);
1381                         for (timeout = 1000; timeout; timeout--)
1382                                 if (spi_readl(as, SR) & SPI_BIT(TXEMPTY))
1383                                         break;
1384                         if (!timeout)
1385                                 dev_warn(master->dev.parent,
1386                                          "timeout waiting for TXEMPTY");
1387                         while (spi_readl(as, SR) & SPI_BIT(RDRF))
1388                                 spi_readl(as, RDR);
1389
1390                         /* Clear any overrun happening while cleaning up */
1391                         spi_readl(as, SR);
1392
1393                 } else if (atmel_spi_use_dma(as, xfer)) {
1394                         atmel_spi_stop_dma(master);
1395                 }
1396
1397                 if (!msg->is_dma_mapped
1398                         && as->use_pdc)
1399                         atmel_spi_dma_unmap_xfer(master, xfer);
1400
1401                 return 0;
1402
1403         } else {
1404                 /* only update length if no error */
1405                 msg->actual_length += xfer->len;
1406         }
1407
1408         if (!msg->is_dma_mapped
1409                 && as->use_pdc)
1410                 atmel_spi_dma_unmap_xfer(master, xfer);
1411
1412         spi_transfer_delay_exec(xfer);
1413
1414         if (xfer->cs_change) {
1415                 if (list_is_last(&xfer->transfer_list,
1416                                  &msg->transfers)) {
1417                         as->keep_cs = true;
1418                 } else {
1419                         as->cs_active = !as->cs_active;
1420                         if (as->cs_active)
1421                                 cs_activate(as, msg->spi);
1422                         else
1423                                 cs_deactivate(as, msg->spi);
1424                 }
1425         }
1426
1427         return 0;
1428 }
1429
1430 static int atmel_spi_transfer_one_message(struct spi_master *master,
1431                                                 struct spi_message *msg)
1432 {
1433         struct atmel_spi *as;
1434         struct spi_transfer *xfer;
1435         struct spi_device *spi = msg->spi;
1436         int ret = 0;
1437
1438         as = spi_master_get_devdata(master);
1439
1440         dev_dbg(&spi->dev, "new message %p submitted for %s\n",
1441                                         msg, dev_name(&spi->dev));
1442
1443         atmel_spi_lock(as);
1444         cs_activate(as, spi);
1445
1446         as->cs_active = true;
1447         as->keep_cs = false;
1448
1449         msg->status = 0;
1450         msg->actual_length = 0;
1451
1452         list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1453                 trace_spi_transfer_start(msg, xfer);
1454
1455                 ret = atmel_spi_one_transfer(master, msg, xfer);
1456                 if (ret)
1457                         goto msg_done;
1458
1459                 trace_spi_transfer_stop(msg, xfer);
1460         }
1461
1462         if (as->use_pdc)
1463                 atmel_spi_disable_pdc_transfer(as);
1464
1465         list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1466                 dev_dbg(&spi->dev,
1467                         "  xfer %p: len %u tx %p/%pad rx %p/%pad\n",
1468                         xfer, xfer->len,
1469                         xfer->tx_buf, &xfer->tx_dma,
1470                         xfer->rx_buf, &xfer->rx_dma);
1471         }
1472
1473 msg_done:
1474         if (!as->keep_cs)
1475                 cs_deactivate(as, msg->spi);
1476
1477         atmel_spi_unlock(as);
1478
1479         msg->status = as->done_status;
1480         spi_finalize_current_message(spi->master);
1481
1482         return ret;
1483 }
1484
1485 static void atmel_spi_cleanup(struct spi_device *spi)
1486 {
1487         struct atmel_spi_device *asd = spi->controller_state;
1488
1489         if (!asd)
1490                 return;
1491
1492         spi->controller_state = NULL;
1493         kfree(asd);
1494 }
1495
1496 static inline unsigned int atmel_get_version(struct atmel_spi *as)
1497 {
1498         return spi_readl(as, VERSION) & 0x00000fff;
1499 }
1500
1501 static void atmel_get_caps(struct atmel_spi *as)
1502 {
1503         unsigned int version;
1504
1505         version = atmel_get_version(as);
1506
1507         as->caps.is_spi2 = version > 0x121;
1508         as->caps.has_wdrbt = version >= 0x210;
1509         as->caps.has_dma_support = version >= 0x212;
1510         as->caps.has_pdc_support = version < 0x212;
1511 }
1512
1513 static void atmel_spi_init(struct atmel_spi *as)
1514 {
1515         spi_writel(as, CR, SPI_BIT(SWRST));
1516         spi_writel(as, CR, SPI_BIT(SWRST)); /* AT91SAM9263 Rev B workaround */
1517
1518         /* It is recommended to enable FIFOs first thing after reset */
1519         if (as->fifo_size)
1520                 spi_writel(as, CR, SPI_BIT(FIFOEN));
1521
1522         if (as->caps.has_wdrbt) {
1523                 spi_writel(as, MR, SPI_BIT(WDRBT) | SPI_BIT(MODFDIS)
1524                                 | SPI_BIT(MSTR));
1525         } else {
1526                 spi_writel(as, MR, SPI_BIT(MSTR) | SPI_BIT(MODFDIS));
1527         }
1528
1529         if (as->use_pdc)
1530                 spi_writel(as, PTCR, SPI_BIT(RXTDIS) | SPI_BIT(TXTDIS));
1531         spi_writel(as, CR, SPI_BIT(SPIEN));
1532 }
1533
1534 static int atmel_spi_probe(struct platform_device *pdev)
1535 {
1536         struct resource         *regs;
1537         int                     irq;
1538         struct clk              *clk;
1539         int                     ret;
1540         struct spi_master       *master;
1541         struct atmel_spi        *as;
1542
1543         /* Select default pin state */
1544         pinctrl_pm_select_default_state(&pdev->dev);
1545
1546         regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1547         if (!regs)
1548                 return -ENXIO;
1549
1550         irq = platform_get_irq(pdev, 0);
1551         if (irq < 0)
1552                 return irq;
1553
1554         clk = devm_clk_get(&pdev->dev, "spi_clk");
1555         if (IS_ERR(clk))
1556                 return PTR_ERR(clk);
1557
1558         /* setup spi core then atmel-specific driver state */
1559         ret = -ENOMEM;
1560         master = spi_alloc_master(&pdev->dev, sizeof(*as));
1561         if (!master)
1562                 goto out_free;
1563
1564         /* the spi->mode bits understood by this driver: */
1565         master->use_gpio_descriptors = true;
1566         master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
1567         master->bits_per_word_mask = SPI_BPW_RANGE_MASK(8, 16);
1568         master->dev.of_node = pdev->dev.of_node;
1569         master->bus_num = pdev->id;
1570         master->num_chipselect = 4;
1571         master->setup = atmel_spi_setup;
1572         master->flags = (SPI_MASTER_MUST_RX | SPI_MASTER_MUST_TX);
1573         master->transfer_one_message = atmel_spi_transfer_one_message;
1574         master->cleanup = atmel_spi_cleanup;
1575         master->auto_runtime_pm = true;
1576         master->max_dma_len = SPI_MAX_DMA_XFER;
1577         master->can_dma = atmel_spi_can_dma;
1578         platform_set_drvdata(pdev, master);
1579
1580         as = spi_master_get_devdata(master);
1581
1582         spin_lock_init(&as->lock);
1583
1584         as->pdev = pdev;
1585         as->regs = devm_ioremap_resource(&pdev->dev, regs);
1586         if (IS_ERR(as->regs)) {
1587                 ret = PTR_ERR(as->regs);
1588                 goto out_unmap_regs;
1589         }
1590         as->phybase = regs->start;
1591         as->irq = irq;
1592         as->clk = clk;
1593
1594         init_completion(&as->xfer_completion);
1595
1596         atmel_get_caps(as);
1597
1598         as->use_dma = false;
1599         as->use_pdc = false;
1600         if (as->caps.has_dma_support) {
1601                 ret = atmel_spi_configure_dma(master, as);
1602                 if (ret == 0) {
1603                         as->use_dma = true;
1604                 } else if (ret == -EPROBE_DEFER) {
1605                         return ret;
1606                 }
1607         } else if (as->caps.has_pdc_support) {
1608                 as->use_pdc = true;
1609         }
1610
1611         if (IS_ENABLED(CONFIG_SOC_SAM_V4_V5)) {
1612                 as->addr_rx_bbuf = dma_alloc_coherent(&pdev->dev,
1613                                                       SPI_MAX_DMA_XFER,
1614                                                       &as->dma_addr_rx_bbuf,
1615                                                       GFP_KERNEL | GFP_DMA);
1616                 if (!as->addr_rx_bbuf) {
1617                         as->use_dma = false;
1618                 } else {
1619                         as->addr_tx_bbuf = dma_alloc_coherent(&pdev->dev,
1620                                         SPI_MAX_DMA_XFER,
1621                                         &as->dma_addr_tx_bbuf,
1622                                         GFP_KERNEL | GFP_DMA);
1623                         if (!as->addr_tx_bbuf) {
1624                                 as->use_dma = false;
1625                                 dma_free_coherent(&pdev->dev, SPI_MAX_DMA_XFER,
1626                                                   as->addr_rx_bbuf,
1627                                                   as->dma_addr_rx_bbuf);
1628                         }
1629                 }
1630                 if (!as->use_dma)
1631                         dev_info(master->dev.parent,
1632                                  "  can not allocate dma coherent memory\n");
1633         }
1634
1635         if (as->caps.has_dma_support && !as->use_dma)
1636                 dev_info(&pdev->dev, "Atmel SPI Controller using PIO only\n");
1637
1638         if (as->use_pdc) {
1639                 ret = devm_request_irq(&pdev->dev, irq, atmel_spi_pdc_interrupt,
1640                                         0, dev_name(&pdev->dev), master);
1641         } else {
1642                 ret = devm_request_irq(&pdev->dev, irq, atmel_spi_pio_interrupt,
1643                                         0, dev_name(&pdev->dev), master);
1644         }
1645         if (ret)
1646                 goto out_unmap_regs;
1647
1648         /* Initialize the hardware */
1649         ret = clk_prepare_enable(clk);
1650         if (ret)
1651                 goto out_free_irq;
1652
1653         as->spi_clk = clk_get_rate(clk);
1654
1655         as->fifo_size = 0;
1656         if (!of_property_read_u32(pdev->dev.of_node, "atmel,fifo-size",
1657                                   &as->fifo_size)) {
1658                 dev_info(&pdev->dev, "Using FIFO (%u data)\n", as->fifo_size);
1659         }
1660
1661         atmel_spi_init(as);
1662
1663         pm_runtime_set_autosuspend_delay(&pdev->dev, AUTOSUSPEND_TIMEOUT);
1664         pm_runtime_use_autosuspend(&pdev->dev);
1665         pm_runtime_set_active(&pdev->dev);
1666         pm_runtime_enable(&pdev->dev);
1667
1668         ret = devm_spi_register_master(&pdev->dev, master);
1669         if (ret)
1670                 goto out_free_dma;
1671
1672         /* go! */
1673         dev_info(&pdev->dev, "Atmel SPI Controller version 0x%x at 0x%08lx (irq %d)\n",
1674                         atmel_get_version(as), (unsigned long)regs->start,
1675                         irq);
1676
1677         return 0;
1678
1679 out_free_dma:
1680         pm_runtime_disable(&pdev->dev);
1681         pm_runtime_set_suspended(&pdev->dev);
1682
1683         if (as->use_dma)
1684                 atmel_spi_release_dma(master);
1685
1686         spi_writel(as, CR, SPI_BIT(SWRST));
1687         spi_writel(as, CR, SPI_BIT(SWRST)); /* AT91SAM9263 Rev B workaround */
1688         clk_disable_unprepare(clk);
1689 out_free_irq:
1690 out_unmap_regs:
1691 out_free:
1692         spi_master_put(master);
1693         return ret;
1694 }
1695
1696 static int atmel_spi_remove(struct platform_device *pdev)
1697 {
1698         struct spi_master       *master = platform_get_drvdata(pdev);
1699         struct atmel_spi        *as = spi_master_get_devdata(master);
1700
1701         pm_runtime_get_sync(&pdev->dev);
1702
1703         /* reset the hardware and block queue progress */
1704         if (as->use_dma) {
1705                 atmel_spi_stop_dma(master);
1706                 atmel_spi_release_dma(master);
1707                 if (IS_ENABLED(CONFIG_SOC_SAM_V4_V5)) {
1708                         dma_free_coherent(&pdev->dev, SPI_MAX_DMA_XFER,
1709                                           as->addr_tx_bbuf,
1710                                           as->dma_addr_tx_bbuf);
1711                         dma_free_coherent(&pdev->dev, SPI_MAX_DMA_XFER,
1712                                           as->addr_rx_bbuf,
1713                                           as->dma_addr_rx_bbuf);
1714                 }
1715         }
1716
1717         spin_lock_irq(&as->lock);
1718         spi_writel(as, CR, SPI_BIT(SWRST));
1719         spi_writel(as, CR, SPI_BIT(SWRST)); /* AT91SAM9263 Rev B workaround */
1720         spi_readl(as, SR);
1721         spin_unlock_irq(&as->lock);
1722
1723         clk_disable_unprepare(as->clk);
1724
1725         pm_runtime_put_noidle(&pdev->dev);
1726         pm_runtime_disable(&pdev->dev);
1727
1728         return 0;
1729 }
1730
1731 #ifdef CONFIG_PM
1732 static int atmel_spi_runtime_suspend(struct device *dev)
1733 {
1734         struct spi_master *master = dev_get_drvdata(dev);
1735         struct atmel_spi *as = spi_master_get_devdata(master);
1736
1737         clk_disable_unprepare(as->clk);
1738         pinctrl_pm_select_sleep_state(dev);
1739
1740         return 0;
1741 }
1742
1743 static int atmel_spi_runtime_resume(struct device *dev)
1744 {
1745         struct spi_master *master = dev_get_drvdata(dev);
1746         struct atmel_spi *as = spi_master_get_devdata(master);
1747
1748         pinctrl_pm_select_default_state(dev);
1749
1750         return clk_prepare_enable(as->clk);
1751 }
1752
1753 #ifdef CONFIG_PM_SLEEP
1754 static int atmel_spi_suspend(struct device *dev)
1755 {
1756         struct spi_master *master = dev_get_drvdata(dev);
1757         int ret;
1758
1759         /* Stop the queue running */
1760         ret = spi_master_suspend(master);
1761         if (ret)
1762                 return ret;
1763
1764         if (!pm_runtime_suspended(dev))
1765                 atmel_spi_runtime_suspend(dev);
1766
1767         return 0;
1768 }
1769
1770 static int atmel_spi_resume(struct device *dev)
1771 {
1772         struct spi_master *master = dev_get_drvdata(dev);
1773         struct atmel_spi *as = spi_master_get_devdata(master);
1774         int ret;
1775
1776         ret = clk_prepare_enable(as->clk);
1777         if (ret)
1778                 return ret;
1779
1780         atmel_spi_init(as);
1781
1782         clk_disable_unprepare(as->clk);
1783
1784         if (!pm_runtime_suspended(dev)) {
1785                 ret = atmel_spi_runtime_resume(dev);
1786                 if (ret)
1787                         return ret;
1788         }
1789
1790         /* Start the queue running */
1791         return spi_master_resume(master);
1792 }
1793 #endif
1794
1795 static const struct dev_pm_ops atmel_spi_pm_ops = {
1796         SET_SYSTEM_SLEEP_PM_OPS(atmel_spi_suspend, atmel_spi_resume)
1797         SET_RUNTIME_PM_OPS(atmel_spi_runtime_suspend,
1798                            atmel_spi_runtime_resume, NULL)
1799 };
1800 #define ATMEL_SPI_PM_OPS        (&atmel_spi_pm_ops)
1801 #else
1802 #define ATMEL_SPI_PM_OPS        NULL
1803 #endif
1804
1805 static const struct of_device_id atmel_spi_dt_ids[] = {
1806         { .compatible = "atmel,at91rm9200-spi" },
1807         { /* sentinel */ }
1808 };
1809
1810 MODULE_DEVICE_TABLE(of, atmel_spi_dt_ids);
1811
1812 static struct platform_driver atmel_spi_driver = {
1813         .driver         = {
1814                 .name   = "atmel_spi",
1815                 .pm     = ATMEL_SPI_PM_OPS,
1816                 .of_match_table = atmel_spi_dt_ids,
1817         },
1818         .probe          = atmel_spi_probe,
1819         .remove         = atmel_spi_remove,
1820 };
1821 module_platform_driver(atmel_spi_driver);
1822
1823 MODULE_DESCRIPTION("Atmel AT32/AT91 SPI Controller driver");
1824 MODULE_AUTHOR("Haavard Skinnemoen (Atmel)");
1825 MODULE_LICENSE("GPL");
1826 MODULE_ALIAS("platform:atmel_spi");