Skip to contentSkip to conversation

spi: loongson: SPI-IO driver for Loongson-2K0300

PATCH In review Binbin Zhou 3 participants 10 messages Nov 23

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

cover spi: loongson: SPI-IO driver for Loongson-2K0300

Hi all:

This series adds a new SPI controller driver for the Loongson-2K0300 SPI-IO blocks (SPI2 / SPI3). On the Loongson-2K0300 these blocks reside in the chip IO address space (0x1610,c000 – 0x1610,ffff) and only support IO-space access; a separate QSPI controller handles the main SPI pins on the same SoC, so this driver uses the dedicated compatible "loongson,ls2k0300-spi-io".

Test results
SPI NOR flash on SPI2, spi-max-frequency = 28000000:
DMA:

    read:  ~3.1 MB/s
    write: ~401 kB/s
  Intterupt:
    read:  ~750 KB/s
    write: ~300 kB/s

Thanks.
Binbin

Binbin Zhou (5):
spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi
compatible
spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi-io
compatible
spi: loongson-io: Add SPI-IO interrupt-driven driver
spi: loongson-io: Add DMA support to SPI-IO driver
MAINTAINERS: Add myself as Loongson SPI maintainer

 .../bindings/spi/loongson,ls2k-spi.yaml       |   45 +
 MAINTAINERS                                   |    2 +
 drivers/spi/Kconfig                           |   16 +
 drivers/spi/Makefile                          |    1 +
 drivers/spi/spi-loongson-io.c                 | 1114 +++++++++++++++++
 5 files changed, 1178 insertions(+)
 create mode 100644 drivers/spi/spi-loongson-io.c

base-commit: e09d1526e19ef8b1008ee81149232db6c2bdee32

Signature · 1 line
2.52.0
#1 lore raw

PATCH 1/5 spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi compatible

The SPI flash controller on Loongson-2K0300 shares the same register layout and functionality as the one on Loongson-2K1000. Add a dedicated compatible string loongson,ls2k0300-spi with loongson,ls2k1000-spi as fallback to allow proper DT binding.

---
 Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml | 4 ++++
 1 file changed, 4 insertions(+)
Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml +4 -0
index de9d32feadf5..8a36dbece788 100644
@@ -19,6 +19,7 @@ properties:
           - loongson,ls2k1000-spi
       - items:
           - enum:
+              - loongson,ls2k0300-spi
               - loongson,ls2k0500-spi
           - const: loongson,ls2k1000-spi
 
@@ -28,6 +29,9 @@ properties:
   clocks:
     maxItems: 1
 
+  interrupts:
+    maxItems: 1
+
 required:
   - compatible
   - reg
Signature · 1 line
2.52.0
#2 lore raw

Re: [PATCH 1/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi compatible

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] spi: dt-bindings: changelog omits addition of interrupts property --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] spi: dt-bindings: changelog omits addition of interrupts property
--

commit 69ba92a75f7fc4022285efadae2a4866e7663918
Author: Binbin Zhou <[email protected]>

spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi compatible

This commit adds the loongson,ls2k0300-spi compatible string and an optional interrupts property to the Loongson LS2K SPI binding schema.

Quoted 13 lines
Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml +1 -0
index de9d32feadf59..8a36dbece7885 100644
@@ -19,6 +19,7 @@ properties:
           - loongson,ls2k1000-spi
       - items:
           - enum:
+              - loongson,ls2k0300-spi
               - loongson,ls2k0500-spi
           - const: loongson,ls2k1000-spi
 

Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml properties: · line 33

Quoted 5 lines
Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml +2 -0
@@ -28,6 +29,9 @@ properties:
   clocks:
     maxItems: 1
 
+  interrupts:
+    maxItems: 1

[Severity: Low]
This isn't a bug, but the commit message only mentions adding the loongson,ls2k0300-spi compatible string and omits the addition of the interrupts property to the schema.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

PATCH 2/5 spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi-io compatible

In reply to Binbin Zhou

Loongson-2K0300 integrates a new SPI-IO controller with enhanced registers and extended capabilities (interrupt, DMA, larger FIFO, etc.) which is distinct from the legacy SPI flash controller.

Define the new compatible loongson,ls2k0300-spi-io and require the associated DMA and interrupt properties for this variant.

---
 .../bindings/spi/loongson,ls2k-spi.yaml       | 41 +++++++++++++++++++
 1 file changed, 41 insertions(+)
Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml +41 -0
index 8a36dbece788..b113d10c5bd9 100644
@@ -16,6 +16,7 @@ properties:
   compatible:
     oneOf:
       - enum:
+          - loongson,ls2k0300-spi-io
           - loongson,ls2k1000-spi
       - items:
           - enum:
@@ -32,6 +33,14 @@ properties:
   interrupts:
     maxItems: 1
 
+  dmas:
+    maxItems: 2
+
+  dma-names:
+    items:
+      - const: tx
+      - const: rx
+
 required:
   - compatible
   - reg
@@ -39,6 +48,23 @@ required:
 
 unevaluatedProperties: false
 
+if:
+  properties:
+    compatible:
+      contains:
+        const: loongson,ls2k0300-spi-io
+
+then:
+  required:
+    - dmas
+    - dma-names
+    - interrupts
+
+else:
+  properties:
+    dmas: false
+    dma-names: false
+
 examples:
   - |
     spi0: spi@1fff0220{
@@ -48,3 +74,18 @@ examples:
         #address-cells = <1>;
         #size-cells = <0>;
     };
+
+  - |
+    #include <dt-bindings/interrupt-controller/irq.h>
+    #include <dt-bindings/clock/loongson,ls2k-clk.h>
+
+    spi@1610c000 {
+        compatible = "loongson,ls2k0300-spi-io";
+        reg = <0x1610c000 0x2000>;
+        clocks = <&clk LS2K0300_CLK_DEV_GATE>;
+        interrupt-parent = <&liointc0>;
+        interrupts = <6 IRQ_TYPE_LEVEL_HIGH>;
+        dmas = <&dma_router 14 1 0x8e>,
+               <&dma_router 14 0 0x8e>;
+        dma-names = "tx", "rx";
+    };
Signature · 1 line
2.52.0
Acked-by on v1 2/5
#4 lore raw

Re: [PATCH 2/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi-io compatible

pw-bot: not-applicable

Sashiko comments on the other binding patch however are worth looking at.

#5 lore raw

PATCH 3/5 spi: loongson-io: Add SPI-IO interrupt-driven driver

In reply to Binbin Zhou

Add a platform driver for the Loongson-2K0300 SPI-IO controller.

On the Loongson-2K0300, SPI2 and SPI3 reside in the chip IO address space and only support IO-space access.

Support 8-bit/16-bit/32-bit words, SPI modes 0-3, LSB-first, programmable clocking and hardware chip select.

Transfer handling is interrupt-driven in small FIFO batches of up to four bytes. On EOT IRQ the driver drains RX data and issues the next batch until the transfer completes. This keeps each interrupt short and works without requiring DMA providers to be available at probe time.

---
 MAINTAINERS                   |   1 +
 drivers/spi/Kconfig           |  16 +
 drivers/spi/Makefile          |   1 +
 drivers/spi/spi-loongson-io.c | 737 ++++++++++++++++++++++++++++++++++
 4 files changed, 755 insertions(+)
 create mode 100644 drivers/spi/spi-loongson-io.c
MAINTAINERS +1 -0
index ce1b9e514e08..70789ce6e507 100644
@@ -15742,6 +15742,7 @@ L:	[email protected]
 S:	Maintained
 F:	Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml
 F:	drivers/spi/spi-loongson-core.c
+F:	drivers/spi/spi-loongson-io.c
 F:	drivers/spi/spi-loongson-pci.c
 F:	drivers/spi/spi-loongson-plat.c
 F:	drivers/spi/spi-loongson.h
drivers/spi/Kconfig +16 -0
index a7b343d124a9..5551b883ce1e 100644
@@ -635,6 +635,22 @@ config SPI_LOONGSON_CORE
 	tristate
 	depends on LOONGARCH || COMPILE_TEST
 
+config SPI_LOONGSON_IO
+	tristate "Loongson SPI-IO Controller Driver"
+	depends on LOONGARCH || COMPILE_TEST
+	depends on OF
+	help
+	  This enables support for the Loongson SPI-IO controller, which is
+	  a separate SPI IP block found on Loongson-2K0300 SPI2/SPI3.
+
+	  It is a generic SPI master for externally connected SPI
+	  peripherals. It does not provide memory-mapped SPI flash
+	  access (no spi-mem support). Transfers can be interrupt-driven
+	  or DMA-driven, with runtime-selectable 8/16/32-bit frame widths
+
+	  This driver can also be built as a module. If so, the module
+	  will be called spi-loongson-io.
+
 config SPI_LOONGSON_PCI
 	tristate "Loongson SPI Controller PCI Driver Support"
 	select SPI_LOONGSON_CORE
drivers/spi/Makefile +1 -0
index b6ab37271555..3af58eaa391a 100644
@@ -83,6 +83,7 @@ obj-$(CONFIG_SPI_KSPI2)			+= spi-kspi2.o
 obj-$(CONFIG_SPI_LJCA)			+= spi-ljca.o
 obj-$(CONFIG_SPI_LM70_LLP)		+= spi-lm70llp.o
 obj-$(CONFIG_SPI_LOONGSON_CORE)		+= spi-loongson-core.o
+obj-$(CONFIG_SPI_LOONGSON_IO)		+= spi-loongson-io.o
 obj-$(CONFIG_SPI_LOONGSON_PCI)		+= spi-loongson-pci.o
 obj-$(CONFIG_SPI_LOONGSON_PLATFORM)	+= spi-loongson-plat.o
 obj-$(CONFIG_SPI_LP8841_RTC)		+= spi-lp8841-rtc.o
drivers/spi/spi-loongson-io.c new file +737 -0

737 lines not on this page · raw message

Signature · 1 line
2.52.0
#6 lore raw

Re: [PATCH 3/5] spi: loongson-io: Add SPI-IO interrupt-driven driver

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [High] spi: loongson-io: missing error IRQ enables and uncleared SR1 in ISR - [High] spi: loongson-io…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [High] spi: loongson-io: missing error IRQ enables and uncleared SR1 in ISR
- [High] spi: loongson-io: 32-bit divisor truncation in loongson_spi_io_timeout()
- [Medium] spi: loongson-io: IRQ enabled before hardware and batch init in probe/xfer
- [Medium] spi: loongson-io: unsynchronized timeout in loongson_spi_io_transfer_one()
- [Low] spi: loongson-io: inverted @high CS contract in loongson_spi_io_set_cs()
--

commit 7a2b450ad49a89d82f040f8bc7f2f42d5aadeb60
Author: Binbin Zhou <[email protected]>

spi: loongson-io: Add SPI-IO interrupt-driven driver

This commit adds an interrupt-driven platform driver for the Loongson-2K0300 SPI-IO controller (SPI2 and SPI3).

Quoted 6 lines
drivers/spi/spi-loongson-io.c new file +0 -0
new file mode 100644
index 0000000000000..e273c9f4a9430
@@ -0,0 +1,737 @@

[ ... ]

drivers/spi/spi-loongson-io.c line 265

Quoted 10 lines
drivers/spi/spi-loongson-io.c new file +10 -0
+static unsigned long loongson_spi_io_timeout(struct loongson_spi_priv *priv,
+					     struct spi_transfer *xfer)
+{
+	u64 frames = xfer->len / priv->frame_bytes;
+	u64 nsec = frames * priv->bits_per_word * NSEC_PER_SEC;
+	u32 rate = priv->hz ? priv->hz : 1000;
+	u64 msec = DIV_ROUND_UP_ULL(nsec, (u64)rate * NSEC_PER_MSEC);
+
+	return msecs_to_jiffies(max_t(u64, msec * 2, 1000));
+}

[Severity: High]
Does DIV_ROUND_UP_ULL() truncate the 64-bit divisor (u64)rate * NSEC_PER_MSEC to 32 bits?

DIV_ROUND_UP_ULL() expands to do_div(), which casts its divisor to uint32_t. For any SPI clock rate >= 4,295 Hz, (u64)rate * NSEC_PER_MSEC exceeds U32_MAX, corrupting the timeout calculation, and when rate is a multiple of 67,108,864 Hz (2^26 Hz), the truncated 32-bit divisor becomes zero and causes a division-by-zero panic. In addition, because transfers run in 4-byte IRQ batches, computing the timeout from ideal wire speed alone leaves large high-speed transfers clamped at the 1000 ms floor despite per-batch interrupt and MMIO overhead; using DIV64_U64_ROUND_UP() avoids the divisor truncation.

[ ... ]

Quoted 5 lines
drivers/spi/spi-loongson-io.c new file +5 -0
+/**
+ * loongson_spi_io_set_cs() - Set the hardware chip-select output
+ * @spi: SPI target device
+ * @high: true to assert chip select
+ *

drivers/spi/spi-loongson-io.c line 288

Quoted 10 lines
drivers/spi/spi-loongson-io.c new file +10 -0
+ * The SSREV bit controls the hardware chip-select assertion state.
+ */
+static void loongson_spi_io_set_cs(struct spi_device *spi, bool high)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
+	u32 val = high ? LOONGSON_SPI_IO_CR1_SSREV : 0;
+
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+				 LOONGSON_SPI_IO_CR1_SSREV, val);
+}

[Severity: Low]
Is the @high polarity in loongson_spi_io_set_cs() inverted relative to the SPI core's set_cs() contract?

Because SPI_CS_HIGH is not set in host->mode_bits, spi_set_cs() passes high == false (logic low) to assert an active-low chip select and high == true (logic high) to deassert it. If LOONGSON_SPI_IO_CR1_SSREV asserts chip select as the comment states, the ternary condition is inverted; if it drives the CS line high, the kernel-doc comment is inverted.

[ ... ]

Quoted 5 lines
drivers/spi/spi-loongson-io.c new file +5 -0
+static irqreturn_t loongson_spi_io_irq_handler(int irq, void *dev_id)
+{
+	struct loongson_spi_priv *priv = dev_id;
+	u32 rx_data;
+	u32 sr1;

drivers/spi/spi-loongson-io.c line 492

Quoted 10 lines
drivers/spi/spi-loongson-io.c new file +10 -0
+
+	sr1 = loongson_spi_readl(priv, LOONGSON_SPI_IO_SR1_REG);
+
+	if (sr1 & LOONGSON_SPI_IO_SR1_ERR_MASK) {
+		dev_err(&priv->controller->dev, "SPI error: SR1=0x%x", sr1);
+		loongson_spi_writel(priv, LOONGSON_SPI_IO_IER_REG, 0);
+		priv->xfer_ret = -EIO;
+		complete(&priv->xfer_completion);
+		return IRQ_HANDLED;
+	}

[Severity: High]
Does the error path in loongson_spi_io_irq_handler() leave LOONGSON_SPI_IO_SR1_ERR_MASK latched in LOONGSON_SPI_IO_SR1_REG while none of the error interrupt bits are enabled in LOONGSON_SPI_IO_IER_REG?

loongson_spi_io_transfer_one() only enables LOONGSON_SPI_IO_IER_EOTIE, so an overrun, underrun, mode fault, or CRC error that halts a transfer before EOT never raises an interrupt and stalls until the transfer timeout. Conversely, because loongson_spi_io_irq_handler() does not mask sr1 against LOONGSON_SPI_IO_IER_REG and does not write LOONGSON_SPI_IO_SR1_ERR_MASK back to LOONGSON_SPI_IO_SR1_REG to clear the status bits, any latched error bit causes every subsequent interrupt from another device on the shared IRQ line to re-enter this error branch, log an error, and complete priv->xfer_completion while idle.

[ ... ]

Quoted 14 lines
drivers/spi/spi-loongson-io.c new file +14 -0
+	reinit_completion(&priv->xfer_completion);
+	priv->xfer_mode = XFER_INTERRUPT;
+
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+				 LOONGSON_SPI_IO_CR1_AUTOSUS,
+				 LOONGSON_SPI_IO_CR1_AUTOSUS);
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_IER_REG,
+				 LOONGSON_SPI_IO_IER_EOTIE,
+				 LOONGSON_SPI_IO_IER_EOTIE);
+
+	loongson_spi_io_start_batch(priv);
+
+	ret = wait_for_completion_timeout(&priv->xfer_completion,
+					  loongson_spi_io_timeout(priv, xfer));

drivers/spi/spi-loongson-io.c line 596

Quoted 10 lines
drivers/spi/spi-loongson-io.c new file +10 -0
+	priv->xfer_mode = XFER_IDLE;
+
+	if (ret == 0) {
+		loongson_spi_writel(priv, LOONGSON_SPI_IO_IER_REG, 0);
+		dev_err(&spi->dev, "Interrupt transfer timeout");
+		return -ETIMEDOUT;
+	}
+
+	return priv->xfer_ret;
+}

[Severity: Medium]
Can a timeout in loongson_spi_io_transfer_one() race with an in-flight loongson_spi_io_irq_handler() on another CPU?

CPU0 CPU1
loongson_spi_io_transfer_one()
wait_for_completion_timeout()
/* times out */

                                  loongson_spi_io_irq_handler()
                                    switch (priv->xfer_mode)
                                    case XFER_INTERRUPT:

priv->xfer_mode = XFER_IDLE;
loongson_spi_writel(..., IER_REG, 0);
return -ETIMEDOUT;
spi_transfer_one_message()
spi_dma_sync_for_cpu()

                                      memcpy(priv->rx_buf, ...)
                                      loongson_spi_io_start_batch()
                                        loongson_spi_update_bits(CR1_REG)
  spi_set_cs()
    loongson_spi_io_set_cs()
      loongson_spi_update_bits(CR1_REG)  <-- unlocked RMW race
  loongson_spi_io_handle_err()
    synchronize_irq(priv->irq)

Because loongson_spi_io_transfer_one() returns -ETIMEDOUT without a spinlock or synchronize_irq(priv->irq), spi_transfer_one_message() runs spi_dma_sync_for_cpu() and loongson_spi_io_set_cs() before calling loongson_spi_io_handle_err(). A concurrent ISR that already read XFER_INTERRUPT can touch priv->rx_buf and priv->tx_buf, start another hardware batch, and perform an unlocked read-modify-write on LOONGSON_SPI_IO_CR1_REG concurrently with loongson_spi_io_set_cs(), clobbering LOONGSON_SPI_IO_CR1_SSREV or LOONGSON_SPI_IO_CR1_CSTART.

[ ... ]

drivers/spi/spi-loongson-io.c line 715

Quoted 7 lines
drivers/spi/spi-loongson-io.c new file +7 -0
+	ret = devm_request_irq(dev, priv->irq, loongson_spi_io_irq_handler,
+			       IRQF_SHARED, dev_name(dev), priv);
+	if (ret)
+		return dev_err_probe(dev, ret, "failed to request IRQ");
+
+	loongson_spi_io_reginit(priv);
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_IER_REG, 0);

[Severity: Medium]
Can an interrupt on the shared IRQ line fire in loongson_spi_io_probe() before the controller registers are initialized and LOONGSON_SPI_IO_IER_REG is masked?

devm_request_irq() registers the IRQF_SHARED handler before loongson_spi_io_reginit() runs and before LOONGSON_SPI_IO_IER_REG is cleared (and without clearing stale status flags in LOONGSON_SPI_IO_SR1_REG). Similarly, in loongson_spi_io_transfer_one(), priv->xfer_mode = XFER_INTERRUPT and LOONGSON_SPI_IO_IER_EOTIE are set before loongson_spi_io_start_batch() initializes priv->batch_size and clears LOONGSON_SPI_IO_SR1_EOT, leaving a window where a shared or stale IRQ sees the previous transfer's priv->batch_size.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#7 lore raw

PATCH 4/5 spi: loongson-io: Add DMA support to SPI-IO driver

In reply to Binbin Zhou

Request optional "tx" and "rx" DMA channels. Their absence is non-fatal and leaves the driver in interrupt-only mode so probe does not fail when DMA providers are not yet available.

DMA is enabled for transfers that meet all of: four-byte alignment, length at or above the runtime-tunable dma_threshold, and both TX and RX buffers present.

---
 drivers/spi/spi-loongson-io.c | 399 +++++++++++++++++++++++++++++++++-
 1 file changed, 388 insertions(+), 11 deletions(-)
drivers/spi/spi-loongson-io.c +388 -11
index e273c9f4a943..c153e483ab41 100644
@@ -7,6 +7,8 @@
 #include <linux/bitfield.h>
 #include <linux/clk.h>
 #include <linux/completion.h>
+#include <linux/dmaengine.h>
+#include <linux/dma-mapping.h>
 #include <linux/err.h>
 #include <linux/interrupt.h>
 #include <linux/io.h>
@@ -14,6 +16,7 @@
 #include <linux/module.h>
 #include <linux/platform_device.h>
 #include <linux/spi/spi.h>
+#include <linux/scatterlist.h>
 #include <linux/string.h>
 
 /* Loongson SPI-IO Controller registers */
@@ -42,11 +45,20 @@
 
 /* Bitfields of LOONGSON_SPI_IO_CR2_REG */
 #define LOONGSON_SPI_IO_CR2_RXFTHLV		GENMASK(1, 0)
+#define LOONGSON_SPI_IO_CR2_RXDMAEN		BIT(7)
 #define LOONGSON_SPI_IO_CR2_TXFTHLV		GENMASK(9, 8)
+#define LOONGSON_SPI_IO_CR2_TXDMAEN		BIT(15)
+
+#define LOONGSON_SPI_IO_CR2_DMAEN_MASK		(LOONGSON_SPI_IO_CR2_RXDMAEN | \
+						 LOONGSON_SPI_IO_CR2_TXDMAEN)
+
+#define LOONGSON_SPI_IO_CR2_MAX_FTHLV		FIELD_MAX(LOONGSON_SPI_IO_CR2_RXFTHLV)
 
 /* Bitfields of LOONGSON_SPI_IO_CR3_REG */
 #define LOONGSON_SPI_IO_CR3_TSIZE		GENMASK(15, 0)
 
+#define LOONGSON_SPI_IO_MAX_FRAMES		(FIELD_MAX(LOONGSON_SPI_IO_CR3_TSIZE) + 1)
+
 /* Bitfields of LOONGSON_SPI_IO_CR4_REG */
 #define LOONGSON_SPI_IO_CR4_CTSIZE		GENMASK(15, 0)
 
@@ -118,10 +130,12 @@
  * enum xfer_mode - Loongson SPI transfer mode
  * @XFER_IDLE: no transfer is in progress
  * @XFER_INTERRUPT: interrupt-driven batch transfer
+ * @XFER_DMA: DMA-driven transfer
  */
 enum xfer_mode {
 	XFER_IDLE,
 	XFER_INTERRUPT,
+	XFER_DMA,
 };
 
 /**
@@ -141,6 +155,10 @@ enum xfer_mode {
  * @xfer_ret: result of the current transfer
  * @batch_size: number of bytes in the current interrupt batch
  * @xfer_completion: completion signaled when the current transfer finishes
+ * @dma_tx: DMA channel for TX
+ * @dma_rx: DMA channel for RX
+ * @use_dma: true if both DMA channels are available
+ * @phys_base: physical base address used for DMA slave configuration
  * @xfer_mode: current transfer mode
  */
 struct loongson_spi_priv {
@@ -160,9 +178,19 @@ struct loongson_spi_priv {
 	int			xfer_ret;
 	u32			batch_size;
 	struct completion	xfer_completion;
+
+	struct dma_chan		*dma_tx;
+	struct dma_chan		*dma_rx;
+	bool			use_dma;
+	phys_addr_t		phys_base;
 	enum xfer_mode		xfer_mode;
 };
 
+/* Module parameter: DMA threshold (bytes), adjustable at runtime */
+static unsigned int dma_threshold = 1024;
+module_param(dma_threshold, uint, 0644);
+MODULE_PARM_DESC(dma_threshold, "Minimum transfer length to use DMA (default 1024)");
+
 static void loongson_spi_writel(struct loongson_spi_priv *priv, u32 reg, u32 data)
 {
 	writel(data, priv->base + reg);
@@ -264,11 +292,59 @@ static unsigned long loongson_spi_io_timeout(struct loongson_spi_priv *priv,
 	return msecs_to_jiffies(max_t(u64, msec * 2, 1000));
 }
 
-static void loongson_spi_io_set_thresh(struct loongson_spi_priv *priv)
+static void loongson_spi_io_set_thresh(struct loongson_spi_priv *priv, bool dma)
 {
+	u32 val = 0;
+
+	if (dma)
+		val = FIELD_PREP(LOONGSON_SPI_IO_CR2_RXFTHLV, LOONGSON_SPI_IO_CR2_MAX_FTHLV) |
+		      FIELD_PREP(LOONGSON_SPI_IO_CR2_TXFTHLV, LOONGSON_SPI_IO_CR2_MAX_FTHLV);
+
 	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR2_REG,
 				 LOONGSON_SPI_IO_CR2_RXFTHLV |
-				 LOONGSON_SPI_IO_CR2_TXFTHLV, 0);
+				 LOONGSON_SPI_IO_CR2_TXFTHLV, val);
+}
+
+/**
+ * loongson_spi_io_dma_drain_rx() - Drain RX FIFO residue after DMA
+ * @priv: controller private data
+ * @xfer: completed SPI transfer
+ *
+ * DMA can leave a tail shorter than its request threshold in the RX FIFO.
+ * Both DMA channels must already be quiescent. Synchronize the RX mapping,
+ * append the residue to the receive buffer, then return mapping ownership
+ * to the device. Residue from a dummy RX buffer is discarded by SPI core.
+ */
+static void loongson_spi_io_dma_drain_rx(struct loongson_spi_priv *priv,
+					 struct spi_transfer *xfer)
+{
+	struct device *rx_dev = dmaengine_get_dma_device(priv->dma_rx);
+	u32 rxflv = FIELD_GET(LOONGSON_SPI_IO_SR2_RXFLV,
+			      loongson_spi_readl(priv, LOONGSON_SPI_IO_SR2_REG));
+	u8 frame_bytes = priv->frame_bytes;
+	u8 *dst = NULL;
+	u32 data;
+
+	if (!rxflv)
+		return;
+
+	if (xfer->rx_buf && rxflv <= xfer->len)
+		dst = (u8 *)xfer->rx_buf + xfer->len - rxflv;
+
+	/* SPI core skips cache sync while transfer_one() is running. */
+	dma_sync_sgtable_for_cpu(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
+	loongson_spi_io_set_thresh(priv, false);
+
+	while (rxflv) {
+		data = loongson_spi_io_read_dr(priv);
+		if (dst) {
+			memcpy(dst, &data, frame_bytes);
+			dst += frame_bytes;
+		}
+		rxflv -= frame_bytes;
+	}
+
+	dma_sync_sgtable_for_device(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
 }
 
 /**
@@ -423,6 +499,42 @@ static int loongson_spi_io_setup(struct spi_device *spi)
 	return 0;
 }
 
+/**
+ * loongson_spi_can_dma() - Check whether a transfer can use DMA
+ * @ctrl: SPI controller
+ * @spi: SPI target device
+ * @xfer: SPI transfer to check
+ *
+ * DMA requires both channels, a four-byte-aligned length and a transfer at
+ * least as large as dma_threshold. Three-wire transfers use interrupt mode
+ * because the DMA path requires both TX and RX scatterlists.
+ *
+ * Return: true when DMA is supported for @xfer.
+ */
+static bool loongson_spi_can_dma(struct spi_controller *ctrl, struct spi_device *spi,
+				 struct spi_transfer *xfer)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(ctrl);
+
+	if (!priv->use_dma)
+		return false;
+
+	/* The DMA path requires both TX and RX scatterlists. */
+	if (spi->mode & SPI_3WIRE)
+		return false;
+
+	if (xfer->len < dma_threshold)
+		return false;
+
+	if (!xfer->tx_buf && !xfer->rx_buf)
+		return false;
+
+	if (xfer->len % 4)
+		return false;
+
+	return true;
+}
+
 /**
  * loongson_spi_io_start_batch() - Start one interrupt-driven FIFO batch
  * @priv: controller private data
@@ -464,14 +576,191 @@ static int loongson_spi_io_start_batch(struct loongson_spi_priv *priv)
 	return batch_size;
 }
 
+/**
+ * loongson_spi_dma_config_and_submit() - Prepare RX and TX slave DMA
+ * @priv: controller private data
+ * @xfer: SPI transfer with scatterlists mapped by SPI core
+ *
+ * Configure both DMA channels for the shared data register and submit RX
+ * before TX. Descriptors remain pending until the caller issues them.
+ *
+ * Return: 0 on success, or a negative error code on configuration,
+ * preparation or submission failure.
+ */
+static int loongson_spi_dma_config_and_submit(struct loongson_spi_priv *priv,
+					      struct spi_transfer *xfer)
+{
+	struct dma_async_tx_descriptor *tx_desc, *rx_desc;
+	struct dma_slave_config tx_cfg = {0}, rx_cfg = {0};
+	struct device *dev = priv->dev;
+	int ret;
+
+	tx_cfg.direction = DMA_MEM_TO_DEV;
+	tx_cfg.dst_addr = priv->phys_base + LOONGSON_SPI_IO_DR_REG;
+	tx_cfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
+	tx_cfg.dst_maxburst = 1;
+
+	ret = dmaengine_slave_config(priv->dma_tx, &tx_cfg);
+	if (ret) {
+		dev_err(dev, "TX DMA config failed: %d", ret);
+		return ret;
+	}
+
+	rx_cfg.direction = DMA_DEV_TO_MEM;
+	rx_cfg.src_addr = priv->phys_base + LOONGSON_SPI_IO_DR_REG;
+	rx_cfg.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
+	rx_cfg.src_maxburst = 1;
+
+	ret = dmaengine_slave_config(priv->dma_rx, &rx_cfg);
+	if (ret) {
+		dev_err(dev, "RX DMA config failed: %d", ret);
+		return ret;
+	}
+
+	rx_desc = dmaengine_prep_slave_sg(priv->dma_rx, xfer->rx_sg.sgl,
+					  xfer->rx_sg.nents, DMA_DEV_TO_MEM,
+					  DMA_CTRL_ACK);
+	if (!rx_desc) {
+		dev_err(dev, "RX DMA prep_slave_sg failed");
+		return -EINVAL;
+	}
+
+	ret = dma_submit_error(dmaengine_submit(rx_desc));
+	if (ret) {
+		dev_err(dev, "RX DMA submit failed");
+		return ret;
+	}
+
+	tx_desc = dmaengine_prep_slave_sg(priv->dma_tx, xfer->tx_sg.sgl,
+					  xfer->tx_sg.nents, DMA_MEM_TO_DEV,
+					  DMA_CTRL_ACK);
+	if (!tx_desc) {
+		dev_err(dev, "TX DMA prep_slave_sg failed");
+		return -EINVAL;
+	}
+
+	ret = dma_submit_error(dmaengine_submit(tx_desc));
+	if (ret) {
+		dev_err(dev, "TX DMA submit failed");
+		return ret;
+	}
+
+	return 0;
+}
+
+/**
+ * loongson_spi_dma_wait_eot() - Wait for the current DMA chunk to finish
+ * @priv: controller private data
+ * @xfer: SPI transfer used to calculate the timeout
+ *
+ * Return: 0 after EOT, %-ETIMEDOUT if EOT does not arrive, or the error
+ * recorded by the IRQ handler.
+ */
+static int loongson_spi_dma_wait_eot(struct loongson_spi_priv *priv,
+				     struct spi_transfer *xfer)
+{
+	if (!wait_for_completion_timeout(&priv->xfer_completion,
+					 loongson_spi_io_timeout(priv, xfer))) {
+		dev_err(priv->dev, "DMA transfer timeout (no EOT)");
+		return -ETIMEDOUT;
+	}
+
+	return priv->xfer_ret;
+}
+
+/**
+ * loongson_spi_dma_transfer() - Run one DMA-driven SPI transfer
+ * @priv: controller private data
+ * @xfer: SPI transfer with TX and RX scatterlists
+ * @bus_started: set to true once CSTART has been written
+ *
+ * One pair of DMA descriptors covers the complete transfer. The SPI engine
+ * is restarted in chunks of at most %LOONGSON_SPI_IO_MAX_FRAMES because its
+ * transfer-count register is 16 bits wide. RX is issued before TX.
+ *
+ * All exits disable and synchronize both DMA channels. A successful transfer
+ * then drains the RX FIFO residue. @bus_started tells the caller whether a
+ * failure can safely retry the transfer in interrupt mode: once it is true,
+ * retrying would duplicate bus traffic and is therefore not allowed.
+ *
+ * Return: 0 on success, or a negative error code.
+ */
+static int loongson_spi_dma_transfer(struct loongson_spi_priv *priv,
+				     struct spi_transfer *xfer,
+				     bool *bus_started)
+{
+	u32 frames = xfer->len / priv->frame_bytes;
+	u32 done, chunk_frames;
+	int ret;
+
+	*bus_started = false;
+
+	ret = loongson_spi_dma_config_and_submit(priv, xfer);
+	if (ret)
+		goto out_stop;
+
+	priv->xfer_ret = 0;
+	priv->xfer_mode = XFER_DMA;
+
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+				 LOONGSON_SPI_IO_CR1_AUTOSUS,
+				 LOONGSON_SPI_IO_CR1_AUTOSUS);
+
+	/* RX must be ready before TX can start filling the controller FIFO. */
+	dma_async_issue_pending(priv->dma_rx);
+	dma_async_issue_pending(priv->dma_tx);
+
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR2_REG,
+				 LOONGSON_SPI_IO_CR2_DMAEN_MASK,
+				 LOONGSON_SPI_IO_CR2_DMAEN_MASK);
+
+	for (done = 0; done < frames; done += chunk_frames) {
+		chunk_frames = min_t(u32, frames - done,
+				     LOONGSON_SPI_IO_MAX_FRAMES);
+
+		priv->xfer_ret = 0;
+		reinit_completion(&priv->xfer_completion);
+		loongson_spi_writel(priv, LOONGSON_SPI_IO_CR3_REG,
+				    chunk_frames - 1);
+		loongson_spi_writel(priv, LOONGSON_SPI_IO_CR4_REG, 0);
+		loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
+				    LOONGSON_SPI_IO_SR1_EOT);
+
+		*bus_started = true;
+		loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+					 LOONGSON_SPI_IO_CR1_CSTART,
+					 LOONGSON_SPI_IO_CR1_CSTART);
+
+		ret = loongson_spi_dma_wait_eot(priv, xfer);
+		if (ret)
+			break;
+	}
+
+out_stop:
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+				 LOONGSON_SPI_IO_CR1_CSTART, 0);
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR2_REG,
+				 LOONGSON_SPI_IO_CR2_DMAEN_MASK, 0);
+	priv->xfer_mode = XFER_IDLE;
+
+	/* Quiesce DMA before letting the CPU handle the RX FIFO residue. */
+	dmaengine_terminate_sync(priv->dma_tx);
+	dmaengine_terminate_sync(priv->dma_rx);
+
+	if (!ret && *bus_started)
+		loongson_spi_io_dma_drain_rx(priv, xfer);
+
+	return ret;
+}
+
 /**
  * loongson_spi_io_irq_handler() - Handle SPI error and end-of-transfer IRQs
  * @irq: interrupt number
  * @dev_id: controller private data
  *
  * In interrupt mode, consume the current RX batch and start the next one.
- * Controller errors disable further interrupts and complete the wait with an
- * error status.
+ * In DMA mode, stop the engine and wake the chunk waiter. Controller errors
+ * disable further interrupts and complete the wait with an error status.
  *
  * Return: %IRQ_HANDLED for a recognized error or EOT, otherwise %IRQ_NONE.
  */
@@ -497,6 +786,12 @@ static irqreturn_t loongson_spi_io_irq_handler(int irq, void *dev_id)
 	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG, LOONGSON_SPI_IO_SR1_EOT);
 
 	switch (priv->xfer_mode) {
+	case XFER_DMA:
+		loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+					 LOONGSON_SPI_IO_CR1_CSTART, 0);
+		priv->xfer_ret = 0;
+		complete(&priv->xfer_completion);
+		break;
 	case XFER_INTERRUPT:
 		for (unsigned int i = 0; i < priv->batch_size;
 		     i += priv->frame_bytes) {
@@ -534,8 +829,10 @@ static irqreturn_t loongson_spi_io_irq_handler(int irq, void *dev_id)
  * @spi: SPI target device
  * @xfer: transfer to execute
  *
- * Apply clock, mode and pin-direction state before running interrupt-driven
- * FIFO batches.
+ * Apply clock, mode and pin-direction state before selecting DMA or
+ * interrupt-driven FIFO batches. DMA setup failures may fall back to
+ * interrupt mode only while the bus has not started; runtime DMA failures
+ * are returned to SPI core without replaying the transfer.
  *
  * Return: 0 on success, or a negative error code.
  */
@@ -543,6 +840,8 @@ static int loongson_spi_io_transfer_one(struct spi_controller *ctrl, struct spi_
 					struct spi_transfer *xfer)
 {
 	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
+	bool bus_started = false;
+	bool use_dma;
 	int ret;
 
 	loongson_spi_io_update_state(spi, xfer);
@@ -563,7 +862,27 @@ static int loongson_spi_io_transfer_one(struct spi_controller *ctrl, struct spi_
 	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
 			    LOONGSON_SPI_IO_SR1_EOT | LOONGSON_SPI_IO_SR1_ERR_MASK);
 
-	loongson_spi_io_set_thresh(priv);
+	use_dma = ctrl->can_dma && ctrl->can_dma(ctrl, spi, xfer);
+	loongson_spi_io_set_thresh(priv, use_dma);
+
+	if (use_dma) {
+		loongson_spi_update_bits(priv, LOONGSON_SPI_IO_SR1_REG,
+					 LOONGSON_SPI_IO_SR1_EOT,
+					 LOONGSON_SPI_IO_SR1_EOT);
+		loongson_spi_update_bits(priv, LOONGSON_SPI_IO_IER_REG,
+					 LOONGSON_SPI_IO_IER_EOTIE,
+					 LOONGSON_SPI_IO_IER_EOTIE);
+		ret = loongson_spi_dma_transfer(priv, xfer, &bus_started);
+		if (!ret)
+			return 0;
+		if (bus_started) {
+			dev_err(&spi->dev, "DMA transfer failed: %d", ret);
+			return ret;
+		}
+
+		dev_dbg(&spi->dev, "DMA setup failed (%d), using interrupt mode", ret);
+		loongson_spi_io_set_thresh(priv, false);
+	}
 
 	priv->tx_buf = xfer->tx_buf;
 	priv->rx_buf = xfer->rx_buf;
@@ -622,8 +941,8 @@ static void loongson_spi_io_reginit(struct loongson_spi_priv *priv)
  * @ctrl: SPI controller
  * @msg: failed SPI message
  *
- * Stop the engine, discard stale RX FIFO data, clear status and software
- * transfer state, then restore the basic configuration.
+ * Stop the engine and DMA channels, discard stale RX FIFO data, clear
+ * status and software transfer state, then restore the basic configuration.
  */
 static void loongson_spi_io_handle_err(struct spi_controller *ctrl,
 				       struct spi_message *msg)
@@ -635,8 +954,15 @@ static void loongson_spi_io_handle_err(struct spi_controller *ctrl,
 
 	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
 				 LOONGSON_SPI_IO_CR1_START_MASK, 0);
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR2_REG,
+				 LOONGSON_SPI_IO_CR2_DMAEN_MASK, 0);
 
-	loongson_spi_io_set_thresh(priv);
+	loongson_spi_io_set_thresh(priv, false);
+
+	if (priv->use_dma) {
+		dmaengine_terminate_sync(priv->dma_tx);
+		dmaengine_terminate_sync(priv->dma_rx);
+	}
 
 	while (FIELD_GET(LOONGSON_SPI_IO_SR2_RXFLV,
 			 loongson_spi_readl(priv, LOONGSON_SPI_IO_SR2_REG)))
@@ -656,11 +982,40 @@ static void loongson_spi_io_handle_err(struct spi_controller *ctrl,
 	loongson_spi_io_reginit(priv);
 }
 
+/**
+ * loongson_spi_io_request_dma_chan() - Request an optional DMA channel
+ * @dev: controller device
+ * @name: DMA channel name, either "tx" or "rx"
+ *
+ * Absence of either channel is non-fatal and selects interrupt-only mode.
+ * Probe deferral is preserved so the DMA provider can be probed later.
+ *
+ * Return: a DMA channel on success, NULL when unavailable, or an ERR_PTR
+ * containing %-EPROBE_DEFER.
+ */
+static struct dma_chan *loongson_spi_io_request_dma_chan(struct device *dev,
+							 const char *name)
+{
+	struct dma_chan *chan = devm_dma_request_chan(dev, name);
+
+	if (IS_ERR(chan)) {
+		int ret = PTR_ERR(chan);
+
+		if (ret == -EPROBE_DEFER)
+			return chan;
+		dev_info(dev, "%s DMA unavailable with %d, using interrupt mode", name, ret);
+		return NULL;
+	}
+
+	return chan;
+}
+
 static int loongson_spi_io_probe(struct platform_device *pdev)
 {
 	struct device *dev = &pdev->dev;
 	struct loongson_spi_priv *priv;
 	struct spi_controller *host;
+	struct resource *res;
 	struct clk *clk;
 	int ret;
 
@@ -679,13 +1034,15 @@ static int loongson_spi_io_probe(struct platform_device *pdev)
 
 	priv = spi_controller_get_devdata(host);
 
-	priv->base = devm_platform_ioremap_resource(pdev, 0);
+	priv->base = devm_platform_get_and_ioremap_resource(pdev, 0, &res);
 	if (IS_ERR(priv->base))
 		return PTR_ERR(priv->base);
 
 	priv->controller = host;
+	priv->phys_base = res->start;
 	priv->dev = dev;
 	priv->xfer_mode = XFER_IDLE;
+	priv->use_dma = false;
 	priv->batch_size = 0;
 
 	init_completion(&priv->xfer_completion);
@@ -702,6 +1059,26 @@ static int loongson_spi_io_probe(struct platform_device *pdev)
 	host->min_speed_hz = (u32)min_t(u64, DIV_ROUND_UP_ULL(priv->clk_rate, 255),
 					U32_MAX);
 
+	priv->dma_tx = loongson_spi_io_request_dma_chan(dev, "tx");
+	if (IS_ERR(priv->dma_tx))
+		return PTR_ERR(priv->dma_tx);
+
+	priv->dma_rx = loongson_spi_io_request_dma_chan(dev, "rx");
+	if (IS_ERR(priv->dma_rx))
+		return PTR_ERR(priv->dma_rx);
+
+	if (priv->dma_tx && priv->dma_rx) {
+		priv->use_dma = true;
+		/* Let SPI core provide and map dummy buffers for full-duplex DMA. */
+		host->flags |= SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX;
+		host->dma_tx = priv->dma_tx;
+		host->dma_rx = priv->dma_rx;
+		host->can_dma = loongson_spi_can_dma;
+		dev_info(dev, "DMA channels acquired");
+	} else {
+		dev_info(dev, "DMA unavailable, using interrupt mode only");
+	}
+
 	priv->irq = platform_get_irq(pdev, 0);
 	if (priv->irq < 0)
 		return dev_err_probe(dev, priv->irq, "no IRQ resource");
Signature · 1 line
2.52.0
#8 lore raw

Re: [PATCH 4/5] spi: loongson-io: Add DMA support to SPI-IO driver

Thank you for your contribution! Sashiko AI review found 8 potential issues to consider: - [High] spi: loongson-io: device DMA sync in loongson_spi_io_dma_drain_rx() loses tail - [High] spi…

Thank you for your contribution! Sashiko AI review found 8 potential issues to consider:
- [High] spi: loongson-io: device DMA sync in loongson_spi_io_dma_drain_rx() loses tail
- [High] spi: loongson-io: ERR_PTR dereference in loongson_spi_dma_config_and_submit()
- [Medium] spi: loongson-io: PIO fallback in loongson_spi_io_transfer_one() corrupts RX
- [Medium] spi: loongson-io: loongson_spi_io_transfer_one() re-evaluates can_dma()
- [Medium] spi: loongson-io: EOT IRQ left enabled after loongson_spi_dma_transfer()
- [Medium] spi: loongson-io: leaked TX DMA channel in loongson_spi_io_probe() fallback
- [Medium] spi: loongson-io: missing buffer alignment and presence checks in loongson_spi_can_dma()
- [Low] spi: loongson-io: unmasked EOTIE on exit in loongson_spi_dma_transfer()
--

commit b9f174f53160693a3668bfcf2827fd85a0dafb9d
Author: Binbin Zhou <[email protected]>

spi: loongson-io: Add DMA support to SPI-IO driver

This commit adds optional TX and RX DMA channel support to the Loongson SPI-IO controller driver, falling back to interrupt mode when DMA is unavailable or below the transfer threshold.

Quoted 4 lines
drivers/spi/spi-loongson-io.c +0 -0
index e273c9f4a9430..c153e483ab41d 100644

[ ... ]

Quoted 3 lines
drivers/spi/spi-loongson-io.c +0 -0
@@ -264,11 +292,59 @@ static unsigned long loongson_spi_io_timeout(struct loongson_spi_priv *priv,
 	return msecs_to_jiffies(max_t(u64, msec * 2, 1000));
 }

[ ... ]

Quoted 21 lines
drivers/spi/spi-loongson-io.c +21 -0
+static void loongson_spi_io_dma_drain_rx(struct loongson_spi_priv *priv,
+					 struct spi_transfer *xfer)
+{
+	struct device *rx_dev = dmaengine_get_dma_device(priv->dma_rx);
+	u32 rxflv = FIELD_GET(LOONGSON_SPI_IO_SR2_RXFLV,
+			      loongson_spi_readl(priv, LOONGSON_SPI_IO_SR2_REG));
+	u8 frame_bytes = priv->frame_bytes;
+	u8 *dst = NULL;
+	u32 data;
+
+	if (!rxflv)
+		return;
+
+	if (xfer->rx_buf && rxflv <= xfer->len)
+		dst = (u8 *)xfer->rx_buf + xfer->len - rxflv;
+
+	/* SPI core skips cache sync while transfer_one() is running. */
+	dma_sync_sgtable_for_cpu(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
+	loongson_spi_io_set_thresh(priv, false);
+
+	while (rxflv) {

drivers/spi/spi-loongson-io.c static unsigned long loongson_spi_io_timeout(struct loongson_spi_priv *priv,

Quoted 10 lines
drivers/spi/spi-loongson-io.c +10 -0
+		data = loongson_spi_io_read_dr(priv);
+		if (dst) {
+			memcpy(dst, &data, frame_bytes);
+			dst += frame_bytes;
+		}
+		rxflv -= frame_bytes;
+	}
+
+	dma_sync_sgtable_for_device(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
+}

[Severity: High]
Does the final dma_sync_sgtable_for_device(..., DMA_FROM_DEVICE) cause the drained tail bytes in xfer->rx_buf to be overwritten when transfer_one() returns?

When loongson_spi_io_transfer_one() returns 0, spi_transfer_one_message() calls spi_dma_sync_for_cpu(), which runs dma_sync_sgtable_for_cpu(..., DMA_FROM_DEVICE) on xfer->rx_sg. For a DMA_FROM_DEVICE mapping, syncing for the device does not copy CPU writes into an active SWIOTLB bounce buffer (and invalidates cache lines on non-coherent DMA), so the subsequent sync for the CPU copies the stale bounce buffer back over the bytes memcpy() just wrote into xfer->rx_buf.

[ ... ]

Quoted 29 lines
drivers/spi/spi-loongson-io.c +25 -0
@@ -423,6 +499,42 @@ static int loongson_spi_io_setup(struct spi_device *spi)
 	return 0;
 }
 
+/**
+ * loongson_spi_can_dma() - Check whether a transfer can use DMA
+ * @ctrl: SPI controller
+ * @spi: SPI target device
+ * @xfer: SPI transfer to check
+ *
+ * DMA requires both channels, a four-byte-aligned length and a transfer at
+ * least as large as dma_threshold. Three-wire transfers use interrupt mode
+ * because the DMA path requires both TX and RX scatterlists.
+ *
+ * Return: true when DMA is supported for @xfer.
+ */
+static bool loongson_spi_can_dma(struct spi_controller *ctrl, struct spi_device *spi,
+				 struct spi_transfer *xfer)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(ctrl);
+
+	if (!priv->use_dma)
+		return false;
+
+	/* The DMA path requires both TX and RX scatterlists. */
+	if (spi->mode & SPI_3WIRE)
+		return false;
+
+	if (xfer->len < dma_threshold)

drivers/spi/spi-loongson-io.c static int loongson_spi_io_setup(struct spi_device *spi) · line 536

Quoted 10 lines
drivers/spi/spi-loongson-io.c +10 -0
+		return false;
+
+	if (!xfer->tx_buf && !xfer->rx_buf)
+		return false;
+
+	if (xfer->len % 4)
+		return false;
+
+	return true;
+}

[Severity: Medium]
Does loongson_spi_can_dma() also need to check that xfer->tx_buf and xfer->rx_buf are both non-NULL and 4-byte aligned, and that xfer->len is non-zero?

loongson_spi_dma_config_and_submit() configures DMA_SLAVE_BUSWIDTH_4_BYTES on both channels. When an unaligned vmalloc buffer is split at page boundaries by spi_map_buf_attrs(), each scatterlist segment length is PAGE_SIZE - offset_in_page(buf) (not a multiple of 4), and loongson2_cmc_dma_prep_slave_sg() rounds each segment up with DIV_ROUND_UP(sg_dma_len(sg), 4), reading or writing extra bytes across segment boundaries.

In addition, checking (!xfer->tx_buf && !xfer->rx_buf) allows a transfer with only one buffer to pass if dummy buffer allocation is not active, and if dma_threshold is set to 0 via sysfs, a transfer with xfer->len == 0 passes loongson_spi_can_dma() and fails in sg_alloc_table() with -EINVAL.

Quoted 3 lines
drivers/spi/spi-loongson-io.c +0 -0
@@ -464,14 +576,191 @@ static int loongson_spi_io_start_batch(struct loongson_spi_priv *priv)
 	return batch_size;
 }

[ ... ]

Quoted 3 lines
drivers/spi/spi-loongson-io.c +3 -0
+static int loongson_spi_dma_config_and_submit(struct loongson_spi_priv *priv,
+					      struct spi_transfer *xfer)
+{

[ ... ]

Quoted 13 lines
drivers/spi/spi-loongson-io.c +13 -0
+	rx_desc = dmaengine_prep_slave_sg(priv->dma_rx, xfer->rx_sg.sgl,
+					  xfer->rx_sg.nents, DMA_DEV_TO_MEM,
+					  DMA_CTRL_ACK);
+	if (!rx_desc) {
+		dev_err(dev, "RX DMA prep_slave_sg failed");
+		return -EINVAL;
+	}
+
+	ret = dma_submit_error(dmaengine_submit(rx_desc));
+	if (ret) {
+		dev_err(dev, "RX DMA submit failed");
+		return ret;
+	}

drivers/spi/spi-loongson-io.c static int loongson_spi_io_start_batch(struct loongson_spi_priv *priv) · line 642

Quoted 10 lines
drivers/spi/spi-loongson-io.c +10 -0
+
+	tx_desc = dmaengine_prep_slave_sg(priv->dma_tx, xfer->tx_sg.sgl,
+					  xfer->tx_sg.nents, DMA_MEM_TO_DEV,
+					  DMA_CTRL_ACK);
+	if (!tx_desc) {
+		dev_err(dev, "TX DMA prep_slave_sg failed");
+		return -EINVAL;
+	}
+
+	ret = dma_submit_error(dmaengine_submit(tx_desc));

[Severity: High]
Can rx_desc or tx_desc be an ERR_PTR here, causing dmaengine_submit() to dereference an error pointer?

The paired DMA engine driver returns ERR_PTR(-ENOMEM) or ERR_PTR(-EINVAL) on failure rather than NULL:

drivers/dma/loongson/loongson2-apb-cmc-dma.c:loongson2_cmc_dma_prep_slave_sg() {
	...
	desc = kzalloc_flex(*desc, sg_req, sg_len, GFP_NOWAIT);
	if (!desc)
		return ERR_PTR(-ENOMEM);
	...
}

Using IS_ERR_OR_NULL() on rx_desc and tx_desc avoids dereferencing the error pointer in dmaengine_submit().

[ ... ]

Quoted 4 lines
drivers/spi/spi-loongson-io.c +4 -0
+static int loongson_spi_dma_transfer(struct loongson_spi_priv *priv,
+				     struct spi_transfer *xfer,
+				     bool *bus_started)
+{

[ ... ]

drivers/spi/spi-loongson-io.c static int loongson_spi_io_start_batch(struct loongson_spi_priv *priv) · line 744

Quoted 6 lines
drivers/spi/spi-loongson-io.c +6 -0
+out_stop:
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+				 LOONGSON_SPI_IO_CR1_CSTART, 0);
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR2_REG,
+				 LOONGSON_SPI_IO_CR2_DMAEN_MASK, 0);
+	priv->xfer_mode = XFER_IDLE;

[Severity: Low]
Should out_stop also clear LOONGSON_SPI_IO_IER_EOTIE in LOONGSON_SPI_IO_IER_REG?

loongson_spi_io_transfer_one() enables LOONGSON_SPI_IO_IER_EOTIE before calling loongson_spi_dma_transfer(), and neither the XFER_DMA IRQ path nor out_stop masks it again, leaving EOT interrupts enabled while priv->xfer_mode is XFER_IDLE.

[ ... ]

drivers/spi/spi-loongson-io.c static irqreturn_t loongson_spi_io_irq_handler(int irq, void *dev_id) · line 794

Quoted 10 lines
drivers/spi/spi-loongson-io.c +6 -0
@@ -497,6 +786,12 @@ static irqreturn_t loongson_spi_io_irq_handler(int irq, void *dev_id)
 	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG, LOONGSON_SPI_IO_SR1_EOT);
 
 	switch (priv->xfer_mode) {
+	case XFER_DMA:
+		loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+					 LOONGSON_SPI_IO_CR1_CSTART, 0);
+		priv->xfer_ret = 0;
+		complete(&priv->xfer_completion);
+		break;

[Severity: Medium]
If loongson_spi_dma_wait_eot() times out, can a late EOT interrupt race with out_stop on LOONGSON_SPI_IO_CR1_REG and priv->xfer_mode?

CPU0 CPU1 (<hardirq>)
loongson_spi_dma_transfer()
loongson_spi_dma_wait_eot()

    /* times out */
  out_stop:
    loongson_spi_update_bits(...,
      LOONGSON_SPI_IO_CR1_REG, ...)
                                        loongson_spi_io_irq_handler()
                                          case XFER_DMA:
                                            loongson_spi_update_bits(...,
                                              LOONGSON_SPI_IO_CR1_REG, ...)
    priv->xfer_mode = XFER_IDLE;

Because LOONGSON_SPI_IO_IER_EOTIE is still enabled when loongson_spi_dma_wait_eot() times out, loongson_spi_io_irq_handler() can run concurrently with out_stop and perform an unsynchronized read-modify-write on LOONGSON_SPI_IO_CR1_REG, or fire after priv->xfer_mode is set to XFER_IDLE.

[ ... ]

drivers/spi/spi-loongson-io.c static int loongson_spi_io_transfer_one(struct spi_controller *ctrl, struct spi_ · line 866

Quoted 7 lines
drivers/spi/spi-loongson-io.c +2 -1
@@ -563,7 +862,27 @@ static int loongson_spi_io_transfer_one(struct spi_controller *ctrl, struct spi_
 	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
 			    LOONGSON_SPI_IO_SR1_EOT | LOONGSON_SPI_IO_SR1_ERR_MASK);
 
-	loongson_spi_io_set_thresh(priv);
+	use_dma = ctrl->can_dma && ctrl->can_dma(ctrl, spi, xfer);
+	loongson_spi_io_set_thresh(priv, use_dma);

[Severity: Medium]
Can calling ctrl->can_dma() again here disagree with the mapping decision __spi_map_msg() already made for this transfer?

Because dma_threshold is writable at runtime (mode 0644), changing it between __spi_map_msg() and loongson_spi_io_transfer_one() can make can_dma() transition from false to true, causing loongson_spi_dma_config_and_submit() to submit unmapped scatterlists with nents == 0 (which makes loongson2_cmc_dma_prep_slave_sg() allocate a 0-element sg_req[] array and loongson2_cmc_dma_start_transfer() read sg_req[0] out of bounds). If dma_threshold is raised instead, the driver takes the interrupt PIO path while xfer->rx_sg is mapped and owned by the DMA device, so SPI core's post-transfer spi_dma_sync_for_cpu() overwrites xfer->rx_buf. Checking xfer->tx_sg_mapped && xfer->rx_sg_mapped here avoids both mismatches.

Quoted 9 lines
drivers/spi/spi-loongson-io.c +9 -0
+
+	if (use_dma) {
+		loongson_spi_update_bits(priv, LOONGSON_SPI_IO_SR1_REG,
+					 LOONGSON_SPI_IO_SR1_EOT,
+					 LOONGSON_SPI_IO_SR1_EOT);
+		loongson_spi_update_bits(priv, LOONGSON_SPI_IO_IER_REG,
+					 LOONGSON_SPI_IO_IER_EOTIE,
+					 LOONGSON_SPI_IO_IER_EOTIE);
+		ret = loongson_spi_dma_transfer(priv, xfer, &bus_started);

drivers/spi/spi-loongson-io.c static int loongson_spi_io_transfer_one(struct spi_controller *ctrl, struct spi_ · line 885

Quoted 10 lines
drivers/spi/spi-loongson-io.c +10 -0
+		if (!ret)
+			return 0;
+		if (bus_started) {
+			dev_err(&spi->dev, "DMA transfer failed: %d", ret);
+			return ret;
+		}
+
+		dev_dbg(&spi->dev, "DMA setup failed (%d), using interrupt mode", ret);
+		loongson_spi_io_set_thresh(priv, false);
+	}

[Severity: Medium]
When DMA setup fails before bus_started is set, does falling through to interrupt mode corrupt xfer->rx_buf because xfer->tx_sg and xfer->rx_sg are still mapped and synced for the DMA device?

spi_transfer_one_message() calls spi_dma_sync_for_device() before transfer_one() and spi_dma_sync_for_cpu() after transfer_one() returns 0. If the driver runs PIO in place while xfer->rx_sg_mapped is true, the post-transfer spi_dma_sync_for_cpu() copies the untouched SWIOTLB bounce buffer over the PIO-received data in xfer->rx_buf. Setting xfer->error |= SPI_TRANS_FAIL_NO_START and returning ret lets spi_transfer_one_message() unmap the scatterlists and retry via its fallback_pio path.

[ ... ]

Quoted 13 lines
drivers/spi/spi-loongson-io.c +9 -0
@@ -702,6 +1059,26 @@ static int loongson_spi_io_probe(struct platform_device *pdev)
 	host->min_speed_hz = (u32)min_t(u64, DIV_ROUND_UP_ULL(priv->clk_rate, 255),
 					U32_MAX);
 
+	priv->dma_tx = loongson_spi_io_request_dma_chan(dev, "tx");
+	if (IS_ERR(priv->dma_tx))
+		return PTR_ERR(priv->dma_tx);
+
+	priv->dma_rx = loongson_spi_io_request_dma_chan(dev, "rx");
+	if (IS_ERR(priv->dma_rx))
+		return PTR_ERR(priv->dma_rx);
+
+	if (priv->dma_tx && priv->dma_rx) {

drivers/spi/spi-loongson-io.c static int loongson_spi_io_probe(struct platform_device *pdev) · line 1080

Quoted 10 lines
drivers/spi/spi-loongson-io.c +10 -0
+		priv->use_dma = true;
+		/* Let SPI core provide and map dummy buffers for full-duplex DMA. */
+		host->flags |= SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX;
+		host->dma_tx = priv->dma_tx;
+		host->dma_rx = priv->dma_rx;
+		host->can_dma = loongson_spi_can_dma;
+		dev_info(dev, "DMA channels acquired");
+	} else {
+		dev_info(dev, "DMA unavailable, using interrupt mode only");
+	}

[Severity: Medium]
If one DMA channel is acquired and the other returns NULL, does the else branch leave the acquired channel allocated while running in interrupt-only mode?

Because devm_dma_request_chan() only releases the channel when the device is unbound, the unused channel remains held for the lifetime of the SPI controller unless the else branch releases a non-NULL priv->dma_tx or priv->dma_rx.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#9 lore raw

PATCH 5/5 MAINTAINERS: Add myself as Loongson SPI maintainer

In reply to Binbin Zhou

Add myself as a maintainer for the Loongson SPI driver. I have been working on the Loongson SPI flash and SPI IO controller drivers and would like to help review and maintain them.

---
 MAINTAINERS | 1 +
 1 file changed, 1 insertion(+)
MAINTAINERS +1 -0
index 70789ce6e507..8223f1b61348 100644
@@ -15738,6 +15738,7 @@ F:	include/dt-bindings/clock/loongson,ls2k-clk.h
 
 LOONGSON SPI DRIVER
 M:	Yinbo Zhu <[email protected]>
+M:	Binbin Zhou <[email protected]>
 L:	[email protected]
 S:	Maintained
 F:	Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml
Signature · 1 line
2.52.0