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