spi: Add support pl022 spi driver
[platform/kernel/linux-starfive.git] / drivers / spi / spi-pl022-starfive.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * A driver for the ARM PL022 PrimeCell SSP/SPI bus master.
4  *
5  * Copyright (C) 2008-2012 ST-Ericsson AB
6  * Copyright (C) 2006 STMicroelectronics Pvt. Ltd.
7  *
8  * Author: Linus Walleij <linus.walleij@stericsson.com>
9  *
10  * Initial version inspired by:
11  *      linux-2.6.17-rc3-mm1/drivers/spi/pxa2xx_spi.c
12  * Initial adoption to PL022 by:
13  *      Sachin Verma <sachin.verma@st.com>
14  */
15
16 #include <linux/init.h>
17 #include <linux/module.h>
18 #include <linux/device.h>
19 #include <linux/ioport.h>
20 #include <linux/errno.h>
21 #include <linux/interrupt.h>
22 #include <linux/spi/spi.h>
23 #include <linux/delay.h>
24 #include <linux/clk.h>
25 #include <linux/err.h>
26 #include <linux/amba/bus.h>
27 #include <linux/amba/pl022.h>
28 #include <linux/io.h>
29 #include <linux/slab.h>
30 #include <linux/dmaengine.h>
31 #include <linux/dma-mapping.h>
32 #include <linux/scatterlist.h>
33 #include <linux/pm_runtime.h>
34 #include <linux/of.h>
35 #include <linux/pinctrl/consumer.h>
36 #include <linux/reset.h>
37 #include <linux/platform_device.h>
38 #include <linux/clk/clk-conf.h>
39 #include <linux/pm_domain.h>
40
41 /*
42  * This macro is used to define some register default values.
43  * reg is masked with mask, the OR:ed with an (again masked)
44  * val shifted sb steps to the left.
45  */
46 #define SSP_WRITE_BITS(reg, val, mask, sb) \
47         ((reg) = (((reg) & ~(mask)) | (((val)<<(sb)) & (mask))))
48
49 /*
50  * This macro is also used to define some default values.
51  * It will just shift val by sb steps to the left and mask
52  * the result with mask.
53  */
54 #define GEN_MASK_BITS(val, mask, sb) \
55         (((val)<<(sb)) & (mask))
56
57 #define DRIVE_TX                0
58 #define DO_NOT_DRIVE_TX         1
59
60 #define DO_NOT_QUEUE_DMA        0
61 #define QUEUE_DMA               1
62
63 #define RX_TRANSFER             1
64 #define TX_TRANSFER             2
65
66 /*
67  * Macros to access SSP Registers with their offsets
68  */
69 #define SSP_CR0(r)      (r + 0x000)
70 #define SSP_CR1(r)      (r + 0x004)
71 #define SSP_DR(r)       (r + 0x008)
72 #define SSP_SR(r)       (r + 0x00C)
73 #define SSP_CPSR(r)     (r + 0x010)
74 #define SSP_IMSC(r)     (r + 0x014)
75 #define SSP_RIS(r)      (r + 0x018)
76 #define SSP_MIS(r)      (r + 0x01C)
77 #define SSP_ICR(r)      (r + 0x020)
78 #define SSP_DMACR(r)    (r + 0x024)
79 #define SSP_CSR(r)      (r + 0x030) /* vendor extension */
80 #define SSP_ITCR(r)     (r + 0x080)
81 #define SSP_ITIP(r)     (r + 0x084)
82 #define SSP_ITOP(r)     (r + 0x088)
83 #define SSP_TDR(r)      (r + 0x08C)
84
85 #define SSP_PID0(r)     (r + 0xFE0)
86 #define SSP_PID1(r)     (r + 0xFE4)
87 #define SSP_PID2(r)     (r + 0xFE8)
88 #define SSP_PID3(r)     (r + 0xFEC)
89
90 #define SSP_CID0(r)     (r + 0xFF0)
91 #define SSP_CID1(r)     (r + 0xFF4)
92 #define SSP_CID2(r)     (r + 0xFF8)
93 #define SSP_CID3(r)     (r + 0xFFC)
94
95 /*
96  * SSP Control Register 0  - SSP_CR0
97  */
98 #define SSP_CR0_MASK_DSS        (0x0FUL << 0)
99 #define SSP_CR0_MASK_FRF        (0x3UL << 4)
100 #define SSP_CR0_MASK_SPO        (0x1UL << 6)
101 #define SSP_CR0_MASK_SPH        (0x1UL << 7)
102 #define SSP_CR0_MASK_SCR        (0xFFUL << 8)
103
104 /*
105  * The ST version of this block moves som bits
106  * in SSP_CR0 and extends it to 32 bits
107  */
108 #define SSP_CR0_MASK_DSS_ST     (0x1FUL << 0)
109 #define SSP_CR0_MASK_HALFDUP_ST (0x1UL << 5)
110 #define SSP_CR0_MASK_CSS_ST     (0x1FUL << 16)
111 #define SSP_CR0_MASK_FRF_ST     (0x3UL << 21)
112
113 /*
114  * SSP Control Register 0  - SSP_CR1
115  */
116 #define SSP_CR1_MASK_LBM        (0x1UL << 0)
117 #define SSP_CR1_MASK_SSE        (0x1UL << 1)
118 #define SSP_CR1_MASK_MS         (0x1UL << 2)
119 #define SSP_CR1_MASK_SOD        (0x1UL << 3)
120
121 /*
122  * The ST version of this block adds some bits
123  * in SSP_CR1
124  */
125 #define SSP_CR1_MASK_RENDN_ST   (0x1UL << 4)
126 #define SSP_CR1_MASK_TENDN_ST   (0x1UL << 5)
127 #define SSP_CR1_MASK_MWAIT_ST   (0x1UL << 6)
128 #define SSP_CR1_MASK_RXIFLSEL_ST (0x7UL << 7)
129 #define SSP_CR1_MASK_TXIFLSEL_ST (0x7UL << 10)
130 /* This one is only in the PL023 variant */
131 #define SSP_CR1_MASK_FBCLKDEL_ST (0x7UL << 13)
132
133 /*
134  * SSP Status Register - SSP_SR
135  */
136 #define SSP_SR_MASK_TFE         (0x1UL << 0) /* Transmit FIFO empty */
137 #define SSP_SR_MASK_TNF         (0x1UL << 1) /* Transmit FIFO not full */
138 #define SSP_SR_MASK_RNE         (0x1UL << 2) /* Receive FIFO not empty */
139 #define SSP_SR_MASK_RFF         (0x1UL << 3) /* Receive FIFO full */
140 #define SSP_SR_MASK_BSY         (0x1UL << 4) /* Busy Flag */
141
142 /*
143  * SSP Clock Prescale Register  - SSP_CPSR
144  */
145 #define SSP_CPSR_MASK_CPSDVSR   (0xFFUL << 0)
146
147 /*
148  * SSP Interrupt Mask Set/Clear Register - SSP_IMSC
149  */
150 #define SSP_IMSC_MASK_RORIM (0x1UL << 0) /* Receive Overrun Interrupt mask */
151 #define SSP_IMSC_MASK_RTIM  (0x1UL << 1) /* Receive timeout Interrupt mask */
152 #define SSP_IMSC_MASK_RXIM  (0x1UL << 2) /* Receive FIFO Interrupt mask */
153 #define SSP_IMSC_MASK_TXIM  (0x1UL << 3) /* Transmit FIFO Interrupt mask */
154
155 /*
156  * SSP Raw Interrupt Status Register - SSP_RIS
157  */
158 /* Receive Overrun Raw Interrupt status */
159 #define SSP_RIS_MASK_RORRIS             (0x1UL << 0)
160 /* Receive Timeout Raw Interrupt status */
161 #define SSP_RIS_MASK_RTRIS              (0x1UL << 1)
162 /* Receive FIFO Raw Interrupt status */
163 #define SSP_RIS_MASK_RXRIS              (0x1UL << 2)
164 /* Transmit FIFO Raw Interrupt status */
165 #define SSP_RIS_MASK_TXRIS              (0x1UL << 3)
166
167 /*
168  * SSP Masked Interrupt Status Register - SSP_MIS
169  */
170 /* Receive Overrun Masked Interrupt status */
171 #define SSP_MIS_MASK_RORMIS             (0x1UL << 0)
172 /* Receive Timeout Masked Interrupt status */
173 #define SSP_MIS_MASK_RTMIS              (0x1UL << 1)
174 /* Receive FIFO Masked Interrupt status */
175 #define SSP_MIS_MASK_RXMIS              (0x1UL << 2)
176 /* Transmit FIFO Masked Interrupt status */
177 #define SSP_MIS_MASK_TXMIS              (0x1UL << 3)
178
179 /*
180  * SSP Interrupt Clear Register - SSP_ICR
181  */
182 /* Receive Overrun Raw Clear Interrupt bit */
183 #define SSP_ICR_MASK_RORIC              (0x1UL << 0)
184 /* Receive Timeout Clear Interrupt bit */
185 #define SSP_ICR_MASK_RTIC               (0x1UL << 1)
186
187 /*
188  * SSP DMA Control Register - SSP_DMACR
189  */
190 /* Receive DMA Enable bit */
191 #define SSP_DMACR_MASK_RXDMAE           (0x1UL << 0)
192 /* Transmit DMA Enable bit */
193 #define SSP_DMACR_MASK_TXDMAE           (0x1UL << 1)
194
195 /*
196  * SSP Chip Select Control Register - SSP_CSR
197  * (vendor extension)
198  */
199 #define SSP_CSR_CSVALUE_MASK            (0x1FUL << 0)
200
201 /*
202  * SSP Integration Test control Register - SSP_ITCR
203  */
204 #define SSP_ITCR_MASK_ITEN              (0x1UL << 0)
205 #define SSP_ITCR_MASK_TESTFIFO          (0x1UL << 1)
206
207 /*
208  * SSP Integration Test Input Register - SSP_ITIP
209  */
210 #define ITIP_MASK_SSPRXD                 (0x1UL << 0)
211 #define ITIP_MASK_SSPFSSIN               (0x1UL << 1)
212 #define ITIP_MASK_SSPCLKIN               (0x1UL << 2)
213 #define ITIP_MASK_RXDMAC                 (0x1UL << 3)
214 #define ITIP_MASK_TXDMAC                 (0x1UL << 4)
215 #define ITIP_MASK_SSPTXDIN               (0x1UL << 5)
216
217 /*
218  * SSP Integration Test output Register - SSP_ITOP
219  */
220 #define ITOP_MASK_SSPTXD                 (0x1UL << 0)
221 #define ITOP_MASK_SSPFSSOUT              (0x1UL << 1)
222 #define ITOP_MASK_SSPCLKOUT              (0x1UL << 2)
223 #define ITOP_MASK_SSPOEn                 (0x1UL << 3)
224 #define ITOP_MASK_SSPCTLOEn              (0x1UL << 4)
225 #define ITOP_MASK_RORINTR                (0x1UL << 5)
226 #define ITOP_MASK_RTINTR                 (0x1UL << 6)
227 #define ITOP_MASK_RXINTR                 (0x1UL << 7)
228 #define ITOP_MASK_TXINTR                 (0x1UL << 8)
229 #define ITOP_MASK_INTR                   (0x1UL << 9)
230 #define ITOP_MASK_RXDMABREQ              (0x1UL << 10)
231 #define ITOP_MASK_RXDMASREQ              (0x1UL << 11)
232 #define ITOP_MASK_TXDMABREQ              (0x1UL << 12)
233 #define ITOP_MASK_TXDMASREQ              (0x1UL << 13)
234
235 /*
236  * SSP Test Data Register - SSP_TDR
237  */
238 #define TDR_MASK_TESTDATA               (0xFFFFFFFF)
239
240 /*
241  * Message State
242  * we use the spi_message.state (void *) pointer to
243  * hold a single state value, that's why all this
244  * (void *) casting is done here.
245  */
246 #define STATE_START                     ((void *) 0)
247 #define STATE_RUNNING                   ((void *) 1)
248 #define STATE_DONE                      ((void *) 2)
249 #define STATE_ERROR                     ((void *) -1)
250 #define STATE_TIMEOUT                   ((void *) -2)
251
252 /*
253  * SSP State - Whether Enabled or Disabled
254  */
255 #define SSP_DISABLED                    (0)
256 #define SSP_ENABLED                     (1)
257
258 /*
259  * SSP DMA State - Whether DMA Enabled or Disabled
260  */
261 #define SSP_DMA_DISABLED                (0)
262 #define SSP_DMA_ENABLED                 (1)
263
264 /*
265  * SSP Clock Defaults
266  */
267 #define SSP_DEFAULT_CLKRATE 0x2
268 #define SSP_DEFAULT_PRESCALE 0x40
269
270 /*
271  * SSP Clock Parameter ranges
272  */
273 #define CPSDVR_MIN 0x02
274 #define CPSDVR_MAX 0xFE
275 #define SCR_MIN 0x00
276 #define SCR_MAX 0xFF
277
278 /*
279  * SSP Interrupt related Macros
280  */
281 #define DEFAULT_SSP_REG_IMSC  0x0UL
282 #define DISABLE_ALL_INTERRUPTS DEFAULT_SSP_REG_IMSC
283 #define ENABLE_ALL_INTERRUPTS ( \
284         SSP_IMSC_MASK_RORIM | \
285         SSP_IMSC_MASK_RTIM | \
286         SSP_IMSC_MASK_RXIM | \
287         SSP_IMSC_MASK_TXIM \
288 )
289
290 #define CLEAR_ALL_INTERRUPTS  0x3
291
292 #define SPI_POLLING_TIMEOUT 1000
293
294 /*
295  * The type of reading going on this chip
296  */
297 enum ssp_reading {
298         READING_NULL,
299         READING_U8,
300         READING_U16,
301         READING_U32
302 };
303
304 /*
305  * The type of writing going on this chip
306  */
307 enum ssp_writing {
308         WRITING_NULL,
309         WRITING_U8,
310         WRITING_U16,
311         WRITING_U32
312 };
313
314 /**
315  * struct vendor_data - vendor-specific config parameters
316  * for PL022 derivates
317  * @fifodepth: depth of FIFOs (both)
318  * @max_bpw: maximum number of bits per word
319  * @unidir: supports unidirection transfers
320  * @extended_cr: 32 bit wide control register 0 with extra
321  * features and extra features in CR1 as found in the ST variants
322  * @pl023: supports a subset of the ST extensions called "PL023"
323  * @loopback: supports loopback mode
324  * @internal_cs_ctrl: supports chip select control register
325  */
326 struct vendor_data {
327         int fifodepth;
328         int max_bpw;
329         bool unidir;
330         bool extended_cr;
331         bool pl023;
332         bool loopback;
333         bool internal_cs_ctrl;
334 };
335
336 /**
337  * struct pl022 - This is the private SSP driver data structure
338  * @adev: AMBA device model hookup
339  * @vendor: vendor data for the IP block
340  * @phybase: the physical memory where the SSP device resides
341  * @virtbase: the virtual memory where the SSP is mapped
342  * @clk: outgoing clock "SPICLK" for the SPI bus
343  * @master: SPI framework hookup
344  * @master_info: controller-specific data from machine setup
345  * @pump_transfers: Tasklet used in Interrupt Transfer mode
346  * @cur_msg: Pointer to current spi_message being processed
347  * @cur_transfer: Pointer to current spi_transfer
348  * @cur_chip: pointer to current clients chip(assigned from controller_state)
349  * @next_msg_cs_active: the next message in the queue has been examined
350  *  and it was found that it uses the same chip select as the previous
351  *  message, so we left it active after the previous transfer, and it's
352  *  active already.
353  * @tx: current position in TX buffer to be read
354  * @tx_end: end position in TX buffer to be read
355  * @rx: current position in RX buffer to be written
356  * @rx_end: end position in RX buffer to be written
357  * @read: the type of read currently going on
358  * @write: the type of write currently going on
359  * @exp_fifo_level: expected FIFO level
360  * @rx_lev_trig: receive FIFO watermark level which triggers IRQ
361  * @tx_lev_trig: transmit FIFO watermark level which triggers IRQ
362  * @dma_rx_channel: optional channel for RX DMA
363  * @dma_tx_channel: optional channel for TX DMA
364  * @sgt_rx: scattertable for the RX transfer
365  * @sgt_tx: scattertable for the TX transfer
366  * @dummypage: a dummy page used for driving data on the bus with DMA
367  * @dma_running: indicates whether DMA is in operation
368  * @cur_cs: current chip select index
369  * @cur_gpiod: current chip select GPIO descriptor
370  */
371 struct pl022 {
372         struct amba_device              *adev;
373         struct vendor_data              *vendor;
374         resource_size_t                 phybase;
375         void __iomem                    *virtbase;
376         struct clk                      *clk;
377         struct reset_control    *rst;
378         struct spi_master               *master;
379         struct pl022_ssp_controller     *master_info;
380         /* Message per-transfer pump */
381         struct tasklet_struct           pump_transfers;
382         struct spi_message              *cur_msg;
383         struct spi_transfer             *cur_transfer;
384         struct chip_data                *cur_chip;
385         bool                            next_msg_cs_active;
386         void                            *tx;
387         void                            *tx_end;
388         void                            *rx;
389         void                            *rx_end;
390         enum ssp_reading                read;
391         enum ssp_writing                write;
392         u32                             exp_fifo_level;
393         enum ssp_rx_level_trig          rx_lev_trig;
394         enum ssp_tx_level_trig          tx_lev_trig;
395         /* DMA settings */
396 #ifdef CONFIG_DMA_ENGINE
397         struct dma_chan                 *dma_rx_channel;
398         struct dma_chan                 *dma_tx_channel;
399         struct sg_table                 sgt_rx;
400         struct sg_table                 sgt_tx;
401         char                            *dummypage;
402         bool                            dma_running;
403 #endif
404         int cur_cs;
405         struct gpio_desc *cur_gpiod;
406 };
407
408 /**
409  * struct chip_data - To maintain runtime state of SSP for each client chip
410  * @cr0: Value of control register CR0 of SSP - on later ST variants this
411  *       register is 32 bits wide rather than just 16
412  * @cr1: Value of control register CR1 of SSP
413  * @dmacr: Value of DMA control Register of SSP
414  * @cpsr: Value of Clock prescale register
415  * @n_bytes: how many bytes(power of 2) reqd for a given data width of client
416  * @enable_dma: Whether to enable DMA or not
417  * @read: function ptr to be used to read when doing xfer for this chip
418  * @write: function ptr to be used to write when doing xfer for this chip
419  * @xfer_type: polling/interrupt/DMA
420  *
421  * Runtime state of the SSP controller, maintained per chip,
422  * This would be set according to the current message that would be served
423  */
424 struct chip_data {
425         u32 cr0;
426         u16 cr1;
427         u16 dmacr;
428         u16 cpsr;
429         u8 n_bytes;
430         bool enable_dma;
431         enum ssp_reading read;
432         enum ssp_writing write;
433         int xfer_type;
434 };
435
436 /**
437  * internal_cs_control - Control chip select signals via SSP_CSR.
438  * @pl022: SSP driver private data structure
439  * @command: select/delect the chip
440  *
441  * Used on controller with internal chip select control via SSP_CSR register
442  * (vendor extension). Each of the 5 LSB in the register controls one chip
443  * select signal.
444  */
445 static void internal_cs_control(struct pl022 *pl022, u32 command)
446 {
447         u32 tmp;
448
449         tmp = readw(SSP_CSR(pl022->virtbase));
450         if (command == SSP_CHIP_SELECT)
451                 tmp &= ~BIT(pl022->cur_cs);
452         else
453                 tmp |= BIT(pl022->cur_cs);
454         writew(tmp, SSP_CSR(pl022->virtbase));
455 }
456
457 static void pl022_cs_control(struct pl022 *pl022, u32 command)
458 {
459         if (pl022->vendor->internal_cs_ctrl)
460                 internal_cs_control(pl022, command);
461         else if (pl022->cur_gpiod)
462                 /*
463                  * This needs to be inverted since with GPIOLIB in
464                  * control, the inversion will be handled by
465                  * GPIOLIB's active low handling. The "command"
466                  * passed into this function will be SSP_CHIP_SELECT
467                  * which is enum:ed to 0, so we need the inverse
468                  * (1) to activate chip select.
469                  */
470                 gpiod_set_value(pl022->cur_gpiod, !command);
471 }
472
473 /**
474  * giveback - current spi_message is over, schedule next message and call
475  * callback of this message. Assumes that caller already
476  * set message->status; dma and pio irqs are blocked
477  * @pl022: SSP driver private data structure
478  */
479 static void giveback(struct pl022 *pl022)
480 {
481         struct spi_transfer *last_transfer;
482
483         pl022->next_msg_cs_active = false;
484
485         last_transfer = list_last_entry(&pl022->cur_msg->transfers,
486                                         struct spi_transfer, transfer_list);
487
488         /* Delay if requested before any change in chip select */
489         /*
490          * FIXME: This runs in interrupt context.
491          * Is this really smart?
492          */
493         spi_transfer_delay_exec(last_transfer);
494
495         if (!last_transfer->cs_change) {
496                 struct spi_message *next_msg;
497
498                 /*
499                  * cs_change was not set. We can keep the chip select
500                  * enabled if there is message in the queue and it is
501                  * for the same spi device.
502                  *
503                  * We cannot postpone this until pump_messages, because
504                  * after calling msg->complete (below) the driver that
505                  * sent the current message could be unloaded, which
506                  * could invalidate the cs_control() callback...
507                  */
508                 /* get a pointer to the next message, if any */
509                 next_msg = spi_get_next_queued_message(pl022->master);
510
511                 /*
512                  * see if the next and current messages point
513                  * to the same spi device.
514                  */
515                 if (next_msg && next_msg->spi != pl022->cur_msg->spi)
516                         next_msg = NULL;
517                 if (!next_msg || pl022->cur_msg->state == STATE_ERROR)
518                         pl022_cs_control(pl022, SSP_CHIP_DESELECT);
519                 else
520                         pl022->next_msg_cs_active = true;
521
522         }
523
524         pl022->cur_msg = NULL;
525         pl022->cur_transfer = NULL;
526         pl022->cur_chip = NULL;
527
528         /* disable the SPI/SSP operation */
529         writew((readw(SSP_CR1(pl022->virtbase)) &
530                 (~SSP_CR1_MASK_SSE)), SSP_CR1(pl022->virtbase));
531
532         spi_finalize_current_message(pl022->master);
533 }
534
535 /**
536  * flush - flush the FIFO to reach a clean state
537  * @pl022: SSP driver private data structure
538  */
539 static int flush(struct pl022 *pl022)
540 {
541         unsigned long limit = loops_per_jiffy << 1;
542
543         dev_dbg(&pl022->adev->dev, "%s\n", __func__);
544         do {
545                 while (readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RNE)
546                         readw(SSP_DR(pl022->virtbase));
547         } while ((readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_BSY) && limit--);
548
549         pl022->exp_fifo_level = 0;
550
551         return limit;
552 }
553
554 /**
555  * restore_state - Load configuration of current chip
556  * @pl022: SSP driver private data structure
557  */
558 static void restore_state(struct pl022 *pl022)
559 {
560         struct chip_data *chip = pl022->cur_chip;
561
562         if (pl022->vendor->extended_cr)
563                 writel(chip->cr0, SSP_CR0(pl022->virtbase));
564         else
565                 writew(chip->cr0, SSP_CR0(pl022->virtbase));
566         writew(chip->cr1, SSP_CR1(pl022->virtbase));
567         writew(chip->dmacr, SSP_DMACR(pl022->virtbase));
568         writew(chip->cpsr, SSP_CPSR(pl022->virtbase));
569         writew(DISABLE_ALL_INTERRUPTS, SSP_IMSC(pl022->virtbase));
570         writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase));
571 }
572
573 /*
574  * Default SSP Register Values
575  */
576 #define DEFAULT_SSP_REG_CR0 ( \
577         GEN_MASK_BITS(SSP_DATA_BITS_12, SSP_CR0_MASK_DSS, 0)    | \
578         GEN_MASK_BITS(SSP_INTERFACE_MOTOROLA_SPI, SSP_CR0_MASK_FRF, 4) | \
579         GEN_MASK_BITS(SSP_CLK_POL_IDLE_LOW, SSP_CR0_MASK_SPO, 6) | \
580         GEN_MASK_BITS(SSP_CLK_SECOND_EDGE, SSP_CR0_MASK_SPH, 7) | \
581         GEN_MASK_BITS(SSP_DEFAULT_CLKRATE, SSP_CR0_MASK_SCR, 8) \
582 )
583
584 /* ST versions have slightly different bit layout */
585 #define DEFAULT_SSP_REG_CR0_ST ( \
586         GEN_MASK_BITS(SSP_DATA_BITS_12, SSP_CR0_MASK_DSS_ST, 0) | \
587         GEN_MASK_BITS(SSP_MICROWIRE_CHANNEL_FULL_DUPLEX, SSP_CR0_MASK_HALFDUP_ST, 5) | \
588         GEN_MASK_BITS(SSP_CLK_POL_IDLE_LOW, SSP_CR0_MASK_SPO, 6) | \
589         GEN_MASK_BITS(SSP_CLK_SECOND_EDGE, SSP_CR0_MASK_SPH, 7) | \
590         GEN_MASK_BITS(SSP_DEFAULT_CLKRATE, SSP_CR0_MASK_SCR, 8) | \
591         GEN_MASK_BITS(SSP_BITS_8, SSP_CR0_MASK_CSS_ST, 16)      | \
592         GEN_MASK_BITS(SSP_INTERFACE_MOTOROLA_SPI, SSP_CR0_MASK_FRF_ST, 21) \
593 )
594
595 /* The PL023 version is slightly different again */
596 #define DEFAULT_SSP_REG_CR0_ST_PL023 ( \
597         GEN_MASK_BITS(SSP_DATA_BITS_12, SSP_CR0_MASK_DSS_ST, 0) | \
598         GEN_MASK_BITS(SSP_CLK_POL_IDLE_LOW, SSP_CR0_MASK_SPO, 6) | \
599         GEN_MASK_BITS(SSP_CLK_SECOND_EDGE, SSP_CR0_MASK_SPH, 7) | \
600         GEN_MASK_BITS(SSP_DEFAULT_CLKRATE, SSP_CR0_MASK_SCR, 8) \
601 )
602
603 #define DEFAULT_SSP_REG_CR1 ( \
604         GEN_MASK_BITS(LOOPBACK_DISABLED, SSP_CR1_MASK_LBM, 0) | \
605         GEN_MASK_BITS(SSP_DISABLED, SSP_CR1_MASK_SSE, 1) | \
606         GEN_MASK_BITS(SSP_MASTER, SSP_CR1_MASK_MS, 2) | \
607         GEN_MASK_BITS(DO_NOT_DRIVE_TX, SSP_CR1_MASK_SOD, 3) \
608 )
609
610 /* ST versions extend this register to use all 16 bits */
611 #define DEFAULT_SSP_REG_CR1_ST ( \
612         DEFAULT_SSP_REG_CR1 | \
613         GEN_MASK_BITS(SSP_RX_MSB, SSP_CR1_MASK_RENDN_ST, 4) | \
614         GEN_MASK_BITS(SSP_TX_MSB, SSP_CR1_MASK_TENDN_ST, 5) | \
615         GEN_MASK_BITS(SSP_MWIRE_WAIT_ZERO, SSP_CR1_MASK_MWAIT_ST, 6) |\
616         GEN_MASK_BITS(SSP_RX_1_OR_MORE_ELEM, SSP_CR1_MASK_RXIFLSEL_ST, 7) | \
617         GEN_MASK_BITS(SSP_TX_1_OR_MORE_EMPTY_LOC, SSP_CR1_MASK_TXIFLSEL_ST, 10) \
618 )
619
620 /*
621  * The PL023 variant has further differences: no loopback mode, no microwire
622  * support, and a new clock feedback delay setting.
623  */
624 #define DEFAULT_SSP_REG_CR1_ST_PL023 ( \
625         GEN_MASK_BITS(SSP_DISABLED, SSP_CR1_MASK_SSE, 1) | \
626         GEN_MASK_BITS(SSP_MASTER, SSP_CR1_MASK_MS, 2) | \
627         GEN_MASK_BITS(DO_NOT_DRIVE_TX, SSP_CR1_MASK_SOD, 3) | \
628         GEN_MASK_BITS(SSP_RX_MSB, SSP_CR1_MASK_RENDN_ST, 4) | \
629         GEN_MASK_BITS(SSP_TX_MSB, SSP_CR1_MASK_TENDN_ST, 5) | \
630         GEN_MASK_BITS(SSP_RX_1_OR_MORE_ELEM, SSP_CR1_MASK_RXIFLSEL_ST, 7) | \
631         GEN_MASK_BITS(SSP_TX_1_OR_MORE_EMPTY_LOC, SSP_CR1_MASK_TXIFLSEL_ST, 10) | \
632         GEN_MASK_BITS(SSP_FEEDBACK_CLK_DELAY_NONE, SSP_CR1_MASK_FBCLKDEL_ST, 13) \
633 )
634
635 #define DEFAULT_SSP_REG_CPSR ( \
636         GEN_MASK_BITS(SSP_DEFAULT_PRESCALE, SSP_CPSR_MASK_CPSDVSR, 0) \
637 )
638
639 #define DEFAULT_SSP_REG_DMACR (\
640         GEN_MASK_BITS(SSP_DMA_DISABLED, SSP_DMACR_MASK_RXDMAE, 0) | \
641         GEN_MASK_BITS(SSP_DMA_DISABLED, SSP_DMACR_MASK_TXDMAE, 1) \
642 )
643
644 /**
645  * load_ssp_default_config - Load default configuration for SSP
646  * @pl022: SSP driver private data structure
647  */
648 static void load_ssp_default_config(struct pl022 *pl022)
649 {
650         if (pl022->vendor->pl023) {
651                 writel(DEFAULT_SSP_REG_CR0_ST_PL023, SSP_CR0(pl022->virtbase));
652                 writew(DEFAULT_SSP_REG_CR1_ST_PL023, SSP_CR1(pl022->virtbase));
653         } else if (pl022->vendor->extended_cr) {
654                 writel(DEFAULT_SSP_REG_CR0_ST, SSP_CR0(pl022->virtbase));
655                 writew(DEFAULT_SSP_REG_CR1_ST, SSP_CR1(pl022->virtbase));
656         } else {
657                 writew(DEFAULT_SSP_REG_CR0, SSP_CR0(pl022->virtbase));
658                 writew(DEFAULT_SSP_REG_CR1, SSP_CR1(pl022->virtbase));
659         }
660         writew(DEFAULT_SSP_REG_DMACR, SSP_DMACR(pl022->virtbase));
661         writew(DEFAULT_SSP_REG_CPSR, SSP_CPSR(pl022->virtbase));
662         writew(DISABLE_ALL_INTERRUPTS, SSP_IMSC(pl022->virtbase));
663         writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase));
664 }
665
666 /*
667  * This will write to TX and read from RX according to the parameters
668  * set in pl022.
669  */
670 static void readwriter(struct pl022 *pl022)
671 {
672         /*
673          * The FIFO depth is different between primecell variants.
674          * I believe filling in too much in the FIFO might cause
675          * errons in 8bit wide transfers on ARM variants (just 8 words
676          * FIFO, means only 8x8 = 64 bits in FIFO) at least.
677          *
678          * To prevent this issue, the TX FIFO is only filled to the
679          * unused RX FIFO fill length, regardless of what the TX
680          * FIFO status flag indicates.
681          */
682         dev_dbg(&pl022->adev->dev,
683                 "%s, rx: %p, rxend: %p, tx: %p, txend: %p\n",
684                 __func__, pl022->rx, pl022->rx_end, pl022->tx, pl022->tx_end);
685
686         /* Read as much as you can */
687         while ((readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RNE)
688                && (pl022->rx < pl022->rx_end)) {
689                 switch (pl022->read) {
690                 case READING_NULL:
691                         readw(SSP_DR(pl022->virtbase));
692                         break;
693                 case READING_U8:
694                         *(u8 *) (pl022->rx) =
695                                 readw(SSP_DR(pl022->virtbase)) & 0xFFU;
696                         break;
697                 case READING_U16:
698                         *(u16 *) (pl022->rx) =
699                                 (u16) readw(SSP_DR(pl022->virtbase));
700                         break;
701                 case READING_U32:
702                         *(u32 *) (pl022->rx) =
703                                 readl(SSP_DR(pl022->virtbase));
704                         break;
705                 }
706                 pl022->rx += (pl022->cur_chip->n_bytes);
707                 pl022->exp_fifo_level--;
708         }
709         /*
710          * Write as much as possible up to the RX FIFO size
711          */
712         while ((pl022->exp_fifo_level < pl022->vendor->fifodepth)
713                && (pl022->tx < pl022->tx_end)) {
714                 switch (pl022->write) {
715                 case WRITING_NULL:
716                         writew(0x0, SSP_DR(pl022->virtbase));
717                         break;
718                 case WRITING_U8:
719                         writew(*(u8 *) (pl022->tx), SSP_DR(pl022->virtbase));
720                         break;
721                 case WRITING_U16:
722                         writew((*(u16 *) (pl022->tx)), SSP_DR(pl022->virtbase));
723                         break;
724                 case WRITING_U32:
725                         writel(*(u32 *) (pl022->tx), SSP_DR(pl022->virtbase));
726                         break;
727                 }
728                 pl022->tx += (pl022->cur_chip->n_bytes);
729                 pl022->exp_fifo_level++;
730                 /*
731                  * This inner reader takes care of things appearing in the RX
732                  * FIFO as we're transmitting. This will happen a lot since the
733                  * clock starts running when you put things into the TX FIFO,
734                  * and then things are continuously clocked into the RX FIFO.
735                  */
736                 while ((readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RNE)
737                        && (pl022->rx < pl022->rx_end)) {
738                         switch (pl022->read) {
739                         case READING_NULL:
740                                 readw(SSP_DR(pl022->virtbase));
741                                 break;
742                         case READING_U8:
743                                 *(u8 *) (pl022->rx) =
744                                         readw(SSP_DR(pl022->virtbase)) & 0xFFU;
745                                 break;
746                         case READING_U16:
747                                 *(u16 *) (pl022->rx) =
748                                         (u16) readw(SSP_DR(pl022->virtbase));
749                                 break;
750                         case READING_U32:
751                                 *(u32 *) (pl022->rx) =
752                                         readl(SSP_DR(pl022->virtbase));
753                                 break;
754                         }
755                         pl022->rx += (pl022->cur_chip->n_bytes);
756                         pl022->exp_fifo_level--;
757                 }
758         }
759         /*
760          * When we exit here the TX FIFO should be full and the RX FIFO
761          * should be empty
762          */
763 }
764
765 /**
766  * next_transfer - Move to the Next transfer in the current spi message
767  * @pl022: SSP driver private data structure
768  *
769  * This function moves though the linked list of spi transfers in the
770  * current spi message and returns with the state of current spi
771  * message i.e whether its last transfer is done(STATE_DONE) or
772  * Next transfer is ready(STATE_RUNNING)
773  */
774 static void *next_transfer(struct pl022 *pl022)
775 {
776         struct spi_message *msg = pl022->cur_msg;
777         struct spi_transfer *trans = pl022->cur_transfer;
778
779         /* Move to next transfer */
780         if (trans->transfer_list.next != &msg->transfers) {
781                 pl022->cur_transfer =
782                     list_entry(trans->transfer_list.next,
783                                struct spi_transfer, transfer_list);
784                 return STATE_RUNNING;
785         }
786         return STATE_DONE;
787 }
788
789 /*
790  * This DMA functionality is only compiled in if we have
791  * access to the generic DMA devices/DMA engine.
792  */
793 #ifdef CONFIG_DMA_ENGINE
794 static void unmap_free_dma_scatter(struct pl022 *pl022)
795 {
796         /* Unmap and free the SG tables */
797         dma_unmap_sg(pl022->dma_tx_channel->device->dev, pl022->sgt_tx.sgl,
798                      pl022->sgt_tx.nents, DMA_TO_DEVICE);
799         dma_unmap_sg(pl022->dma_rx_channel->device->dev, pl022->sgt_rx.sgl,
800                      pl022->sgt_rx.nents, DMA_FROM_DEVICE);
801         sg_free_table(&pl022->sgt_rx);
802         sg_free_table(&pl022->sgt_tx);
803 }
804
805 static void dma_callback(void *data)
806 {
807         struct pl022 *pl022 = data;
808         struct spi_message *msg = pl022->cur_msg;
809
810         BUG_ON(!pl022->sgt_rx.sgl);
811
812 #ifdef VERBOSE_DEBUG
813         /*
814          * Optionally dump out buffers to inspect contents, this is
815          * good if you want to convince yourself that the loopback
816          * read/write contents are the same, when adopting to a new
817          * DMA engine.
818          */
819         {
820                 struct scatterlist *sg;
821                 unsigned int i;
822
823                 dma_sync_sg_for_cpu(&pl022->adev->dev,
824                                     pl022->sgt_rx.sgl,
825                                     pl022->sgt_rx.nents,
826                                     DMA_FROM_DEVICE);
827
828                 for_each_sg(pl022->sgt_rx.sgl, sg, pl022->sgt_rx.nents, i) {
829                         dev_dbg(&pl022->adev->dev, "SPI RX SG ENTRY: %d", i);
830                         print_hex_dump(KERN_ERR, "SPI RX: ",
831                                        DUMP_PREFIX_OFFSET,
832                                        16,
833                                        1,
834                                        sg_virt(sg),
835                                        sg_dma_len(sg),
836                                        1);
837                 }
838                 for_each_sg(pl022->sgt_tx.sgl, sg, pl022->sgt_tx.nents, i) {
839                         dev_dbg(&pl022->adev->dev, "SPI TX SG ENTRY: %d", i);
840                         print_hex_dump(KERN_ERR, "SPI TX: ",
841                                        DUMP_PREFIX_OFFSET,
842                                        16,
843                                        1,
844                                        sg_virt(sg),
845                                        sg_dma_len(sg),
846                                        1);
847                 }
848         }
849 #endif
850
851         unmap_free_dma_scatter(pl022);
852
853         /* Update total bytes transferred */
854         msg->actual_length += pl022->cur_transfer->len;
855         /* Move to next transfer */
856         msg->state = next_transfer(pl022);
857         if (msg->state != STATE_DONE && pl022->cur_transfer->cs_change)
858                 pl022_cs_control(pl022, SSP_CHIP_DESELECT);
859         tasklet_schedule(&pl022->pump_transfers);
860 }
861
862 static void setup_dma_scatter(struct pl022 *pl022,
863                               void *buffer,
864                               unsigned int length,
865                               struct sg_table *sgtab)
866 {
867         struct scatterlist *sg;
868         int bytesleft = length;
869         void *bufp = buffer;
870         int mapbytes;
871         int i;
872
873         if (buffer) {
874                 for_each_sg(sgtab->sgl, sg, sgtab->nents, i) {
875                         /*
876                          * If there are less bytes left than what fits
877                          * in the current page (plus page alignment offset)
878                          * we just feed in this, else we stuff in as much
879                          * as we can.
880                          */
881                         if (bytesleft < (PAGE_SIZE - offset_in_page(bufp)))
882                                 mapbytes = bytesleft;
883                         else
884                                 mapbytes = PAGE_SIZE - offset_in_page(bufp);
885                         sg_set_page(sg, virt_to_page(bufp),
886                                     mapbytes, offset_in_page(bufp));
887                         bufp += mapbytes;
888                         bytesleft -= mapbytes;
889                         dev_dbg(&pl022->adev->dev,
890                                 "set RX/TX target page @ %p, %d bytes, %d left\n",
891                                 bufp, mapbytes, bytesleft);
892                 }
893         } else {
894                 /* Map the dummy buffer on every page */
895                 for_each_sg(sgtab->sgl, sg, sgtab->nents, i) {
896                         if (bytesleft < PAGE_SIZE)
897                                 mapbytes = bytesleft;
898                         else
899                                 mapbytes = PAGE_SIZE;
900                         sg_set_page(sg, virt_to_page(pl022->dummypage),
901                                     mapbytes, 0);
902                         bytesleft -= mapbytes;
903                         dev_dbg(&pl022->adev->dev,
904                                 "set RX/TX to dummy page %d bytes, %d left\n",
905                                 mapbytes, bytesleft);
906
907                 }
908         }
909         BUG_ON(bytesleft);
910 }
911
912 /**
913  * configure_dma - configures the channels for the next transfer
914  * @pl022: SSP driver's private data structure
915  */
916 static int configure_dma(struct pl022 *pl022)
917 {
918         struct dma_slave_config rx_conf = {
919                 .src_addr = SSP_DR(pl022->phybase),
920                 .direction = DMA_DEV_TO_MEM,
921                 .device_fc = false,
922         };
923         struct dma_slave_config tx_conf = {
924                 .dst_addr = SSP_DR(pl022->phybase),
925                 .direction = DMA_MEM_TO_DEV,
926                 .device_fc = false,
927         };
928         unsigned int pages;
929         int ret;
930         int rx_sglen, tx_sglen;
931         struct dma_chan *rxchan = pl022->dma_rx_channel;
932         struct dma_chan *txchan = pl022->dma_tx_channel;
933         struct dma_async_tx_descriptor *rxdesc;
934         struct dma_async_tx_descriptor *txdesc;
935
936         /* Check that the channels are available */
937         if (!rxchan || !txchan)
938                 return -ENODEV;
939
940         /*
941          * If supplied, the DMA burstsize should equal the FIFO trigger level.
942          * Notice that the DMA engine uses one-to-one mapping. Since we can
943          * not trigger on 2 elements this needs explicit mapping rather than
944          * calculation.
945          */
946         switch (pl022->rx_lev_trig) {
947         case SSP_RX_1_OR_MORE_ELEM:
948                 rx_conf.src_maxburst = 1;
949                 break;
950         case SSP_RX_4_OR_MORE_ELEM:
951                 rx_conf.src_maxburst = 4;
952                 break;
953         case SSP_RX_8_OR_MORE_ELEM:
954                 rx_conf.src_maxburst = 8;
955                 break;
956         case SSP_RX_16_OR_MORE_ELEM:
957                 rx_conf.src_maxburst = 16;
958                 break;
959         case SSP_RX_32_OR_MORE_ELEM:
960                 rx_conf.src_maxburst = 32;
961                 break;
962         default:
963                 rx_conf.src_maxburst = pl022->vendor->fifodepth >> 1;
964                 break;
965         }
966
967         switch (pl022->tx_lev_trig) {
968         case SSP_TX_1_OR_MORE_EMPTY_LOC:
969                 tx_conf.dst_maxburst = 1;
970                 break;
971         case SSP_TX_4_OR_MORE_EMPTY_LOC:
972                 tx_conf.dst_maxburst = 4;
973                 break;
974         case SSP_TX_8_OR_MORE_EMPTY_LOC:
975                 tx_conf.dst_maxburst = 8;
976                 break;
977         case SSP_TX_16_OR_MORE_EMPTY_LOC:
978                 tx_conf.dst_maxburst = 16;
979                 break;
980         case SSP_TX_32_OR_MORE_EMPTY_LOC:
981                 tx_conf.dst_maxburst = 32;
982                 break;
983         default:
984                 tx_conf.dst_maxburst = pl022->vendor->fifodepth >> 1;
985                 break;
986         }
987
988         switch (pl022->read) {
989         case READING_NULL:
990                 /* Use the same as for writing */
991                 rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_UNDEFINED;
992                 break;
993         case READING_U8:
994                 rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
995                 break;
996         case READING_U16:
997                 rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
998                 break;
999         case READING_U32:
1000                 rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
1001                 break;
1002         }
1003
1004         switch (pl022->write) {
1005         case WRITING_NULL:
1006                 /* Use the same as for reading */
1007                 tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_UNDEFINED;
1008                 break;
1009         case WRITING_U8:
1010                 tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
1011                 break;
1012         case WRITING_U16:
1013                 tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
1014                 break;
1015         case WRITING_U32:
1016                 tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
1017                 break;
1018         }
1019
1020         /* SPI pecularity: we need to read and write the same width */
1021         if (rx_conf.src_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED)
1022                 rx_conf.src_addr_width = tx_conf.dst_addr_width;
1023         if (tx_conf.dst_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED)
1024                 tx_conf.dst_addr_width = rx_conf.src_addr_width;
1025         BUG_ON(rx_conf.src_addr_width != tx_conf.dst_addr_width);
1026
1027         dmaengine_slave_config(rxchan, &rx_conf);
1028         dmaengine_slave_config(txchan, &tx_conf);
1029
1030         /* Create sglists for the transfers */
1031         pages = DIV_ROUND_UP(pl022->cur_transfer->len, PAGE_SIZE);
1032         dev_dbg(&pl022->adev->dev, "using %d pages for transfer\n", pages);
1033
1034         ret = sg_alloc_table(&pl022->sgt_rx, pages, GFP_ATOMIC);
1035         if (ret)
1036                 goto err_alloc_rx_sg;
1037
1038         ret = sg_alloc_table(&pl022->sgt_tx, pages, GFP_ATOMIC);
1039         if (ret)
1040                 goto err_alloc_tx_sg;
1041
1042         /* Fill in the scatterlists for the RX+TX buffers */
1043         setup_dma_scatter(pl022, pl022->rx,
1044                           pl022->cur_transfer->len, &pl022->sgt_rx);
1045         setup_dma_scatter(pl022, pl022->tx,
1046                           pl022->cur_transfer->len, &pl022->sgt_tx);
1047
1048         /* Map DMA buffers */
1049         rx_sglen = dma_map_sg(rxchan->device->dev, pl022->sgt_rx.sgl,
1050                            pl022->sgt_rx.nents, DMA_FROM_DEVICE);
1051         if (!rx_sglen)
1052                 goto err_rx_sgmap;
1053
1054         tx_sglen = dma_map_sg(txchan->device->dev, pl022->sgt_tx.sgl,
1055                            pl022->sgt_tx.nents, DMA_TO_DEVICE);
1056         if (!tx_sglen)
1057                 goto err_tx_sgmap;
1058
1059         /* Send both scatterlists */
1060         rxdesc = dmaengine_prep_slave_sg(rxchan,
1061                                       pl022->sgt_rx.sgl,
1062                                       rx_sglen,
1063                                       DMA_DEV_TO_MEM,
1064                                       DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1065         if (!rxdesc)
1066                 goto err_rxdesc;
1067
1068         txdesc = dmaengine_prep_slave_sg(txchan,
1069                                       pl022->sgt_tx.sgl,
1070                                       tx_sglen,
1071                                       DMA_MEM_TO_DEV,
1072                                       DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1073         if (!txdesc)
1074                 goto err_txdesc;
1075
1076         /* Put the callback on the RX transfer only, that should finish last */
1077         rxdesc->callback = dma_callback;
1078         rxdesc->callback_param = pl022;
1079
1080         /* Submit and fire RX and TX with TX last so we're ready to read! */
1081         dmaengine_submit(rxdesc);
1082         dmaengine_submit(txdesc);
1083         dma_async_issue_pending(rxchan);
1084         dma_async_issue_pending(txchan);
1085         pl022->dma_running = true;
1086
1087         return 0;
1088
1089 err_txdesc:
1090         dmaengine_terminate_all(txchan);
1091 err_rxdesc:
1092         dmaengine_terminate_all(rxchan);
1093         dma_unmap_sg(txchan->device->dev, pl022->sgt_tx.sgl,
1094                      pl022->sgt_tx.nents, DMA_TO_DEVICE);
1095 err_tx_sgmap:
1096         dma_unmap_sg(rxchan->device->dev, pl022->sgt_rx.sgl,
1097                      pl022->sgt_rx.nents, DMA_FROM_DEVICE);
1098 err_rx_sgmap:
1099         sg_free_table(&pl022->sgt_tx);
1100 err_alloc_tx_sg:
1101         sg_free_table(&pl022->sgt_rx);
1102 err_alloc_rx_sg:
1103         return -ENOMEM;
1104 }
1105
1106 static int pl022_dma_probe(struct pl022 *pl022)
1107 {
1108         dma_cap_mask_t mask;
1109
1110         /* Try to acquire a generic DMA engine slave channel */
1111         dma_cap_zero(mask);
1112         dma_cap_set(DMA_SLAVE, mask);
1113         /*
1114          * We need both RX and TX channels to do DMA, else do none
1115          * of them.
1116          */
1117         pl022->dma_rx_channel = dma_request_channel(mask,
1118                                             pl022->master_info->dma_filter,
1119                                             pl022->master_info->dma_rx_param);
1120         if (!pl022->dma_rx_channel) {
1121                 dev_dbg(&pl022->adev->dev, "no RX DMA channel!\n");
1122                 goto err_no_rxchan;
1123         }
1124
1125         pl022->dma_tx_channel = dma_request_channel(mask,
1126                                             pl022->master_info->dma_filter,
1127                                             pl022->master_info->dma_tx_param);
1128         if (!pl022->dma_tx_channel) {
1129                 dev_dbg(&pl022->adev->dev, "no TX DMA channel!\n");
1130                 goto err_no_txchan;
1131         }
1132
1133         pl022->dummypage = kmalloc(PAGE_SIZE, GFP_KERNEL);
1134         if (!pl022->dummypage)
1135                 goto err_no_dummypage;
1136
1137         dev_info(&pl022->adev->dev, "setup for DMA on RX %s, TX %s\n",
1138                  dma_chan_name(pl022->dma_rx_channel),
1139                  dma_chan_name(pl022->dma_tx_channel));
1140
1141         return 0;
1142
1143 err_no_dummypage:
1144         dma_release_channel(pl022->dma_tx_channel);
1145 err_no_txchan:
1146         dma_release_channel(pl022->dma_rx_channel);
1147         pl022->dma_rx_channel = NULL;
1148 err_no_rxchan:
1149         dev_err(&pl022->adev->dev,
1150                         "Failed to work in dma mode, work without dma!\n");
1151         return -ENODEV;
1152 }
1153
1154 static int pl022_dma_autoprobe(struct pl022 *pl022)
1155 {
1156         struct device *dev = &pl022->adev->dev;
1157         struct dma_chan *chan;
1158         int err;
1159
1160         /* automatically configure DMA channels from platform, normally using DT */
1161         chan = dma_request_chan(dev, "rx");
1162         if (IS_ERR(chan)) {
1163                 err = PTR_ERR(chan);
1164                 goto err_no_rxchan;
1165         }
1166
1167         pl022->dma_rx_channel = chan;
1168
1169         chan = dma_request_chan(dev, "tx");
1170         if (IS_ERR(chan)) {
1171                 err = PTR_ERR(chan);
1172                 goto err_no_txchan;
1173         }
1174
1175         pl022->dma_tx_channel = chan;
1176
1177         pl022->dummypage = kmalloc(PAGE_SIZE, GFP_KERNEL);
1178         if (!pl022->dummypage) {
1179                 err = -ENOMEM;
1180                 goto err_no_dummypage;
1181         }
1182
1183         return 0;
1184
1185 err_no_dummypage:
1186         dma_release_channel(pl022->dma_tx_channel);
1187         pl022->dma_tx_channel = NULL;
1188 err_no_txchan:
1189         dma_release_channel(pl022->dma_rx_channel);
1190         pl022->dma_rx_channel = NULL;
1191 err_no_rxchan:
1192         return err;
1193 }
1194
1195 static void terminate_dma(struct pl022 *pl022)
1196 {
1197         struct dma_chan *rxchan = pl022->dma_rx_channel;
1198         struct dma_chan *txchan = pl022->dma_tx_channel;
1199
1200         dmaengine_terminate_all(rxchan);
1201         dmaengine_terminate_all(txchan);
1202         unmap_free_dma_scatter(pl022);
1203         pl022->dma_running = false;
1204 }
1205
1206 static void pl022_dma_remove(struct pl022 *pl022)
1207 {
1208         if (pl022->dma_running)
1209                 terminate_dma(pl022);
1210         if (pl022->dma_tx_channel)
1211                 dma_release_channel(pl022->dma_tx_channel);
1212         if (pl022->dma_rx_channel)
1213                 dma_release_channel(pl022->dma_rx_channel);
1214         kfree(pl022->dummypage);
1215 }
1216
1217 #else
1218 static inline int configure_dma(struct pl022 *pl022)
1219 {
1220         return -ENODEV;
1221 }
1222
1223 static inline int pl022_dma_autoprobe(struct pl022 *pl022)
1224 {
1225         return 0;
1226 }
1227
1228 static inline int pl022_dma_probe(struct pl022 *pl022)
1229 {
1230         return 0;
1231 }
1232
1233 static inline void pl022_dma_remove(struct pl022 *pl022)
1234 {
1235 }
1236 #endif
1237
1238 /**
1239  * pl022_interrupt_handler - Interrupt handler for SSP controller
1240  * @irq: IRQ number
1241  * @dev_id: Local device data
1242  *
1243  * This function handles interrupts generated for an interrupt based transfer.
1244  * If a receive overrun (ROR) interrupt is there then we disable SSP, flag the
1245  * current message's state as STATE_ERROR and schedule the tasklet
1246  * pump_transfers which will do the postprocessing of the current message by
1247  * calling giveback(). Otherwise it reads data from RX FIFO till there is no
1248  * more data, and writes data in TX FIFO till it is not full. If we complete
1249  * the transfer we move to the next transfer and schedule the tasklet.
1250  */
1251 static irqreturn_t pl022_interrupt_handler(int irq, void *dev_id)
1252 {
1253         struct pl022 *pl022 = dev_id;
1254         struct spi_message *msg = pl022->cur_msg;
1255         u16 irq_status = 0;
1256
1257         if (unlikely(!msg)) {
1258                 dev_err(&pl022->adev->dev,
1259                         "bad message state in interrupt handler");
1260                 /* Never fail */
1261                 return IRQ_HANDLED;
1262         }
1263
1264         /* Read the Interrupt Status Register */
1265         irq_status = readw(SSP_MIS(pl022->virtbase));
1266
1267         if (unlikely(!irq_status))
1268                 return IRQ_NONE;
1269
1270         /*
1271          * This handles the FIFO interrupts, the timeout
1272          * interrupts are flatly ignored, they cannot be
1273          * trusted.
1274          */
1275         if (unlikely(irq_status & SSP_MIS_MASK_RORMIS)) {
1276                 /*
1277                  * Overrun interrupt - bail out since our Data has been
1278                  * corrupted
1279                  */
1280                 dev_err(&pl022->adev->dev, "FIFO overrun\n");
1281                 if (readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RFF)
1282                         dev_err(&pl022->adev->dev,
1283                                 "RXFIFO is full\n");
1284
1285                 /*
1286                  * Disable and clear interrupts, disable SSP,
1287                  * mark message with bad status so it can be
1288                  * retried.
1289                  */
1290                 writew(DISABLE_ALL_INTERRUPTS,
1291                        SSP_IMSC(pl022->virtbase));
1292                 writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase));
1293                 writew((readw(SSP_CR1(pl022->virtbase)) &
1294                         (~SSP_CR1_MASK_SSE)), SSP_CR1(pl022->virtbase));
1295                 msg->state = STATE_ERROR;
1296
1297                 /* Schedule message queue handler */
1298                 tasklet_schedule(&pl022->pump_transfers);
1299                 return IRQ_HANDLED;
1300         }
1301
1302         readwriter(pl022);
1303
1304         if (pl022->tx == pl022->tx_end) {
1305                 /* Disable Transmit interrupt, enable receive interrupt */
1306                 writew((readw(SSP_IMSC(pl022->virtbase)) &
1307                        ~SSP_IMSC_MASK_TXIM) | SSP_IMSC_MASK_RXIM,
1308                        SSP_IMSC(pl022->virtbase));
1309         }
1310
1311         /*
1312          * Since all transactions must write as much as shall be read,
1313          * we can conclude the entire transaction once RX is complete.
1314          * At this point, all TX will always be finished.
1315          */
1316         if (pl022->rx >= pl022->rx_end) {
1317                 writew(DISABLE_ALL_INTERRUPTS,
1318                        SSP_IMSC(pl022->virtbase));
1319                 writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase));
1320                 if (unlikely(pl022->rx > pl022->rx_end)) {
1321                         dev_warn(&pl022->adev->dev, "read %u surplus "
1322                                  "bytes (did you request an odd "
1323                                  "number of bytes on a 16bit bus?)\n",
1324                                  (u32) (pl022->rx - pl022->rx_end));
1325                 }
1326                 /* Update total bytes transferred */
1327                 msg->actual_length += pl022->cur_transfer->len;
1328                 /* Move to next transfer */
1329                 msg->state = next_transfer(pl022);
1330                 if (msg->state != STATE_DONE && pl022->cur_transfer->cs_change)
1331                         pl022_cs_control(pl022, SSP_CHIP_DESELECT);
1332                 tasklet_schedule(&pl022->pump_transfers);
1333                 return IRQ_HANDLED;
1334         }
1335
1336         return IRQ_HANDLED;
1337 }
1338
1339 /*
1340  * This sets up the pointers to memory for the next message to
1341  * send out on the SPI bus.
1342  */
1343 static int set_up_next_transfer(struct pl022 *pl022,
1344                                 struct spi_transfer *transfer)
1345 {
1346         int residue;
1347
1348         /* Sanity check the message for this bus width */
1349         residue = pl022->cur_transfer->len % pl022->cur_chip->n_bytes;
1350         if (unlikely(residue != 0)) {
1351                 dev_err(&pl022->adev->dev,
1352                         "message of %u bytes to transmit but the current "
1353                         "chip bus has a data width of %u bytes!\n",
1354                         pl022->cur_transfer->len,
1355                         pl022->cur_chip->n_bytes);
1356                 dev_err(&pl022->adev->dev, "skipping this message\n");
1357                 return -EIO;
1358         }
1359         pl022->tx = (void *)transfer->tx_buf;
1360         pl022->tx_end = pl022->tx + pl022->cur_transfer->len;
1361         pl022->rx = (void *)transfer->rx_buf;
1362         pl022->rx_end = pl022->rx + pl022->cur_transfer->len;
1363         pl022->write =
1364             pl022->tx ? pl022->cur_chip->write : WRITING_NULL;
1365         pl022->read = pl022->rx ? pl022->cur_chip->read : READING_NULL;
1366         return 0;
1367 }
1368
1369 /**
1370  * pump_transfers - Tasklet function which schedules next transfer
1371  * when running in interrupt or DMA transfer mode.
1372  * @data: SSP driver private data structure
1373  *
1374  */
1375 static void pump_transfers(unsigned long data)
1376 {
1377         struct pl022 *pl022 = (struct pl022 *) data;
1378         struct spi_message *message = NULL;
1379         struct spi_transfer *transfer = NULL;
1380         struct spi_transfer *previous = NULL;
1381
1382         /* Get current state information */
1383         message = pl022->cur_msg;
1384         transfer = pl022->cur_transfer;
1385
1386         /* Handle for abort */
1387         if (message->state == STATE_ERROR) {
1388                 message->status = -EIO;
1389                 giveback(pl022);
1390                 return;
1391         }
1392
1393         /* Handle end of message */
1394         if (message->state == STATE_DONE) {
1395                 message->status = 0;
1396                 giveback(pl022);
1397                 return;
1398         }
1399
1400         /* Delay if requested at end of transfer before CS change */
1401         if (message->state == STATE_RUNNING) {
1402                 previous = list_entry(transfer->transfer_list.prev,
1403                                         struct spi_transfer,
1404                                         transfer_list);
1405                 /*
1406                  * FIXME: This runs in interrupt context.
1407                  * Is this really smart?
1408                  */
1409                 spi_transfer_delay_exec(previous);
1410
1411                 /* Reselect chip select only if cs_change was requested */
1412                 if (previous->cs_change)
1413                         pl022_cs_control(pl022, SSP_CHIP_SELECT);
1414         } else {
1415                 /* STATE_START */
1416                 message->state = STATE_RUNNING;
1417         }
1418
1419         if (set_up_next_transfer(pl022, transfer)) {
1420                 message->state = STATE_ERROR;
1421                 message->status = -EIO;
1422                 giveback(pl022);
1423                 return;
1424         }
1425         /* Flush the FIFOs and let's go! */
1426         flush(pl022);
1427
1428         if (pl022->cur_chip->enable_dma) {
1429                 if (configure_dma(pl022)) {
1430                         dev_dbg(&pl022->adev->dev,
1431                                 "configuration of DMA failed, fall back to interrupt mode\n");
1432                         goto err_config_dma;
1433                 }
1434                 return;
1435         }
1436
1437 err_config_dma:
1438         /* enable all interrupts except RX */
1439         writew(ENABLE_ALL_INTERRUPTS & ~SSP_IMSC_MASK_RXIM, SSP_IMSC(pl022->virtbase));
1440 }
1441
1442 static void do_interrupt_dma_transfer(struct pl022 *pl022)
1443 {
1444         /*
1445          * Default is to enable all interrupts except RX -
1446          * this will be enabled once TX is complete
1447          */
1448         u32 irqflags = (u32)(ENABLE_ALL_INTERRUPTS & ~SSP_IMSC_MASK_RXIM);
1449
1450         /* Enable target chip, if not already active */
1451         if (!pl022->next_msg_cs_active)
1452                 pl022_cs_control(pl022, SSP_CHIP_SELECT);
1453
1454         if (set_up_next_transfer(pl022, pl022->cur_transfer)) {
1455                 /* Error path */
1456                 pl022->cur_msg->state = STATE_ERROR;
1457                 pl022->cur_msg->status = -EIO;
1458                 giveback(pl022);
1459                 return;
1460         }
1461         /* If we're using DMA, set up DMA here */
1462         if (pl022->cur_chip->enable_dma) {
1463                 /* Configure DMA transfer */
1464                 if (configure_dma(pl022)) {
1465                         dev_dbg(&pl022->adev->dev,
1466                                 "configuration of DMA failed, fall back to interrupt mode\n");
1467                         goto err_config_dma;
1468                 }
1469                 /* Disable interrupts in DMA mode, IRQ from DMA controller */
1470                 irqflags = DISABLE_ALL_INTERRUPTS;
1471         }
1472 err_config_dma:
1473         /* Enable SSP, turn on interrupts */
1474         writew((readw(SSP_CR1(pl022->virtbase)) | SSP_CR1_MASK_SSE),
1475                SSP_CR1(pl022->virtbase));
1476         writew(irqflags, SSP_IMSC(pl022->virtbase));
1477 }
1478
1479 static void print_current_status(struct pl022 *pl022)
1480 {
1481         u32 read_cr0;
1482         u16 read_cr1, read_dmacr, read_sr;
1483
1484         if (pl022->vendor->extended_cr)
1485                 read_cr0 = readl(SSP_CR0(pl022->virtbase));
1486         else
1487                 read_cr0 = readw(SSP_CR0(pl022->virtbase));
1488         read_cr1 = readw(SSP_CR1(pl022->virtbase));
1489         read_dmacr = readw(SSP_DMACR(pl022->virtbase));
1490         read_sr = readw(SSP_SR(pl022->virtbase));
1491
1492         dev_warn(&pl022->adev->dev, "spi-pl022 CR0: %x\n", read_cr0);
1493         dev_warn(&pl022->adev->dev, "spi-pl022 CR1: %x\n", read_cr1);
1494         dev_warn(&pl022->adev->dev, "spi-pl022 DMACR: %x\n", read_dmacr);
1495         dev_warn(&pl022->adev->dev, "spi-pl022 SR: %x\n", read_sr);
1496         dev_warn(&pl022->adev->dev,
1497                         "spi-pl022 exp_fifo_level/fifodepth: %u/%d\n",
1498                         pl022->exp_fifo_level,
1499                         pl022->vendor->fifodepth);
1500
1501 }
1502
1503 static void do_polling_transfer(struct pl022 *pl022)
1504 {
1505         struct spi_message *message = NULL;
1506         struct spi_transfer *transfer = NULL;
1507         struct spi_transfer *previous = NULL;
1508         unsigned long time, timeout;
1509
1510         message = pl022->cur_msg;
1511
1512         while (message->state != STATE_DONE) {
1513                 /* Handle for abort */
1514                 if (message->state == STATE_ERROR)
1515                         break;
1516                 transfer = pl022->cur_transfer;
1517
1518                 /* Delay if requested at end of transfer */
1519                 if (message->state == STATE_RUNNING) {
1520                         previous =
1521                             list_entry(transfer->transfer_list.prev,
1522                                        struct spi_transfer, transfer_list);
1523                         spi_transfer_delay_exec(previous);
1524                         if (previous->cs_change)
1525                                 pl022_cs_control(pl022, SSP_CHIP_SELECT);
1526                 } else {
1527                         /* STATE_START */
1528                         message->state = STATE_RUNNING;
1529                         if (!pl022->next_msg_cs_active)
1530                                 pl022_cs_control(pl022, SSP_CHIP_SELECT);
1531                 }
1532
1533                 /* Configuration Changing Per Transfer */
1534                 if (set_up_next_transfer(pl022, transfer)) {
1535                         /* Error path */
1536                         message->state = STATE_ERROR;
1537                         break;
1538                 }
1539                 /* Flush FIFOs and enable SSP */
1540                 flush(pl022);
1541                 writew((readw(SSP_CR1(pl022->virtbase)) | SSP_CR1_MASK_SSE),
1542                        SSP_CR1(pl022->virtbase));
1543
1544                 dev_dbg(&pl022->adev->dev, "polling transfer ongoing ...\n");
1545
1546                 timeout = jiffies + msecs_to_jiffies(SPI_POLLING_TIMEOUT);
1547                 while (pl022->tx < pl022->tx_end || pl022->rx < pl022->rx_end) {
1548                         time = jiffies;
1549                         readwriter(pl022);
1550                         if (time_after(time, timeout)) {
1551                                 dev_warn(&pl022->adev->dev,
1552                                 "%s: timeout!\n", __func__);
1553                                 message->state = STATE_TIMEOUT;
1554                                 print_current_status(pl022);
1555                                 goto out;
1556                         }
1557                         cpu_relax();
1558                 }
1559
1560                 /* Update total byte transferred */
1561                 message->actual_length += pl022->cur_transfer->len;
1562                 /* Move to next transfer */
1563                 message->state = next_transfer(pl022);
1564                 if (message->state != STATE_DONE
1565                     && pl022->cur_transfer->cs_change)
1566                         pl022_cs_control(pl022, SSP_CHIP_DESELECT);
1567         }
1568 out:
1569         /* Handle end of message */
1570         if (message->state == STATE_DONE)
1571                 message->status = 0;
1572         else if (message->state == STATE_TIMEOUT)
1573                 message->status = -EAGAIN;
1574         else
1575                 message->status = -EIO;
1576
1577         giveback(pl022);
1578 }
1579
1580 static int pl022_transfer_one_message(struct spi_master *master,
1581                                       struct spi_message *msg)
1582 {
1583         struct pl022 *pl022 = spi_master_get_devdata(master);
1584
1585         /* Initial message state */
1586         pl022->cur_msg = msg;
1587         msg->state = STATE_START;
1588
1589         pl022->cur_transfer = list_entry(msg->transfers.next,
1590                                          struct spi_transfer, transfer_list);
1591
1592         /* Setup the SPI using the per chip configuration */
1593         pl022->cur_chip = spi_get_ctldata(msg->spi);
1594         pl022->cur_cs = msg->spi->chip_select;
1595         /* This is always available but may be set to -ENOENT */
1596         pl022->cur_gpiod = msg->spi->cs_gpiod;
1597
1598         restore_state(pl022);
1599         flush(pl022);
1600
1601         if (pl022->cur_chip->xfer_type == POLLING_TRANSFER)
1602                 do_polling_transfer(pl022);
1603         else
1604                 do_interrupt_dma_transfer(pl022);
1605
1606         return 0;
1607 }
1608
1609 static int pl022_unprepare_transfer_hardware(struct spi_master *master)
1610 {
1611         struct pl022 *pl022 = spi_master_get_devdata(master);
1612
1613         /* nothing more to do - disable spi/ssp and power off */
1614         writew((readw(SSP_CR1(pl022->virtbase)) &
1615                 (~SSP_CR1_MASK_SSE)), SSP_CR1(pl022->virtbase));
1616
1617         return 0;
1618 }
1619
1620 static int verify_controller_parameters(struct pl022 *pl022,
1621                                 struct pl022_config_chip const *chip_info)
1622 {
1623         if ((chip_info->iface < SSP_INTERFACE_MOTOROLA_SPI)
1624             || (chip_info->iface > SSP_INTERFACE_UNIDIRECTIONAL)) {
1625                 dev_err(&pl022->adev->dev,
1626                         "interface is configured incorrectly\n");
1627                 return -EINVAL;
1628         }
1629         if ((chip_info->iface == SSP_INTERFACE_UNIDIRECTIONAL) &&
1630             (!pl022->vendor->unidir)) {
1631                 dev_err(&pl022->adev->dev,
1632                         "unidirectional mode not supported in this "
1633                         "hardware version\n");
1634                 return -EINVAL;
1635         }
1636         if ((chip_info->hierarchy != SSP_MASTER)
1637             && (chip_info->hierarchy != SSP_SLAVE)) {
1638                 dev_err(&pl022->adev->dev,
1639                         "hierarchy is configured incorrectly\n");
1640                 return -EINVAL;
1641         }
1642         if ((chip_info->com_mode != INTERRUPT_TRANSFER)
1643             && (chip_info->com_mode != DMA_TRANSFER)
1644             && (chip_info->com_mode != POLLING_TRANSFER)) {
1645                 dev_err(&pl022->adev->dev,
1646                         "Communication mode is configured incorrectly\n");
1647                 return -EINVAL;
1648         }
1649         switch (chip_info->rx_lev_trig) {
1650         case SSP_RX_1_OR_MORE_ELEM:
1651         case SSP_RX_4_OR_MORE_ELEM:
1652         case SSP_RX_8_OR_MORE_ELEM:
1653                 /* These are always OK, all variants can handle this */
1654                 break;
1655         case SSP_RX_16_OR_MORE_ELEM:
1656                 if (pl022->vendor->fifodepth < 16) {
1657                         dev_err(&pl022->adev->dev,
1658                         "RX FIFO Trigger Level is configured incorrectly\n");
1659                         return -EINVAL;
1660                 }
1661                 break;
1662         case SSP_RX_32_OR_MORE_ELEM:
1663                 if (pl022->vendor->fifodepth < 32) {
1664                         dev_err(&pl022->adev->dev,
1665                         "RX FIFO Trigger Level is configured incorrectly\n");
1666                         return -EINVAL;
1667                 }
1668                 break;
1669         default:
1670                 dev_err(&pl022->adev->dev,
1671                         "RX FIFO Trigger Level is configured incorrectly\n");
1672                 return -EINVAL;
1673         }
1674         switch (chip_info->tx_lev_trig) {
1675         case SSP_TX_1_OR_MORE_EMPTY_LOC:
1676         case SSP_TX_4_OR_MORE_EMPTY_LOC:
1677         case SSP_TX_8_OR_MORE_EMPTY_LOC:
1678                 /* These are always OK, all variants can handle this */
1679                 break;
1680         case SSP_TX_16_OR_MORE_EMPTY_LOC:
1681                 if (pl022->vendor->fifodepth < 16) {
1682                         dev_err(&pl022->adev->dev,
1683                         "TX FIFO Trigger Level is configured incorrectly\n");
1684                         return -EINVAL;
1685                 }
1686                 break;
1687         case SSP_TX_32_OR_MORE_EMPTY_LOC:
1688                 if (pl022->vendor->fifodepth < 32) {
1689                         dev_err(&pl022->adev->dev,
1690                         "TX FIFO Trigger Level is configured incorrectly\n");
1691                         return -EINVAL;
1692                 }
1693                 break;
1694         default:
1695                 dev_err(&pl022->adev->dev,
1696                         "TX FIFO Trigger Level is configured incorrectly\n");
1697                 return -EINVAL;
1698         }
1699         if (chip_info->iface == SSP_INTERFACE_NATIONAL_MICROWIRE) {
1700                 if ((chip_info->ctrl_len < SSP_BITS_4)
1701                     || (chip_info->ctrl_len > SSP_BITS_32)) {
1702                         dev_err(&pl022->adev->dev,
1703                                 "CTRL LEN is configured incorrectly\n");
1704                         return -EINVAL;
1705                 }
1706                 if ((chip_info->wait_state != SSP_MWIRE_WAIT_ZERO)
1707                     && (chip_info->wait_state != SSP_MWIRE_WAIT_ONE)) {
1708                         dev_err(&pl022->adev->dev,
1709                                 "Wait State is configured incorrectly\n");
1710                         return -EINVAL;
1711                 }
1712                 /* Half duplex is only available in the ST Micro version */
1713                 if (pl022->vendor->extended_cr) {
1714                         if ((chip_info->duplex !=
1715                              SSP_MICROWIRE_CHANNEL_FULL_DUPLEX)
1716                             && (chip_info->duplex !=
1717                                 SSP_MICROWIRE_CHANNEL_HALF_DUPLEX)) {
1718                                 dev_err(&pl022->adev->dev,
1719                                         "Microwire duplex mode is configured incorrectly\n");
1720                                 return -EINVAL;
1721                         }
1722                 } else {
1723                         if (chip_info->duplex != SSP_MICROWIRE_CHANNEL_FULL_DUPLEX) {
1724                                 dev_err(&pl022->adev->dev,
1725                                         "Microwire half duplex mode requested,"
1726                                         " but this is only available in the"
1727                                         " ST version of PL022\n");
1728                                 return -EINVAL;
1729                         }
1730                 }
1731         }
1732         return 0;
1733 }
1734
1735 static inline u32 spi_rate(u32 rate, u16 cpsdvsr, u16 scr)
1736 {
1737         return rate / (cpsdvsr * (1 + scr));
1738 }
1739
1740 static int calculate_effective_freq(struct pl022 *pl022, int freq, struct
1741                                     ssp_clock_params * clk_freq)
1742 {
1743         /* Lets calculate the frequency parameters */
1744         u16 cpsdvsr = CPSDVR_MIN, scr = SCR_MIN;
1745         u32 rate, max_tclk, min_tclk, best_freq = 0, best_cpsdvsr = 0,
1746                 best_scr = 0, tmp, found = 0;
1747
1748         rate = clk_get_rate(pl022->clk);
1749         /* cpsdvscr = 2 & scr 0 */
1750         max_tclk = spi_rate(rate, CPSDVR_MIN, SCR_MIN);
1751         /* cpsdvsr = 254 & scr = 255 */
1752         min_tclk = spi_rate(rate, CPSDVR_MAX, SCR_MAX);
1753
1754         if (freq > max_tclk)
1755                 dev_warn(&pl022->adev->dev,
1756                         "Max speed that can be programmed is %d Hz, you requested %d\n",
1757                         max_tclk, freq);
1758
1759         if (freq < min_tclk) {
1760                 dev_err(&pl022->adev->dev,
1761                         "Requested frequency: %d Hz is less than minimum possible %d Hz\n",
1762                         freq, min_tclk);
1763                 return -EINVAL;
1764         }
1765
1766         /*
1767          * best_freq will give closest possible available rate (<= requested
1768          * freq) for all values of scr & cpsdvsr.
1769          */
1770         while ((cpsdvsr <= CPSDVR_MAX) && !found) {
1771                 while (scr <= SCR_MAX) {
1772                         tmp = spi_rate(rate, cpsdvsr, scr);
1773
1774                         if (tmp > freq) {
1775                                 /* we need lower freq */
1776                                 scr++;
1777                                 continue;
1778                         }
1779
1780                         /*
1781                          * If found exact value, mark found and break.
1782                          * If found more closer value, update and break.
1783                          */
1784                         if (tmp > best_freq) {
1785                                 best_freq = tmp;
1786                                 best_cpsdvsr = cpsdvsr;
1787                                 best_scr = scr;
1788
1789                                 if (tmp == freq)
1790                                         found = 1;
1791                         }
1792                         /*
1793                          * increased scr will give lower rates, which are not
1794                          * required
1795                          */
1796                         break;
1797                 }
1798                 cpsdvsr += 2;
1799                 scr = SCR_MIN;
1800         }
1801
1802         WARN(!best_freq, "pl022: Matching cpsdvsr and scr not found for %d Hz rate\n",
1803                         freq);
1804
1805         if (best_freq != freq)
1806                 dev_warn(&pl022->adev->dev,
1807                 "Requested frequency: %d Hz is unsupported,select by default %d Hz\n",
1808                         freq, best_freq);
1809         clk_freq->cpsdvsr = (u8) (best_cpsdvsr & 0xFF);
1810         clk_freq->scr = (u8) (best_scr & 0xFF);
1811         dev_dbg(&pl022->adev->dev,
1812                 "SSP Target Frequency is: %u, Effective Frequency is %u\n",
1813                 freq, best_freq);
1814         dev_dbg(&pl022->adev->dev, "SSP cpsdvsr = %d, scr = %d\n",
1815                 clk_freq->cpsdvsr, clk_freq->scr);
1816
1817         return 0;
1818 }
1819
1820 /*
1821  * A piece of default chip info unless the platform
1822  * supplies it.
1823  */
1824 static const struct pl022_config_chip pl022_default_chip_info = {
1825         .com_mode = INTERRUPT_TRANSFER,
1826         .iface = SSP_INTERFACE_MOTOROLA_SPI,
1827         .hierarchy = SSP_MASTER,
1828         .slave_tx_disable = DO_NOT_DRIVE_TX,
1829         .rx_lev_trig = SSP_RX_1_OR_MORE_ELEM,
1830         .tx_lev_trig = SSP_TX_1_OR_MORE_EMPTY_LOC,
1831         .ctrl_len = SSP_BITS_8,
1832         .wait_state = SSP_MWIRE_WAIT_ZERO,
1833         .duplex = SSP_MICROWIRE_CHANNEL_FULL_DUPLEX,
1834 };
1835
1836 /**
1837  * pl022_setup - setup function registered to SPI master framework
1838  * @spi: spi device which is requesting setup
1839  *
1840  * This function is registered to the SPI framework for this SPI master
1841  * controller. If it is the first time when setup is called by this device,
1842  * this function will initialize the runtime state for this chip and save
1843  * the same in the device structure. Else it will update the runtime info
1844  * with the updated chip info. Nothing is really being written to the
1845  * controller hardware here, that is not done until the actual transfer
1846  * commence.
1847  */
1848
1849 static int pl022_setup(struct spi_device *spi)
1850 {
1851         struct pl022_config_chip const *chip_info;
1852         struct pl022_config_chip chip_info_dt;
1853         struct chip_data *chip;
1854         struct ssp_clock_params clk_freq = { .cpsdvsr = 0, .scr = 0};
1855         int status = 0;
1856         struct pl022 *pl022 = spi_master_get_devdata(spi->master);
1857         unsigned int bits = spi->bits_per_word;
1858         u32 tmp;
1859         struct device_node *np = spi->dev.of_node;
1860
1861         if (!spi->max_speed_hz)
1862                 return -EINVAL;
1863
1864         /* Get controller_state if one is supplied */
1865         chip = spi_get_ctldata(spi);
1866
1867         if (chip == NULL) {
1868                 chip = kzalloc(sizeof(struct chip_data), GFP_KERNEL);
1869                 if (!chip)
1870                         return -ENOMEM;
1871                 dev_dbg(&spi->dev,
1872                         "allocated memory for controller's runtime state\n");
1873         }
1874
1875         /* Get controller data if one is supplied */
1876         chip_info = spi->controller_data;
1877
1878         if (chip_info == NULL) {
1879                 if (np) {
1880                         chip_info_dt = pl022_default_chip_info;
1881
1882                         chip_info_dt.hierarchy = SSP_MASTER;
1883                         of_property_read_u32(np, "pl022,interface",
1884                                 &chip_info_dt.iface);
1885                         of_property_read_u32(np, "pl022,com-mode",
1886                                 &chip_info_dt.com_mode);
1887                         of_property_read_u32(np, "pl022,rx-level-trig",
1888                                 &chip_info_dt.rx_lev_trig);
1889                         of_property_read_u32(np, "pl022,tx-level-trig",
1890                                 &chip_info_dt.tx_lev_trig);
1891                         of_property_read_u32(np, "pl022,ctrl-len",
1892                                 &chip_info_dt.ctrl_len);
1893                         of_property_read_u32(np, "pl022,wait-state",
1894                                 &chip_info_dt.wait_state);
1895                         of_property_read_u32(np, "pl022,duplex",
1896                                 &chip_info_dt.duplex);
1897
1898                         chip_info = &chip_info_dt;
1899                 } else {
1900                         chip_info = &pl022_default_chip_info;
1901                         /* spi_board_info.controller_data not is supplied */
1902                         dev_dbg(&spi->dev,
1903                                 "using default controller_data settings\n");
1904                 }
1905         } else
1906                 dev_dbg(&spi->dev,
1907                         "using user supplied controller_data settings\n");
1908
1909         /*
1910          * We can override with custom divisors, else we use the board
1911          * frequency setting
1912          */
1913         if ((chip_info->clk_freq.cpsdvsr == 0)
1914             && (chip_info->clk_freq.scr == 0)) {
1915                 status = calculate_effective_freq(pl022,
1916                                                   spi->max_speed_hz,
1917                                                   &clk_freq);
1918                 if (status < 0)
1919                         goto err_config_params;
1920         } else {
1921                 memcpy(&clk_freq, &chip_info->clk_freq, sizeof(clk_freq));
1922                 if ((clk_freq.cpsdvsr % 2) != 0)
1923                         clk_freq.cpsdvsr =
1924                                 clk_freq.cpsdvsr - 1;
1925         }
1926         if ((clk_freq.cpsdvsr < CPSDVR_MIN)
1927             || (clk_freq.cpsdvsr > CPSDVR_MAX)) {
1928                 status = -EINVAL;
1929                 dev_err(&spi->dev,
1930                         "cpsdvsr is configured incorrectly\n");
1931                 goto err_config_params;
1932         }
1933
1934         status = verify_controller_parameters(pl022, chip_info);
1935         if (status) {
1936                 dev_err(&spi->dev, "controller data is incorrect");
1937                 goto err_config_params;
1938         }
1939
1940         pl022->rx_lev_trig = chip_info->rx_lev_trig;
1941         pl022->tx_lev_trig = chip_info->tx_lev_trig;
1942
1943         /* Now set controller state based on controller data */
1944         chip->xfer_type = chip_info->com_mode;
1945
1946         /* Check bits per word with vendor specific range */
1947         if ((bits <= 3) || (bits > pl022->vendor->max_bpw)) {
1948                 status = -ENOTSUPP;
1949                 dev_err(&spi->dev, "illegal data size for this controller!\n");
1950                 dev_err(&spi->dev, "This controller can only handle 4 <= n <= %d bit words\n",
1951                                 pl022->vendor->max_bpw);
1952                 goto err_config_params;
1953         } else if (bits <= 8) {
1954                 dev_dbg(&spi->dev, "4 <= n <=8 bits per word\n");
1955                 chip->n_bytes = 1;
1956                 chip->read = READING_U8;
1957                 chip->write = WRITING_U8;
1958         } else if (bits <= 16) {
1959                 dev_dbg(&spi->dev, "9 <= n <= 16 bits per word\n");
1960                 chip->n_bytes = 2;
1961                 chip->read = READING_U16;
1962                 chip->write = WRITING_U16;
1963         } else {
1964                 dev_dbg(&spi->dev, "17 <= n <= 32 bits per word\n");
1965                 chip->n_bytes = 4;
1966                 chip->read = READING_U32;
1967                 chip->write = WRITING_U32;
1968         }
1969
1970         /* Now Initialize all register settings required for this chip */
1971         chip->cr0 = 0;
1972         chip->cr1 = 0;
1973         chip->dmacr = 0;
1974         chip->cpsr = 0;
1975         if ((chip_info->com_mode == DMA_TRANSFER)
1976             && ((pl022->master_info)->enable_dma)) {
1977                 chip->enable_dma = true;
1978                 dev_dbg(&spi->dev, "DMA mode set in controller state\n");
1979                 SSP_WRITE_BITS(chip->dmacr, SSP_DMA_ENABLED,
1980                                SSP_DMACR_MASK_RXDMAE, 0);
1981                 SSP_WRITE_BITS(chip->dmacr, SSP_DMA_ENABLED,
1982                                SSP_DMACR_MASK_TXDMAE, 1);
1983         } else {
1984                 chip->enable_dma = false;
1985                 dev_dbg(&spi->dev, "DMA mode NOT set in controller state\n");
1986                 SSP_WRITE_BITS(chip->dmacr, SSP_DMA_DISABLED,
1987                                SSP_DMACR_MASK_RXDMAE, 0);
1988                 SSP_WRITE_BITS(chip->dmacr, SSP_DMA_DISABLED,
1989                                SSP_DMACR_MASK_TXDMAE, 1);
1990         }
1991
1992         chip->cpsr = clk_freq.cpsdvsr;
1993
1994         /* Special setup for the ST micro extended control registers */
1995         if (pl022->vendor->extended_cr) {
1996                 u32 etx;
1997
1998                 if (pl022->vendor->pl023) {
1999                         /* These bits are only in the PL023 */
2000                         SSP_WRITE_BITS(chip->cr1, chip_info->clkdelay,
2001                                        SSP_CR1_MASK_FBCLKDEL_ST, 13);
2002                 } else {
2003                         /* These bits are in the PL022 but not PL023 */
2004                         SSP_WRITE_BITS(chip->cr0, chip_info->duplex,
2005                                        SSP_CR0_MASK_HALFDUP_ST, 5);
2006                         SSP_WRITE_BITS(chip->cr0, chip_info->ctrl_len,
2007                                        SSP_CR0_MASK_CSS_ST, 16);
2008                         SSP_WRITE_BITS(chip->cr0, chip_info->iface,
2009                                        SSP_CR0_MASK_FRF_ST, 21);
2010                         SSP_WRITE_BITS(chip->cr1, chip_info->wait_state,
2011                                        SSP_CR1_MASK_MWAIT_ST, 6);
2012                 }
2013                 SSP_WRITE_BITS(chip->cr0, bits - 1,
2014                                SSP_CR0_MASK_DSS_ST, 0);
2015
2016                 if (spi->mode & SPI_LSB_FIRST) {
2017                         tmp = SSP_RX_LSB;
2018                         etx = SSP_TX_LSB;
2019                 } else {
2020                         tmp = SSP_RX_MSB;
2021                         etx = SSP_TX_MSB;
2022                 }
2023                 SSP_WRITE_BITS(chip->cr1, tmp, SSP_CR1_MASK_RENDN_ST, 4);
2024                 SSP_WRITE_BITS(chip->cr1, etx, SSP_CR1_MASK_TENDN_ST, 5);
2025                 SSP_WRITE_BITS(chip->cr1, chip_info->rx_lev_trig,
2026                                SSP_CR1_MASK_RXIFLSEL_ST, 7);
2027                 SSP_WRITE_BITS(chip->cr1, chip_info->tx_lev_trig,
2028                                SSP_CR1_MASK_TXIFLSEL_ST, 10);
2029         } else {
2030                 SSP_WRITE_BITS(chip->cr0, bits - 1,
2031                                SSP_CR0_MASK_DSS, 0);
2032                 SSP_WRITE_BITS(chip->cr0, chip_info->iface,
2033                                SSP_CR0_MASK_FRF, 4);
2034         }
2035
2036         /* Stuff that is common for all versions */
2037         if (spi->mode & SPI_CPOL)
2038                 tmp = SSP_CLK_POL_IDLE_HIGH;
2039         else
2040                 tmp = SSP_CLK_POL_IDLE_LOW;
2041         SSP_WRITE_BITS(chip->cr0, tmp, SSP_CR0_MASK_SPO, 6);
2042
2043         if (spi->mode & SPI_CPHA)
2044                 tmp = SSP_CLK_SECOND_EDGE;
2045         else
2046                 tmp = SSP_CLK_FIRST_EDGE;
2047         SSP_WRITE_BITS(chip->cr0, tmp, SSP_CR0_MASK_SPH, 7);
2048
2049         SSP_WRITE_BITS(chip->cr0, clk_freq.scr, SSP_CR0_MASK_SCR, 8);
2050         /* Loopback is available on all versions except PL023 */
2051         if (pl022->vendor->loopback) {
2052                 if (spi->mode & SPI_LOOP)
2053                         tmp = LOOPBACK_ENABLED;
2054                 else
2055                         tmp = LOOPBACK_DISABLED;
2056                 SSP_WRITE_BITS(chip->cr1, tmp, SSP_CR1_MASK_LBM, 0);
2057         }
2058         SSP_WRITE_BITS(chip->cr1, SSP_DISABLED, SSP_CR1_MASK_SSE, 1);
2059         SSP_WRITE_BITS(chip->cr1, chip_info->hierarchy, SSP_CR1_MASK_MS, 2);
2060         SSP_WRITE_BITS(chip->cr1, chip_info->slave_tx_disable, SSP_CR1_MASK_SOD,
2061                 3);
2062
2063         /* Save controller_state */
2064         spi_set_ctldata(spi, chip);
2065         return status;
2066  err_config_params:
2067         spi_set_ctldata(spi, NULL);
2068         kfree(chip);
2069         return status;
2070 }
2071
2072 /**
2073  * pl022_cleanup - cleanup function registered to SPI master framework
2074  * @spi: spi device which is requesting cleanup
2075  *
2076  * This function is registered to the SPI framework for this SPI master
2077  * controller. It will free the runtime state of chip.
2078  */
2079 static void pl022_cleanup(struct spi_device *spi)
2080 {
2081         struct chip_data *chip = spi_get_ctldata(spi);
2082
2083         spi_set_ctldata(spi, NULL);
2084         kfree(chip);
2085 }
2086
2087 static struct pl022_ssp_controller *
2088 pl022_platform_data_dt_get(struct device *dev)
2089 {
2090         struct device_node *np = dev->of_node;
2091         struct pl022_ssp_controller *pd;
2092
2093         if (!np) {
2094                 dev_err(dev, "no dt node defined\n");
2095                 return NULL;
2096         }
2097
2098         if (strncmp(dev->bus->name, "platform", strlen("platform")))
2099                 pd = devm_kzalloc(dev, sizeof(struct pl022_ssp_controller), GFP_KERNEL);
2100         else
2101                 pd = kzalloc(sizeof(struct pl022_ssp_controller), GFP_KERNEL);
2102         if (!pd)
2103                 return NULL;
2104
2105         pd->bus_id = -1;
2106         pd->enable_dma = 1;
2107         of_property_read_u32(np, "pl022,autosuspend-delay",
2108                              &pd->autosuspend_delay);
2109         pd->rt = of_property_read_bool(np, "pl022,rt");
2110
2111         return pd;
2112 }
2113
2114 static int pl022_platform_probe(struct platform_device *pdev, const struct amba_id *id)
2115 {
2116         struct device *dev = &pdev->dev;
2117         struct spi_master *master;
2118         struct pl022_ssp_controller *platform_info;
2119         struct amba_device *adev;
2120         struct pl022 *pl022 = NULL;
2121         struct resource *res;
2122         int status = 0;
2123         int irq;
2124
2125         dev_info(dev,
2126                 "ARM PL022 driver for StarFive SoC platform, device ID: 0x%08x\n",
2127                 id->id);
2128
2129         adev = devm_kzalloc(dev, sizeof(*adev), GFP_KERNEL);
2130         adev->dev = pdev->dev;
2131         platform_info = pl022_platform_data_dt_get(dev);
2132         if (!platform_info) {
2133                 dev_err(dev, "probe: no platform data defined\n");
2134                 return -ENODEV;
2135         }
2136         /* Allocate master with space for data */
2137         master = spi_alloc_master(dev, sizeof(struct pl022));
2138         if (master == NULL) {
2139                 dev_err(dev, "probe - cannot alloc SPI master\n");
2140                 return -ENOMEM;
2141         }
2142
2143         pl022 = spi_master_get_devdata(master);
2144         pl022->master = master;
2145         pl022->master_info = platform_info;
2146         pl022->adev = adev;
2147         pl022->vendor = id->data;
2148         pl022->master->dev.parent = &pdev->dev;
2149         /*
2150          * Bus Number Which has been Assigned to this SSP controller
2151          * on this board
2152          */
2153         master->bus_num = platform_info->bus_id;
2154         master->cleanup = pl022_cleanup;
2155         master->setup = pl022_setup;
2156         /* If open CONFIG_PM, auto_runtime_pm should be false when of-platform.*/
2157         master->auto_runtime_pm = true;
2158         master->transfer_one_message = pl022_transfer_one_message;
2159         master->unprepare_transfer_hardware = pl022_unprepare_transfer_hardware;
2160         master->rt = platform_info->rt;
2161         master->dev.of_node = dev->of_node;
2162         master->use_gpio_descriptors = true;
2163
2164         /*
2165          * Supports mode 0-3, loopback, and active low CS. Transfers are
2166          * always MS bit first on the original pl022.
2167          */
2168         master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LOOP;
2169         if (pl022->vendor->extended_cr)
2170                 master->mode_bits |= SPI_LSB_FIRST;
2171
2172         dev_dbg(dev, "BUSNO: %d\n", master->bus_num);
2173
2174         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2175         pl022->phybase = res->start;
2176         pl022->virtbase = devm_ioremap_resource(dev, res);
2177         if (pl022->virtbase == NULL) {
2178                 status = -ENOMEM;
2179                 goto err_no_ioremap;
2180         }
2181         dev_info(dev, "mapped registers from %llx to %llx\n",
2182                  pdev->resource->start, pdev->resource->end);
2183
2184         pl022->clk = devm_clk_get(dev, NULL);
2185         if (IS_ERR(pl022->clk)) {
2186                 status = PTR_ERR(pl022->clk);
2187                 dev_err(dev, "could not retrieve SSP/SPI bus clock\n");
2188                 goto err_no_clk;
2189         }
2190         status = clk_prepare_enable(pl022->clk);
2191         if (status) {
2192                 dev_err(dev, "could not enable SSP/SPI bus clock\n");
2193                 goto err_no_clk_en;
2194         }
2195
2196         pl022->rst = devm_reset_control_get_exclusive(dev, "rst_apb");
2197         if (!IS_ERR(pl022->rst)) {
2198                 status = reset_control_deassert(pl022->rst);
2199                 if (status) {
2200                         dev_err(dev, "could not deassert SSP/SPI bus reset\n");
2201                         goto err_no_rst_clr;
2202                 }
2203         } else {
2204                 status = PTR_ERR(pl022->rst);
2205                 dev_err(dev, "could not retrieve SSP/SPI bus reset\n");
2206                 goto err_no_rst;
2207         }
2208
2209         /* Initialize transfer pump */
2210         tasklet_init(&pl022->pump_transfers, pump_transfers,
2211                      (unsigned long)pl022);
2212
2213         /* Disable SSP */
2214         writew((readw(SSP_CR1(pl022->virtbase)) & (~SSP_CR1_MASK_SSE)),
2215                SSP_CR1(pl022->virtbase));
2216         load_ssp_default_config(pl022);
2217
2218         /* Obtain IRQ line. */
2219         irq = platform_get_irq(pdev, 0);
2220         if (irq < 0) {
2221                 status = -ENXIO;
2222                 goto err_no_irq;
2223         }
2224         status = devm_request_irq(dev, irq, pl022_interrupt_handler,
2225                                   0, "pl022", pl022);
2226         if (status < 0) {
2227                 dev_err(dev, "probe - cannot get IRQ (%d)\n", status);
2228                 goto err_no_irq;
2229         }
2230
2231         /* Get DMA channels, try autoconfiguration first */
2232         status = pl022_dma_autoprobe(pl022);
2233         if (status == -EPROBE_DEFER) {
2234                 dev_dbg(dev, "deferring probe to get DMA channel\n");
2235                 goto err_no_irq;
2236         }
2237
2238         /* dma is not used unless configured in the device tree */
2239         platform_info->enable_dma = 0;
2240
2241         /* If that failed, use channels from platform_info */
2242         if (status == 0)
2243                 platform_info->enable_dma = 1;
2244         else if (platform_info->enable_dma) {
2245                 status = pl022_dma_probe(pl022);
2246                 if (status != 0)
2247                         platform_info->enable_dma = 0;
2248         }
2249
2250         /* Register with the SPI framework */
2251         dev_set_drvdata(dev, pl022);
2252
2253         status = devm_spi_register_master(dev, master);
2254         if (status != 0) {
2255                 dev_err(dev,
2256                         "probe - problem registering spi master\n");
2257                 goto err_spi_register;
2258         }
2259         dev_dbg(dev, "probe succeeded\n");
2260
2261         clk_disable_unprepare(pl022->clk);
2262
2263         return 0;
2264  err_spi_register:
2265         if (platform_info->enable_dma)
2266                 pl022_dma_remove(pl022);
2267  err_no_irq:
2268         reset_control_assert(pl022->rst);
2269  err_no_rst_clr:
2270  err_no_rst:
2271         clk_disable_unprepare(pl022->clk);
2272  err_no_clk_en:
2273  err_no_clk:
2274  err_no_ioremap:
2275         release_mem_region(pdev->resource->start, resource_size(pdev->resource));
2276         spi_master_put(master);
2277         return status;
2278 }
2279 static int pl022_probe(struct amba_device *adev, const struct amba_id *id)
2280 {
2281         struct device *dev = &adev->dev;
2282         struct pl022_ssp_controller *platform_info =
2283                         dev_get_platdata(&adev->dev);
2284         struct spi_master *master;
2285         struct pl022 *pl022 = NULL;     /*Data for this driver */
2286         int status = 0;
2287
2288         dev_info(&adev->dev,
2289                 "ARM PL022 driver for StarFive SoC platform, device ID: 0x%08x\n",
2290                 adev->periphid);
2291         if (!platform_info && IS_ENABLED(CONFIG_OF))
2292                 platform_info = pl022_platform_data_dt_get(dev);
2293
2294         if (!platform_info) {
2295                 dev_err(dev, "probe: no platform data defined\n");
2296                 return -ENODEV;
2297         }
2298
2299         /* Allocate master with space for data */
2300         master = spi_alloc_master(dev, sizeof(struct pl022));
2301         if (master == NULL) {
2302                 dev_err(&adev->dev, "probe - cannot alloc SPI master\n");
2303                 return -ENOMEM;
2304         }
2305
2306         pl022 = spi_master_get_devdata(master);
2307         pl022->master = master;
2308         pl022->master_info = platform_info;
2309         pl022->adev = adev;
2310         pl022->vendor = id->data;
2311
2312         /*
2313          * Bus Number Which has been Assigned to this SSP controller
2314          * on this board
2315          */
2316         master->bus_num = platform_info->bus_id;
2317         master->cleanup = pl022_cleanup;
2318         master->setup = pl022_setup;
2319         /* If open CONFIG_PM, auto_runtime_pm should be false when of-platform.*/
2320         master->auto_runtime_pm = true;
2321         master->transfer_one_message = pl022_transfer_one_message;
2322         master->unprepare_transfer_hardware = pl022_unprepare_transfer_hardware;
2323         master->rt = platform_info->rt;
2324         master->dev.of_node = dev->of_node;
2325         master->use_gpio_descriptors = true;
2326
2327         /*
2328          * Supports mode 0-3, loopback, and active low CS. Transfers are
2329          * always MS bit first on the original pl022.
2330          */
2331         master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LOOP;
2332         if (pl022->vendor->extended_cr)
2333                 master->mode_bits |= SPI_LSB_FIRST;
2334
2335         dev_dbg(&adev->dev, "BUSNO: %d\n", master->bus_num);
2336
2337         status = amba_request_regions(adev, NULL);
2338         if (status)
2339                 goto err_no_ioregion;
2340
2341         pl022->phybase = adev->res.start;
2342         pl022->virtbase = devm_ioremap(dev, adev->res.start,
2343                                        resource_size(&adev->res));
2344         if (pl022->virtbase == NULL) {
2345                 status = -ENOMEM;
2346                 goto err_no_ioremap;
2347         }
2348         dev_info(&adev->dev, "mapped registers from %pa to %p\n",
2349                 &adev->res.start, pl022->virtbase);
2350
2351         pl022->clk = devm_clk_get(&adev->dev, NULL);
2352         if (IS_ERR(pl022->clk)) {
2353                 status = PTR_ERR(pl022->clk);
2354                 dev_err(&adev->dev, "could not retrieve SSP/SPI bus clock\n");
2355                 goto err_no_clk;
2356         }
2357
2358         status = clk_prepare_enable(pl022->clk);
2359         if (status) {
2360                 dev_err(&adev->dev, "could not enable SSP/SPI bus clock\n");
2361                 goto err_no_clk_en;
2362         }
2363
2364         pl022->rst = devm_reset_control_get_exclusive(&adev->dev, "rst_apb");
2365         if (!IS_ERR(pl022->rst)) {
2366                 status = reset_control_deassert(pl022->rst);
2367                 if (status) {
2368                         dev_err(&adev->dev, "could not deassert SSP/SPI bus reset\n");
2369                         goto err_no_rst_clr;
2370                 }
2371         } else {
2372                 status = PTR_ERR(pl022->rst);
2373                 dev_err(&adev->dev, "could not retrieve SSP/SPI bus reset\n");
2374                 goto err_no_rst;
2375         }
2376
2377         /* Initialize transfer pump */
2378         tasklet_init(&pl022->pump_transfers, pump_transfers,
2379                      (unsigned long)pl022);
2380
2381         /* Disable SSP */
2382         writew((readw(SSP_CR1(pl022->virtbase)) & (~SSP_CR1_MASK_SSE)),
2383                SSP_CR1(pl022->virtbase));
2384         load_ssp_default_config(pl022);
2385
2386         status = devm_request_irq(dev, adev->irq[0], pl022_interrupt_handler,
2387                                   0, "pl022", pl022);
2388         if (status < 0) {
2389                 dev_err(&adev->dev, "probe - cannot get IRQ (%d)\n", status);
2390                 goto err_no_irq;
2391         }
2392
2393         /* Get DMA channels, try autoconfiguration first */
2394         status = pl022_dma_autoprobe(pl022);
2395         if (status == -EPROBE_DEFER) {
2396                 dev_dbg(dev, "deferring probe to get DMA channel\n");
2397                 goto err_no_irq;
2398         }
2399
2400         /* dma is not used unless configured in the device tree */
2401         platform_info->enable_dma = 0;
2402
2403         /* If that failed, use channels from platform_info */
2404         if (status == 0)
2405                 platform_info->enable_dma = 1;
2406         else if (platform_info->enable_dma) {
2407                 status = pl022_dma_probe(pl022);
2408                 if (status != 0)
2409                         platform_info->enable_dma = 0;
2410         }
2411
2412         /* Register with the SPI framework */
2413         amba_set_drvdata(adev, pl022);
2414
2415         status = devm_spi_register_master(&adev->dev, master);
2416         if (status != 0) {
2417                 dev_err(&adev->dev,
2418                         "probe - problem registering spi master\n");
2419                 goto err_spi_register;
2420         }
2421         dev_dbg(dev, "probe succeeded\n");
2422
2423         platform_info->autosuspend_delay = 100;
2424         /* let runtime pm put suspend */
2425         if (platform_info->autosuspend_delay > 0) {
2426                 dev_info(&adev->dev,
2427                         "will use autosuspend for runtime pm, delay %dms\n",
2428                         platform_info->autosuspend_delay);
2429                 pm_runtime_set_autosuspend_delay(dev,
2430                         platform_info->autosuspend_delay);
2431                 pm_runtime_use_autosuspend(dev);
2432         }
2433
2434         pm_runtime_put(dev);
2435
2436         return 0;
2437
2438  err_spi_register:
2439         if (platform_info->enable_dma)
2440                 pl022_dma_remove(pl022);
2441  err_no_irq:
2442         reset_control_assert(pl022->rst);
2443  err_no_rst_clr:
2444  err_no_rst:
2445         clk_disable_unprepare(pl022->clk);
2446  err_no_clk_en:
2447  err_no_clk:
2448  err_no_ioremap:
2449         amba_release_regions(adev);
2450  err_no_ioregion:
2451         spi_master_put(master);
2452
2453         return status;
2454 }
2455
2456 static void
2457 pl022_remove(struct amba_device *adev)
2458 {
2459         struct pl022 *pl022 = amba_get_drvdata(adev);
2460
2461         if (!pl022)
2462                 return;
2463
2464         /*
2465          * undo pm_runtime_put() in probe.  I assume that we're not
2466          * accessing the primecell here.
2467          */
2468         pm_runtime_get_noresume(&adev->dev);
2469
2470         load_ssp_default_config(pl022);
2471         if (pl022->master_info->enable_dma)
2472                 pl022_dma_remove(pl022);
2473
2474         clk_disable_unprepare(pl022->clk);
2475         amba_release_regions(adev);
2476         tasklet_disable(&pl022->pump_transfers);
2477 }
2478
2479 #ifdef CONFIG_PM_SLEEP
2480 static int pl022_suspend(struct device *dev)
2481 {
2482         struct pl022 *pl022 = dev_get_drvdata(dev);
2483         int ret;
2484
2485         ret = spi_master_suspend(pl022->master);
2486         if (ret)
2487                 return ret;
2488
2489         ret = pm_runtime_force_suspend(dev);
2490         if (ret) {
2491                 spi_master_resume(pl022->master);
2492                 return ret;
2493         }
2494
2495         pinctrl_pm_select_sleep_state(dev);
2496
2497         dev_dbg(dev, "starfive spi suspended\n");
2498
2499         return 0;
2500 }
2501
2502 static int pl022_resume(struct device *dev)
2503 {
2504         struct pl022 *pl022 = dev_get_drvdata(dev);
2505         int ret;
2506
2507         ret = pm_runtime_force_resume(dev);
2508         if (ret)
2509                 dev_err(dev, "problem resuming\n");
2510
2511         /* Start the queue running */
2512         ret = spi_master_resume(pl022->master);
2513         if (!ret)
2514                 dev_dbg(dev, "starfive spi resumed\n");
2515
2516         return ret;
2517 }
2518 #endif
2519
2520 #ifdef CONFIG_PM
2521 static int pl022_runtime_suspend(struct device *dev)
2522 {
2523         struct pl022 *pl022 = dev_get_drvdata(dev);
2524
2525         clk_disable_unprepare(pl022->clk);
2526         pinctrl_pm_select_idle_state(dev);
2527
2528         dev_dbg(dev, "starfive spi runtime suspend");
2529
2530         return 0;
2531 }
2532
2533 static int pl022_runtime_resume(struct device *dev)
2534 {
2535         struct pl022 *pl022 = dev_get_drvdata(dev);
2536
2537         pinctrl_pm_select_default_state(dev);
2538         clk_prepare_enable(pl022->clk);
2539
2540         dev_dbg(dev, "stafive spi runtime resume");
2541         return 0;
2542 }
2543 #endif
2544
2545 static const struct dev_pm_ops pl022_dev_pm_ops = {
2546         SET_SYSTEM_SLEEP_PM_OPS(pl022_suspend, pl022_resume)
2547         SET_RUNTIME_PM_OPS(pl022_runtime_suspend, pl022_runtime_resume, NULL)
2548 };
2549
2550 static struct vendor_data vendor_arm = {
2551         .fifodepth = 8,
2552         .max_bpw = 16,
2553         .unidir = false,
2554         .extended_cr = false,
2555         .pl023 = false,
2556         .loopback = true,
2557         .internal_cs_ctrl = false,
2558 };
2559
2560 static struct vendor_data vendor_st = {
2561         .fifodepth = 32,
2562         .max_bpw = 32,
2563         .unidir = false,
2564         .extended_cr = true,
2565         .pl023 = false,
2566         .loopback = true,
2567         .internal_cs_ctrl = false,
2568 };
2569
2570 static struct vendor_data vendor_st_pl023 = {
2571         .fifodepth = 32,
2572         .max_bpw = 32,
2573         .unidir = false,
2574         .extended_cr = true,
2575         .pl023 = true,
2576         .loopback = false,
2577         .internal_cs_ctrl = false,
2578 };
2579
2580 static struct vendor_data vendor_lsi = {
2581         .fifodepth = 8,
2582         .max_bpw = 16,
2583         .unidir = false,
2584         .extended_cr = false,
2585         .pl023 = false,
2586         .loopback = true,
2587         .internal_cs_ctrl = true,
2588 };
2589
2590 static const struct amba_id pl022_ids[] = {
2591         {
2592                 /*
2593                  * ARM PL022 variant, this has a 16bit wide
2594                  * and 8 locations deep TX/RX FIFO
2595                  */
2596                 .id     = 0x00041022,
2597                 .mask   = 0x000fffff,
2598                 .data   = &vendor_arm,
2599         },
2600         {
2601                 /*
2602                  * ST Micro derivative, this has 32bit wide
2603                  * and 32 locations deep TX/RX FIFO
2604                  */
2605                 .id     = 0x01080022,
2606                 .mask   = 0xffffffff,
2607                 .data   = &vendor_st,
2608         },
2609         {
2610                 /*
2611                  * ST-Ericsson derivative "PL023" (this is not
2612                  * an official ARM number), this is a PL022 SSP block
2613                  * stripped to SPI mode only, it has 32bit wide
2614                  * and 32 locations deep TX/RX FIFO but no extended
2615                  * CR0/CR1 register
2616                  */
2617                 .id     = 0x00080023,
2618                 .mask   = 0xffffffff,
2619                 .data   = &vendor_st_pl023,
2620         },
2621         {
2622                 /*
2623                  * PL022 variant that has a chip select control register whih
2624                  * allows control of 5 output signals nCS[0:4].
2625                  */
2626                 .id     = 0x000b6022,
2627                 .mask   = 0x000fffff,
2628                 .data   = &vendor_lsi,
2629         },
2630         { 0, 0 },
2631 };
2632
2633 MODULE_DEVICE_TABLE(amba, pl022_ids);
2634
2635 static struct amba_driver pl022_driver = {
2636         .drv = {
2637                 .name   = "ssp-pl022",
2638                 .pm     = &pl022_dev_pm_ops,
2639         },
2640         .id_table       = pl022_ids,
2641         .probe          = pl022_probe,
2642         .remove         = pl022_remove,
2643 };
2644
2645 static int __init pl022_init(void)
2646 {
2647         return amba_driver_register(&pl022_driver);
2648 }
2649 #if !IS_MODULE(CONFIG_SPI_PL022_STARFIVE)
2650         subsys_initcall(pl022_init);
2651 #else
2652         module_init(pl022_init);
2653 #endif
2654
2655 static void __exit pl022_exit(void)
2656 {
2657         amba_driver_unregister(&pl022_driver);
2658 }
2659 module_exit(pl022_exit);
2660
2661 /*
2662  * Register PL022 in platform bus to accommodate overlay use.
2663  * Because overlay only trigger response from the platform bus
2664  * not amba bus.
2665  */
2666 static int starfive_of_pl022_probe(struct platform_device *pdev)
2667 {
2668         int ret;
2669         const struct amba_id id = {
2670                 .id = 0x00041022,
2671                 .mask = 0x000fffff,
2672                 .data = &vendor_arm
2673         };
2674         struct device *dev = &pdev->dev;
2675
2676         ret = of_clk_set_defaults(dev->of_node, false);
2677         if (ret < 0)
2678                 goto err_probe;
2679
2680         ret = dev_pm_domain_attach(dev, true);
2681         if (ret)
2682                 goto err_probe;
2683         ret = pl022_platform_probe(pdev, &id);
2684
2685         pm_runtime_enable(dev);
2686         pm_runtime_set_autosuspend_delay(dev, 100);
2687         pm_runtime_use_autosuspend(dev);
2688
2689         if (ret) {
2690                 pm_runtime_disable(dev);
2691                 pm_runtime_set_suspended(dev);
2692                 pm_runtime_put_noidle(dev);
2693                 dev_pm_domain_detach(dev, true);
2694         }
2695
2696 err_probe:
2697         return ret;
2698 }
2699
2700 static int starfive_of_pl022_remove(struct platform_device *pdev)
2701 {
2702         struct pl022 *pl022 = dev_get_drvdata(&pdev->dev);
2703
2704         if (!pl022)
2705                 return 0;
2706
2707         pm_runtime_get_sync(&pdev->dev);
2708         pm_runtime_get_noresume(&pdev->dev);
2709
2710         load_ssp_default_config(pl022);
2711         if (pl022->master_info->enable_dma)
2712                 pl022_dma_remove(pl022);
2713
2714         clk_disable_unprepare(pl022->clk);
2715         tasklet_disable(&pl022->pump_transfers);
2716
2717         pm_runtime_put_noidle(&pdev->dev);
2718         pm_runtime_disable(&pdev->dev);
2719         pm_runtime_set_suspended(&pdev->dev);
2720         pm_runtime_put_noidle(&pdev->dev);
2721         dev_pm_domain_detach(&pdev->dev, true);
2722
2723         return 0;
2724 }
2725
2726 static const struct of_device_id starfive_of_pl022_match[] = {
2727         { .compatible = "starfive,jh7110-spi-pl022" },
2728         { },
2729 };
2730 MODULE_DEVICE_TABLE(of, starfive_of_pl022_match);
2731
2732 static struct platform_driver starfive_of_pl022_driver = {
2733         .driver = {
2734                 .name = "starfive-spi-pl022",
2735                 .of_match_table = starfive_of_pl022_match,
2736                 .pm     = &pl022_dev_pm_ops,
2737         },
2738         .probe = starfive_of_pl022_probe,
2739         .remove = starfive_of_pl022_remove,
2740 };
2741 #if !IS_MODULE(CONFIG_SPI_PL022_STARFIVE)
2742         module_platform_driver(starfive_of_pl022_driver);
2743 /* platform register end */
2744 #endif
2745
2746 MODULE_AUTHOR("xingyu.wu <xingyu.wu@starfivetech.com>");
2747 MODULE_AUTHOR("Linus Walleij <linus.walleij@stericsson.com>");
2748 MODULE_DESCRIPTION("PL022 SSP Controller Driver");
2749 MODULE_LICENSE("GPL");