]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/spi/spi-bcm2835.c
spi: bcm2835: Convert to use CS GPIO descriptors
[linux.git] / drivers / spi / spi-bcm2835.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Driver for Broadcom BCM2835 SPI Controllers
4  *
5  * Copyright (C) 2012 Chris Boot
6  * Copyright (C) 2013 Stephen Warren
7  * Copyright (C) 2015 Martin Sperl
8  *
9  * This driver is inspired by:
10  * spi-ath79.c, Copyright (C) 2009-2011 Gabor Juhos <juhosg@openwrt.org>
11  * spi-atmel.c, Copyright (C) 2006 Atmel Corporation
12  */
13
14 #include <linux/clk.h>
15 #include <linux/completion.h>
16 #include <linux/debugfs.h>
17 #include <linux/delay.h>
18 #include <linux/dma-mapping.h>
19 #include <linux/dmaengine.h>
20 #include <linux/err.h>
21 #include <linux/interrupt.h>
22 #include <linux/io.h>
23 #include <linux/kernel.h>
24 #include <linux/module.h>
25 #include <linux/of.h>
26 #include <linux/of_address.h>
27 #include <linux/of_device.h>
28 #include <linux/gpio/consumer.h>
29 #include <linux/gpio/machine.h> /* FIXME: using chip internals */
30 #include <linux/gpio/driver.h> /* FIXME: using chip internals */
31 #include <linux/of_irq.h>
32 #include <linux/spi/spi.h>
33
34 /* SPI register offsets */
35 #define BCM2835_SPI_CS                  0x00
36 #define BCM2835_SPI_FIFO                0x04
37 #define BCM2835_SPI_CLK                 0x08
38 #define BCM2835_SPI_DLEN                0x0c
39 #define BCM2835_SPI_LTOH                0x10
40 #define BCM2835_SPI_DC                  0x14
41
42 /* Bitfields in CS */
43 #define BCM2835_SPI_CS_LEN_LONG         0x02000000
44 #define BCM2835_SPI_CS_DMA_LEN          0x01000000
45 #define BCM2835_SPI_CS_CSPOL2           0x00800000
46 #define BCM2835_SPI_CS_CSPOL1           0x00400000
47 #define BCM2835_SPI_CS_CSPOL0           0x00200000
48 #define BCM2835_SPI_CS_RXF              0x00100000
49 #define BCM2835_SPI_CS_RXR              0x00080000
50 #define BCM2835_SPI_CS_TXD              0x00040000
51 #define BCM2835_SPI_CS_RXD              0x00020000
52 #define BCM2835_SPI_CS_DONE             0x00010000
53 #define BCM2835_SPI_CS_LEN              0x00002000
54 #define BCM2835_SPI_CS_REN              0x00001000
55 #define BCM2835_SPI_CS_ADCS             0x00000800
56 #define BCM2835_SPI_CS_INTR             0x00000400
57 #define BCM2835_SPI_CS_INTD             0x00000200
58 #define BCM2835_SPI_CS_DMAEN            0x00000100
59 #define BCM2835_SPI_CS_TA               0x00000080
60 #define BCM2835_SPI_CS_CSPOL            0x00000040
61 #define BCM2835_SPI_CS_CLEAR_RX         0x00000020
62 #define BCM2835_SPI_CS_CLEAR_TX         0x00000010
63 #define BCM2835_SPI_CS_CPOL             0x00000008
64 #define BCM2835_SPI_CS_CPHA             0x00000004
65 #define BCM2835_SPI_CS_CS_10            0x00000002
66 #define BCM2835_SPI_CS_CS_01            0x00000001
67
68 #define BCM2835_SPI_FIFO_SIZE           64
69 #define BCM2835_SPI_FIFO_SIZE_3_4       48
70 #define BCM2835_SPI_DMA_MIN_LENGTH      96
71 #define BCM2835_SPI_MODE_BITS   (SPI_CPOL | SPI_CPHA | SPI_CS_HIGH \
72                                 | SPI_NO_CS | SPI_3WIRE)
73
74 #define DRV_NAME        "spi-bcm2835"
75
76 /* define polling limits */
77 unsigned int polling_limit_us = 30;
78 module_param(polling_limit_us, uint, 0664);
79 MODULE_PARM_DESC(polling_limit_us,
80                  "time in us to run a transfer in polling mode\n");
81
82 /**
83  * struct bcm2835_spi - BCM2835 SPI controller
84  * @regs: base address of register map
85  * @clk: core clock, divided to calculate serial clock
86  * @irq: interrupt, signals TX FIFO empty or RX FIFO ¾ full
87  * @tfr: SPI transfer currently processed
88  * @tx_buf: pointer whence next transmitted byte is read
89  * @rx_buf: pointer where next received byte is written
90  * @tx_len: remaining bytes to transmit
91  * @rx_len: remaining bytes to receive
92  * @tx_prologue: bytes transmitted without DMA if first TX sglist entry's
93  *      length is not a multiple of 4 (to overcome hardware limitation)
94  * @rx_prologue: bytes received without DMA if first RX sglist entry's
95  *      length is not a multiple of 4 (to overcome hardware limitation)
96  * @tx_spillover: whether @tx_prologue spills over to second TX sglist entry
97  * @dma_pending: whether a DMA transfer is in progress
98  * @debugfs_dir: the debugfs directory - neede to remove debugfs when
99  *      unloading the module
100  * @count_transfer_polling: count of how often polling mode is used
101  * @count_transfer_irq: count of how often interrupt mode is used
102  * @count_transfer_irq_after_polling: count of how often we fall back to
103  *      interrupt mode after starting in polling mode.
104  *      These are counted as well in @count_transfer_polling and
105  *      @count_transfer_irq
106  * @count_transfer_dma: count how often dma mode is used
107  */
108 struct bcm2835_spi {
109         void __iomem *regs;
110         struct clk *clk;
111         int irq;
112         struct spi_transfer *tfr;
113         const u8 *tx_buf;
114         u8 *rx_buf;
115         int tx_len;
116         int rx_len;
117         int tx_prologue;
118         int rx_prologue;
119         unsigned int tx_spillover;
120         unsigned int dma_pending;
121
122         struct dentry *debugfs_dir;
123         u64 count_transfer_polling;
124         u64 count_transfer_irq;
125         u64 count_transfer_irq_after_polling;
126         u64 count_transfer_dma;
127 };
128
129 #if defined(CONFIG_DEBUG_FS)
130 static void bcm2835_debugfs_create(struct bcm2835_spi *bs,
131                                    const char *dname)
132 {
133         char name[64];
134         struct dentry *dir;
135
136         /* get full name */
137         snprintf(name, sizeof(name), "spi-bcm2835-%s", dname);
138
139         /* the base directory */
140         dir = debugfs_create_dir(name, NULL);
141         bs->debugfs_dir = dir;
142
143         /* the counters */
144         debugfs_create_u64("count_transfer_polling", 0444, dir,
145                            &bs->count_transfer_polling);
146         debugfs_create_u64("count_transfer_irq", 0444, dir,
147                            &bs->count_transfer_irq);
148         debugfs_create_u64("count_transfer_irq_after_polling", 0444, dir,
149                            &bs->count_transfer_irq_after_polling);
150         debugfs_create_u64("count_transfer_dma", 0444, dir,
151                            &bs->count_transfer_dma);
152 }
153
154 static void bcm2835_debugfs_remove(struct bcm2835_spi *bs)
155 {
156         debugfs_remove_recursive(bs->debugfs_dir);
157         bs->debugfs_dir = NULL;
158 }
159 #else
160 static void bcm2835_debugfs_create(struct bcm2835_spi *bs,
161                                    const char *dname)
162 {
163 }
164
165 static void bcm2835_debugfs_remove(struct bcm2835_spi *bs)
166 {
167 }
168 #endif /* CONFIG_DEBUG_FS */
169
170 static inline u32 bcm2835_rd(struct bcm2835_spi *bs, unsigned reg)
171 {
172         return readl(bs->regs + reg);
173 }
174
175 static inline void bcm2835_wr(struct bcm2835_spi *bs, unsigned reg, u32 val)
176 {
177         writel(val, bs->regs + reg);
178 }
179
180 static inline void bcm2835_rd_fifo(struct bcm2835_spi *bs)
181 {
182         u8 byte;
183
184         while ((bs->rx_len) &&
185                (bcm2835_rd(bs, BCM2835_SPI_CS) & BCM2835_SPI_CS_RXD)) {
186                 byte = bcm2835_rd(bs, BCM2835_SPI_FIFO);
187                 if (bs->rx_buf)
188                         *bs->rx_buf++ = byte;
189                 bs->rx_len--;
190         }
191 }
192
193 static inline void bcm2835_wr_fifo(struct bcm2835_spi *bs)
194 {
195         u8 byte;
196
197         while ((bs->tx_len) &&
198                (bcm2835_rd(bs, BCM2835_SPI_CS) & BCM2835_SPI_CS_TXD)) {
199                 byte = bs->tx_buf ? *bs->tx_buf++ : 0;
200                 bcm2835_wr(bs, BCM2835_SPI_FIFO, byte);
201                 bs->tx_len--;
202         }
203 }
204
205 /**
206  * bcm2835_rd_fifo_count() - blindly read exactly @count bytes from RX FIFO
207  * @bs: BCM2835 SPI controller
208  * @count: bytes to read from RX FIFO
209  *
210  * The caller must ensure that @bs->rx_len is greater than or equal to @count,
211  * that the RX FIFO contains at least @count bytes and that the DMA Enable flag
212  * in the CS register is set (such that a read from the FIFO register receives
213  * 32-bit instead of just 8-bit).  Moreover @bs->rx_buf must not be %NULL.
214  */
215 static inline void bcm2835_rd_fifo_count(struct bcm2835_spi *bs, int count)
216 {
217         u32 val;
218         int len;
219
220         bs->rx_len -= count;
221
222         while (count > 0) {
223                 val = bcm2835_rd(bs, BCM2835_SPI_FIFO);
224                 len = min(count, 4);
225                 memcpy(bs->rx_buf, &val, len);
226                 bs->rx_buf += len;
227                 count -= 4;
228         }
229 }
230
231 /**
232  * bcm2835_wr_fifo_count() - blindly write exactly @count bytes to TX FIFO
233  * @bs: BCM2835 SPI controller
234  * @count: bytes to write to TX FIFO
235  *
236  * The caller must ensure that @bs->tx_len is greater than or equal to @count,
237  * that the TX FIFO can accommodate @count bytes and that the DMA Enable flag
238  * in the CS register is set (such that a write to the FIFO register transmits
239  * 32-bit instead of just 8-bit).
240  */
241 static inline void bcm2835_wr_fifo_count(struct bcm2835_spi *bs, int count)
242 {
243         u32 val;
244         int len;
245
246         bs->tx_len -= count;
247
248         while (count > 0) {
249                 if (bs->tx_buf) {
250                         len = min(count, 4);
251                         memcpy(&val, bs->tx_buf, len);
252                         bs->tx_buf += len;
253                 } else {
254                         val = 0;
255                 }
256                 bcm2835_wr(bs, BCM2835_SPI_FIFO, val);
257                 count -= 4;
258         }
259 }
260
261 /**
262  * bcm2835_wait_tx_fifo_empty() - busy-wait for TX FIFO to empty
263  * @bs: BCM2835 SPI controller
264  *
265  * The caller must ensure that the RX FIFO can accommodate as many bytes
266  * as have been written to the TX FIFO:  Transmission is halted once the
267  * RX FIFO is full, causing this function to spin forever.
268  */
269 static inline void bcm2835_wait_tx_fifo_empty(struct bcm2835_spi *bs)
270 {
271         while (!(bcm2835_rd(bs, BCM2835_SPI_CS) & BCM2835_SPI_CS_DONE))
272                 cpu_relax();
273 }
274
275 /**
276  * bcm2835_rd_fifo_blind() - blindly read up to @count bytes from RX FIFO
277  * @bs: BCM2835 SPI controller
278  * @count: bytes available for reading in RX FIFO
279  */
280 static inline void bcm2835_rd_fifo_blind(struct bcm2835_spi *bs, int count)
281 {
282         u8 val;
283
284         count = min(count, bs->rx_len);
285         bs->rx_len -= count;
286
287         while (count) {
288                 val = bcm2835_rd(bs, BCM2835_SPI_FIFO);
289                 if (bs->rx_buf)
290                         *bs->rx_buf++ = val;
291                 count--;
292         }
293 }
294
295 /**
296  * bcm2835_wr_fifo_blind() - blindly write up to @count bytes to TX FIFO
297  * @bs: BCM2835 SPI controller
298  * @count: bytes available for writing in TX FIFO
299  */
300 static inline void bcm2835_wr_fifo_blind(struct bcm2835_spi *bs, int count)
301 {
302         u8 val;
303
304         count = min(count, bs->tx_len);
305         bs->tx_len -= count;
306
307         while (count) {
308                 val = bs->tx_buf ? *bs->tx_buf++ : 0;
309                 bcm2835_wr(bs, BCM2835_SPI_FIFO, val);
310                 count--;
311         }
312 }
313
314 static void bcm2835_spi_reset_hw(struct spi_controller *ctlr)
315 {
316         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
317         u32 cs = bcm2835_rd(bs, BCM2835_SPI_CS);
318
319         /* Disable SPI interrupts and transfer */
320         cs &= ~(BCM2835_SPI_CS_INTR |
321                 BCM2835_SPI_CS_INTD |
322                 BCM2835_SPI_CS_DMAEN |
323                 BCM2835_SPI_CS_TA);
324         /* and reset RX/TX FIFOS */
325         cs |= BCM2835_SPI_CS_CLEAR_RX | BCM2835_SPI_CS_CLEAR_TX;
326
327         /* and reset the SPI_HW */
328         bcm2835_wr(bs, BCM2835_SPI_CS, cs);
329         /* as well as DLEN */
330         bcm2835_wr(bs, BCM2835_SPI_DLEN, 0);
331 }
332
333 static irqreturn_t bcm2835_spi_interrupt(int irq, void *dev_id)
334 {
335         struct spi_controller *ctlr = dev_id;
336         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
337         u32 cs = bcm2835_rd(bs, BCM2835_SPI_CS);
338
339         /*
340          * An interrupt is signaled either if DONE is set (TX FIFO empty)
341          * or if RXR is set (RX FIFO >= ¾ full).
342          */
343         if (cs & BCM2835_SPI_CS_RXF)
344                 bcm2835_rd_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE);
345         else if (cs & BCM2835_SPI_CS_RXR)
346                 bcm2835_rd_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE_3_4);
347
348         if (bs->tx_len && cs & BCM2835_SPI_CS_DONE)
349                 bcm2835_wr_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE);
350
351         /* Read as many bytes as possible from FIFO */
352         bcm2835_rd_fifo(bs);
353         /* Write as many bytes as possible to FIFO */
354         bcm2835_wr_fifo(bs);
355
356         if (!bs->rx_len) {
357                 /* Transfer complete - reset SPI HW */
358                 bcm2835_spi_reset_hw(ctlr);
359                 /* wake up the framework */
360                 complete(&ctlr->xfer_completion);
361         }
362
363         return IRQ_HANDLED;
364 }
365
366 static int bcm2835_spi_transfer_one_irq(struct spi_controller *ctlr,
367                                         struct spi_device *spi,
368                                         struct spi_transfer *tfr,
369                                         u32 cs, bool fifo_empty)
370 {
371         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
372
373         /* update usage statistics */
374         bs->count_transfer_irq++;
375
376         /*
377          * Enable HW block, but with interrupts still disabled.
378          * Otherwise the empty TX FIFO would immediately trigger an interrupt.
379          */
380         bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_TA);
381
382         /* fill TX FIFO as much as possible */
383         if (fifo_empty)
384                 bcm2835_wr_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE);
385         bcm2835_wr_fifo(bs);
386
387         /* enable interrupts */
388         cs |= BCM2835_SPI_CS_INTR | BCM2835_SPI_CS_INTD | BCM2835_SPI_CS_TA;
389         bcm2835_wr(bs, BCM2835_SPI_CS, cs);
390
391         /* signal that we need to wait for completion */
392         return 1;
393 }
394
395 /**
396  * bcm2835_spi_transfer_prologue() - transfer first few bytes without DMA
397  * @ctlr: SPI master controller
398  * @tfr: SPI transfer
399  * @bs: BCM2835 SPI controller
400  * @cs: CS register
401  *
402  * A limitation in DMA mode is that the FIFO must be accessed in 4 byte chunks.
403  * Only the final write access is permitted to transmit less than 4 bytes, the
404  * SPI controller deduces its intended size from the DLEN register.
405  *
406  * If a TX or RX sglist contains multiple entries, one per page, and the first
407  * entry starts in the middle of a page, that first entry's length may not be
408  * a multiple of 4.  Subsequent entries are fine because they span an entire
409  * page, hence do have a length that's a multiple of 4.
410  *
411  * This cannot happen with kmalloc'ed buffers (which is what most clients use)
412  * because they are contiguous in physical memory and therefore not split on
413  * page boundaries by spi_map_buf().  But it *can* happen with vmalloc'ed
414  * buffers.
415  *
416  * The DMA engine is incapable of combining sglist entries into a continuous
417  * stream of 4 byte chunks, it treats every entry separately:  A TX entry is
418  * rounded up a to a multiple of 4 bytes by transmitting surplus bytes, an RX
419  * entry is rounded up by throwing away received bytes.
420  *
421  * Overcome this limitation by transferring the first few bytes without DMA:
422  * E.g. if the first TX sglist entry's length is 23 and the first RX's is 42,
423  * write 3 bytes to the TX FIFO but read only 2 bytes from the RX FIFO.
424  * The residue of 1 byte in the RX FIFO is picked up by DMA.  Together with
425  * the rest of the first RX sglist entry it makes up a multiple of 4 bytes.
426  *
427  * Should the RX prologue be larger, say, 3 vis-à-vis a TX prologue of 1,
428  * write 1 + 4 = 5 bytes to the TX FIFO and read 3 bytes from the RX FIFO.
429  * Caution, the additional 4 bytes spill over to the second TX sglist entry
430  * if the length of the first is *exactly* 1.
431  *
432  * At most 6 bytes are written and at most 3 bytes read.  Do we know the
433  * transfer has this many bytes?  Yes, see BCM2835_SPI_DMA_MIN_LENGTH.
434  *
435  * The FIFO is normally accessed with 8-bit width by the CPU and 32-bit width
436  * by the DMA engine.  Toggling the DMA Enable flag in the CS register switches
437  * the width but also garbles the FIFO's contents.  The prologue must therefore
438  * be transmitted in 32-bit width to ensure that the following DMA transfer can
439  * pick up the residue in the RX FIFO in ungarbled form.
440  */
441 static void bcm2835_spi_transfer_prologue(struct spi_controller *ctlr,
442                                           struct spi_transfer *tfr,
443                                           struct bcm2835_spi *bs,
444                                           u32 cs)
445 {
446         int tx_remaining;
447
448         bs->tfr          = tfr;
449         bs->tx_prologue  = 0;
450         bs->rx_prologue  = 0;
451         bs->tx_spillover = false;
452
453         if (!sg_is_last(&tfr->tx_sg.sgl[0]))
454                 bs->tx_prologue = sg_dma_len(&tfr->tx_sg.sgl[0]) & 3;
455
456         if (!sg_is_last(&tfr->rx_sg.sgl[0])) {
457                 bs->rx_prologue = sg_dma_len(&tfr->rx_sg.sgl[0]) & 3;
458
459                 if (bs->rx_prologue > bs->tx_prologue) {
460                         if (sg_is_last(&tfr->tx_sg.sgl[0])) {
461                                 bs->tx_prologue  = bs->rx_prologue;
462                         } else {
463                                 bs->tx_prologue += 4;
464                                 bs->tx_spillover =
465                                         !(sg_dma_len(&tfr->tx_sg.sgl[0]) & ~3);
466                         }
467                 }
468         }
469
470         /* rx_prologue > 0 implies tx_prologue > 0, so check only the latter */
471         if (!bs->tx_prologue)
472                 return;
473
474         /* Write and read RX prologue.  Adjust first entry in RX sglist. */
475         if (bs->rx_prologue) {
476                 bcm2835_wr(bs, BCM2835_SPI_DLEN, bs->rx_prologue);
477                 bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_TA
478                                                   | BCM2835_SPI_CS_DMAEN);
479                 bcm2835_wr_fifo_count(bs, bs->rx_prologue);
480                 bcm2835_wait_tx_fifo_empty(bs);
481                 bcm2835_rd_fifo_count(bs, bs->rx_prologue);
482                 bcm2835_spi_reset_hw(ctlr);
483
484                 dma_sync_single_for_device(ctlr->dma_rx->device->dev,
485                                            sg_dma_address(&tfr->rx_sg.sgl[0]),
486                                            bs->rx_prologue, DMA_FROM_DEVICE);
487
488                 sg_dma_address(&tfr->rx_sg.sgl[0]) += bs->rx_prologue;
489                 sg_dma_len(&tfr->rx_sg.sgl[0])     -= bs->rx_prologue;
490         }
491
492         /*
493          * Write remaining TX prologue.  Adjust first entry in TX sglist.
494          * Also adjust second entry if prologue spills over to it.
495          */
496         tx_remaining = bs->tx_prologue - bs->rx_prologue;
497         if (tx_remaining) {
498                 bcm2835_wr(bs, BCM2835_SPI_DLEN, tx_remaining);
499                 bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_TA
500                                                   | BCM2835_SPI_CS_DMAEN);
501                 bcm2835_wr_fifo_count(bs, tx_remaining);
502                 bcm2835_wait_tx_fifo_empty(bs);
503                 bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_CLEAR_TX);
504         }
505
506         if (likely(!bs->tx_spillover)) {
507                 sg_dma_address(&tfr->tx_sg.sgl[0]) += bs->tx_prologue;
508                 sg_dma_len(&tfr->tx_sg.sgl[0])     -= bs->tx_prologue;
509         } else {
510                 sg_dma_len(&tfr->tx_sg.sgl[0])      = 0;
511                 sg_dma_address(&tfr->tx_sg.sgl[1]) += 4;
512                 sg_dma_len(&tfr->tx_sg.sgl[1])     -= 4;
513         }
514 }
515
516 /**
517  * bcm2835_spi_undo_prologue() - reconstruct original sglist state
518  * @bs: BCM2835 SPI controller
519  *
520  * Undo changes which were made to an SPI transfer's sglist when transmitting
521  * the prologue.  This is necessary to ensure the same memory ranges are
522  * unmapped that were originally mapped.
523  */
524 static void bcm2835_spi_undo_prologue(struct bcm2835_spi *bs)
525 {
526         struct spi_transfer *tfr = bs->tfr;
527
528         if (!bs->tx_prologue)
529                 return;
530
531         if (bs->rx_prologue) {
532                 sg_dma_address(&tfr->rx_sg.sgl[0]) -= bs->rx_prologue;
533                 sg_dma_len(&tfr->rx_sg.sgl[0])     += bs->rx_prologue;
534         }
535
536         if (likely(!bs->tx_spillover)) {
537                 sg_dma_address(&tfr->tx_sg.sgl[0]) -= bs->tx_prologue;
538                 sg_dma_len(&tfr->tx_sg.sgl[0])     += bs->tx_prologue;
539         } else {
540                 sg_dma_len(&tfr->tx_sg.sgl[0])      = bs->tx_prologue - 4;
541                 sg_dma_address(&tfr->tx_sg.sgl[1]) -= 4;
542                 sg_dma_len(&tfr->tx_sg.sgl[1])     += 4;
543         }
544 }
545
546 static void bcm2835_spi_dma_done(void *data)
547 {
548         struct spi_controller *ctlr = data;
549         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
550
551         /* reset fifo and HW */
552         bcm2835_spi_reset_hw(ctlr);
553
554         /* and terminate tx-dma as we do not have an irq for it
555          * because when the rx dma will terminate and this callback
556          * is called the tx-dma must have finished - can't get to this
557          * situation otherwise...
558          */
559         if (cmpxchg(&bs->dma_pending, true, false)) {
560                 dmaengine_terminate_async(ctlr->dma_tx);
561                 bcm2835_spi_undo_prologue(bs);
562         }
563
564         /* and mark as completed */;
565         complete(&ctlr->xfer_completion);
566 }
567
568 static int bcm2835_spi_prepare_sg(struct spi_controller *ctlr,
569                                   struct spi_transfer *tfr,
570                                   bool is_tx)
571 {
572         struct dma_chan *chan;
573         struct scatterlist *sgl;
574         unsigned int nents;
575         enum dma_transfer_direction dir;
576         unsigned long flags;
577
578         struct dma_async_tx_descriptor *desc;
579         dma_cookie_t cookie;
580
581         if (is_tx) {
582                 dir   = DMA_MEM_TO_DEV;
583                 chan  = ctlr->dma_tx;
584                 nents = tfr->tx_sg.nents;
585                 sgl   = tfr->tx_sg.sgl;
586                 flags = 0 /* no  tx interrupt */;
587
588         } else {
589                 dir   = DMA_DEV_TO_MEM;
590                 chan  = ctlr->dma_rx;
591                 nents = tfr->rx_sg.nents;
592                 sgl   = tfr->rx_sg.sgl;
593                 flags = DMA_PREP_INTERRUPT;
594         }
595         /* prepare the channel */
596         desc = dmaengine_prep_slave_sg(chan, sgl, nents, dir, flags);
597         if (!desc)
598                 return -EINVAL;
599
600         /* set callback for rx */
601         if (!is_tx) {
602                 desc->callback = bcm2835_spi_dma_done;
603                 desc->callback_param = ctlr;
604         }
605
606         /* submit it to DMA-engine */
607         cookie = dmaengine_submit(desc);
608
609         return dma_submit_error(cookie);
610 }
611
612 static int bcm2835_spi_transfer_one_dma(struct spi_controller *ctlr,
613                                         struct spi_device *spi,
614                                         struct spi_transfer *tfr,
615                                         u32 cs)
616 {
617         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
618         int ret;
619
620         /* update usage statistics */
621         bs->count_transfer_dma++;
622
623         /*
624          * Transfer first few bytes without DMA if length of first TX or RX
625          * sglist entry is not a multiple of 4 bytes (hardware limitation).
626          */
627         bcm2835_spi_transfer_prologue(ctlr, tfr, bs, cs);
628
629         /* setup tx-DMA */
630         ret = bcm2835_spi_prepare_sg(ctlr, tfr, true);
631         if (ret)
632                 goto err_reset_hw;
633
634         /* start TX early */
635         dma_async_issue_pending(ctlr->dma_tx);
636
637         /* mark as dma pending */
638         bs->dma_pending = 1;
639
640         /* set the DMA length */
641         bcm2835_wr(bs, BCM2835_SPI_DLEN, bs->tx_len);
642
643         /* start the HW */
644         bcm2835_wr(bs, BCM2835_SPI_CS,
645                    cs | BCM2835_SPI_CS_TA | BCM2835_SPI_CS_DMAEN);
646
647         /* setup rx-DMA late - to run transfers while
648          * mapping of the rx buffers still takes place
649          * this saves 10us or more.
650          */
651         ret = bcm2835_spi_prepare_sg(ctlr, tfr, false);
652         if (ret) {
653                 /* need to reset on errors */
654                 dmaengine_terminate_sync(ctlr->dma_tx);
655                 bs->dma_pending = false;
656                 goto err_reset_hw;
657         }
658
659         /* start rx dma late */
660         dma_async_issue_pending(ctlr->dma_rx);
661
662         /* wait for wakeup in framework */
663         return 1;
664
665 err_reset_hw:
666         bcm2835_spi_reset_hw(ctlr);
667         bcm2835_spi_undo_prologue(bs);
668         return ret;
669 }
670
671 static bool bcm2835_spi_can_dma(struct spi_controller *ctlr,
672                                 struct spi_device *spi,
673                                 struct spi_transfer *tfr)
674 {
675         /* we start DMA efforts only on bigger transfers */
676         if (tfr->len < BCM2835_SPI_DMA_MIN_LENGTH)
677                 return false;
678
679         /* return OK */
680         return true;
681 }
682
683 static void bcm2835_dma_release(struct spi_controller *ctlr)
684 {
685         if (ctlr->dma_tx) {
686                 dmaengine_terminate_sync(ctlr->dma_tx);
687                 dma_release_channel(ctlr->dma_tx);
688                 ctlr->dma_tx = NULL;
689         }
690         if (ctlr->dma_rx) {
691                 dmaengine_terminate_sync(ctlr->dma_rx);
692                 dma_release_channel(ctlr->dma_rx);
693                 ctlr->dma_rx = NULL;
694         }
695 }
696
697 static void bcm2835_dma_init(struct spi_controller *ctlr, struct device *dev)
698 {
699         struct dma_slave_config slave_config;
700         const __be32 *addr;
701         dma_addr_t dma_reg_base;
702         int ret;
703
704         /* base address in dma-space */
705         addr = of_get_address(ctlr->dev.of_node, 0, NULL, NULL);
706         if (!addr) {
707                 dev_err(dev, "could not get DMA-register address - not using dma mode\n");
708                 goto err;
709         }
710         dma_reg_base = be32_to_cpup(addr);
711
712         /* get tx/rx dma */
713         ctlr->dma_tx = dma_request_slave_channel(dev, "tx");
714         if (!ctlr->dma_tx) {
715                 dev_err(dev, "no tx-dma configuration found - not using dma mode\n");
716                 goto err;
717         }
718         ctlr->dma_rx = dma_request_slave_channel(dev, "rx");
719         if (!ctlr->dma_rx) {
720                 dev_err(dev, "no rx-dma configuration found - not using dma mode\n");
721                 goto err_release;
722         }
723
724         /* configure DMAs */
725         slave_config.dst_addr = (u32)(dma_reg_base + BCM2835_SPI_FIFO);
726         slave_config.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
727
728         ret = dmaengine_slave_config(ctlr->dma_tx, &slave_config);
729         if (ret)
730                 goto err_config;
731
732         slave_config.src_addr = (u32)(dma_reg_base + BCM2835_SPI_FIFO);
733         slave_config.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
734
735         ret = dmaengine_slave_config(ctlr->dma_rx, &slave_config);
736         if (ret)
737                 goto err_config;
738
739         /* all went well, so set can_dma */
740         ctlr->can_dma = bcm2835_spi_can_dma;
741         /* need to do TX AND RX DMA, so we need dummy buffers */
742         ctlr->flags = SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX;
743
744         return;
745
746 err_config:
747         dev_err(dev, "issue configuring dma: %d - not using DMA mode\n",
748                 ret);
749 err_release:
750         bcm2835_dma_release(ctlr);
751 err:
752         return;
753 }
754
755 static int bcm2835_spi_transfer_one_poll(struct spi_controller *ctlr,
756                                          struct spi_device *spi,
757                                          struct spi_transfer *tfr,
758                                          u32 cs)
759 {
760         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
761         unsigned long timeout;
762
763         /* update usage statistics */
764         bs->count_transfer_polling++;
765
766         /* enable HW block without interrupts */
767         bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_TA);
768
769         /* fill in the fifo before timeout calculations
770          * if we are interrupted here, then the data is
771          * getting transferred by the HW while we are interrupted
772          */
773         bcm2835_wr_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE);
774
775         /* set the timeout to at least 2 jiffies */
776         timeout = jiffies + 2 + HZ * polling_limit_us / 1000000;
777
778         /* loop until finished the transfer */
779         while (bs->rx_len) {
780                 /* fill in tx fifo with remaining data */
781                 bcm2835_wr_fifo(bs);
782
783                 /* read from fifo as much as possible */
784                 bcm2835_rd_fifo(bs);
785
786                 /* if there is still data pending to read
787                  * then check the timeout
788                  */
789                 if (bs->rx_len && time_after(jiffies, timeout)) {
790                         dev_dbg_ratelimited(&spi->dev,
791                                             "timeout period reached: jiffies: %lu remaining tx/rx: %d/%d - falling back to interrupt mode\n",
792                                             jiffies - timeout,
793                                             bs->tx_len, bs->rx_len);
794                         /* fall back to interrupt mode */
795
796                         /* update usage statistics */
797                         bs->count_transfer_irq_after_polling++;
798
799                         return bcm2835_spi_transfer_one_irq(ctlr, spi,
800                                                             tfr, cs, false);
801                 }
802         }
803
804         /* Transfer complete - reset SPI HW */
805         bcm2835_spi_reset_hw(ctlr);
806         /* and return without waiting for completion */
807         return 0;
808 }
809
810 static int bcm2835_spi_transfer_one(struct spi_controller *ctlr,
811                                     struct spi_device *spi,
812                                     struct spi_transfer *tfr)
813 {
814         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
815         unsigned long spi_hz, clk_hz, cdiv, spi_used_hz;
816         unsigned long hz_per_byte, byte_limit;
817         u32 cs = bcm2835_rd(bs, BCM2835_SPI_CS);
818
819         /* set clock */
820         spi_hz = tfr->speed_hz;
821         clk_hz = clk_get_rate(bs->clk);
822
823         if (spi_hz >= clk_hz / 2) {
824                 cdiv = 2; /* clk_hz/2 is the fastest we can go */
825         } else if (spi_hz) {
826                 /* CDIV must be a multiple of two */
827                 cdiv = DIV_ROUND_UP(clk_hz, spi_hz);
828                 cdiv += (cdiv % 2);
829
830                 if (cdiv >= 65536)
831                         cdiv = 0; /* 0 is the slowest we can go */
832         } else {
833                 cdiv = 0; /* 0 is the slowest we can go */
834         }
835         spi_used_hz = cdiv ? (clk_hz / cdiv) : (clk_hz / 65536);
836         bcm2835_wr(bs, BCM2835_SPI_CLK, cdiv);
837
838         /* handle all the 3-wire mode */
839         if (spi->mode & SPI_3WIRE && tfr->rx_buf &&
840             tfr->rx_buf != ctlr->dummy_rx)
841                 cs |= BCM2835_SPI_CS_REN;
842         else
843                 cs &= ~BCM2835_SPI_CS_REN;
844
845         /*
846          * The driver always uses software-controlled GPIO Chip Select.
847          * Set the hardware-controlled native Chip Select to an invalid
848          * value to prevent it from interfering.
849          */
850         cs |= BCM2835_SPI_CS_CS_10 | BCM2835_SPI_CS_CS_01;
851
852         /* set transmit buffers and length */
853         bs->tx_buf = tfr->tx_buf;
854         bs->rx_buf = tfr->rx_buf;
855         bs->tx_len = tfr->len;
856         bs->rx_len = tfr->len;
857
858         /* Calculate the estimated time in us the transfer runs.  Note that
859          * there is 1 idle clocks cycles after each byte getting transferred
860          * so we have 9 cycles/byte.  This is used to find the number of Hz
861          * per byte per polling limit.  E.g., we can transfer 1 byte in 30 us
862          * per 300,000 Hz of bus clock.
863          */
864         hz_per_byte = polling_limit_us ? (9 * 1000000) / polling_limit_us : 0;
865         byte_limit = hz_per_byte ? spi_used_hz / hz_per_byte : 1;
866
867         /* run in polling mode for short transfers */
868         if (tfr->len < byte_limit)
869                 return bcm2835_spi_transfer_one_poll(ctlr, spi, tfr, cs);
870
871         /* run in dma mode if conditions are right
872          * Note that unlike poll or interrupt mode DMA mode does not have
873          * this 1 idle clock cycle pattern but runs the spi clock without gaps
874          */
875         if (ctlr->can_dma && bcm2835_spi_can_dma(ctlr, spi, tfr))
876                 return bcm2835_spi_transfer_one_dma(ctlr, spi, tfr, cs);
877
878         /* run in interrupt-mode */
879         return bcm2835_spi_transfer_one_irq(ctlr, spi, tfr, cs, true);
880 }
881
882 static int bcm2835_spi_prepare_message(struct spi_controller *ctlr,
883                                        struct spi_message *msg)
884 {
885         struct spi_device *spi = msg->spi;
886         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
887         u32 cs = bcm2835_rd(bs, BCM2835_SPI_CS);
888         int ret;
889
890         if (ctlr->can_dma) {
891                 /*
892                  * DMA transfers are limited to 16 bit (0 to 65535 bytes) by
893                  * the SPI HW due to DLEN. Split up transfers (32-bit FIFO
894                  * aligned) if the limit is exceeded.
895                  */
896                 ret = spi_split_transfers_maxsize(ctlr, msg, 65532,
897                                                   GFP_KERNEL | GFP_DMA);
898                 if (ret)
899                         return ret;
900         }
901
902         cs &= ~(BCM2835_SPI_CS_CPOL | BCM2835_SPI_CS_CPHA);
903
904         if (spi->mode & SPI_CPOL)
905                 cs |= BCM2835_SPI_CS_CPOL;
906         if (spi->mode & SPI_CPHA)
907                 cs |= BCM2835_SPI_CS_CPHA;
908
909         bcm2835_wr(bs, BCM2835_SPI_CS, cs);
910
911         return 0;
912 }
913
914 static void bcm2835_spi_handle_err(struct spi_controller *ctlr,
915                                    struct spi_message *msg)
916 {
917         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
918
919         /* if an error occurred and we have an active dma, then terminate */
920         if (cmpxchg(&bs->dma_pending, true, false)) {
921                 dmaengine_terminate_sync(ctlr->dma_tx);
922                 dmaengine_terminate_sync(ctlr->dma_rx);
923                 bcm2835_spi_undo_prologue(bs);
924         }
925         /* and reset */
926         bcm2835_spi_reset_hw(ctlr);
927 }
928
929 static int chip_match_name(struct gpio_chip *chip, void *data)
930 {
931         return !strcmp(chip->label, data);
932 }
933
934 static int bcm2835_spi_setup(struct spi_device *spi)
935 {
936         struct gpio_chip *chip;
937         enum gpio_lookup_flags lflags;
938
939         /*
940          * sanity checking the native-chipselects
941          */
942         if (spi->mode & SPI_NO_CS)
943                 return 0;
944         /*
945          * The SPI core has successfully requested the CS GPIO line from the
946          * device tree, so we are done.
947          */
948         if (spi->cs_gpiod)
949                 return 0;
950         if (spi->chip_select > 1) {
951                 /* error in the case of native CS requested with CS > 1
952                  * officially there is a CS2, but it is not documented
953                  * which GPIO is connected with that...
954                  */
955                 dev_err(&spi->dev,
956                         "setup: only two native chip-selects are supported\n");
957                 return -EINVAL;
958         }
959
960         /*
961          * Translate native CS to GPIO
962          *
963          * FIXME: poking around in the gpiolib internals like this is
964          * not very good practice. Find a way to locate the real problem
965          * and fix it. Why is the GPIO descriptor in spi->cs_gpiod
966          * sometimes not assigned correctly? Erroneous device trees?
967          */
968
969         /* get the gpio chip for the base */
970         chip = gpiochip_find("pinctrl-bcm2835", chip_match_name);
971         if (!chip)
972                 return 0;
973
974         /*
975          * Retrieve the corresponding GPIO line used for CS.
976          * The inversion semantics will be handled by the GPIO core
977          * code, so we pass GPIOS_OUT_LOW for "unasserted" and
978          * the correct flag for inversion semantics. The SPI_CS_HIGH
979          * on spi->mode cannot be checked for polarity in this case
980          * as the flag use_gpio_descriptors enforces SPI_CS_HIGH.
981          */
982         if (of_property_read_bool(spi->dev.of_node, "spi-cs-high"))
983                 lflags = GPIO_ACTIVE_HIGH;
984         else
985                 lflags = GPIO_ACTIVE_LOW;
986         spi->cs_gpiod = gpiochip_request_own_desc(chip, 8 - spi->chip_select,
987                                                   DRV_NAME,
988                                                   lflags,
989                                                   GPIOD_OUT_LOW);
990         if (IS_ERR(spi->cs_gpiod))
991                 return PTR_ERR(spi->cs_gpiod);
992
993         /* and set up the "mode" and level */
994         dev_info(&spi->dev, "setting up native-CS%i to use GPIO\n",
995                  spi->chip_select);
996
997         return 0;
998 }
999
1000 static int bcm2835_spi_probe(struct platform_device *pdev)
1001 {
1002         struct spi_controller *ctlr;
1003         struct bcm2835_spi *bs;
1004         struct resource *res;
1005         int err;
1006
1007         ctlr = spi_alloc_master(&pdev->dev, sizeof(*bs));
1008         if (!ctlr)
1009                 return -ENOMEM;
1010
1011         platform_set_drvdata(pdev, ctlr);
1012
1013         ctlr->use_gpio_descriptors = true;
1014         ctlr->mode_bits = BCM2835_SPI_MODE_BITS;
1015         ctlr->bits_per_word_mask = SPI_BPW_MASK(8);
1016         ctlr->num_chipselect = 3;
1017         ctlr->setup = bcm2835_spi_setup;
1018         ctlr->transfer_one = bcm2835_spi_transfer_one;
1019         ctlr->handle_err = bcm2835_spi_handle_err;
1020         ctlr->prepare_message = bcm2835_spi_prepare_message;
1021         ctlr->dev.of_node = pdev->dev.of_node;
1022
1023         bs = spi_controller_get_devdata(ctlr);
1024
1025         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1026         bs->regs = devm_ioremap_resource(&pdev->dev, res);
1027         if (IS_ERR(bs->regs)) {
1028                 err = PTR_ERR(bs->regs);
1029                 goto out_controller_put;
1030         }
1031
1032         bs->clk = devm_clk_get(&pdev->dev, NULL);
1033         if (IS_ERR(bs->clk)) {
1034                 err = PTR_ERR(bs->clk);
1035                 dev_err(&pdev->dev, "could not get clk: %d\n", err);
1036                 goto out_controller_put;
1037         }
1038
1039         bs->irq = platform_get_irq(pdev, 0);
1040         if (bs->irq <= 0) {
1041                 err = bs->irq ? bs->irq : -ENODEV;
1042                 goto out_controller_put;
1043         }
1044
1045         clk_prepare_enable(bs->clk);
1046
1047         bcm2835_dma_init(ctlr, &pdev->dev);
1048
1049         /* initialise the hardware with the default polarities */
1050         bcm2835_wr(bs, BCM2835_SPI_CS,
1051                    BCM2835_SPI_CS_CLEAR_RX | BCM2835_SPI_CS_CLEAR_TX);
1052
1053         err = devm_request_irq(&pdev->dev, bs->irq, bcm2835_spi_interrupt, 0,
1054                                dev_name(&pdev->dev), ctlr);
1055         if (err) {
1056                 dev_err(&pdev->dev, "could not request IRQ: %d\n", err);
1057                 goto out_clk_disable;
1058         }
1059
1060         err = devm_spi_register_controller(&pdev->dev, ctlr);
1061         if (err) {
1062                 dev_err(&pdev->dev, "could not register SPI controller: %d\n",
1063                         err);
1064                 goto out_clk_disable;
1065         }
1066
1067         bcm2835_debugfs_create(bs, dev_name(&pdev->dev));
1068
1069         return 0;
1070
1071 out_clk_disable:
1072         clk_disable_unprepare(bs->clk);
1073 out_controller_put:
1074         spi_controller_put(ctlr);
1075         return err;
1076 }
1077
1078 static int bcm2835_spi_remove(struct platform_device *pdev)
1079 {
1080         struct spi_controller *ctlr = platform_get_drvdata(pdev);
1081         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
1082
1083         bcm2835_debugfs_remove(bs);
1084
1085         /* Clear FIFOs, and disable the HW block */
1086         bcm2835_wr(bs, BCM2835_SPI_CS,
1087                    BCM2835_SPI_CS_CLEAR_RX | BCM2835_SPI_CS_CLEAR_TX);
1088
1089         clk_disable_unprepare(bs->clk);
1090
1091         bcm2835_dma_release(ctlr);
1092
1093         return 0;
1094 }
1095
1096 static const struct of_device_id bcm2835_spi_match[] = {
1097         { .compatible = "brcm,bcm2835-spi", },
1098         {}
1099 };
1100 MODULE_DEVICE_TABLE(of, bcm2835_spi_match);
1101
1102 static struct platform_driver bcm2835_spi_driver = {
1103         .driver         = {
1104                 .name           = DRV_NAME,
1105                 .of_match_table = bcm2835_spi_match,
1106         },
1107         .probe          = bcm2835_spi_probe,
1108         .remove         = bcm2835_spi_remove,
1109 };
1110 module_platform_driver(bcm2835_spi_driver);
1111
1112 MODULE_DESCRIPTION("SPI controller driver for Broadcom BCM2835");
1113 MODULE_AUTHOR("Chris Boot <bootc@bootc.net>");
1114 MODULE_LICENSE("GPL");