drivers: thermal: step_wise: add support for hysteresis
[platform/kernel/linux-rpi.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/platform_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 static 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  * @clk_hz: core clock cached speed
87  * @irq: interrupt, signals TX FIFO empty or RX FIFO ¾ full
88  * @tfr: SPI transfer currently processed
89  * @ctlr: SPI controller reverse lookup
90  * @tx_buf: pointer whence next transmitted byte is read
91  * @rx_buf: pointer where next received byte is written
92  * @tx_len: remaining bytes to transmit
93  * @rx_len: remaining bytes to receive
94  * @tx_prologue: bytes transmitted without DMA if first TX sglist entry's
95  *      length is not a multiple of 4 (to overcome hardware limitation)
96  * @rx_prologue: bytes received without DMA if first RX sglist entry's
97  *      length is not a multiple of 4 (to overcome hardware limitation)
98  * @tx_spillover: whether @tx_prologue spills over to second TX sglist entry
99  * @debugfs_dir: the debugfs directory - neede to remove debugfs when
100  *      unloading the module
101  * @count_transfer_polling: count of how often polling mode is used
102  * @count_transfer_irq: count of how often interrupt mode is used
103  * @count_transfer_irq_after_polling: count of how often we fall back to
104  *      interrupt mode after starting in polling mode.
105  *      These are counted as well in @count_transfer_polling and
106  *      @count_transfer_irq
107  * @count_transfer_dma: count how often dma mode is used
108  * @target: SPI target currently selected
109  *      (used by bcm2835_spi_dma_tx_done() to write @clear_rx_cs)
110  * @tx_dma_active: whether a TX DMA descriptor is in progress
111  * @rx_dma_active: whether a RX DMA descriptor is in progress
112  *      (used by bcm2835_spi_dma_tx_done() to handle a race)
113  * @fill_tx_desc: preallocated TX DMA descriptor used for RX-only transfers
114  *      (cyclically copies from zero page to TX FIFO)
115  * @fill_tx_addr: bus address of zero page
116  */
117 struct bcm2835_spi {
118         void __iomem *regs;
119         phys_addr_t phys_addr;
120         struct clk *clk;
121         unsigned long clk_hz;
122         int irq;
123         struct spi_transfer *tfr;
124         struct spi_controller *ctlr;
125         const u8 *tx_buf;
126         u8 *rx_buf;
127         int tx_len;
128         int rx_len;
129         int tx_prologue;
130         int rx_prologue;
131         unsigned int tx_spillover;
132
133         struct dentry *debugfs_dir;
134         u64 count_transfer_polling;
135         u64 count_transfer_irq;
136         u64 count_transfer_irq_after_polling;
137         u64 count_transfer_dma;
138
139         struct bcm2835_spidev *target;
140         unsigned int tx_dma_active;
141         unsigned int rx_dma_active;
142         struct dma_async_tx_descriptor *fill_tx_desc;
143         dma_addr_t fill_tx_addr;
144 };
145
146 /**
147  * struct bcm2835_spidev - BCM2835 SPI target
148  * @prepare_cs: precalculated CS register value for ->prepare_message()
149  *      (uses target-specific clock polarity and phase settings)
150  * @clear_rx_desc: preallocated RX DMA descriptor used for TX-only transfers
151  *      (cyclically clears RX FIFO by writing @clear_rx_cs to CS register)
152  * @clear_rx_addr: bus address of @clear_rx_cs
153  * @clear_rx_cs: precalculated CS register value to clear RX FIFO
154  *      (uses target-specific clock polarity and phase settings)
155  */
156 struct bcm2835_spidev {
157         u32 prepare_cs;
158         struct dma_async_tx_descriptor *clear_rx_desc;
159         dma_addr_t clear_rx_addr;
160         u32 clear_rx_cs ____cacheline_aligned;
161 };
162
163 #if defined(CONFIG_DEBUG_FS)
164 static void bcm2835_debugfs_create(struct bcm2835_spi *bs,
165                                    const char *dname)
166 {
167         char name[64];
168         struct dentry *dir;
169
170         /* get full name */
171         snprintf(name, sizeof(name), "spi-bcm2835-%s", dname);
172
173         /* the base directory */
174         dir = debugfs_create_dir(name, NULL);
175         bs->debugfs_dir = dir;
176
177         /* the counters */
178         debugfs_create_u64("count_transfer_polling", 0444, dir,
179                            &bs->count_transfer_polling);
180         debugfs_create_u64("count_transfer_irq", 0444, dir,
181                            &bs->count_transfer_irq);
182         debugfs_create_u64("count_transfer_irq_after_polling", 0444, dir,
183                            &bs->count_transfer_irq_after_polling);
184         debugfs_create_u64("count_transfer_dma", 0444, dir,
185                            &bs->count_transfer_dma);
186 }
187
188 static void bcm2835_debugfs_remove(struct bcm2835_spi *bs)
189 {
190         debugfs_remove_recursive(bs->debugfs_dir);
191         bs->debugfs_dir = NULL;
192 }
193 #else
194 static void bcm2835_debugfs_create(struct bcm2835_spi *bs,
195                                    const char *dname)
196 {
197 }
198
199 static void bcm2835_debugfs_remove(struct bcm2835_spi *bs)
200 {
201 }
202 #endif /* CONFIG_DEBUG_FS */
203
204 static inline u32 bcm2835_rd(struct bcm2835_spi *bs, unsigned int reg)
205 {
206         return readl(bs->regs + reg);
207 }
208
209 static inline void bcm2835_wr(struct bcm2835_spi *bs, unsigned int reg, u32 val)
210 {
211         writel(val, bs->regs + reg);
212 }
213
214 static inline void bcm2835_rd_fifo(struct bcm2835_spi *bs)
215 {
216         u8 byte;
217
218         while ((bs->rx_len) &&
219                (bcm2835_rd(bs, BCM2835_SPI_CS) & BCM2835_SPI_CS_RXD)) {
220                 byte = bcm2835_rd(bs, BCM2835_SPI_FIFO);
221                 if (bs->rx_buf)
222                         *bs->rx_buf++ = byte;
223                 bs->rx_len--;
224         }
225 }
226
227 static inline void bcm2835_wr_fifo(struct bcm2835_spi *bs)
228 {
229         u8 byte;
230
231         while ((bs->tx_len) &&
232                (bcm2835_rd(bs, BCM2835_SPI_CS) & BCM2835_SPI_CS_TXD)) {
233                 byte = bs->tx_buf ? *bs->tx_buf++ : 0;
234                 bcm2835_wr(bs, BCM2835_SPI_FIFO, byte);
235                 bs->tx_len--;
236         }
237 }
238
239 /**
240  * bcm2835_rd_fifo_count() - blindly read exactly @count bytes from RX FIFO
241  * @bs: BCM2835 SPI controller
242  * @count: bytes to read from RX FIFO
243  *
244  * The caller must ensure that @bs->rx_len is greater than or equal to @count,
245  * that the RX FIFO contains at least @count bytes and that the DMA Enable flag
246  * in the CS register is set (such that a read from the FIFO register receives
247  * 32-bit instead of just 8-bit).  Moreover @bs->rx_buf must not be %NULL.
248  */
249 static inline void bcm2835_rd_fifo_count(struct bcm2835_spi *bs, int count)
250 {
251         u32 val;
252         int len;
253
254         bs->rx_len -= count;
255
256         do {
257                 val = bcm2835_rd(bs, BCM2835_SPI_FIFO);
258                 len = min(count, 4);
259                 memcpy(bs->rx_buf, &val, len);
260                 bs->rx_buf += len;
261                 count -= 4;
262         } while (count > 0);
263 }
264
265 /**
266  * bcm2835_wr_fifo_count() - blindly write exactly @count bytes to TX FIFO
267  * @bs: BCM2835 SPI controller
268  * @count: bytes to write to TX FIFO
269  *
270  * The caller must ensure that @bs->tx_len is greater than or equal to @count,
271  * that the TX FIFO can accommodate @count bytes and that the DMA Enable flag
272  * in the CS register is set (such that a write to the FIFO register transmits
273  * 32-bit instead of just 8-bit).
274  */
275 static inline void bcm2835_wr_fifo_count(struct bcm2835_spi *bs, int count)
276 {
277         u32 val;
278         int len;
279
280         bs->tx_len -= count;
281
282         do {
283                 if (bs->tx_buf) {
284                         len = min(count, 4);
285                         memcpy(&val, bs->tx_buf, len);
286                         bs->tx_buf += len;
287                 } else {
288                         val = 0;
289                 }
290                 bcm2835_wr(bs, BCM2835_SPI_FIFO, val);
291                 count -= 4;
292         } while (count > 0);
293 }
294
295 /**
296  * bcm2835_wait_tx_fifo_empty() - busy-wait for TX FIFO to empty
297  * @bs: BCM2835 SPI controller
298  *
299  * The caller must ensure that the RX FIFO can accommodate as many bytes
300  * as have been written to the TX FIFO:  Transmission is halted once the
301  * RX FIFO is full, causing this function to spin forever.
302  */
303 static inline void bcm2835_wait_tx_fifo_empty(struct bcm2835_spi *bs)
304 {
305         while (!(bcm2835_rd(bs, BCM2835_SPI_CS) & BCM2835_SPI_CS_DONE))
306                 cpu_relax();
307 }
308
309 /**
310  * bcm2835_rd_fifo_blind() - blindly read up to @count bytes from RX FIFO
311  * @bs: BCM2835 SPI controller
312  * @count: bytes available for reading in RX FIFO
313  */
314 static inline void bcm2835_rd_fifo_blind(struct bcm2835_spi *bs, int count)
315 {
316         u8 val;
317
318         count = min(count, bs->rx_len);
319         bs->rx_len -= count;
320
321         do {
322                 val = bcm2835_rd(bs, BCM2835_SPI_FIFO);
323                 if (bs->rx_buf)
324                         *bs->rx_buf++ = val;
325         } while (--count);
326 }
327
328 /**
329  * bcm2835_wr_fifo_blind() - blindly write up to @count bytes to TX FIFO
330  * @bs: BCM2835 SPI controller
331  * @count: bytes available for writing in TX FIFO
332  */
333 static inline void bcm2835_wr_fifo_blind(struct bcm2835_spi *bs, int count)
334 {
335         u8 val;
336
337         count = min(count, bs->tx_len);
338         bs->tx_len -= count;
339
340         do {
341                 val = bs->tx_buf ? *bs->tx_buf++ : 0;
342                 bcm2835_wr(bs, BCM2835_SPI_FIFO, val);
343         } while (--count);
344 }
345
346 static void bcm2835_spi_reset_hw(struct bcm2835_spi *bs)
347 {
348         u32 cs = bcm2835_rd(bs, BCM2835_SPI_CS);
349
350         /* Disable SPI interrupts and transfer */
351         cs &= ~(BCM2835_SPI_CS_INTR |
352                 BCM2835_SPI_CS_INTD |
353                 BCM2835_SPI_CS_DMAEN |
354                 BCM2835_SPI_CS_TA);
355         /*
356          * Transmission sometimes breaks unless the DONE bit is written at the
357          * end of every transfer.  The spec says it's a RO bit.  Either the
358          * spec is wrong and the bit is actually of type RW1C, or it's a
359          * hardware erratum.
360          */
361         cs |= BCM2835_SPI_CS_DONE;
362         /* and reset RX/TX FIFOS */
363         cs |= BCM2835_SPI_CS_CLEAR_RX | BCM2835_SPI_CS_CLEAR_TX;
364
365         /* and reset the SPI_HW */
366         bcm2835_wr(bs, BCM2835_SPI_CS, cs);
367         /* as well as DLEN */
368         bcm2835_wr(bs, BCM2835_SPI_DLEN, 0);
369 }
370
371 static irqreturn_t bcm2835_spi_interrupt(int irq, void *dev_id)
372 {
373         struct bcm2835_spi *bs = dev_id;
374         u32 cs = bcm2835_rd(bs, BCM2835_SPI_CS);
375
376         /* Bail out early if interrupts are not enabled */
377         if (!(cs & BCM2835_SPI_CS_INTR))
378                 return IRQ_NONE;
379
380         /*
381          * An interrupt is signaled either if DONE is set (TX FIFO empty)
382          * or if RXR is set (RX FIFO >= ¾ full).
383          */
384         if (cs & BCM2835_SPI_CS_RXF)
385                 bcm2835_rd_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE);
386         else if (cs & BCM2835_SPI_CS_RXR)
387                 bcm2835_rd_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE_3_4);
388
389         if (bs->tx_len && cs & BCM2835_SPI_CS_DONE)
390                 bcm2835_wr_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE);
391
392         /* Read as many bytes as possible from FIFO */
393         bcm2835_rd_fifo(bs);
394         /* Write as many bytes as possible to FIFO */
395         bcm2835_wr_fifo(bs);
396
397         if (!bs->rx_len) {
398                 /* Transfer complete - reset SPI HW */
399                 bcm2835_spi_reset_hw(bs);
400                 /* wake up the framework */
401                 spi_finalize_current_transfer(bs->ctlr);
402         }
403
404         return IRQ_HANDLED;
405 }
406
407 static int bcm2835_spi_transfer_one_irq(struct spi_controller *ctlr,
408                                         struct spi_device *spi,
409                                         struct spi_transfer *tfr,
410                                         u32 cs, bool fifo_empty)
411 {
412         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
413
414         /* update usage statistics */
415         bs->count_transfer_irq++;
416
417         /*
418          * Enable HW block, but with interrupts still disabled.
419          * Otherwise the empty TX FIFO would immediately trigger an interrupt.
420          */
421         bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_TA);
422
423         /* fill TX FIFO as much as possible */
424         if (fifo_empty)
425                 bcm2835_wr_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE);
426         bcm2835_wr_fifo(bs);
427
428         /* enable interrupts */
429         cs |= BCM2835_SPI_CS_INTR | BCM2835_SPI_CS_INTD | BCM2835_SPI_CS_TA;
430         bcm2835_wr(bs, BCM2835_SPI_CS, cs);
431
432         /* signal that we need to wait for completion */
433         return 1;
434 }
435
436 /**
437  * bcm2835_spi_transfer_prologue() - transfer first few bytes without DMA
438  * @ctlr: SPI host controller
439  * @tfr: SPI transfer
440  * @bs: BCM2835 SPI controller
441  * @cs: CS register
442  *
443  * A limitation in DMA mode is that the FIFO must be accessed in 4 byte chunks.
444  * Only the final write access is permitted to transmit less than 4 bytes, the
445  * SPI controller deduces its intended size from the DLEN register.
446  *
447  * If a TX or RX sglist contains multiple entries, one per page, and the first
448  * entry starts in the middle of a page, that first entry's length may not be
449  * a multiple of 4.  Subsequent entries are fine because they span an entire
450  * page, hence do have a length that's a multiple of 4.
451  *
452  * This cannot happen with kmalloc'ed buffers (which is what most clients use)
453  * because they are contiguous in physical memory and therefore not split on
454  * page boundaries by spi_map_buf().  But it *can* happen with vmalloc'ed
455  * buffers.
456  *
457  * The DMA engine is incapable of combining sglist entries into a continuous
458  * stream of 4 byte chunks, it treats every entry separately:  A TX entry is
459  * rounded up a to a multiple of 4 bytes by transmitting surplus bytes, an RX
460  * entry is rounded up by throwing away received bytes.
461  *
462  * Overcome this limitation by transferring the first few bytes without DMA:
463  * E.g. if the first TX sglist entry's length is 23 and the first RX's is 42,
464  * write 3 bytes to the TX FIFO but read only 2 bytes from the RX FIFO.
465  * The residue of 1 byte in the RX FIFO is picked up by DMA.  Together with
466  * the rest of the first RX sglist entry it makes up a multiple of 4 bytes.
467  *
468  * Should the RX prologue be larger, say, 3 vis-à-vis a TX prologue of 1,
469  * write 1 + 4 = 5 bytes to the TX FIFO and read 3 bytes from the RX FIFO.
470  * Caution, the additional 4 bytes spill over to the second TX sglist entry
471  * if the length of the first is *exactly* 1.
472  *
473  * At most 6 bytes are written and at most 3 bytes read.  Do we know the
474  * transfer has this many bytes?  Yes, see BCM2835_SPI_DMA_MIN_LENGTH.
475  *
476  * The FIFO is normally accessed with 8-bit width by the CPU and 32-bit width
477  * by the DMA engine.  Toggling the DMA Enable flag in the CS register switches
478  * the width but also garbles the FIFO's contents.  The prologue must therefore
479  * be transmitted in 32-bit width to ensure that the following DMA transfer can
480  * pick up the residue in the RX FIFO in ungarbled form.
481  */
482 static void bcm2835_spi_transfer_prologue(struct spi_controller *ctlr,
483                                           struct spi_transfer *tfr,
484                                           struct bcm2835_spi *bs,
485                                           u32 cs)
486 {
487         int tx_remaining;
488
489         bs->tfr          = tfr;
490         bs->tx_prologue  = 0;
491         bs->rx_prologue  = 0;
492         bs->tx_spillover = false;
493
494         if (bs->tx_buf && !sg_is_last(&tfr->tx_sg.sgl[0]))
495                 bs->tx_prologue = sg_dma_len(&tfr->tx_sg.sgl[0]) & 3;
496
497         if (bs->rx_buf && !sg_is_last(&tfr->rx_sg.sgl[0])) {
498                 bs->rx_prologue = sg_dma_len(&tfr->rx_sg.sgl[0]) & 3;
499
500                 if (bs->rx_prologue > bs->tx_prologue) {
501                         if (!bs->tx_buf || sg_is_last(&tfr->tx_sg.sgl[0])) {
502                                 bs->tx_prologue  = bs->rx_prologue;
503                         } else {
504                                 bs->tx_prologue += 4;
505                                 bs->tx_spillover =
506                                         !(sg_dma_len(&tfr->tx_sg.sgl[0]) & ~3);
507                         }
508                 }
509         }
510
511         /* rx_prologue > 0 implies tx_prologue > 0, so check only the latter */
512         if (!bs->tx_prologue)
513                 return;
514
515         /* Write and read RX prologue.  Adjust first entry in RX sglist. */
516         if (bs->rx_prologue) {
517                 bcm2835_wr(bs, BCM2835_SPI_DLEN, bs->rx_prologue);
518                 bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_TA
519                                                   | BCM2835_SPI_CS_DMAEN);
520                 bcm2835_wr_fifo_count(bs, bs->rx_prologue);
521                 bcm2835_wait_tx_fifo_empty(bs);
522                 bcm2835_rd_fifo_count(bs, bs->rx_prologue);
523                 bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_CLEAR_RX
524                                                   | BCM2835_SPI_CS_CLEAR_TX
525                                                   | BCM2835_SPI_CS_DONE);
526
527                 dma_sync_single_for_device(ctlr->dma_rx->device->dev,
528                                            sg_dma_address(&tfr->rx_sg.sgl[0]),
529                                            bs->rx_prologue, DMA_FROM_DEVICE);
530
531                 sg_dma_address(&tfr->rx_sg.sgl[0]) += bs->rx_prologue;
532                 sg_dma_len(&tfr->rx_sg.sgl[0])     -= bs->rx_prologue;
533         }
534
535         if (!bs->tx_buf)
536                 return;
537
538         /*
539          * Write remaining TX prologue.  Adjust first entry in TX sglist.
540          * Also adjust second entry if prologue spills over to it.
541          */
542         tx_remaining = bs->tx_prologue - bs->rx_prologue;
543         if (tx_remaining) {
544                 bcm2835_wr(bs, BCM2835_SPI_DLEN, tx_remaining);
545                 bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_TA
546                                                   | BCM2835_SPI_CS_DMAEN);
547                 bcm2835_wr_fifo_count(bs, tx_remaining);
548                 bcm2835_wait_tx_fifo_empty(bs);
549                 bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_CLEAR_TX
550                                                   | BCM2835_SPI_CS_DONE);
551         }
552
553         if (likely(!bs->tx_spillover)) {
554                 sg_dma_address(&tfr->tx_sg.sgl[0]) += bs->tx_prologue;
555                 sg_dma_len(&tfr->tx_sg.sgl[0])     -= bs->tx_prologue;
556         } else {
557                 sg_dma_len(&tfr->tx_sg.sgl[0])      = 0;
558                 sg_dma_address(&tfr->tx_sg.sgl[1]) += 4;
559                 sg_dma_len(&tfr->tx_sg.sgl[1])     -= 4;
560         }
561 }
562
563 /**
564  * bcm2835_spi_undo_prologue() - reconstruct original sglist state
565  * @bs: BCM2835 SPI controller
566  *
567  * Undo changes which were made to an SPI transfer's sglist when transmitting
568  * the prologue.  This is necessary to ensure the same memory ranges are
569  * unmapped that were originally mapped.
570  */
571 static void bcm2835_spi_undo_prologue(struct bcm2835_spi *bs)
572 {
573         struct spi_transfer *tfr = bs->tfr;
574
575         if (!bs->tx_prologue)
576                 return;
577
578         if (bs->rx_prologue) {
579                 sg_dma_address(&tfr->rx_sg.sgl[0]) -= bs->rx_prologue;
580                 sg_dma_len(&tfr->rx_sg.sgl[0])     += bs->rx_prologue;
581         }
582
583         if (!bs->tx_buf)
584                 goto out;
585
586         if (likely(!bs->tx_spillover)) {
587                 sg_dma_address(&tfr->tx_sg.sgl[0]) -= bs->tx_prologue;
588                 sg_dma_len(&tfr->tx_sg.sgl[0])     += bs->tx_prologue;
589         } else {
590                 sg_dma_len(&tfr->tx_sg.sgl[0])      = bs->tx_prologue - 4;
591                 sg_dma_address(&tfr->tx_sg.sgl[1]) -= 4;
592                 sg_dma_len(&tfr->tx_sg.sgl[1])     += 4;
593         }
594 out:
595         bs->tx_prologue = 0;
596 }
597
598 /**
599  * bcm2835_spi_dma_rx_done() - callback for DMA RX channel
600  * @data: SPI host controller
601  *
602  * Used for bidirectional and RX-only transfers.
603  */
604 static void bcm2835_spi_dma_rx_done(void *data)
605 {
606         struct spi_controller *ctlr = data;
607         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
608
609         /* terminate tx-dma as we do not have an irq for it
610          * because when the rx dma will terminate and this callback
611          * is called the tx-dma must have finished - can't get to this
612          * situation otherwise...
613          */
614         dmaengine_terminate_async(ctlr->dma_tx);
615         bs->tx_dma_active = false;
616         bs->rx_dma_active = false;
617         bcm2835_spi_undo_prologue(bs);
618
619         /* reset fifo and HW */
620         bcm2835_spi_reset_hw(bs);
621
622         /* and mark as completed */;
623         spi_finalize_current_transfer(ctlr);
624 }
625
626 /**
627  * bcm2835_spi_dma_tx_done() - callback for DMA TX channel
628  * @data: SPI host controller
629  *
630  * Used for TX-only transfers.
631  */
632 static void bcm2835_spi_dma_tx_done(void *data)
633 {
634         struct spi_controller *ctlr = data;
635         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
636
637         /* busy-wait for TX FIFO to empty */
638         while (!(bcm2835_rd(bs, BCM2835_SPI_CS) & BCM2835_SPI_CS_DONE))
639                 bcm2835_wr(bs, BCM2835_SPI_CS, bs->target->clear_rx_cs);
640
641         bs->tx_dma_active = false;
642         smp_wmb();
643
644         /*
645          * In case of a very short transfer, RX DMA may not have been
646          * issued yet.  The onus is then on bcm2835_spi_transfer_one_dma()
647          * to terminate it immediately after issuing.
648          */
649         if (cmpxchg(&bs->rx_dma_active, true, false))
650                 dmaengine_terminate_async(ctlr->dma_rx);
651
652         bcm2835_spi_undo_prologue(bs);
653         bcm2835_spi_reset_hw(bs);
654         spi_finalize_current_transfer(ctlr);
655 }
656
657 /**
658  * bcm2835_spi_prepare_sg() - prepare and submit DMA descriptor for sglist
659  * @ctlr: SPI host controller
660  * @tfr: SPI transfer
661  * @bs: BCM2835 SPI controller
662  * @target: BCM2835 SPI target
663  * @is_tx: whether to submit DMA descriptor for TX or RX sglist
664  *
665  * Prepare and submit a DMA descriptor for the TX or RX sglist of @tfr.
666  * Return 0 on success or a negative error number.
667  */
668 static int bcm2835_spi_prepare_sg(struct spi_controller *ctlr,
669                                   struct spi_transfer *tfr,
670                                   struct bcm2835_spi *bs,
671                                   struct bcm2835_spidev *target,
672                                   bool is_tx)
673 {
674         struct dma_chan *chan;
675         struct scatterlist *sgl;
676         unsigned int nents;
677         enum dma_transfer_direction dir;
678         unsigned long flags;
679
680         struct dma_async_tx_descriptor *desc;
681         dma_cookie_t cookie;
682
683         if (is_tx) {
684                 dir   = DMA_MEM_TO_DEV;
685                 chan  = ctlr->dma_tx;
686                 nents = tfr->tx_sg.nents;
687                 sgl   = tfr->tx_sg.sgl;
688                 flags = tfr->rx_buf ? 0 : DMA_PREP_INTERRUPT;
689         } else {
690                 dir   = DMA_DEV_TO_MEM;
691                 chan  = ctlr->dma_rx;
692                 nents = tfr->rx_sg.nents;
693                 sgl   = tfr->rx_sg.sgl;
694                 flags = DMA_PREP_INTERRUPT;
695         }
696         /* prepare the channel */
697         desc = dmaengine_prep_slave_sg(chan, sgl, nents, dir, flags);
698         if (!desc)
699                 return -EINVAL;
700
701         /*
702          * Completion is signaled by the RX channel for bidirectional and
703          * RX-only transfers; else by the TX channel for TX-only transfers.
704          */
705         if (!is_tx) {
706                 desc->callback = bcm2835_spi_dma_rx_done;
707                 desc->callback_param = ctlr;
708         } else if (!tfr->rx_buf) {
709                 desc->callback = bcm2835_spi_dma_tx_done;
710                 desc->callback_param = ctlr;
711                 bs->target = target;
712         }
713
714         /* submit it to DMA-engine */
715         cookie = dmaengine_submit(desc);
716
717         return dma_submit_error(cookie);
718 }
719
720 /**
721  * bcm2835_spi_transfer_one_dma() - perform SPI transfer using DMA engine
722  * @ctlr: SPI host controller
723  * @tfr: SPI transfer
724  * @target: BCM2835 SPI target
725  * @cs: CS register
726  *
727  * For *bidirectional* transfers (both tx_buf and rx_buf are non-%NULL), set up
728  * the TX and RX DMA channel to copy between memory and FIFO register.
729  *
730  * For *TX-only* transfers (rx_buf is %NULL), copying the RX FIFO's contents to
731  * memory is pointless.  However not reading the RX FIFO isn't an option either
732  * because transmission is halted once it's full.  As a workaround, cyclically
733  * clear the RX FIFO by setting the CLEAR_RX bit in the CS register.
734  *
735  * The CS register value is precalculated in bcm2835_spi_setup().  Normally
736  * this is called only once, on target registration.  A DMA descriptor to write
737  * this value is preallocated in bcm2835_dma_init().  All that's left to do
738  * when performing a TX-only transfer is to submit this descriptor to the RX
739  * DMA channel.  Latency is thereby minimized.  The descriptor does not
740  * generate any interrupts while running.  It must be terminated once the
741  * TX DMA channel is done.
742  *
743  * Clearing the RX FIFO is paced by the DREQ signal.  The signal is asserted
744  * when the RX FIFO becomes half full, i.e. 32 bytes.  (Tuneable with the DC
745  * register.)  Reading 32 bytes from the RX FIFO would normally require 8 bus
746  * accesses, whereas clearing it requires only 1 bus access.  So an 8-fold
747  * reduction in bus traffic and thus energy consumption is achieved.
748  *
749  * For *RX-only* transfers (tx_buf is %NULL), fill the TX FIFO by cyclically
750  * copying from the zero page.  The DMA descriptor to do this is preallocated
751  * in bcm2835_dma_init().  It must be terminated once the RX DMA channel is
752  * done and can then be reused.
753  *
754  * The BCM2835 DMA driver autodetects when a transaction copies from the zero
755  * page and utilizes the DMA controller's ability to synthesize zeroes instead
756  * of copying them from memory.  This reduces traffic on the memory bus.  The
757  * feature is not available on so-called "lite" channels, but normally TX DMA
758  * is backed by a full-featured channel.
759  *
760  * Zero-filling the TX FIFO is paced by the DREQ signal.  Unfortunately the
761  * BCM2835 SPI controller continues to assert DREQ even after the DLEN register
762  * has been counted down to zero (hardware erratum).  Thus, when the transfer
763  * has finished, the DMA engine zero-fills the TX FIFO until it is half full.
764  * (Tuneable with the DC register.)  So up to 9 gratuitous bus accesses are
765  * performed at the end of an RX-only transfer.
766  */
767 static int bcm2835_spi_transfer_one_dma(struct spi_controller *ctlr,
768                                         struct spi_transfer *tfr,
769                                         struct bcm2835_spidev *target,
770                                         u32 cs)
771 {
772         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
773         dma_cookie_t cookie;
774         int ret;
775
776         /* update usage statistics */
777         bs->count_transfer_dma++;
778
779         /*
780          * Transfer first few bytes without DMA if length of first TX or RX
781          * sglist entry is not a multiple of 4 bytes (hardware limitation).
782          */
783         bcm2835_spi_transfer_prologue(ctlr, tfr, bs, cs);
784
785         /* setup tx-DMA */
786         if (bs->tx_buf) {
787                 ret = bcm2835_spi_prepare_sg(ctlr, tfr, bs, target, true);
788         } else {
789                 cookie = dmaengine_submit(bs->fill_tx_desc);
790                 ret = dma_submit_error(cookie);
791         }
792         if (ret)
793                 goto err_reset_hw;
794
795         /* set the DMA length */
796         bcm2835_wr(bs, BCM2835_SPI_DLEN, bs->tx_len);
797
798         /* start the HW */
799         bcm2835_wr(bs, BCM2835_SPI_CS,
800                    cs | BCM2835_SPI_CS_TA | BCM2835_SPI_CS_DMAEN);
801
802         bs->tx_dma_active = true;
803         smp_wmb();
804
805         /* start TX early */
806         dma_async_issue_pending(ctlr->dma_tx);
807
808         /* setup rx-DMA late - to run transfers while
809          * mapping of the rx buffers still takes place
810          * this saves 10us or more.
811          */
812         if (bs->rx_buf) {
813                 ret = bcm2835_spi_prepare_sg(ctlr, tfr, bs, target, false);
814         } else {
815                 cookie = dmaengine_submit(target->clear_rx_desc);
816                 ret = dma_submit_error(cookie);
817         }
818         if (ret) {
819                 /* need to reset on errors */
820                 dmaengine_terminate_sync(ctlr->dma_tx);
821                 bs->tx_dma_active = false;
822                 goto err_reset_hw;
823         }
824
825         /* start rx dma late */
826         dma_async_issue_pending(ctlr->dma_rx);
827         bs->rx_dma_active = true;
828         smp_mb();
829
830         /*
831          * In case of a very short TX-only transfer, bcm2835_spi_dma_tx_done()
832          * may run before RX DMA is issued.  Terminate RX DMA if so.
833          */
834         if (!bs->rx_buf && !bs->tx_dma_active &&
835             cmpxchg(&bs->rx_dma_active, true, false)) {
836                 dmaengine_terminate_async(ctlr->dma_rx);
837                 bcm2835_spi_reset_hw(bs);
838         }
839
840         /* wait for wakeup in framework */
841         return 1;
842
843 err_reset_hw:
844         bcm2835_spi_reset_hw(bs);
845         bcm2835_spi_undo_prologue(bs);
846         return ret;
847 }
848
849 static bool bcm2835_spi_can_dma(struct spi_controller *ctlr,
850                                 struct spi_device *spi,
851                                 struct spi_transfer *tfr)
852 {
853         /* we start DMA efforts only on bigger transfers */
854         if (tfr->len < BCM2835_SPI_DMA_MIN_LENGTH)
855                 return false;
856
857         /* return OK */
858         return true;
859 }
860
861 static void bcm2835_dma_release(struct spi_controller *ctlr,
862                                 struct bcm2835_spi *bs)
863 {
864         if (ctlr->dma_tx) {
865                 dmaengine_terminate_sync(ctlr->dma_tx);
866
867                 if (bs->fill_tx_desc)
868                         dmaengine_desc_free(bs->fill_tx_desc);
869
870                 if (bs->fill_tx_addr)
871                         dma_unmap_page_attrs(ctlr->dma_tx->device->dev,
872                                              bs->fill_tx_addr, sizeof(u32),
873                                              DMA_TO_DEVICE,
874                                              DMA_ATTR_SKIP_CPU_SYNC);
875
876                 dma_release_channel(ctlr->dma_tx);
877                 ctlr->dma_tx = NULL;
878         }
879
880         if (ctlr->dma_rx) {
881                 dmaengine_terminate_sync(ctlr->dma_rx);
882                 dma_release_channel(ctlr->dma_rx);
883                 ctlr->dma_rx = NULL;
884         }
885 }
886
887 static int bcm2835_dma_init(struct spi_controller *ctlr, struct device *dev,
888                             struct bcm2835_spi *bs)
889 {
890         struct dma_slave_config slave_config;
891         int ret;
892
893         /* get tx/rx dma */
894         ctlr->dma_tx = dma_request_chan(dev, "tx");
895         if (IS_ERR(ctlr->dma_tx)) {
896                 ret = dev_err_probe(dev, PTR_ERR(ctlr->dma_tx),
897                         "no tx-dma configuration found - not using dma mode\n");
898                 ctlr->dma_tx = NULL;
899                 goto err;
900         }
901         ctlr->dma_rx = dma_request_chan(dev, "rx");
902         if (IS_ERR(ctlr->dma_rx)) {
903                 ret = dev_err_probe(dev, PTR_ERR(ctlr->dma_rx),
904                         "no rx-dma configuration found - not using dma mode\n");
905                 ctlr->dma_rx = NULL;
906                 goto err_release;
907         }
908
909         /*
910          * The TX DMA channel either copies a transfer's TX buffer to the FIFO
911          * or, in case of an RX-only transfer, cyclically copies from the zero
912          * page to the FIFO using a preallocated, reusable descriptor.
913          */
914         slave_config.dst_addr = bs->phys_addr + BCM2835_SPI_FIFO;
915         slave_config.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
916
917         ret = dmaengine_slave_config(ctlr->dma_tx, &slave_config);
918         if (ret)
919                 goto err_config;
920
921         bs->fill_tx_addr = dma_map_page_attrs(ctlr->dma_tx->device->dev,
922                                               ZERO_PAGE(0), 0, sizeof(u32),
923                                               DMA_TO_DEVICE,
924                                               DMA_ATTR_SKIP_CPU_SYNC);
925         if (dma_mapping_error(ctlr->dma_tx->device->dev, bs->fill_tx_addr)) {
926                 dev_err(dev, "cannot map zero page - not using DMA mode\n");
927                 bs->fill_tx_addr = 0;
928                 ret = -ENOMEM;
929                 goto err_release;
930         }
931
932         bs->fill_tx_desc = dmaengine_prep_dma_cyclic(ctlr->dma_tx,
933                                                      bs->fill_tx_addr,
934                                                      sizeof(u32), 0,
935                                                      DMA_MEM_TO_DEV, 0);
936         if (!bs->fill_tx_desc) {
937                 dev_err(dev, "cannot prepare fill_tx_desc - not using DMA mode\n");
938                 ret = -ENOMEM;
939                 goto err_release;
940         }
941
942         ret = dmaengine_desc_set_reuse(bs->fill_tx_desc);
943         if (ret) {
944                 dev_err(dev, "cannot reuse fill_tx_desc - not using DMA mode\n");
945                 goto err_release;
946         }
947
948         /*
949          * The RX DMA channel is used bidirectionally:  It either reads the
950          * RX FIFO or, in case of a TX-only transfer, cyclically writes a
951          * precalculated value to the CS register to clear the RX FIFO.
952          */
953         slave_config.src_addr = bs->phys_addr + BCM2835_SPI_FIFO;
954         slave_config.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
955         slave_config.dst_addr = bs->phys_addr + BCM2835_SPI_CS;
956         slave_config.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
957
958         ret = dmaengine_slave_config(ctlr->dma_rx, &slave_config);
959         if (ret)
960                 goto err_config;
961
962         /* all went well, so set can_dma */
963         ctlr->can_dma = bcm2835_spi_can_dma;
964
965         return 0;
966
967 err_config:
968         dev_err(dev, "issue configuring dma: %d - not using DMA mode\n",
969                 ret);
970 err_release:
971         bcm2835_dma_release(ctlr, bs);
972 err:
973         /*
974          * Only report error for deferred probing, otherwise fall back to
975          * interrupt mode
976          */
977         if (ret != -EPROBE_DEFER)
978                 ret = 0;
979
980         return ret;
981 }
982
983 static int bcm2835_spi_transfer_one_poll(struct spi_controller *ctlr,
984                                          struct spi_device *spi,
985                                          struct spi_transfer *tfr,
986                                          u32 cs)
987 {
988         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
989         unsigned long timeout;
990
991         /* update usage statistics */
992         bs->count_transfer_polling++;
993
994         /* enable HW block without interrupts */
995         bcm2835_wr(bs, BCM2835_SPI_CS, cs | BCM2835_SPI_CS_TA);
996
997         /* fill in the fifo before timeout calculations
998          * if we are interrupted here, then the data is
999          * getting transferred by the HW while we are interrupted
1000          */
1001         bcm2835_wr_fifo_blind(bs, BCM2835_SPI_FIFO_SIZE);
1002
1003         /* set the timeout to at least 2 jiffies */
1004         timeout = jiffies + 2 + HZ * polling_limit_us / 1000000;
1005
1006         /* loop until finished the transfer */
1007         while (bs->rx_len) {
1008                 /* fill in tx fifo with remaining data */
1009                 bcm2835_wr_fifo(bs);
1010
1011                 /* read from fifo as much as possible */
1012                 bcm2835_rd_fifo(bs);
1013
1014                 /* if there is still data pending to read
1015                  * then check the timeout
1016                  */
1017                 if (bs->rx_len && time_after(jiffies, timeout)) {
1018                         dev_dbg_ratelimited(&spi->dev,
1019                                             "timeout period reached: jiffies: %lu remaining tx/rx: %d/%d - falling back to interrupt mode\n",
1020                                             jiffies - timeout,
1021                                             bs->tx_len, bs->rx_len);
1022                         /* fall back to interrupt mode */
1023
1024                         /* update usage statistics */
1025                         bs->count_transfer_irq_after_polling++;
1026
1027                         return bcm2835_spi_transfer_one_irq(ctlr, spi,
1028                                                             tfr, cs, false);
1029                 }
1030         }
1031
1032         /* Transfer complete - reset SPI HW */
1033         bcm2835_spi_reset_hw(bs);
1034         /* and return without waiting for completion */
1035         return 0;
1036 }
1037
1038 static int bcm2835_spi_transfer_one(struct spi_controller *ctlr,
1039                                     struct spi_device *spi,
1040                                     struct spi_transfer *tfr)
1041 {
1042         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
1043         struct bcm2835_spidev *target = spi_get_ctldata(spi);
1044         unsigned long spi_hz, cdiv;
1045         unsigned long hz_per_byte, byte_limit;
1046         u32 cs = target->prepare_cs;
1047
1048         if (unlikely(!tfr->len)) {
1049                 static int warned;
1050
1051                 if (!warned)
1052                         dev_warn(&spi->dev,
1053                                  "zero-length SPI transfer ignored\n");
1054                 warned = 1;
1055                 return 0;
1056         }
1057
1058         /* set clock */
1059         spi_hz = tfr->speed_hz;
1060
1061         if (spi_hz >= bs->clk_hz / 2) {
1062                 cdiv = 2; /* clk_hz/2 is the fastest we can go */
1063         } else if (spi_hz) {
1064                 /* CDIV must be a multiple of two */
1065                 cdiv = DIV_ROUND_UP(bs->clk_hz, spi_hz);
1066                 cdiv += (cdiv % 2);
1067
1068                 if (cdiv >= 65536)
1069                         cdiv = 0; /* 0 is the slowest we can go */
1070         } else {
1071                 cdiv = 0; /* 0 is the slowest we can go */
1072         }
1073         tfr->effective_speed_hz = cdiv ? (bs->clk_hz / cdiv) : (bs->clk_hz / 65536);
1074         bcm2835_wr(bs, BCM2835_SPI_CLK, cdiv);
1075
1076         /* handle all the 3-wire mode */
1077         if (spi->mode & SPI_3WIRE && tfr->rx_buf)
1078                 cs |= BCM2835_SPI_CS_REN;
1079
1080         /* set transmit buffers and length */
1081         bs->tx_buf = tfr->tx_buf;
1082         bs->rx_buf = tfr->rx_buf;
1083         bs->tx_len = tfr->len;
1084         bs->rx_len = tfr->len;
1085
1086         /* Calculate the estimated time in us the transfer runs.  Note that
1087          * there is 1 idle clocks cycles after each byte getting transferred
1088          * so we have 9 cycles/byte.  This is used to find the number of Hz
1089          * per byte per polling limit.  E.g., we can transfer 1 byte in 30 us
1090          * per 300,000 Hz of bus clock.
1091          */
1092         hz_per_byte = polling_limit_us ? (9 * 1000000) / polling_limit_us : 0;
1093         byte_limit = hz_per_byte ? tfr->effective_speed_hz / hz_per_byte : 1;
1094
1095         /* run in polling mode for short transfers */
1096         if (tfr->len < byte_limit)
1097                 return bcm2835_spi_transfer_one_poll(ctlr, spi, tfr, cs);
1098
1099         /* run in dma mode if conditions are right
1100          * Note that unlike poll or interrupt mode DMA mode does not have
1101          * this 1 idle clock cycle pattern but runs the spi clock without gaps
1102          */
1103         if (ctlr->can_dma && bcm2835_spi_can_dma(ctlr, spi, tfr))
1104                 return bcm2835_spi_transfer_one_dma(ctlr, tfr, target, cs);
1105
1106         /* run in interrupt-mode */
1107         return bcm2835_spi_transfer_one_irq(ctlr, spi, tfr, cs, true);
1108 }
1109
1110 static int bcm2835_spi_prepare_message(struct spi_controller *ctlr,
1111                                        struct spi_message *msg)
1112 {
1113         struct spi_device *spi = msg->spi;
1114         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
1115         struct bcm2835_spidev *target = spi_get_ctldata(spi);
1116         int ret;
1117
1118         if (ctlr->can_dma) {
1119                 /*
1120                  * DMA transfers are limited to 16 bit (0 to 65535 bytes) by
1121                  * the SPI HW due to DLEN. Split up transfers (32-bit FIFO
1122                  * aligned) if the limit is exceeded.
1123                  */
1124                 ret = spi_split_transfers_maxsize(ctlr, msg, 65532,
1125                                                   GFP_KERNEL | GFP_DMA);
1126                 if (ret)
1127                         return ret;
1128         }
1129
1130         /*
1131          * Set up clock polarity before spi_transfer_one_message() asserts
1132          * chip select to avoid a gratuitous clock signal edge.
1133          */
1134         bcm2835_wr(bs, BCM2835_SPI_CS, target->prepare_cs);
1135
1136         return 0;
1137 }
1138
1139 static void bcm2835_spi_handle_err(struct spi_controller *ctlr,
1140                                    struct spi_message *msg)
1141 {
1142         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
1143
1144         /* if an error occurred and we have an active dma, then terminate */
1145         if (ctlr->dma_tx) {
1146                 dmaengine_terminate_sync(ctlr->dma_tx);
1147                 bs->tx_dma_active = false;
1148         }
1149         if (ctlr->dma_rx) {
1150                 dmaengine_terminate_sync(ctlr->dma_rx);
1151                 bs->rx_dma_active = false;
1152         }
1153         bcm2835_spi_undo_prologue(bs);
1154
1155         /* and reset */
1156         bcm2835_spi_reset_hw(bs);
1157 }
1158
1159 static int chip_match_name(struct gpio_chip *chip, void *data)
1160 {
1161         return !strcmp(chip->label, data);
1162 }
1163
1164 static void bcm2835_spi_cleanup(struct spi_device *spi)
1165 {
1166         struct bcm2835_spidev *target = spi_get_ctldata(spi);
1167         struct spi_controller *ctlr = spi->controller;
1168
1169         if (target->clear_rx_desc)
1170                 dmaengine_desc_free(target->clear_rx_desc);
1171
1172         if (target->clear_rx_addr)
1173                 dma_unmap_single(ctlr->dma_rx->device->dev,
1174                                  target->clear_rx_addr,
1175                                  sizeof(u32),
1176                                  DMA_TO_DEVICE);
1177
1178         kfree(target);
1179 }
1180
1181 static int bcm2835_spi_setup_dma(struct spi_controller *ctlr,
1182                                  struct spi_device *spi,
1183                                  struct bcm2835_spi *bs,
1184                                  struct bcm2835_spidev *target)
1185 {
1186         int ret;
1187
1188         if (!ctlr->dma_rx)
1189                 return 0;
1190
1191         target->clear_rx_addr = dma_map_single(ctlr->dma_rx->device->dev,
1192                                                &target->clear_rx_cs,
1193                                                sizeof(u32),
1194                                                DMA_TO_DEVICE);
1195         if (dma_mapping_error(ctlr->dma_rx->device->dev, target->clear_rx_addr)) {
1196                 dev_err(&spi->dev, "cannot map clear_rx_cs\n");
1197                 target->clear_rx_addr = 0;
1198                 return -ENOMEM;
1199         }
1200
1201         target->clear_rx_desc = dmaengine_prep_dma_cyclic(ctlr->dma_rx,
1202                                                           target->clear_rx_addr,
1203                                                           sizeof(u32), 0,
1204                                                           DMA_MEM_TO_DEV, 0);
1205         if (!target->clear_rx_desc) {
1206                 dev_err(&spi->dev, "cannot prepare clear_rx_desc\n");
1207                 return -ENOMEM;
1208         }
1209
1210         ret = dmaengine_desc_set_reuse(target->clear_rx_desc);
1211         if (ret) {
1212                 dev_err(&spi->dev, "cannot reuse clear_rx_desc\n");
1213                 return ret;
1214         }
1215
1216         return 0;
1217 }
1218
1219 static int bcm2835_spi_setup(struct spi_device *spi)
1220 {
1221         struct spi_controller *ctlr = spi->controller;
1222         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
1223         struct bcm2835_spidev *target = spi_get_ctldata(spi);
1224         struct gpio_chip *chip;
1225         int len;
1226         int ret;
1227         u32 cs;
1228
1229         if (!target) {
1230                 target = kzalloc(ALIGN(sizeof(*target), dma_get_cache_alignment()),
1231                               GFP_KERNEL);
1232                 if (!target)
1233                         return -ENOMEM;
1234
1235                 spi_set_ctldata(spi, target);
1236
1237                 ret = bcm2835_spi_setup_dma(ctlr, spi, bs, target);
1238                 if (ret)
1239                         goto err_cleanup;
1240         }
1241
1242         /*
1243          * Precalculate SPI target's CS register value for ->prepare_message():
1244          * The driver always uses software-controlled GPIO chip select, hence
1245          * set the hardware-controlled native chip select to an invalid value
1246          * to prevent it from interfering.
1247          */
1248         cs = BCM2835_SPI_CS_CS_10 | BCM2835_SPI_CS_CS_01;
1249         if (spi->mode & SPI_CPOL)
1250                 cs |= BCM2835_SPI_CS_CPOL;
1251         if (spi->mode & SPI_CPHA)
1252                 cs |= BCM2835_SPI_CS_CPHA;
1253         target->prepare_cs = cs;
1254
1255         /*
1256          * Precalculate SPI target's CS register value to clear RX FIFO
1257          * in case of a TX-only DMA transfer.
1258          */
1259         if (ctlr->dma_rx) {
1260                 target->clear_rx_cs = cs | BCM2835_SPI_CS_TA |
1261                                         BCM2835_SPI_CS_DMAEN |
1262                                         BCM2835_SPI_CS_CLEAR_RX;
1263                 dma_sync_single_for_device(ctlr->dma_rx->device->dev,
1264                                            target->clear_rx_addr,
1265                                            sizeof(u32),
1266                                            DMA_TO_DEVICE);
1267         }
1268
1269         /*
1270          * sanity checking the native-chipselects
1271          */
1272         if (spi->mode & SPI_NO_CS)
1273                 return 0;
1274         /*
1275          * The SPI core has successfully requested the CS GPIO line from the
1276          * device tree, so we are done.
1277          */
1278         if (spi_get_csgpiod(spi, 0))
1279                 return 0;
1280         if (spi_get_chipselect(spi, 0) > 1) {
1281                 /* error in the case of native CS requested with CS > 1
1282                  * officially there is a CS2, but it is not documented
1283                  * which GPIO is connected with that...
1284                  */
1285                 dev_err(&spi->dev,
1286                         "setup: only two native chip-selects are supported\n");
1287                 ret = -EINVAL;
1288                 goto err_cleanup;
1289         }
1290
1291         /* Skip forced CS conversion if controller has an empty cs-gpios property */
1292         if (of_find_property(ctlr->dev.of_node, "cs-gpios", &len) && len == 0)
1293                 return 0;
1294
1295         /*
1296          * Translate native CS to GPIO
1297          *
1298          * FIXME: poking around in the gpiolib internals like this is
1299          * not very good practice. Find a way to locate the real problem
1300          * and fix it. Why is the GPIO descriptor in spi->cs_gpiod
1301          * sometimes not assigned correctly? Erroneous device trees?
1302          */
1303
1304         /* get the gpio chip for the base */
1305         chip = gpiochip_find("pinctrl-bcm2835", chip_match_name);
1306         if (!chip)
1307                 return 0;
1308
1309         spi_set_csgpiod(spi, 0, gpiochip_request_own_desc(chip,
1310                                                           8 - (spi_get_chipselect(spi, 0)),
1311                                                           DRV_NAME,
1312                                                           GPIO_LOOKUP_FLAGS_DEFAULT,
1313                                                           GPIOD_OUT_LOW));
1314         if (IS_ERR(spi_get_csgpiod(spi, 0))) {
1315                 ret = PTR_ERR(spi_get_csgpiod(spi, 0));
1316                 goto err_cleanup;
1317         }
1318
1319         /* and set up the "mode" and level */
1320         dev_info(&spi->dev, "setting up native-CS%i to use GPIO\n",
1321                  spi_get_chipselect(spi, 0));
1322
1323         return 0;
1324
1325 err_cleanup:
1326         bcm2835_spi_cleanup(spi);
1327         return ret;
1328 }
1329
1330 static int bcm2835_spi_probe(struct platform_device *pdev)
1331 {
1332         struct spi_controller *ctlr;
1333         struct bcm2835_spi *bs;
1334         struct resource *iomem;
1335         int err;
1336
1337         ctlr = devm_spi_alloc_host(&pdev->dev, sizeof(*bs));
1338         if (!ctlr)
1339                 return -ENOMEM;
1340
1341         platform_set_drvdata(pdev, ctlr);
1342
1343         ctlr->use_gpio_descriptors = true;
1344         ctlr->mode_bits = BCM2835_SPI_MODE_BITS;
1345         ctlr->bits_per_word_mask = SPI_BPW_MASK(8);
1346         ctlr->num_chipselect = 3;
1347         ctlr->setup = bcm2835_spi_setup;
1348         ctlr->cleanup = bcm2835_spi_cleanup;
1349         ctlr->transfer_one = bcm2835_spi_transfer_one;
1350         ctlr->handle_err = bcm2835_spi_handle_err;
1351         ctlr->prepare_message = bcm2835_spi_prepare_message;
1352         ctlr->dev.of_node = pdev->dev.of_node;
1353
1354         bs = spi_controller_get_devdata(ctlr);
1355         bs->ctlr = ctlr;
1356
1357         bs->regs = devm_platform_get_and_ioremap_resource(pdev, 0, &iomem);
1358         if (IS_ERR(bs->regs))
1359                 return PTR_ERR(bs->regs);
1360
1361         bs->phys_addr = iomem->start;
1362         bs->clk = devm_clk_get(&pdev->dev, NULL);
1363         if (IS_ERR(bs->clk))
1364                 return dev_err_probe(&pdev->dev, PTR_ERR(bs->clk),
1365                                      "could not get clk\n");
1366
1367         ctlr->max_speed_hz = clk_get_rate(bs->clk) / 2;
1368
1369         bs->irq = platform_get_irq(pdev, 0);
1370         if (bs->irq < 0)
1371                 return bs->irq;
1372
1373         err = clk_prepare_enable(bs->clk);
1374         if (err)
1375                 return err;
1376         bs->clk_hz = clk_get_rate(bs->clk);
1377
1378         err = bcm2835_dma_init(ctlr, &pdev->dev, bs);
1379         if (err)
1380                 goto out_clk_disable;
1381
1382         /* initialise the hardware with the default polarities */
1383         bcm2835_wr(bs, BCM2835_SPI_CS,
1384                    BCM2835_SPI_CS_CLEAR_RX | BCM2835_SPI_CS_CLEAR_TX);
1385
1386         err = devm_request_irq(&pdev->dev, bs->irq, bcm2835_spi_interrupt,
1387                                IRQF_SHARED, dev_name(&pdev->dev), bs);
1388         if (err) {
1389                 dev_err(&pdev->dev, "could not request IRQ: %d\n", err);
1390                 goto out_dma_release;
1391         }
1392
1393         err = spi_register_controller(ctlr);
1394         if (err) {
1395                 dev_err(&pdev->dev, "could not register SPI controller: %d\n",
1396                         err);
1397                 goto out_dma_release;
1398         }
1399
1400         bcm2835_debugfs_create(bs, dev_name(&pdev->dev));
1401
1402         return 0;
1403
1404 out_dma_release:
1405         bcm2835_dma_release(ctlr, bs);
1406 out_clk_disable:
1407         clk_disable_unprepare(bs->clk);
1408         return err;
1409 }
1410
1411 static void bcm2835_spi_remove(struct platform_device *pdev)
1412 {
1413         struct spi_controller *ctlr = platform_get_drvdata(pdev);
1414         struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr);
1415
1416         bcm2835_debugfs_remove(bs);
1417
1418         spi_unregister_controller(ctlr);
1419
1420         bcm2835_dma_release(ctlr, bs);
1421
1422         /* Clear FIFOs, and disable the HW block */
1423         bcm2835_wr(bs, BCM2835_SPI_CS,
1424                    BCM2835_SPI_CS_CLEAR_RX | BCM2835_SPI_CS_CLEAR_TX);
1425
1426         clk_disable_unprepare(bs->clk);
1427 }
1428
1429 static const struct of_device_id bcm2835_spi_match[] = {
1430         { .compatible = "brcm,bcm2835-spi", },
1431         {}
1432 };
1433 MODULE_DEVICE_TABLE(of, bcm2835_spi_match);
1434
1435 static struct platform_driver bcm2835_spi_driver = {
1436         .driver         = {
1437                 .name           = DRV_NAME,
1438                 .of_match_table = bcm2835_spi_match,
1439         },
1440         .probe          = bcm2835_spi_probe,
1441         .remove_new     = bcm2835_spi_remove,
1442         .shutdown       = bcm2835_spi_remove,
1443 };
1444 module_platform_driver(bcm2835_spi_driver);
1445
1446 MODULE_DESCRIPTION("SPI controller driver for Broadcom BCM2835");
1447 MODULE_AUTHOR("Chris Boot <bootc@bootc.net>");
1448 MODULE_LICENSE("GPL");