Devicetree
 help / color / mirror / Atom feed
* [PATCH v2 0/5] spi: loongson: SPI-IO driver for Loongson-2K0300
@ 2026-11-30  2:32 Binbin Zhou
  2026-11-30  2:33 ` [PATCH v2 1/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi compatible Binbin Zhou
                   ` (4 more replies)
  0 siblings, 5 replies; 8+ messages in thread
From: Binbin Zhou @ 2026-11-30  2:32 UTC (permalink / raw)
  To: Binbin Zhou, Huacai Chen, Rob Herring, Krzysztof Kozlowski,
	Conor Dooley, Yinbo Zhu, Mark Brown
  Cc: Huacai Chen, Xuerui Wang, loongarch, devicetree, linux-spi,
	Bingxiong Li, Binbin Zhou

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

========
V2:
Issues from sashiko.

Patch (2/5):
  - Add Acked-by tag from Conor, thanks.
Patch (3/5):
  - Drop SPI_3WIRE support;
  - Add optimize_message()/prepare_message()/unprepare_message() callbacks;
  - Split transfer_one() into setup_transfer()/transfer_one_irq()/
    transfer_one_dma(), and share the idle restore via reset_state()
    between handle_err() and unprepare_message().
  - Enable the OVR/UDR/CRC/MODF interrupts (new IER_ERR_MASK); in the IRQ
    handler clear the W1C status first and ignore errors while idle.
  - Use DIV64_U64_ROUND_UP() for the timeout math (fixes 32-bit builds) and
    derive max/min_speed_hz from the CFG2_BRINT limits.
  - Request the IRQ without IRQF_SHARED, use a fixed "loongson-spi-io" name,
    and initialize the controller before requesting the IRQ.
Patch (4/5):
  - Tighten can_dma(): require both tx_buf and rx_buf, non-zero length,
    4-byte aligned length and buffers.
  - Return PTR_ERR()/-ENOMEM on dmaengine_prep_slave_sg() failure instead of a
    fixed -EINVAL, so the fallback to interrupt mode is taken correctly.

Link to V1:
https://lore.kernel.org/all/cover.1795425389.git.zhoubinbin@loongson.cn/

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: Add spi-io interrupt-driven driver
  spi: loongson: 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                 | 1206 +++++++++++++++++
 5 files changed, 1270 insertions(+)
 create mode 100644 drivers/spi/spi-loongson-io.c


base-commit: 543bc7b4337302ae75119059bdeff6df8eb34b56
-- 
2.52.0


^ permalink raw reply	[flat|nested] 8+ messages in thread

* [PATCH v2 1/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi compatible
  2026-11-30  2:32 [PATCH v2 0/5] spi: loongson: SPI-IO driver for Loongson-2K0300 Binbin Zhou
@ 2026-11-30  2:33 ` Binbin Zhou
  2026-11-30  2:33 ` [PATCH v2 2/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi-io compatible Binbin Zhou
                   ` (3 subsequent siblings)
  4 siblings, 0 replies; 8+ messages in thread
From: Binbin Zhou @ 2026-11-30  2:33 UTC (permalink / raw)
  To: Binbin Zhou, Huacai Chen, Rob Herring, Krzysztof Kozlowski,
	Conor Dooley, Yinbo Zhu, Mark Brown
  Cc: Huacai Chen, Xuerui Wang, loongarch, devicetree, linux-spi,
	Bingxiong Li, Binbin Zhou

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.

Also add an optional interrupts property, now that the driver supports
interrupt-driven transfers in addition to polling.

Signed-off-by: Binbin Zhou <zhoubinbin@loongson.cn>
---
 Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml b/Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml
index de9d32feadf5..8a36dbece788 100644
--- a/Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml
+++ b/Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml
@@ -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
-- 
2.52.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH v2 2/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi-io compatible
  2026-11-30  2:32 [PATCH v2 0/5] spi: loongson: SPI-IO driver for Loongson-2K0300 Binbin Zhou
  2026-11-30  2:33 ` [PATCH v2 1/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi compatible Binbin Zhou
@ 2026-11-30  2:33 ` Binbin Zhou
  2026-11-30  2:33 ` [PATCH v2 3/5] spi: loongson: Add spi-io interrupt-driven driver Binbin Zhou
                   ` (2 subsequent siblings)
  4 siblings, 0 replies; 8+ messages in thread
From: Binbin Zhou @ 2026-11-30  2:33 UTC (permalink / raw)
  To: Binbin Zhou, Huacai Chen, Rob Herring, Krzysztof Kozlowski,
	Conor Dooley, Yinbo Zhu, Mark Brown
  Cc: Huacai Chen, Xuerui Wang, loongarch, devicetree, linux-spi,
	Bingxiong Li, Binbin Zhou, Conor Dooley

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.

Acked-by: Conor Dooley <conor.dooley@microchip.com>
Signed-off-by: Binbin Zhou <zhoubinbin@loongson.cn>
---
 .../bindings/spi/loongson,ls2k-spi.yaml       | 41 +++++++++++++++++++
 1 file changed, 41 insertions(+)

diff --git a/Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml b/Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml
index 8a36dbece788..b113d10c5bd9 100644
--- a/Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml
+++ b/Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml
@@ -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";
+    };
-- 
2.52.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH v2 3/5] spi: loongson: Add spi-io interrupt-driven driver
  2026-11-30  2:32 [PATCH v2 0/5] spi: loongson: SPI-IO driver for Loongson-2K0300 Binbin Zhou
  2026-11-30  2:33 ` [PATCH v2 1/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi compatible Binbin Zhou
  2026-11-30  2:33 ` [PATCH v2 2/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi-io compatible Binbin Zhou
@ 2026-11-30  2:33 ` Binbin Zhou
  2026-11-30  2:48   ` sashiko-bot
  2026-11-30  2:33 ` [PATCH v2 4/5] spi: loongson: Add DMA support to SPI-IO driver Binbin Zhou
  2026-11-30  2:33 ` [PATCH v2 5/5] MAINTAINERS: Add myself as Loongson SPI maintainer Binbin Zhou
  4 siblings, 1 reply; 8+ messages in thread
From: Binbin Zhou @ 2026-11-30  2:33 UTC (permalink / raw)
  To: Binbin Zhou, Huacai Chen, Rob Herring, Krzysztof Kozlowski,
	Conor Dooley, Yinbo Zhu, Mark Brown
  Cc: Huacai Chen, Xuerui Wang, loongarch, devicetree, linux-spi,
	Bingxiong Li, 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.

Signed-off-by: Bingxiong Li <libingxiong@loongson.cn>
Signed-off-by: Binbin Zhou <zhoubinbin@loongson.cn>
---
 MAINTAINERS                   |   1 +
 drivers/spi/Kconfig           |  16 +
 drivers/spi/Makefile          |   1 +
 drivers/spi/spi-loongson-io.c | 831 ++++++++++++++++++++++++++++++++++
 4 files changed, 849 insertions(+)
 create mode 100644 drivers/spi/spi-loongson-io.c

diff --git a/MAINTAINERS b/MAINTAINERS
index 1d72916bba39..fd12d7e68774 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -15736,6 +15736,7 @@ L:	linux-spi@vger.kernel.org
 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
diff --git a/drivers/spi/Kconfig b/drivers/spi/Kconfig
index 7809acbac35b..37339eb7a543 100644
--- a/drivers/spi/Kconfig
+++ b/drivers/spi/Kconfig
@@ -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
diff --git a/drivers/spi/Makefile b/drivers/spi/Makefile
index b6ab37271555..3af58eaa391a 100644
--- a/drivers/spi/Makefile
+++ b/drivers/spi/Makefile
@@ -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
diff --git a/drivers/spi/spi-loongson-io.c b/drivers/spi/spi-loongson-io.c
new file mode 100644
index 000000000000..2ca9ee7e2d1d
--- /dev/null
+++ b/drivers/spi/spi-loongson-io.c
@@ -0,0 +1,831 @@
+// SPDX-License-Identifier: GPL-2.0+
+//
+// Platform driver for Loongson-2K0300 SPI IO Support
+//
+// Copyright (C) 2017-2026 Loongson Technology Corporation Limited
+
+#include <linux/bitfield.h>
+#include <linux/clk.h>
+#include <linux/completion.h>
+#include <linux/err.h>
+#include <linux/interrupt.h>
+#include <linux/io.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/platform_device.h>
+#include <linux/spi/spi.h>
+#include <linux/string.h>
+
+/* Loongson SPI-IO Controller registers */
+#define LOONGSON_SPI_IO_CR1_REG			0x00
+#define LOONGSON_SPI_IO_CR2_REG			0x04
+#define LOONGSON_SPI_IO_CR3_REG			0x08
+#define LOONGSON_SPI_IO_CR4_REG			0x0c
+#define LOONGSON_SPI_IO_IER_REG			0x10
+#define LOONGSON_SPI_IO_SR1_REG			0x14
+#define LOONGSON_SPI_IO_SR2_REG			0x18
+#define LOONGSON_SPI_IO_CFG1_REG		0x20
+#define LOONGSON_SPI_IO_CFG2_REG		0x24
+#define LOONGSON_SPI_IO_CFG3_REG		0x28
+#define LOONGSON_SPI_IO_CRC1_REG		0x30
+#define LOONGSON_SPI_IO_CRC2_REG		0x34
+#define LOONGSON_SPI_IO_DR_REG			0x40
+
+/* Bitfields of LOONGSON_SPI_IO_CR1_REG */
+#define LOONGSON_SPI_IO_CR1_SPE			BIT(0)
+#define LOONGSON_SPI_IO_CR1_CSTART		BIT(1)
+#define LOONGSON_SPI_IO_CR1_AUTOSUS		BIT(2)
+#define LOONGSON_SPI_IO_CR1_SSREV		BIT(8)
+
+#define LOONGSON_SPI_IO_CR1_START_MASK		(LOONGSON_SPI_IO_CR1_CSTART | \
+						 LOONGSON_SPI_IO_CR1_AUTOSUS)
+
+/* Bitfields of LOONGSON_SPI_IO_CR2_REG */
+#define LOONGSON_SPI_IO_CR2_RXFTHLV		GENMASK(1, 0)
+#define LOONGSON_SPI_IO_CR2_TXFTHLV		GENMASK(9, 8)
+
+/* Bitfields of LOONGSON_SPI_IO_CR3_REG */
+#define LOONGSON_SPI_IO_CR3_TSIZE		GENMASK(15, 0)
+
+/* Bitfields of LOONGSON_SPI_IO_CR4_REG */
+#define LOONGSON_SPI_IO_CR4_CTSIZE		GENMASK(15, 0)
+
+/* Bitfields of LOONGSON_SPI_IO_IER_REG */
+#define LOONGSON_SPI_IO_IER_RXAIE		BIT(0)
+#define LOONGSON_SPI_IO_IER_TXAIE		BIT(1)
+#define LOONGSON_SPI_IO_IER_DXAIE		BIT(2)
+#define LOONGSON_SPI_IO_IER_RXEIE		BIT(4)
+#define LOONGSON_SPI_IO_IER_TXEIE		BIT(5)
+#define LOONGSON_SPI_IO_IER_SUSPIE		BIT(7)
+#define LOONGSON_SPI_IO_IER_OVRIE		BIT(8)
+#define LOONGSON_SPI_IO_IER_UDRIE		BIT(9)
+#define LOONGSON_SPI_IO_IER_CRCEIE		BIT(10)
+#define LOONGSON_SPI_IO_IER_MODFIE		BIT(11)
+#define LOONGSON_SPI_IO_IER_EOTIE		BIT(15)
+
+#define LOONGSON_SPI_IO_IER_ERR_MASK		(LOONGSON_SPI_IO_IER_OVRIE | \
+						 LOONGSON_SPI_IO_IER_UDRIE | \
+						 LOONGSON_SPI_IO_IER_CRCEIE | \
+						 LOONGSON_SPI_IO_IER_MODFIE)
+
+/* Bitfields of LOONGSON_SPI_IO_SR1_REG */
+#define LOONGSON_SPI_IO_SR1_RXA			BIT(0)
+#define LOONGSON_SPI_IO_SR1_TXA			BIT(1)
+#define LOONGSON_SPI_IO_SR1_DXA			BIT(2)
+#define LOONGSON_SPI_IO_SR1_RXE			BIT(4)
+#define LOONGSON_SPI_IO_SR1_TXE			BIT(5)
+#define LOONGSON_SPI_IO_SR1_SUSP		BIT(7)
+#define LOONGSON_SPI_IO_SR1_OVR			BIT(8)
+#define LOONGSON_SPI_IO_SR1_UDR			BIT(9)
+#define LOONGSON_SPI_IO_SR1_CRCE		BIT(10)
+#define LOONGSON_SPI_IO_SR1_MODF		BIT(11)
+#define LOONGSON_SPI_IO_SR1_EOT			BIT(15)
+
+#define LOONGSON_SPI_IO_SR1_ERR_MASK		(LOONGSON_SPI_IO_SR1_OVR | \
+						 LOONGSON_SPI_IO_SR1_UDR | \
+						 LOONGSON_SPI_IO_SR1_MODF | \
+						 LOONGSON_SPI_IO_SR1_CRCE)
+
+/* Bitfields of LOONGSON_SPI_IO_SR2_REG */
+#define LOONGSON_SPI_IO_SR2_RXFLV		GENMASK(2, 0)
+#define LOONGSON_SPI_IO_SR2_TXFLV		GENMASK(10, 8)
+
+/* Bitfields of LOONGSON_SPI_IO_CFG1_REG */
+#define LOONGSON_SPI_IO_CFG1_CPOL		BIT(0)
+#define LOONGSON_SPI_IO_CFG1_CPHA		BIT(1)
+#define LOONGSON_SPI_IO_CFG1_LSBFRST		BIT(7)
+#define LOONGSON_SPI_IO_CFG1_DSIZE		GENMASK(12, 8)
+
+/* Bitfields of LOONGSON_SPI_IO_CFG2_REG */
+#define LOONGSON_SPI_IO_CFG2_BRDEC		GENMASK(7, 2)
+#define LOONGSON_SPI_IO_CFG2_BRINT		GENMASK(15, 8)
+
+#define LOONGSON_SPI_IO_CFG2_MIN_BRINT		2
+#define LOONGSON_SPI_IO_CFG2_MAX_BRINT		FIELD_MAX(LOONGSON_SPI_IO_CFG2_BRINT)
+
+/* Bitfields of LOONGSON_SPI_IO_CFG3_REG */
+#define LOONGSON_SPI_IO_CFG3_MSTR		BIT(0)
+#define LOONGSON_SPI_IO_CFG3_DIOSWP		BIT(1)
+#define LOONGSON_SPI_IO_CFG3_DIE		BIT(2)
+#define LOONGSON_SPI_IO_CFG3_DOE		BIT(3)
+#define LOONGSON_SPI_IO_CFG3_SSMODE		GENMASK(9, 8)
+
+/* Bitfields of LOONGSON_SPI_IO_CRC1_REG */
+#define LOONGSON_SPI_IO_CRC1_CRCEN		BIT(0)
+#define LOONGSON_SPI_IO_CRC1_CRCPOLY		GENMASK(31, 1)
+
+/* Bitfields of LOONGSON_SPI_IO_CRC2_REG */
+#define LOONGSON_SPI_IO_CRC2_RCRCINI		BIT(0)
+#define LOONGSON_SPI_IO_CRC2_TCRCINI		BIT(1)
+#define LOONGSON_SPI_IO_CRC2_CRCSIZE		GENMASK(12, 8)
+
+/*
+ * Driver-side software chunk size, not a hardware limit: the FIFO is serviced
+ * four bytes at a time and each transfer's timeout has a one second floor, so
+ * split oversized messages into pieces that comfortably fit.
+ */
+#define LOONGSON_SPI_IO_XFER_CHUNK_SIZE		SZ_64K
+
+/**
+ * enum xfer_mode - Loongson SPI transfer mode
+ * @XFER_IDLE: no transfer is in progress
+ * @XFER_INTERRUPT: interrupt-driven batch transfer
+ */
+enum xfer_mode {
+	XFER_IDLE,
+	XFER_INTERRUPT,
+};
+
+/**
+ * struct loongson_spi_priv - private data for the Loongson SPI controller
+ * @controller: SPI controller instance
+ * @dev: device backing the controller
+ * @base: MMIO base address of the SPI controller
+ * @hz: last requested SPI bus clock in Hz
+ * @clk_rate: parent clock rate in Hz
+ * @mode: current SPI mode bits
+ * @bits_per_word: current word size in bits
+ * @frame_bytes: bytes occupied by one frame in the FIFO and transfer buffers
+ * @irq: interrupt number
+ * @tx_buf: current transmit buffer for interrupt mode
+ * @rx_buf: current receive buffer for interrupt mode
+ * @remaining: bytes left in the current interrupt transfer
+ * @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
+ * @xfer_mode: current transfer mode
+ */
+struct loongson_spi_priv {
+	struct spi_controller   *controller;
+	struct device		*dev;
+	void __iomem		*base;
+	u32                     hz;
+	u64                     clk_rate;
+	u8                      mode;
+	u8			bits_per_word;
+	u8			frame_bytes;
+
+	int			irq;
+	const u8		*tx_buf;
+	u8			*rx_buf;
+	u32			remaining;
+	int			xfer_ret;
+	u32			batch_size;
+	struct completion	xfer_completion;
+	enum xfer_mode		xfer_mode;
+};
+
+static void loongson_spi_writel(struct loongson_spi_priv *priv, u32 reg, u32 data)
+{
+	writel(data, priv->base + reg);
+}
+
+static u32 loongson_spi_readl(struct loongson_spi_priv *priv, u32 reg)
+{
+	return readl(priv->base + reg);
+}
+
+static void loongson_spi_update_bits(struct loongson_spi_priv *priv, u32 reg,
+				     u32 mask, u32 val)
+{
+	u32 tmp = readl(priv->base + reg);
+
+	tmp &= ~mask;
+	tmp |= val & mask;
+	writel(tmp, priv->base + reg);
+}
+
+/**
+ * loongson_spi_io_read_dr() - Read one complete frame from the RX FIFO
+ * @priv: controller private data
+ *
+ * The APB read width follows the 1, 2 or 4 byte FIFO storage width selected
+ * by DSIZE. The unused high bits are zero and the low byte is stored first.
+ *
+ * Return: one frame in a little-endian container.
+ */
+static u32 loongson_spi_io_read_dr(struct loongson_spi_priv *priv)
+{
+	void __iomem *dr = priv->base + LOONGSON_SPI_IO_DR_REG;
+
+	switch (priv->frame_bytes) {
+	case 1:
+		return readb(dr);
+	case 2:
+		return readw(dr);
+	default:
+		return readl(dr);
+	}
+}
+
+/**
+ * loongson_spi_io_write_dr() - Write one complete frame to the TX FIFO
+ * @priv: controller private data
+ * @data: frame in a little-endian container
+ *
+ * Select the APB write strobes for a 1, 2 or 4 byte FIFO access according to
+ * the storage width selected by DSIZE.
+ */
+static void loongson_spi_io_write_dr(struct loongson_spi_priv *priv, u32 data)
+{
+	void __iomem *dr = priv->base + LOONGSON_SPI_IO_DR_REG;
+
+	if (priv->frame_bytes == 1)
+		writeb(data, dr);
+	else if (priv->frame_bytes == 2)
+		writew(data, dr);
+	else
+		writel(data, dr);
+}
+
+/**
+ * loongson_spi_io_cfg_write() - Write a configuration register
+ * @priv: controller private data
+ * @reg: configuration register offset
+ * @val: value to write
+ *
+ * CFG1/CFG2/CFG3 and CRCx writes are rejected while CR1.SPE is set.
+ * Temporarily disable the peripheral and restore CR1 around the write.
+ * The caller must ensure that no transfer is active. In normal SS mode
+ * ss_o = !SPE, so callers must also ensure CS is deasserted; toggling SPE
+ * while CS is active glitches the CS line.
+ */
+static void loongson_spi_io_cfg_write(struct loongson_spi_priv *priv, u32 reg, u32 val)
+{
+	u32 cr1 = loongson_spi_readl(priv, LOONGSON_SPI_IO_CR1_REG);
+
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_CR1_REG,
+			    cr1 & ~LOONGSON_SPI_IO_CR1_SPE);
+	loongson_spi_writel(priv, reg, val);
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_CR1_REG, cr1);
+}
+
+/**
+ * loongson_spi_io_timeout() - Calculate a transfer completion timeout
+ * @priv: controller private data
+ * @xfer: SPI transfer being timed
+ *
+ * Use twice the calculated wire time, with a minimum timeout of one second.
+ *
+ * Return: timeout in jiffies.
+ */
+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 = DIV64_U64_ROUND_UP(nsec, (u64)rate * NSEC_PER_MSEC);
+
+	return msecs_to_jiffies(max_t(u64, msec * 2, 1000));
+}
+
+static void loongson_spi_io_set_thresh(struct loongson_spi_priv *priv)
+{
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR2_REG,
+				 LOONGSON_SPI_IO_CR2_RXFTHLV |
+				 LOONGSON_SPI_IO_CR2_TXFTHLV, 0);
+}
+
+/**
+ * loongson_spi_io_drain_rx() - Discard every frame currently in the RX FIFO
+ * @priv: controller private data
+ */
+static void loongson_spi_io_drain_rx(struct loongson_spi_priv *priv)
+{
+	while (FIELD_GET(LOONGSON_SPI_IO_SR2_RXFLV,
+			 loongson_spi_readl(priv, LOONGSON_SPI_IO_SR2_REG)))
+		loongson_spi_io_read_dr(priv);
+}
+
+/**
+ * loongson_spi_io_set_cs() - Drive the chip-select output level
+ * @spi: SPI target device
+ * @level: true drives the CS line to logic high, i.e. deasserted for the
+ *         default active-low chip selects (SPI core passes the electrical
+ *         level, not the logical assert state)
+ *
+ * SSREV selects the CS output level.
+ */
+static void loongson_spi_io_set_cs(struct spi_device *spi, bool level)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
+	u32 val = level ? LOONGSON_SPI_IO_CR1_SSREV : 0;
+
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+				 LOONGSON_SPI_IO_CR1_SSREV, val);
+}
+
+/**
+ * loongson_spi_io_set_clk() - Program the SPI bus clock divider
+ * @priv: controller private data
+ * @hz: requested SPI bus clock in Hz
+ */
+static void loongson_spi_io_set_clk(struct loongson_spi_priv *priv, unsigned int hz)
+{
+	u32 val;
+
+	val = clamp_val(DIV_ROUND_UP_ULL(priv->clk_rate, hz),
+			LOONGSON_SPI_IO_CFG2_MIN_BRINT, LOONGSON_SPI_IO_CFG2_MAX_BRINT);
+
+	loongson_spi_io_cfg_write(priv, LOONGSON_SPI_IO_CFG2_REG,
+				  FIELD_PREP(LOONGSON_SPI_IO_CFG2_BRINT, val));
+
+	priv->hz = hz;
+}
+
+/**
+ * loongson_spi_io_set_mode() - Apply SPI mode bits and word size
+ * @priv: controller private data
+ * @mode: SPI mode bits from the target device
+ * @bits_per_word: word size in bits
+ *
+ * Configure CPOL, CPHA and LSB_FIRST. DSIZE is programmed as the word size
+ * minus one.
+ */
+static void loongson_spi_io_set_mode(struct loongson_spi_priv *priv, u32 mode,
+				     u8 bits_per_word)
+{
+	u32 val = 0;
+
+	if (mode & SPI_CPOL)
+		val |= LOONGSON_SPI_IO_CFG1_CPOL;
+
+	if (mode & SPI_CPHA)
+		val |= LOONGSON_SPI_IO_CFG1_CPHA;
+
+	if (mode & SPI_LSB_FIRST)
+		val |= LOONGSON_SPI_IO_CFG1_LSBFRST;
+
+	val |= FIELD_PREP(LOONGSON_SPI_IO_CFG1_DSIZE, bits_per_word - 1);
+	loongson_spi_io_cfg_write(priv, LOONGSON_SPI_IO_CFG1_REG, val);
+
+	priv->mode = mode;
+	priv->bits_per_word = bits_per_word;
+
+	if (bits_per_word <= 8)
+		priv->frame_bytes = 1;
+	else if (bits_per_word <= 16)
+		priv->frame_bytes = 2;
+	else
+		priv->frame_bytes = 4;
+}
+
+/**
+ * loongson_spi_io_update_state() - Apply per-transfer clock and device mode
+ * @spi: SPI target device
+ * @t: SPI transfer being configured
+ */
+static void loongson_spi_io_update_state(struct spi_device *spi, struct spi_transfer *t)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
+	u8 bits_per_word = spi->bits_per_word;
+
+	if (t && t->bits_per_word)
+		bits_per_word = t->bits_per_word;
+
+	if (t && priv->hz != t->speed_hz)
+		loongson_spi_io_set_clk(priv, t->speed_hz);
+
+	if (((spi->mode ^ priv->mode) & (SPI_MODE_X_MASK | SPI_LSB_FIRST)) ||
+	    priv->bits_per_word != bits_per_word)
+		loongson_spi_io_set_mode(priv, spi->mode, bits_per_word);
+}
+
+/**
+ * loongson_spi_io_setup() - Validate an SPI target chip select
+ * @spi: SPI target device being configured
+ *
+ * Return: 0 if the chip select is supported, otherwise %-EINVAL.
+ */
+static int loongson_spi_io_setup(struct spi_device *spi)
+{
+	if (spi_get_chipselect(spi, 0) >= spi->controller->num_chipselect)
+		return -EINVAL;
+
+	return 0;
+}
+
+/**
+ * loongson_spi_io_optimize_message() - Split oversized transfers once
+ * @msg: message to optimize
+ *
+ * Return: 0 on success, or a negative error code.
+ */
+static int loongson_spi_io_optimize_message(struct spi_message *msg)
+{
+	struct spi_controller *ctrl = msg->spi->controller;
+
+	return spi_split_transfers_maxsize(ctrl, msg,
+					   LOONGSON_SPI_IO_XFER_CHUNK_SIZE);
+}
+
+/**
+ * loongson_spi_io_prepare_message() - Set up the controller for one message
+ * @ctrl: SPI controller
+ * @msg: message that is about to be transferred
+ *
+ * Runs before spi_map_msg(). Only resets message-scoped FIFO/status state;
+ * the interrupt path programs its own thresholds per transfer.
+ *
+ * Return: always 0.
+ */
+static int loongson_spi_io_prepare_message(struct spi_controller *ctrl,
+					   struct spi_message *msg)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(ctrl);
+
+	loongson_spi_io_drain_rx(priv);
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
+			    LOONGSON_SPI_IO_SR1_EOT | LOONGSON_SPI_IO_SR1_ERR_MASK);
+
+	return 0;
+}
+
+/**
+ * loongson_spi_io_start_batch() - Start one interrupt-driven FIFO batch
+ * @priv: controller private data
+ *
+ * Preload up to four FIFO bytes using whole frames, with zero-filled frames
+ * when no TX buffer is present. TSIZE counts frames rather than bytes.
+ */
+static void loongson_spi_io_start_batch(struct loongson_spi_priv *priv)
+{
+	u32 batch_size, frames;
+	u32 tx_data;
+
+	if (priv->remaining == 0)
+		return;
+
+	batch_size = min_t(u32, priv->remaining, 4);
+	frames = batch_size / priv->frame_bytes;
+	priv->batch_size = batch_size;
+
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_CR3_REG, frames - 1);
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_CR4_REG, 0);
+
+	for (unsigned int i = 0; i < batch_size; i += priv->frame_bytes) {
+		tx_data = 0;
+		if (priv->tx_buf) {
+			memcpy(&tx_data, priv->tx_buf, priv->frame_bytes);
+			priv->tx_buf += priv->frame_bytes;
+		}
+		loongson_spi_io_write_dr(priv, tx_data);
+	}
+
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG, LOONGSON_SPI_IO_SR1_EOT);
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+				 LOONGSON_SPI_IO_CR1_START_MASK,
+				 LOONGSON_SPI_IO_CR1_START_MASK);
+}
+
+/**
+ * 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.
+ *
+ * Return: %IRQ_HANDLED for a recognized error or EOT, otherwise %IRQ_NONE.
+ */
+static irqreturn_t loongson_spi_io_irq_handler(int irq, void *dev_id)
+{
+	struct loongson_spi_priv *priv = dev_id;
+	u32 rx_data, sr1;
+
+	sr1 = loongson_spi_readl(priv, LOONGSON_SPI_IO_SR1_REG);
+
+	if (sr1 & LOONGSON_SPI_IO_SR1_ERR_MASK) {
+		loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
+				    sr1 & LOONGSON_SPI_IO_SR1_ERR_MASK);
+
+		if (priv->xfer_mode == XFER_IDLE)
+			return IRQ_HANDLED;
+
+		dev_err(&priv->controller->dev, "SPI error: SR1=0x%x", sr1);
+		loongson_spi_writel(priv, LOONGSON_SPI_IO_IER_REG, 0);
+		loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+					 LOONGSON_SPI_IO_CR1_START_MASK |
+					 LOONGSON_SPI_IO_CR1_CSTART, 0);
+		priv->xfer_ret = -EIO;
+		complete(&priv->xfer_completion);
+		return IRQ_HANDLED;
+	}
+
+	if (!(sr1 & LOONGSON_SPI_IO_SR1_EOT))
+		return IRQ_NONE;
+
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG, LOONGSON_SPI_IO_SR1_EOT);
+
+	switch (priv->xfer_mode) {
+	case XFER_INTERRUPT:
+		for (unsigned int i = 0; i < priv->batch_size; i += priv->frame_bytes) {
+			rx_data = loongson_spi_io_read_dr(priv);
+			if (priv->rx_buf) {
+				memcpy(priv->rx_buf, &rx_data, priv->frame_bytes);
+				priv->rx_buf += priv->frame_bytes;
+			}
+		}
+		priv->remaining -= priv->batch_size;
+
+		if (priv->remaining == 0) {
+			loongson_spi_update_bits(priv, LOONGSON_SPI_IO_IER_REG,
+						 LOONGSON_SPI_IO_IER_EOTIE, 0);
+			loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+						 LOONGSON_SPI_IO_CR1_CSTART, 0);
+			priv->xfer_ret = 0;
+			complete(&priv->xfer_completion);
+		} else {
+			loongson_spi_io_start_batch(priv);
+		}
+		break;
+	case XFER_IDLE:
+	default:
+		dev_warn(&priv->controller->dev, "EOT with no active transfer");
+		break;
+	}
+
+	return IRQ_HANDLED;
+}
+
+/**
+ * loongson_spi_io_setup_transfer() - Configure hardware state for one transfer
+ * @spi: SPI target device
+ * @xfer: transfer to prepare
+ *
+ * Apply per-transfer clock/mode updates, validate frame alignment and clear
+ * stale controller status from any previous transfer.
+ *
+ * Return: 0 on success, or a negative error code.
+ */
+static int loongson_spi_io_setup_transfer(struct spi_device *spi, struct spi_transfer *xfer)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
+
+	loongson_spi_io_update_state(spi, xfer);
+
+	if (xfer->len % priv->frame_bytes) {
+		dev_err(&spi->dev, "length %u is not aligned to %u-byte frames",
+			xfer->len, priv->frame_bytes);
+		return -EINVAL;
+	}
+
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
+			    LOONGSON_SPI_IO_SR1_EOT | LOONGSON_SPI_IO_SR1_ERR_MASK);
+
+	return 0;
+}
+
+/**
+ * loongson_spi_io_transfer_one_irq() - Execute one interrupt-driven SPI transfer
+ * @spi: SPI target device
+ * @xfer: transfer to execute
+ *
+ * Drive FIFO batches using the EOT interrupt until all bytes have been sent.
+ *
+ * Return: 0 on success, or a negative error code.
+ */
+static int loongson_spi_io_transfer_one_irq(struct spi_device *spi, struct spi_transfer *xfer)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
+	int ret;
+
+	loongson_spi_io_set_thresh(priv);
+
+	priv->tx_buf = xfer->tx_buf;
+	priv->rx_buf = xfer->rx_buf;
+	priv->remaining = xfer->len;
+	priv->xfer_ret = 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_ERR_MASK,
+				 LOONGSON_SPI_IO_IER_EOTIE | LOONGSON_SPI_IO_IER_ERR_MASK);
+
+	loongson_spi_io_start_batch(priv);
+
+	ret = wait_for_completion_timeout(&priv->xfer_completion,
+					  loongson_spi_io_timeout(priv, xfer));
+	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;
+}
+
+/**
+ * loongson_spi_io_transfer_one() - Execute one SPI transfer
+ * @ctrl: SPI controller
+ * @spi: SPI target device
+ * @xfer: transfer to execute
+ *
+ * Apply clock and mode state before running interrupt-driven FIFO batches.
+ *
+ * Return: 0 on success, or a negative error code.
+ */
+static int loongson_spi_io_transfer_one(struct spi_controller *ctrl, struct spi_device *spi,
+					struct spi_transfer *xfer)
+{
+	int ret;
+
+	if (xfer->len == 0)
+		return 0;
+
+	ret = loongson_spi_io_setup_transfer(spi, xfer);
+	if (ret)
+		return ret;
+
+	return loongson_spi_io_transfer_one_irq(spi, xfer);
+}
+
+/**
+ * loongson_spi_io_reginit() - Restore the basic controller configuration
+ * @priv: controller private data
+ *
+ * Select master full-duplex pin directions and enable the SPI peripheral.
+ */
+static void loongson_spi_io_reginit(struct loongson_spi_priv *priv)
+{
+	u32 cr1;
+
+	/* CFG3 is only writable while SPE is clear; cfg_write() handles that. */
+	loongson_spi_io_cfg_write(priv, LOONGSON_SPI_IO_CFG3_REG,
+				  LOONGSON_SPI_IO_CFG3_MSTR |
+				  LOONGSON_SPI_IO_CFG3_DIE |
+				  LOONGSON_SPI_IO_CFG3_DOE);
+
+	cr1 = loongson_spi_readl(priv, LOONGSON_SPI_IO_CR1_REG);
+	cr1 &= ~LOONGSON_SPI_IO_CR1_START_MASK;
+	cr1 |= LOONGSON_SPI_IO_CR1_SPE;
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_CR1_REG, cr1);
+}
+
+/**
+ * loongson_spi_io_reset_state() - Return the controller to its idle default
+ * @priv: controller private data
+ *
+ * Only touches the controller itself: callers must have already stopped the
+ * engine. Safe after spi_unmap_msg().
+ */
+static void loongson_spi_io_reset_state(struct loongson_spi_priv *priv)
+{
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_IER_REG, 0);
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+				 LOONGSON_SPI_IO_CR1_START_MASK, 0);
+	loongson_spi_io_set_thresh(priv);
+	loongson_spi_io_drain_rx(priv);
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
+			    LOONGSON_SPI_IO_SR1_EOT | LOONGSON_SPI_IO_SR1_ERR_MASK);
+
+	priv->tx_buf = NULL;
+	priv->rx_buf = NULL;
+	priv->remaining = 0;
+	priv->batch_size = 0;
+	priv->xfer_ret = 0;
+	priv->xfer_mode = XFER_IDLE;
+	reinit_completion(&priv->xfer_completion);
+
+	loongson_spi_io_reginit(priv);
+}
+
+/**
+ * loongson_spi_io_handle_err() - Stop the engine after a failed message
+ * @ctrl: SPI controller
+ * @msg: failed SPI message
+ *
+ * The final idle-state restore is made idempotent via
+ * loongson_spi_io_reset_state().
+ */
+static void loongson_spi_io_handle_err(struct spi_controller *ctrl,
+				       struct spi_message *msg)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(ctrl);
+
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_IER_REG, 0);
+	synchronize_irq(priv->irq);
+
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
+				 LOONGSON_SPI_IO_CR1_START_MASK, 0);
+
+	loongson_spi_io_reset_state(priv);
+}
+
+/**
+ * loongson_spi_io_unprepare_message() - Restore idle state after a message
+ * @ctrl: SPI controller
+ * @msg: completed message
+ *
+ * Runs after spi_unmap_msg() for both successful and failed messages.
+ * transfer_one() has already stopped the engine on every exit path, so only
+ * the controller's idle state is restored here.
+ *
+ * Return: always 0.
+ */
+static int loongson_spi_io_unprepare_message(struct spi_controller *ctrl,
+					     struct spi_message *msg)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(ctrl);
+
+	loongson_spi_io_reset_state(priv);
+
+	return 0;
+}
+
+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 clk *clk;
+	int ret;
+
+	host = devm_spi_alloc_host(dev, sizeof(*priv));
+	if (!host)
+		return -ENOMEM;
+
+	host->mode_bits = SPI_MODE_X_MASK | SPI_LSB_FIRST;
+	host->bits_per_word_mask = SPI_BPW_MASK(8) | SPI_BPW_MASK(16) | SPI_BPW_MASK(32);
+	host->setup = loongson_spi_io_setup;
+	host->optimize_message = loongson_spi_io_optimize_message;
+	host->prepare_message = loongson_spi_io_prepare_message;
+	host->unprepare_message = loongson_spi_io_unprepare_message;
+	host->transfer_one = loongson_spi_io_transfer_one;
+	host->set_cs = loongson_spi_io_set_cs;
+	host->handle_err = loongson_spi_io_handle_err;
+	host->num_chipselect = 1;
+	dev_set_drvdata(dev, host);
+
+	priv = spi_controller_get_devdata(host);
+
+	priv->base = devm_platform_ioremap_resource(pdev, 0);
+	if (IS_ERR(priv->base))
+		return PTR_ERR(priv->base);
+
+	priv->controller = host;
+	priv->dev = dev;
+	priv->xfer_mode = XFER_IDLE;
+	priv->batch_size = 0;
+
+	init_completion(&priv->xfer_completion);
+
+	clk = devm_clk_get_enabled(dev, NULL);
+	if (IS_ERR(clk))
+		return dev_err_probe(dev, PTR_ERR(clk), "unable to get clock");
+	priv->clk_rate = clk_get_rate(clk);
+	if (!priv->clk_rate)
+		return dev_err_probe(dev, -EINVAL, "clock rate is zero");
+
+	/* the divider is >= 2, and BRINT is 8 bits wide. */
+	host->max_speed_hz = (u32)min_t(u64,
+					div_u64(priv->clk_rate, LOONGSON_SPI_IO_CFG2_MIN_BRINT),
+					U32_MAX);
+	host->min_speed_hz = (u32)min_t(u64,
+					DIV_ROUND_UP_ULL(priv->clk_rate,
+							 LOONGSON_SPI_IO_CFG2_MAX_BRINT),
+					U32_MAX);
+
+	loongson_spi_io_reginit(priv);
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_IER_REG, 0);
+	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
+			    LOONGSON_SPI_IO_SR1_EOT | LOONGSON_SPI_IO_SR1_ERR_MASK);
+
+	priv->irq = platform_get_irq(pdev, 0);
+	if (priv->irq < 0)
+		return dev_err_probe(dev, priv->irq, "no IRQ resource");
+
+	ret = devm_request_irq(dev, priv->irq, loongson_spi_io_irq_handler,
+			       0, "loongson-spi-io", priv);
+	if (ret)
+		return dev_err_probe(dev, ret, "failed to request IRQ");
+
+	return devm_spi_register_controller(dev, host);
+}
+
+static const struct of_device_id loongson_spi_io_id_table[] = {
+	{ .compatible = "loongson,ls2k0300-spi-io" },
+	{ }
+};
+MODULE_DEVICE_TABLE(of, loongson_spi_io_id_table);
+
+static struct platform_driver loongson_spi_io_plat_driver = {
+	.probe = loongson_spi_io_probe,
+	.driver	= {
+		.name	= "loongson-spi-io",
+		.of_match_table = loongson_spi_io_id_table,
+	},
+};
+module_platform_driver(loongson_spi_io_plat_driver);
+
+MODULE_DESCRIPTION("Loongson spi io controller driver");
+MODULE_AUTHOR("Loongson Technology Corporation Limited");
+MODULE_LICENSE("GPL");
-- 
2.52.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH v2 4/5] spi: loongson: Add DMA support to SPI-IO driver
  2026-11-30  2:32 [PATCH v2 0/5] spi: loongson: SPI-IO driver for Loongson-2K0300 Binbin Zhou
                   ` (2 preceding siblings ...)
  2026-11-30  2:33 ` [PATCH v2 3/5] spi: loongson: Add spi-io interrupt-driven driver Binbin Zhou
@ 2026-11-30  2:33 ` Binbin Zhou
  2026-11-30  2:53   ` sashiko-bot
  2026-11-30  2:33 ` [PATCH v2 5/5] MAINTAINERS: Add myself as Loongson SPI maintainer Binbin Zhou
  4 siblings, 1 reply; 8+ messages in thread
From: Binbin Zhou @ 2026-11-30  2:33 UTC (permalink / raw)
  To: Binbin Zhou, Huacai Chen, Rob Herring, Krzysztof Kozlowski,
	Conor Dooley, Yinbo Zhu, Mark Brown
  Cc: Huacai Chen, Xuerui Wang, loongarch, devicetree, linux-spi,
	Bingxiong Li, 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.

Signed-off-by: Binbin Zhou <zhoubinbin@loongson.cn>
---
 drivers/spi/spi-loongson-io.c | 411 ++++++++++++++++++++++++++++++++--
 1 file changed, 393 insertions(+), 18 deletions(-)

diff --git a/drivers/spi/spi-loongson-io.c b/drivers/spi/spi-loongson-io.c
index 2ca9ee7e2d1d..4e67c40518cb 100644
--- a/drivers/spi/spi-loongson-io.c
+++ b/drivers/spi/spi-loongson-io.c
@@ -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)
 
@@ -130,10 +142,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,
 };
 
 /**
@@ -153,6 +167,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 {
@@ -172,9 +190,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);
@@ -280,11 +308,24 @@ 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)
+/**
+ * loongson_spi_io_set_thresh() - Program the FIFO thresholds
+ * @priv: controller private data
+ * @dma: true selects the maximum threshold (4 bytes) for DMA; false selects
+ *       the minimum, i.e. one frame aligned up to DSIZE, for interrupt-driven
+ *       batches
+ */
+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_RXFTHLV | LOONGSON_SPI_IO_CR2_TXFTHLV,
+				 val);
 }
 
 /**
@@ -425,8 +466,9 @@ static int loongson_spi_io_optimize_message(struct spi_message *msg)
  * @ctrl: SPI controller
  * @msg: message that is about to be transferred
  *
- * Runs before spi_map_msg(). Only resets message-scoped FIFO/status state;
- * the interrupt path programs its own thresholds per transfer.
+ * Runs before spi_map_msg(), so tx_sg/rx_sg are not available yet. Only resets
+ * message-scoped FIFO/status state; the DMA or interrupt path programs its own
+ * thresholds per transfer.
  *
  * Return: always 0.
  */
@@ -442,6 +484,42 @@ static int loongson_spi_io_prepare_message(struct spi_controller *ctrl,
 	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, non-NULL TX and RX buffers with four-byte
+ * aligned addresses, a non-zero four-byte-aligned length, and a transfer
+ * at least as large as dma_threshold.
+ *
+ * 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;
+
+	if (!xfer->len || (xfer->len % 4))
+		return false;
+
+	if (!xfer->tx_buf || !xfer->rx_buf)
+		return false;
+
+	if (!IS_ALIGNED((unsigned long)xfer->tx_buf, 4) ||
+	    !IS_ALIGNED((unsigned long)xfer->rx_buf, 4))
+		return false;
+
+	if (xfer->len < dma_threshold)
+		return false;
+
+	return true;
+}
+
 /**
  * loongson_spi_io_start_batch() - Start one interrupt-driven FIFO batch
  * @priv: controller private data
@@ -479,14 +557,195 @@ static void loongson_spi_io_start_batch(struct loongson_spi_priv *priv)
 				 LOONGSON_SPI_IO_CR1_START_MASK);
 }
 
+/**
+ * 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 (IS_ERR_OR_NULL(rx_desc)) {
+		ret = rx_desc ? PTR_ERR(rx_desc) : -ENOMEM;
+		dev_err(priv->dev, "RX DMA prep_slave_sg failed: %d", ret);
+		return ret;
+	}
+
+	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 (IS_ERR_OR_NULL(tx_desc)) {
+		ret = tx_desc ? PTR_ERR(tx_desc) : -ENOMEM;
+		dev_err(priv->dev, "TX DMA prep_slave_sg failed: %d", ret);
+		return ret;
+	}
+
+	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 EOT/error interrupts, stop the engine and terminate
+ * both DMA channels. Any RX FIFO residue is discarded by the message
+ * teardown path. @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_IER_REG,
+				 LOONGSON_SPI_IO_IER_EOTIE |
+				 LOONGSON_SPI_IO_IER_ERR_MASK, 0);
+	priv->xfer_mode = XFER_IDLE;
+
+	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);
+
+	/* Quiesce both DMA channels before returning. */
+	dmaengine_terminate_sync(priv->dma_tx);
+	dmaengine_terminate_sync(priv->dma_rx);
+
+	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.
  */
@@ -520,6 +779,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) {
 			rx_data = loongson_spi_io_read_dr(priv);
@@ -592,7 +857,7 @@ static int loongson_spi_io_transfer_one_irq(struct spi_device *spi, struct spi_t
 	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
 	int ret;
 
-	loongson_spi_io_set_thresh(priv);
+	loongson_spi_io_set_thresh(priv, false);
 
 	priv->tx_buf = xfer->tx_buf;
 	priv->rx_buf = xfer->rx_buf;
@@ -623,13 +888,54 @@ static int loongson_spi_io_transfer_one_irq(struct spi_device *spi, struct spi_t
 	return priv->xfer_ret;
 }
 
+/**
+ * loongson_spi_io_transfer_one_dma() - Execute one DMA-driven SPI transfer
+ * @spi: SPI target device
+ * @xfer: transfer to execute
+ *
+ * Enable EOT and error interrupts, then submit both DMA channels via
+ * loongson_spi_dma_transfer(). The transfer is retried in interrupt mode on
+ * configuration failure before the bus has started; runtime DMA errors are
+ * returned to SPI core without replay.
+ *
+ * Return: 0 on success, or a negative error code.
+ */
+static int loongson_spi_io_transfer_one_dma(struct spi_device *spi, struct spi_transfer *xfer)
+{
+	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
+	bool bus_started = false;
+	int ret;
+
+	loongson_spi_io_set_thresh(priv, true);
+
+	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_ERR_MASK,
+				 LOONGSON_SPI_IO_IER_EOTIE | LOONGSON_SPI_IO_IER_ERR_MASK);
+
+	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 with %d, using interrupt mode", ret);
+
+	return loongson_spi_io_transfer_one_irq(spi, xfer);
+}
+
 /**
  * loongson_spi_io_transfer_one() - Execute one SPI transfer
  * @ctrl: SPI controller
  * @spi: SPI target device
  * @xfer: transfer to execute
  *
- * Apply clock and mode state before running interrupt-driven FIFO batches.
+ * Apply clock and mode state, then run the transfer via DMA or
+ * interrupt-driven FIFO batches.
  *
  * Return: 0 on success, or a negative error code.
  */
@@ -645,6 +951,9 @@ static int loongson_spi_io_transfer_one(struct spi_controller *ctrl, struct spi_
 	if (ret)
 		return ret;
 
+	if (ctrl->can_dma && ctrl->can_dma(ctrl, spi, xfer))
+		return loongson_spi_io_transfer_one_dma(spi, xfer);
+
 	return loongson_spi_io_transfer_one_irq(spi, xfer);
 }
 
@@ -675,14 +984,17 @@ static void loongson_spi_io_reginit(struct loongson_spi_priv *priv)
  * @priv: controller private data
  *
  * Only touches the controller itself: callers must have already stopped the
- * engine. Safe after spi_unmap_msg().
+ * engine and, if applicable, DMA. Safe after spi_unmap_msg().
  */
 static void loongson_spi_io_reset_state(struct loongson_spi_priv *priv)
 {
 	loongson_spi_writel(priv, LOONGSON_SPI_IO_IER_REG, 0);
 	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR1_REG,
 				 LOONGSON_SPI_IO_CR1_START_MASK, 0);
-	loongson_spi_io_set_thresh(priv);
+	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_CR2_REG,
+				 LOONGSON_SPI_IO_CR2_DMAEN_MASK, 0);
+
+	loongson_spi_io_set_thresh(priv, false);
 	loongson_spi_io_drain_rx(priv);
 	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
 			    LOONGSON_SPI_IO_SR1_EOT | LOONGSON_SPI_IO_SR1_ERR_MASK);
@@ -699,12 +1011,13 @@ static void loongson_spi_io_reset_state(struct loongson_spi_priv *priv)
 }
 
 /**
- * loongson_spi_io_handle_err() - Stop the engine after a failed message
+ * loongson_spi_io_handle_err() - Stop engine and DMA after a failed message
  * @ctrl: SPI controller
  * @msg: failed SPI message
  *
- * The final idle-state restore is made idempotent via
- * loongson_spi_io_reset_state().
+ * Runs before spi_unmap_msg(), so this is the only place where DMA must be
+ * terminated: once the buffers are unmapped the descriptors are stale. The
+ * final idle-state restore is made idempotent via loongson_spi_io_reset_state().
  */
 static void loongson_spi_io_handle_err(struct spi_controller *ctrl,
 				       struct spi_message *msg)
@@ -716,6 +1029,13 @@ 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);
+
+	if (priv->use_dma) {
+		dmaengine_terminate_sync(priv->dma_tx);
+		dmaengine_terminate_sync(priv->dma_rx);
+	}
 
 	loongson_spi_io_reset_state(priv);
 }
@@ -725,9 +1045,10 @@ static void loongson_spi_io_handle_err(struct spi_controller *ctrl,
  * @ctrl: SPI controller
  * @msg: completed message
  *
- * Runs after spi_unmap_msg() for both successful and failed messages.
- * transfer_one() has already stopped the engine on every exit path, so only
- * the controller's idle state is restored here.
+ * Runs after spi_unmap_msg() for both successful and failed messages, so it
+ * must not touch DMA descriptors or buffers. transfer_one() has already
+ * stopped the engine and, for DMA transfers, terminated both channels on every
+ * exit path; therefore only the controller's idle state is restored here.
  *
  * Return: always 0.
  */
@@ -741,11 +1062,40 @@ static int loongson_spi_io_unprepare_message(struct spi_controller *ctrl,
 	return 0;
 }
 
+/**
+ * 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;
 
@@ -767,13 +1117,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);
@@ -794,6 +1146,29 @@ static int loongson_spi_io_probe(struct platform_device *pdev)
 							 LOONGSON_SPI_IO_CFG2_MAX_BRINT),
 					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 if (priv->dma_tx || priv->dma_rx) {
+		return dev_err_probe(dev, -EINVAL,
+				     "Both 'tx' and 'rx' DMA channels are required");
+	} else {
+		dev_info(dev, "no DMA channels, using interrupt mode only");
+	}
+
 	loongson_spi_io_reginit(priv);
 	loongson_spi_writel(priv, LOONGSON_SPI_IO_IER_REG, 0);
 	loongson_spi_writel(priv, LOONGSON_SPI_IO_SR1_REG,
-- 
2.52.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH v2 5/5] MAINTAINERS: Add myself as Loongson SPI maintainer
  2026-11-30  2:32 [PATCH v2 0/5] spi: loongson: SPI-IO driver for Loongson-2K0300 Binbin Zhou
                   ` (3 preceding siblings ...)
  2026-11-30  2:33 ` [PATCH v2 4/5] spi: loongson: Add DMA support to SPI-IO driver Binbin Zhou
@ 2026-11-30  2:33 ` Binbin Zhou
  4 siblings, 0 replies; 8+ messages in thread
From: Binbin Zhou @ 2026-11-30  2:33 UTC (permalink / raw)
  To: Binbin Zhou, Huacai Chen, Rob Herring, Krzysztof Kozlowski,
	Conor Dooley, Yinbo Zhu, Mark Brown
  Cc: Huacai Chen, Xuerui Wang, loongarch, devicetree, linux-spi,
	Bingxiong Li, Binbin Zhou

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

Signed-off-by: Binbin Zhou <zhoubinbin@loongson.cn>
---
 MAINTAINERS | 1 +
 1 file changed, 1 insertion(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index fd12d7e68774..3acc7a7ebf72 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -15732,6 +15732,7 @@ F:	include/dt-bindings/clock/loongson,ls2k-clk.h
 
 LOONGSON SPI DRIVER
 M:	Yinbo Zhu <zhuyinbo@loongson.cn>
+M:	Binbin Zhou <zhoubinbin@loongson.cn>
 L:	linux-spi@vger.kernel.org
 S:	Maintained
 F:	Documentation/devicetree/bindings/spi/loongson,ls2k-spi.yaml
-- 
2.52.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* Re: [PATCH v2 3/5] spi: loongson: Add spi-io interrupt-driven driver
  2026-11-30  2:33 ` [PATCH v2 3/5] spi: loongson: Add spi-io interrupt-driven driver Binbin Zhou
@ 2026-11-30  2:48   ` sashiko-bot
  0 siblings, 0 replies; 8+ messages in thread
From: sashiko-bot @ 2026-11-30  2:48 UTC (permalink / raw)
  To: Binbin Zhou; +Cc: devicetree, robh, conor+dt

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [High] spi: loongson: CS glitch in loongson_spi_io_cfg_write() while
  CS is active
- [Medium] spi: loongson: unsynchronized IRQ and active engine on
  timeout in loongson_spi_io_transfer_one_irq()
--

commit 142d6eaee16a385552bbf9c942915b74af0d7e00
Author: Binbin Zhou <zhoubinbin@loongson.cn>

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

This commit adds an interrupt-driven platform driver for the
Loongson-2K0300 SPI-IO controller.

> diff --git a/drivers/spi/spi-loongson-io.c b/drivers/spi/spi-loongson-io.c
> new file mode 100644
> index 0000000000000..2ca9ee7e2d1da
> --- /dev/null
> +++ b/drivers/spi/spi-loongson-io.c

[ ... ]

> +/**
> + * loongson_spi_io_cfg_write() - Write a configuration register
> + * @priv: controller private data
> + * @reg: configuration register offset
> + * @val: value to write
> + *
> + * CFG1/CFG2/CFG3 and CRCx writes are rejected while CR1.SPE is set.
> + * Temporarily disable the peripheral and restore CR1 around the write.
> + * The caller must ensure that no transfer is active. In normal SS mode
> + * ss_o = !SPE, so callers must also ensure CS is deasserted; toggling SPE
> + * while CS is active glitches the CS line.
> + */
> +static void loongson_spi_io_cfg_write(struct loongson_spi_priv *priv, u32 reg, u32 val)
> +{
> +	u32 cr1 = loongson_spi_readl(priv, LOONGSON_SPI_IO_CR1_REG);
> +
> +	loongson_spi_writel(priv, LOONGSON_SPI_IO_CR1_REG,
> +			    cr1 & ~LOONGSON_SPI_IO_CR1_SPE);
> +	loongson_spi_writel(priv, reg, val);
> +	loongson_spi_writel(priv, LOONGSON_SPI_IO_CR1_REG, cr1);
> +}

[ ... ]

> +static void loongson_spi_io_update_state(struct spi_device *spi, struct spi_transfer *t)
> +{
> +	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
> +	u8 bits_per_word = spi->bits_per_word;
> +
> +	if (t && t->bits_per_word)
> +		bits_per_word = t->bits_per_word;
> +
> +	if (t && priv->hz != t->speed_hz)
> +		loongson_spi_io_set_clk(priv, t->speed_hz);
> +
> +	if (((spi->mode ^ priv->mode) & (SPI_MODE_X_MASK | SPI_LSB_FIRST)) ||
> +	    priv->bits_per_word != bits_per_word)
> +		loongson_spi_io_set_mode(priv, spi->mode, bits_per_word);
> +}

[Severity: High]
Does calling loongson_spi_io_set_clk() and loongson_spi_io_set_mode()
from loongson_spi_io_transfer_one() glitch the hardware chip-select line?

spi_transfer_one_message() asserts CS via loongson_spi_io_set_cs() and
waits cs_setup before calling transfer_one().  Inside transfer_one(),
loongson_spi_io_set_clk() and loongson_spi_io_set_mode() invoke
loongson_spi_io_cfg_write(), which clears and restores
LOONGSON_SPI_IO_CR1_SPE while CS is active (on the first transfer after
probe and whenever speed_hz, bits_per_word, or spi->mode changes).
As noted above loongson_spi_io_cfg_write(), toggling SPE while CS is
asserted pulses CS high mid-transaction, and also changes CPOL/CPHA in
LOONGSON_SPI_IO_CFG1_REG while the target is selected.

Similarly, loongson_spi_io_unprepare_message() calls
loongson_spi_io_reset_state() -> loongson_spi_io_reginit() ->
loongson_spi_io_cfg_write(), which toggles SPE at the end of a message
even when the final transfer sets cs_change to keep CS active.  In
addition, loongson_spi_io_reginit() sets LOONGSON_SPI_IO_CR1_SPE during
probe without setting LOONGSON_SPI_IO_CR1_SSREV, driving the active-low
CS line low at probe time before any SPI device is set up.

[ ... ]

> +static int loongson_spi_io_transfer_one_irq(struct spi_device *spi, struct spi_transfer *xfer)
> +{
> +	struct loongson_spi_priv *priv = spi_controller_get_devdata(spi->controller);
> +	int ret;
> +
> +	loongson_spi_io_set_thresh(priv);
> +
> +	priv->tx_buf = xfer->tx_buf;
> +	priv->rx_buf = xfer->rx_buf;
> +	priv->remaining = xfer->len;
> +	priv->xfer_ret = 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_ERR_MASK,
> +				 LOONGSON_SPI_IO_IER_EOTIE | LOONGSON_SPI_IO_IER_ERR_MASK);
> +
> +	loongson_spi_io_start_batch(priv);
> +
> +	ret = wait_for_completion_timeout(&priv->xfer_completion,
> +					  loongson_spi_io_timeout(priv, xfer));
> +	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]
When wait_for_completion_timeout() times out, can an in-flight
loongson_spi_io_irq_handler() race with the timeout path before
loongson_spi_io_handle_err() runs synchronize_irq()?

CPU0                              CPU1
loongson_spi_io_transfer_one_irq()
  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()
  spi_set_cs()
    loongson_spi_io_set_cs()
      loongson_spi_update_bits(..., CR1_REG, ...)
                                      memcpy(priv->rx_buf, ...)
                                      loongson_spi_update_bits(..., CR1_REG, ...)
                                        <-- data race on rx_buf and CR1_REG

The timeout path returns -ETIMEDOUT without clearing
LOONGSON_SPI_IO_CR1_START_MASK or calling synchronize_irq(priv->irq).
Before spi_transfer_one_message() reaches ctlr->handle_err(), an
in-flight ISR on CPU1 can still write to priv->rx_buf after
spi_dma_sync_for_cpu(), start another batch from priv->tx_buf, or perform
unlocked read-modify-writes on LOONGSON_SPI_IO_IER_REG and
LOONGSON_SPI_IO_CR1_REG concurrently with loongson_spi_io_set_cs().

Also, LOONGSON_SPI_IO_IER_REG is enabled before
loongson_spi_io_start_batch() initializes priv->batch_size, leaving a
window where priv->batch_size holds the previous transfer's final batch
size.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796005812.git.zhoubinbin@loongson.cn?part=3

^ permalink raw reply	[flat|nested] 8+ messages in thread

* Re: [PATCH v2 4/5] spi: loongson: Add DMA support to SPI-IO driver
  2026-11-30  2:33 ` [PATCH v2 4/5] spi: loongson: Add DMA support to SPI-IO driver Binbin Zhou
@ 2026-11-30  2:53   ` sashiko-bot
  0 siblings, 0 replies; 8+ messages in thread
From: sashiko-bot @ 2026-11-30  2:53 UTC (permalink / raw)
  To: Binbin Zhou; +Cc: devicetree, robh, conor+dt

Thank you for your contribution! Sashiko AI review found 7 potential
issues to consider:
- [High] spi: loongson: premature RX DMA termination in
  loongson_spi_dma_transfer()
- [Medium] spi: loongson: mapped buffer PIO fallback in
  loongson_spi_io_transfer_one_dma()
- [Medium] spi: loongson: re-evaluating can_dma() in
  loongson_spi_io_transfer_one()
- [Medium] spi: loongson: early IRQ/DMA enable and W1C RMW in
  loongson_spi_dma_transfer()
- [Medium] spi: loongson: probe failure on single channel in
  loongson_spi_io_probe()
- [Medium] spi: loongson: race with IRQ handler on timeout in
  loongson_spi_dma_transfer()
- [Medium] spi: loongson: 64K split in
  loongson_spi_io_optimize_message() defeats DMA loop
--

commit 4d011885c7facd92535ffe39b1f4dcba7ecfea2a
Author: Binbin Zhou <zhoubinbin@loongson.cn>

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

This commit adds optional TX and RX DMA channel support to the Loongson
SPI-IO controller driver for four-byte-aligned full-duplex transfers at or
above dma_threshold.

> diff --git a/drivers/spi/spi-loongson-io.c b/drivers/spi/spi-loongson-io.c
> index 2ca9ee7e2d1da..4e67c40518cb7 100644
> --- a/drivers/spi/spi-loongson-io.c
> +++ b/drivers/spi/spi-loongson-io.c
[ ... ]
> @@ -479,14 +557,195 @@ static void loongson_spi_io_start_batch(struct loongson_spi_priv *priv)
>  				 LOONGSON_SPI_IO_CR1_START_MASK);
>  }
>  
[ ... ]
> +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);

[Severity: Medium]
Can this loop in loongson_spi_dma_transfer() ever run more than one
iteration?  loongson_spi_io_optimize_message() unconditionally splits all
transfers at LOONGSON_SPI_IO_XFER_CHUNK_SIZE (64 KiB) before DMA mapping:

drivers/spi/spi-loongson-io.c:loongson_spi_io_optimize_message() {
	struct spi_controller *ctrl = msg->spi->controller;

	return spi_split_transfers_maxsize(ctrl, msg,
					   LOONGSON_SPI_IO_XFER_CHUNK_SIZE);
}

Because xfer->len is at most 65536 and priv->frame_bytes is 1, 2 or 4,
frames never exceeds LOONGSON_SPI_IO_MAX_FRAMES (65536).  Transfers larger
than 64 KiB are split into separate 64 KiB spi_transfer entries, each paying
for separate scatter-gather mapping, DMA descriptor setup and synchronous
dmaengine_terminate_sync() calls instead of using a single pair of DMA
descriptors across chunks.

> +
> +		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;
> +	}

[Severity: Medium]
Does enabling LOONGSON_SPI_IO_IER_REG in loongson_spi_io_transfer_one_dma()
and LOONGSON_SPI_IO_CR2_DMAEN_MASK above before reinit_completion() and
LOONGSON_SPI_IO_CR3_REG leave a window where an error interrupt is lost and
TX DMA writes to LOONGSON_SPI_IO_DR_REG before TSIZE is programmed?

CPU0                                  CPU1 (<hardirq>)
loongson_spi_io_transfer_one_dma()
  loongson_spi_update_bits(...,
    LOONGSON_SPI_IO_IER_REG, ...)
  loongson_spi_dma_transfer()
    priv->xfer_mode = XFER_DMA;
    dma_async_issue_pending(...)
    loongson_spi_update_bits(...,
      LOONGSON_SPI_IO_CR2_REG,
      LOONGSON_SPI_IO_CR2_DMAEN_MASK)
                                      loongson_spi_io_irq_handler()
                                        loongson_spi_writel(...,
                                          LOONGSON_SPI_IO_IER_REG, 0);
                                        priv->xfer_ret = -EIO;
                                        complete(&priv->xfer_completion);
    priv->xfer_ret = 0;
    reinit_completion(&priv->xfer_completion);
    ...
    loongson_spi_dma_wait_eot()       <-- waits with IER_REG == 0 until timeout

Also, loongson_spi_io_transfer_one_dma() clears LOONGSON_SPI_IO_SR1_EOT
with loongson_spi_update_bits() on the write-1-to-clear
LOONGSON_SPI_IO_SR1_REG register, which writes back 1s to any other set
status bits in SR1_REG.

> +
> +out_stop:
> +	loongson_spi_update_bits(priv, LOONGSON_SPI_IO_IER_REG,
> +				 LOONGSON_SPI_IO_IER_EOTIE |
> +				 LOONGSON_SPI_IO_IER_ERR_MASK, 0);
> +	priv->xfer_mode = XFER_IDLE;
> +
> +	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);
> +
> +	/* Quiesce both DMA channels before returning. */
> +	dmaengine_terminate_sync(priv->dma_tx);
> +	dmaengine_terminate_sync(priv->dma_rx);
> +
> +	return ret;
> +}

[Severity: High]
Does terminating priv->dma_rx immediately after LOONGSON_SPI_IO_SR1_EOT
truncate the trailing bytes of xfer->rx_buf?

The SPI controller raises LOONGSON_SPI_IO_SR1_EOT when the last frame is
shifted from the wire into the SPI RX FIFO, which is when the final RX DMA
request is asserted to drain the FIFO into memory.  loongson_spi_dma_config_and_submit()
does not set a completion callback (or DMA_PREP_INTERRUPT) on rx_desc, and
out_stop immediately clears LOONGSON_SPI_IO_CR2_DMAEN_MASK and calls
dmaengine_terminate_sync(priv->dma_rx) upon EOT.  Any frames still in the RX
FIFO or in flight in the RX DMA channel are never written to xfer->rx_buf,
and because loongson_spi_io_drain_rx() only runs at message boundaries,
leftover RX FIFO bytes corrupt the start of the next transfer in a
multi-transfer message.

[Severity: Medium]
Can out_stop race with loongson_spi_io_irq_handler() when
loongson_spi_dma_wait_eot() times out?

CPU0                                  CPU1 (<hardirq>)
loongson_spi_dma_transfer()
  loongson_spi_dma_wait_eot()
    /* timeout */
  loongson_spi_update_bits(...,
    LOONGSON_SPI_IO_IER_REG, ..., 0)
                                      loongson_spi_io_irq_handler()
                                        /* error branch reads CR1 */
  priv->xfer_mode = XFER_IDLE;
  loongson_spi_update_bits(...,
    LOONGSON_SPI_IO_CR1_REG,
    LOONGSON_SPI_IO_CR1_CSTART, 0)
                                        loongson_spi_update_bits(...,
                                          LOONGSON_SPI_IO_CR1_REG,
                                          LOONGSON_SPI_IO_CR1_START_MASK, 0)
                                          <-- RMW races on CR1_REG

Unlike loongson_spi_io_handle_err(), out_stop does not call
synchronize_irq(priv->irq) after masking LOONGSON_SPI_IO_IER_REG before
modifying priv->xfer_mode and LOONGSON_SPI_IO_CR1_REG, so a concurrent
interrupt can hit the XFER_IDLE warning without clearing CSTART or race on
the unlocked read-modify-write of LOONGSON_SPI_IO_CR1_REG.

[ ... ]
> @@ -623,13 +888,54 @@ static int loongson_spi_io_transfer_one_irq(struct spi_device *spi, struct spi_t
>  	return priv->xfer_ret;
>  }
>  
> +/**
> + * loongson_spi_io_transfer_one_dma() - Execute one DMA-driven SPI transfer
> + * @spi: SPI target device
> + * @xfer: transfer to execute
> + *
> + * Enable EOT and error interrupts, then submit both DMA channels via
> + * loongson_spi_dma_transfer(). The transfer is retried in interrupt mode on
> + * configuration failure before the bus has started; runtime DMA errors are
> + * returned to SPI core without replay.
> + *
> + * Return: 0 on success, or a negative error code.
> + */
> +static int loongson_spi_io_transfer_one_dma(struct spi_device *spi, struct spi_transfer *xfer)
> +{
[ ... ]
> +	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 with %d, using interrupt mode", ret);
> +
> +	return loongson_spi_io_transfer_one_irq(spi, xfer);
> +}

[Severity: Medium]
When loongson_spi_dma_transfer() fails before bus_started, does falling back
directly to loongson_spi_io_transfer_one_irq() corrupt xfer->rx_buf while
xfer->rx_sg is still mapped for DMA?

Before calling transfer_one(), spi_transfer_one_message() calls
spi_dma_sync_for_device(), giving ownership of xfer->rx_sg to the DMA
device.  If loongson_spi_io_transfer_one_irq() writes received data into
xfer->rx_buf with the CPU and returns 0, spi_transfer_one_message() then
calls spi_dma_sync_for_cpu() on the still-mapped xfer->rx_sg, which
overwrites or invalidates the PIO-written data when bounce buffers or
non-coherent caches are used.  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.

> +
>  /**
>   * loongson_spi_io_transfer_one() - Execute one SPI transfer
>   * @ctrl: SPI controller
>   * @spi: SPI target device
>   * @xfer: transfer to execute
>   *
> - * Apply clock and mode state before running interrupt-driven FIFO batches.
> + * Apply clock and mode state, then run the transfer via DMA or
> + * interrupt-driven FIFO batches.
>   *
>   * Return: 0 on success, or a negative error code.
>   */
> @@ -645,6 +951,9 @@ static int loongson_spi_io_transfer_one(struct spi_controller *ctrl, struct spi_
>  	if (ret)
>  		return ret;
>  
> +	if (ctrl->can_dma && ctrl->can_dma(ctrl, spi, xfer))
> +		return loongson_spi_io_transfer_one_dma(spi, xfer);
> +
>  	return loongson_spi_io_transfer_one_irq(spi, xfer);
>  }

[Severity: Medium]
What happens if dma_threshold (0644 in sysfs) changes between
__spi_map_msg() and loongson_spi_io_transfer_one()?

If dma_threshold is lowered after __spi_map_msg() decided not to map the
transfer, ctrl->can_dma() returns true here with an unmapped scatterlist
(xfer->rx_sg.sgl == NULL, xfer->rx_sg.nents == 0);
loongson2_cmc_dma_prep_slave_sg() then allocates a 0-element desc->sg_req[]
flexible array and loongson2_cmc_dma_start_transfer() reads
desc->sg_req[0] out of bounds.  Conversely, if dma_threshold is raised after
__spi_map_msg() mapped the transfer, this falls back to
loongson_spi_io_transfer_one_irq() on a buffer synced for DMA_FROM_DEVICE.
Checking xfer->tx_sg_mapped && xfer->rx_sg_mapped (or
spi_xfer_is_dma_mapped()) avoids re-evaluating can_dma().

[ ... ]
> @@ -741,11 +1062,40 @@ static int loongson_spi_io_unprepare_message(struct spi_controller *ctrl,
>  	return 0;
>  }
>  
> +/**
> + * 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;
> +}
[ ... ]
> @@ -794,6 +1146,29 @@ static int loongson_spi_io_probe(struct platform_device *pdev)
>  							 LOONGSON_SPI_IO_CFG2_MAX_BRINT),
>  					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 if (priv->dma_tx || priv->dma_rx) {
> +		return dev_err_probe(dev, -EINVAL,
> +				     "Both 'tx' and 'rx' DMA channels are required");
> +	} else {
> +		dev_info(dev, "no DMA channels, using interrupt mode only");
> +	}

[Severity: Medium]
If one DMA channel is acquired and the second fails with a non-deferral
error (for example when the shared DMA controller has only one free channel
left), loongson_spi_io_request_dma_chan() logs "using interrupt mode" and
returns NULL, but the else-if branch here then fails probe with -EINVAL.
Should loongson_spi_io_probe() fall back to interrupt-only mode when only
one channel is available, matching the comment on
loongson_spi_io_request_dma_chan()?

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796005812.git.zhoubinbin@loongson.cn?part=4

^ permalink raw reply	[flat|nested] 8+ messages in thread

end of thread, other threads:[~2026-11-30  2:53 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-30  2:32 [PATCH v2 0/5] spi: loongson: SPI-IO driver for Loongson-2K0300 Binbin Zhou
2026-11-30  2:33 ` [PATCH v2 1/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi compatible Binbin Zhou
2026-11-30  2:33 ` [PATCH v2 2/5] spi: dt-bindings: loongson,ls2k-spi: Document loongson,ls2k0300-spi-io compatible Binbin Zhou
2026-11-30  2:33 ` [PATCH v2 3/5] spi: loongson: Add spi-io interrupt-driven driver Binbin Zhou
2026-11-30  2:48   ` sashiko-bot
2026-11-30  2:33 ` [PATCH v2 4/5] spi: loongson: Add DMA support to SPI-IO driver Binbin Zhou
2026-11-30  2:53   ` sashiko-bot
2026-11-30  2:33 ` [PATCH v2 5/5] MAINTAINERS: Add myself as Loongson SPI maintainer Binbin Zhou

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox