Skip to contentSkip to conversation

Apple M1 (Pro/Max) NVMe driver

PATCH Superseded Sven Peter 12 participants 55 messages Mar 21, 2022 – Apr 5, 2022

Subsystems (3)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Sven Peter

author
#0 lore raw

cover Apple M1 (Pro/Max) NVMe driver

Hi,

This series includes everything[*] required to get NVMe up and running on Apple's M1, M1 Pro and M1 Max SoCs.

The NVMe controller on these machines is not attached to a PCI bus and this driver originally started out when Arnd added platform support to pci.c and I added the required Apple quirks. Christoph Hellwig stumbled upon an early version and suggested to instead rewrite it as a stand-alone driver since some of these quirks are rather awkward to implement and would affect the hot path otherwise [1].

Here's the first version that creates apple.c to handle these weird NVMe controllers. The following parts are included:

- Device tree bindings: Since this is the first and probably only SoC that has NVMe outside of a PCIe bus I've put them into soc/apple. The same bindings are also used by u-boot and OpenBSD already.

- SART address filter: Some of the buffers required by the NVMe controller sit behind a simple DMA address filter Apple calls SART. It allows to specify up to 16 physical address ranges that are allowed and will reject access to anything else. Unlike a real IOMMU there's no way to setup pagetables and also not all buffers are subject to this filtering. Most buffers used by the NVMe commands themselves use an integrated IOMMU instead.

- RTKit IPC protocol: The NVMe controller is running a proprietary RTOS Apple calls RTKit and we need to communicate with it in order to bring up and use the NVMe controller. This communication happens over a mailbox interface that is already upstream. This protocol is also used for various other drivers present on these SoCs (SMC, display controller, Thunderbolt/USB4).

- And finally the NVMe driver itself: The driver registers a platform device and is mainly based on pci.c with a few special Apple quirks. The biggest difference to normal NVMe (except for the missing PCI bus) is that command submission works differently: The SQ is replaced with a simple array and a command is triggered by writing its tag to a MMIO register. Additionally, the command must also be setup in the proprietary NVMMU before it can be submitted. There is some code duplication with pci.c for the setup of the PRPs. Depending on what you prefer this could be moved to a common file shared between pci.c and apple.c.

The hardware here is the same hardware that's already used in T2 Macs. The only difference is that the T2 chip itself initializes the controller, disable some quirks (the NVMMU and the weird submission array) and then exposes it over a PCIe interface.

The driver itself has been successfully used by multiple people as their daily driver for weeks at this point and no major issues have been reported.
A smaller issue is that flushes on the devices take *much* longer than expected. Jens Axboe has a workaround where the flushes are delayed but that one isn't ready for submission yet.

Best,

Sven

[1] https://lore.kernel.org/linux-nvme/[email protected]/
[*] The only missing part in this series are the device tree updates
but since these will go through arm-soc anyway I haven't included them here but will instead submit them once this series is in a shape where it can be merged.

Hector Martin (2):
nvme-apple: Add support for multiple power domains
nvme-apple: Add support for suspend/resume

Jens Axboe (1):
nvme-apple: Serialize command issue

Sven Peter (6):
dt-bindings: soc: apple: Add Apple SART
dt-bindings: soc: apple: Add ANS NVMe
soc: apple: Always include Makefile
soc: apple: Add SART driver
soc: apple: Add RTKit IPC library
nvme-apple: Add initial Apple SoC NVMe driver

 .../bindings/soc/apple/apple,nvme-ans.yaml    |   75 +
 .../bindings/soc/apple/apple,sart.yaml        |   52 +
 MAINTAINERS                                   |    3 +
 drivers/nvme/host/Kconfig                     |   12 +
 drivers/nvme/host/Makefile                    |    3 +
 drivers/nvme/host/apple.c                     | 1568 +++++++++++++++++
 drivers/soc/Makefile                          |    2 +-
 drivers/soc/apple/Kconfig                     |   24 +
 drivers/soc/apple/Makefile                    |    6 +
 drivers/soc/apple/rtkit-crashlog.c            |  147 ++
 drivers/soc/apple/rtkit-internal.h            |   76 +
 drivers/soc/apple/rtkit.c                     |  842 +++++++++
 drivers/soc/apple/sart.c                      |  318 ++++
 include/linux/soc/apple/rtkit.h               |  203 +++
 include/linux/soc/apple/sart.h                |   77 +
 15 files changed, 3407 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml
 create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,sart.yaml
 create mode 100644 drivers/nvme/host/apple.c
 create mode 100644 drivers/soc/apple/rtkit-crashlog.c
 create mode 100644 drivers/soc/apple/rtkit-internal.h
 create mode 100644 drivers/soc/apple/rtkit.c
 create mode 100644 drivers/soc/apple/sart.c
 create mode 100644 include/linux/soc/apple/rtkit.h
 create mode 100644 include/linux/soc/apple/sart.h
Signature · 1 line
2.25.1
author
#1 lore raw

PATCH 1/9 dt-bindings: soc: apple: Add Apple SART

Apple SoCs such as the M1 come with a simple DMA address filter called SART. Unlike a real IOMMU no pagetables can be configured but instead DMA transactions can be allowed for up to 16 paddr regions.

---
 .../bindings/soc/apple/apple,sart.yaml        | 52 +++++++++++++++++++
 MAINTAINERS                                   |  1 +
 2 files changed, 53 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,sart.yaml
Documentation/devicetree/bindings/soc/apple/apple,sart.yaml new file +52 -0
new file mode 100644
index 000000000000..d8177b3a3fba
@@ -0,0 +1,52 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/soc/apple/apple,sart.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Apple SART DMA address filter
+
+maintainers:
+  - Sven Peter <[email protected]>
+
+description:
+  Apple SART is a simple address filter for DMA transactions. Regions of
+  physical memory must be added to the SART's allow list before any
+  DMA can target these. Unlike a proper IOMMU no remapping can be done and
+  special support in the consumer driver is required since not all DMA
+  transactions of a single device are subject to SART filtering.
+
+  SART1 has first been used since at least the A11 (iPhone 8 and iPhone X)
+  and allows 36 bit of physical address space and filter entries with sizes
+  up to 24 bit.
+
+  SART2, first seen in A14 and M1, allows 36 bit of physical address space
+  and filter entry size up to 36 bit.
+
+  SART3, first seen in M1 Pro/Max, extends both the address space and filter
+  entry size to 42 bit.
+
+properties:
+  compatible:
+    enum:
+      - apple,t6000-sart
+      - apple,t8103-sart
+
+  reg:
+    maxItems: 1
+
+  power-domains:
+    maxItems: 1
+
+required:
+  - compatible
+  - reg
+
+additionalProperties: false
+
+examples:
+  - |
+    sart@7bc50000 {
+      compatible = "apple,t8103-sart";
+      reg = <0x7bc50000 0x4000>;
+    };
MAINTAINERS +1 -0
index cd0f68d4a34a..027c3b4ad61c 100644
@@ -1774,6 +1774,7 @@ F:	Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml
 F:	Documentation/devicetree/bindings/pci/apple,pcie.yaml
 F:	Documentation/devicetree/bindings/pinctrl/apple,pinctrl.yaml
 F:	Documentation/devicetree/bindings/power/apple*
+F:	Documentation/devicetree/bindings/soc/apple/*
 F:	Documentation/devicetree/bindings/watchdog/apple,wdt.yaml
 F:	arch/arm64/boot/dts/apple/
 F:	drivers/i2c/busses/i2c-pasemi-core.c
Signature · 1 line
2.25.1
author
#4 lore raw

PATCH 2/9 dt-bindings: soc: apple: Add ANS NVMe

In reply to Sven Peter

Apple SoCs such as the M1 come with an embedded NVMe coprocessor called ANS2.

---
 .../bindings/soc/apple/apple,nvme-ans.yaml    | 75 +++++++++++++++++++
 1 file changed, 75 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml
Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml new file +75 -0
new file mode 100644
index 000000000000..e1f4c1c572aa
@@ -0,0 +1,75 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/soc/apple/apple,nvme-ans.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Apple ANS NVM Express host controller
+
+maintainers:
+  - Sven Peter <[email protected]>
+
+properties:
+  compatible:
+    items:
+      - enum:
+          - apple,t8103-nvme-ans2
+          - apple,t6000-nvme-ans2
+      - const: apple,nvme-ans2
+
+  reg:
+    items:
+      - description: NVMe and NVMMU registers
+      - description: ANS2 co-processor control registers
+
+  reg-names:
+    items:
+      - const: nvme
+      - const: ans
+
+  resets:
+    maxItems: 1
+
+  power-domains: true
+
+  mboxes:
+    maxItems: 1
+    description: Mailbox of the ANS2 co-processor
+
+  interrupts:
+    maxItems: 1
+
+  apple,sart:
+    maxItems: 1
+    $ref: /schemas/types.yaml#/definitions/phandle
+    description: |
+      Reference to the SART address filter.
+
+      The SART address filter is documented in apple,sart.yaml.
+
+required:
+  - compatible
+  - reg
+  - reg-names
+  - resets
+  - mboxes
+  - interrupts
+  - apple,sart
+
+additionalProperties: false
+
+examples:
+  - |
+    #include <dt-bindings/interrupt-controller/apple-aic.h>
+    #include <dt-bindings/interrupt-controller/irq.h>
+
+    nvme@7bcc0000 {
+      compatible = "apple,t8103-nvme-ans2", "apple,nvme-ans2";
+      reg = <0x7bcc0000 0x40000>, <0x77400000 0x4000>;
+      reg-names = "nvme", "ans";
+      interrupts = <AIC_IRQ 590 IRQ_TYPE_LEVEL_HIGH>;
+      mboxes = <&ans>;
+      apple,sart = <&sart>;
+      power-domains = <&ps_ans2>;
+      resets = <&ps_ans2>;
+     };
Signature · 1 line
2.25.1
author
#8 lore raw

PATCH 3/9 soc: apple: Always include Makefile

In reply to Sven Peter

We want to allow the code inside drivers/soc/apple to be compiled with COMPILE_TEST but this will currently result in linking errors because ARCH_APPLE is not set and make will never recurse into drivers/soc/apple.
Let's just unconditionally recurse into apple/ since all drivers in there are guarded by config options anyways.

---
 drivers/soc/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/soc/Makefile +1 -1
index adb30c2d4fea..608f8ce8b600 100644
@@ -4,7 +4,7 @@
 #
 
 obj-$(CONFIG_ARCH_ACTIONS)	+= actions/
-obj-$(CONFIG_ARCH_APPLE)	+= apple/
+obj-y				+= apple/
 obj-y				+= aspeed/
 obj-$(CONFIG_ARCH_AT91)		+= atmel/
 obj-y				+= bcm/
Signature · 1 line
2.25.1
author
#9 lore raw

PATCH 4/9 soc: apple: Add SART driver

In reply to Sven Peter

The NVMe co-processor on the Apple M1 uses a DMA address filter called SART for some DMA transactions. This adds a simple driver used to configure the memory regions from which DMA transactions are allowed.

---
 MAINTAINERS                    |   1 +
 drivers/soc/apple/Kconfig      |  11 ++
 drivers/soc/apple/Makefile     |   3 +
 drivers/soc/apple/sart.c       | 318 +++++++++++++++++++++++++++++++++
 include/linux/soc/apple/sart.h |  77 ++++++++
 5 files changed, 410 insertions(+)
 create mode 100644 drivers/soc/apple/sart.c
 create mode 100644 include/linux/soc/apple/sart.h
MAINTAINERS +1 -0
index 027c3b4ad61c..3d37fe7a0408 100644
@@ -1787,6 +1787,7 @@ F:	drivers/watchdog/apple_wdt.c
 F:	include/dt-bindings/interrupt-controller/apple-aic.h
 F:	include/dt-bindings/pinctrl/apple.h
 F:	include/linux/apple-mailbox.h
+F:	include/linux/soc/apple/*
 
 ARM/ARTPEC MACHINE SUPPORT
 M:	Jesper Nilsson <[email protected]>
drivers/soc/apple/Kconfig +11 -0
index 9b8de31d6a8f..8c37ffd53fbd 100644
@@ -17,6 +17,17 @@ config APPLE_PMGR_PWRSTATE
 	  controls for SoC devices. This driver manages them through the
 	  generic power domain framework, and also provides reset support.
 
+config APPLE_SART
+	tristate "Apple SART DMA address filter"
+	depends on ARCH_APPLE || COMPILE_TEST
+	default ARCH_APPLE
+	help
+	  Apple SART is a simple DMA address filter used on Apple SoCs such
+	  as the M1. It is usually required for the NVMe coprocessor which does
+	  not use a proper IOMMU.
+
+	  Say 'y' here if you have an Apple SoC.
+
 endmenu
 
 endif
drivers/soc/apple/Makefile +3 -0
index c114e84667e4..c83c66317098 100644
@@ -1,2 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0-only
 obj-$(CONFIG_APPLE_PMGR_PWRSTATE)	+= apple-pmgr-pwrstate.o
+
+obj-$(CONFIG_APPLE_SART) += apple-sart.o
+apple-sart-y = sart.o
drivers/soc/apple/sart.c new file +318 -0

318 lines not on this page · raw message

include/linux/soc/apple/sart.h new file +77 -0

77 lines not on this page · raw message

Signature · 1 line
2.25.1
author
#18 lore raw

PATCH 5/9 soc: apple: Add RTKit IPC library

In reply to Sven Peter

Apple SoCs such as the M1 come with multiple embedded co-processors running proprietary firmware. Communication with those is established over a simple mailbox using the RTKit IPC protocol.

---
 drivers/soc/apple/Kconfig          |  13 +
 drivers/soc/apple/Makefile         |   3 +
 drivers/soc/apple/rtkit-crashlog.c | 147 +++++
 drivers/soc/apple/rtkit-internal.h |  76 +++
 drivers/soc/apple/rtkit.c          | 842 +++++++++++++++++++++++++++++
 include/linux/soc/apple/rtkit.h    | 203 +++++++
 6 files changed, 1284 insertions(+)
 create mode 100644 drivers/soc/apple/rtkit-crashlog.c
 create mode 100644 drivers/soc/apple/rtkit-internal.h
 create mode 100644 drivers/soc/apple/rtkit.c
 create mode 100644 include/linux/soc/apple/rtkit.h
drivers/soc/apple/Kconfig +13 -0
index 8c37ffd53fbd..feb56419ac3c 100644
@@ -17,6 +17,19 @@ config APPLE_PMGR_PWRSTATE
 	  controls for SoC devices. This driver manages them through the
 	  generic power domain framework, and also provides reset support.
 
+config APPLE_RTKIT
+	tristate "Apple RTKit co-processor IPC protocol"
+	depends on MAILBOX
+	depends on ARCH_APPLE || (COMPILE_TEST && 64BIT)
+	default ARCH_APPLE
+	help
+	  Apple SoCs such as the M1 come with various co-processors running
+	  their proprietary RTKit operating system. This option enables support
+	  for the protocol library used to communicate with those. It is used
+	  by various client drivers.
+
+	  Say 'y' here if you have an Apple SoC.
+
 config APPLE_SART
 	tristate "Apple SART DMA address filter"
 	depends on ARCH_APPLE || COMPILE_TEST
drivers/soc/apple/Makefile +3 -0
index c83c66317098..e293770cf66d 100644
@@ -1,5 +1,8 @@
 # SPDX-License-Identifier: GPL-2.0-only
 obj-$(CONFIG_APPLE_PMGR_PWRSTATE)	+= apple-pmgr-pwrstate.o
 
+obj-$(CONFIG_APPLE_RTKIT) += apple-rtkit.o
+apple-rtkit-y = rtkit.o rtkit-crashlog.o
+
 obj-$(CONFIG_APPLE_SART) += apple-sart.o
 apple-sart-y = sart.o
drivers/soc/apple/rtkit-crashlog.c new file +147 -0

147 lines not on this page · raw message

drivers/soc/apple/rtkit-internal.h new file +76 -0

76 lines not on this page · raw message

drivers/soc/apple/rtkit.c new file +842 -0

842 lines not on this page · raw message

include/linux/soc/apple/rtkit.h new file +203 -0

203 lines not on this page · raw message

Signature · 1 line
2.25.1
author
#31 lore raw

PATCH 6/9 nvme-apple: Add initial Apple SoC NVMe driver

In reply to Sven Peter

Apple SoCs such as the M1 come with an embedded NVMe controller that is not attached to any PCIe bus. Additionally, it doesn't confirm to the NVMe specification and requires a bunch of changes to command submission and IOMMU configuration to work.

---
 MAINTAINERS                |    1 +
 drivers/nvme/host/Kconfig  |   12 +
 drivers/nvme/host/Makefile |    3 +
 drivers/nvme/host/apple.c  | 1456 ++++++++++++++++++++++++++++++++++++
 4 files changed, 1472 insertions(+)
 create mode 100644 drivers/nvme/host/apple.c
MAINTAINERS +1 -0
index 3d37fe7a0408..0a493298b6ff 100644
@@ -1781,6 +1781,7 @@ F:	drivers/i2c/busses/i2c-pasemi-core.c
 F:	drivers/i2c/busses/i2c-pasemi-platform.c
 F:	drivers/irqchip/irq-apple-aic.c
 F:	drivers/mailbox/apple-mailbox.c
+F:	drivers/nvme/host/apple.c
 F:	drivers/pinctrl/pinctrl-apple-gpio.c
 F:	drivers/soc/apple/*
 F:	drivers/watchdog/apple_wdt.c
drivers/nvme/host/Kconfig +12 -0
index dc0450ca23a3..439848a4b685 100644
@@ -83,3 +83,15 @@ config NVME_TCP
 	  from https://github.com/linux-nvme/nvme-cli.
 
 	  If unsure, say N.
+
+config NVME_APPLE
+	tristate "Apple ANS2 NVM Express host driver"
+	depends on OF && BLOCK
+	depends on (APPLE_RTKIT && APPLE_SART && ARCH_APPLE) || COMPILE_TEST
+	select NVME_CORE
+	help
+	  This provides support for the NVMe controller embedded in Apple SoCs
+	  such as the M1.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called nvme-apple.
drivers/nvme/host/Makefile +3 -0
index dfaacd472e5d..2927820c70a3 100644
@@ -8,6 +8,7 @@ obj-$(CONFIG_NVME_FABRICS)		+= nvme-fabrics.o
 obj-$(CONFIG_NVME_RDMA)			+= nvme-rdma.o
 obj-$(CONFIG_NVME_FC)			+= nvme-fc.o
 obj-$(CONFIG_NVME_TCP)			+= nvme-tcp.o
+obj-$(CONFIG_NVME_APPLE)		+= nvme-apple.o
 
 nvme-core-y				:= core.o ioctl.o
 nvme-core-$(CONFIG_TRACING)		+= trace.o
@@ -25,3 +26,5 @@ nvme-rdma-y				+= rdma.o
 nvme-fc-y				+= fc.o
 
 nvme-tcp-y				+= tcp.o
+
+nvme-apple-y				+= apple.o
drivers/nvme/host/apple.c new file +1456 -0

1,456 lines not on this page · raw message

Signature · 1 line
2.25.1
author
#48 lore raw

PATCH 7/9 nvme-apple: Serialize command issue

In reply to Sven Peter

From: Jens Axboe <[email protected]>

This controller shouldn't need serialization of command issue since the SQ is replaced by a simple array and commands are issued by writing the array index to a MMIO register.
Without serialization however sometimes commands are still executed correctly and appear in the CQ but never trigger an interrupt.

[sven: added our best guess why this needs to be done]
---
 drivers/nvme/host/apple.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
drivers/nvme/host/apple.c +12 -0
index 587d6c7014a0..a4193429564e 100644
@@ -292,6 +292,7 @@ static void apple_nvmmu_inval(struct apple_nvme_queue *q, unsigned int tag)
 static void apple_nvme_submit_cmd(struct apple_nvme_queue *q,
 				  struct nvme_command *cmd)
 {
+	struct apple_nvme *anv = queue_to_apple_nvme(q);
 	u32 tag = nvme_tag_from_cid(cmd->common.command_id);
 	struct apple_nvmmu_tcb *tcb = &q->tcbs[tag];
 
@@ -308,7 +309,18 @@ static void apple_nvme_submit_cmd(struct apple_nvme_queue *q,
 		tcb->dma_flags |= APPLE_ANS_TCB_DMA_FROM_DEVICE;
 
 	memcpy(&q->sqes[tag], cmd, sizeof(*cmd));
+
+	/*
+	 * This lock here doesn't make much sense at a first glace but
+	 * removing it will result in occasional missed completetion
+	 * interrupts even though the commands still appear on the CQ.
+	 * It's unclear why this happens but our best guess is that
+	 * there is a bug in the firmware triggered when a write to the
+	 * CQ and the SQ happen simultaneously.
+	 */
+	spin_lock_irq(&anv->lock);
 	writel(tag, q->sq_db);
+	spin_unlock_irq(&anv->lock);
 }
 
 /*
Signature · 1 line
2.25.1
author
#51 lore raw

PATCH 8/9 nvme-apple: Add support for multiple power domains

In reply to Sven Peter

From: Hector Martin <[email protected]>

Turns out we really need this, as the APCIE_ST*_SYS domains really do hard-depend on ANS2, at least on t6000.

---
 drivers/nvme/host/apple.c | 67 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 67 insertions(+)
drivers/nvme/host/apple.c +67 -0
index a4193429564e..d89b4ab80169 100644
@@ -29,6 +29,7 @@
 #include <linux/of_platform.h>
 #include <linux/once.h>
 #include <linux/platform_device.h>
+#include <linux/pm_domain.h>
 #include <linux/soc/apple/rtkit.h>
 #include <linux/soc/apple/sart.h>
 #include <linux/reset.h>
@@ -178,6 +179,10 @@ struct apple_nvme {
 	void __iomem *mmio_coproc;
 	void __iomem *mmio_nvme;
 
+	struct device **pd_dev;
+	struct device_link **pd_link;
+	int pd_count;
+
 	struct apple_sart *sart;
 	struct apple_rtkit *rtk;
 	struct reset_control *reset;
@@ -1313,6 +1318,62 @@ static int apple_nvme_queue_alloc(struct apple_nvme *anv,
 	return 0;
 }
 
+static void apple_nvme_detach_genpd(struct apple_nvme *anv)
+{
+	int i;
+
+	if (anv->pd_count <= 1)
+		return;
+
+	for (i = anv->pd_count - 1; i >= 0; i--) {
+		if (anv->pd_link[i])
+			device_link_del(anv->pd_link[i]);
+		if (!IS_ERR_OR_NULL(anv->pd_dev[i]))
+			dev_pm_domain_detach(anv->pd_dev[i], true);
+	}
+}
+
+static int apple_nvme_attach_genpd(struct apple_nvme *anv)
+{
+	struct device *dev = anv->dev;
+	int i;
+
+	anv->pd_count = of_count_phandle_with_args(dev->of_node,
+						   "power-domains",
+						   "#power-domain-cells");
+	if (anv->pd_count <= 1)
+		return 0;
+
+	anv->pd_dev = devm_kcalloc(dev, anv->pd_count, sizeof(*anv->pd_dev),
+				   GFP_KERNEL);
+	if (!anv->pd_dev)
+		return -ENOMEM;
+
+	anv->pd_link = devm_kcalloc(dev, anv->pd_count, sizeof(*anv->pd_link),
+				    GFP_KERNEL);
+	if (!anv->pd_link)
+		return -ENOMEM;
+
+	for (i = 0; i < anv->pd_count; i++) {
+		anv->pd_dev[i] = dev_pm_domain_attach_by_id(dev, i);
+		if (IS_ERR(anv->pd_dev[i])) {
+			apple_nvme_detach_genpd(anv);
+			return PTR_ERR(anv->pd_dev[i]);
+		}
+
+		anv->pd_link[i] = device_link_add(dev, anv->pd_dev[i],
+						  DL_FLAG_STATELESS |
+						  DL_FLAG_PM_RUNTIME |
+						  DL_FLAG_RPM_ACTIVE);
+		if (!anv->pd_link[i]) {
+			apple_nvme_detach_genpd(anv);
+			return -EINVAL;
+		}
+	}
+
+	return 0;
+}
+
 static int apple_nvme_probe(struct platform_device *pdev)
 {
 	struct device *dev = &pdev->dev;
@@ -1327,6 +1388,10 @@ static int apple_nvme_probe(struct platform_device *pdev)
 	anv->adminq.is_adminq = true;
 	platform_set_drvdata(pdev, anv);
 
+	ret = apple_nvme_attach_genpd(anv);
+	if (ret < 0)
+		return dev_err_probe(dev, ret, "Failed to attach power domains");
+
 	if (dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64)))
 		return -ENXIO;
 
@@ -1435,6 +1500,8 @@ static int apple_nvme_remove(struct platform_device *pdev)
 	if (apple_rtkit_is_running(anv->rtk))
 		apple_rtkit_shutdown(anv->rtk);
 
+	apple_nvme_detach_genpd(anv);
+
 	return 0;
 }
 
Signature · 1 line
2.25.1
author
#52 lore raw

PATCH 9/9 nvme-apple: Add support for suspend/resume

In reply to Sven Peter

From: Hector Martin <[email protected]>

---
 drivers/nvme/host/apple.c | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
drivers/nvme/host/apple.c +33 -0
index d89b4ab80169..c949a18ec690 100644
@@ -1514,6 +1514,36 @@ static void apple_nvme_shutdown(struct platform_device *pdev)
 		apple_rtkit_shutdown(anv->rtk);
 }
 
+#ifdef CONFIG_PM_SLEEP
+static int apple_nvme_resume(struct device *dev)
+{
+	struct apple_nvme *anv = dev_get_drvdata(dev);
+
+	return  nvme_reset_ctrl(&anv->ctrl);
+}
+
+static int apple_nvme_suspend(struct device *dev)
+{
+	struct apple_nvme *anv = dev_get_drvdata(dev);
+	int ret = 0;
+
+	apple_nvme_disable(anv, true);
+
+	if (apple_rtkit_is_running(anv->rtk))
+		ret = apple_rtkit_shutdown(anv->rtk);
+
+	writel_relaxed(0, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL);
+	(void)readl_relaxed(anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL);
+
+	return ret;
+}
+
+static const struct dev_pm_ops apple_nvme_pm_ops = {
+	.suspend	= apple_nvme_suspend,
+	.resume		= apple_nvme_resume,
+};
+#endif
+
 static const struct of_device_id apple_nvme_of_match[] = {
 	{ .compatible = "apple,nvme-ans2" },
 	{},
@@ -1524,6 +1554,9 @@ static struct platform_driver apple_nvme_driver = {
 	.driver = {
 		.name = "nvme-apple",
 		.of_match_table = apple_nvme_of_match,
+#ifdef CONFIG_PM_SLEEP
+		.pm = &apple_nvme_pm_ops,
+#endif
 	},
 	.probe = apple_nvme_probe,
 	.remove = apple_nvme_remove,
Signature · 1 line
2.25.1
maintainer
#32 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Sven Peter
Quoted 9 lines · Sven Peter
drivers/nvme/host/apple.c new file +9 -0
+static bool apple_nvme_poll_cq(struct apple_nvme_queue *q,
+			       struct io_comp_batch *iob)
+{
+	bool found = false;
+
+	while (apple_nvme_cqe_pending(q)) {
+		found = true;
+
+		/*

drivers/nvme/host/apple.c line 633

Quoted 10 lines
drivers/nvme/host/apple.c new file +10 -0
+		 * load-load control dependency between phase and the rest of
+		 * the cqe requires a full read memory barrier
+		 */
+		dma_rmb();
+		apple_nvme_handle_cqe(q, iob, q->cq_head);
+		apple_nvme_update_cq_head(q);
+	}
+
+	if (found)
+		writel_relaxed(q->cq_head, q->cq_db);

Doesn't a relaxed write mean that a subsequent write can bypass the previous? If so, that sounds like it can corrupt the cq head.

#10 lore raw

Re: [PATCH 4/9] soc: apple: Add SART driver

In reply to Sven Peter
Quoted 8 lines · Sven Peter

The NVMe co-processor on the Apple M1 uses a DMA address filter called SART for some DMA transactions. This adds a simple driver used to configure the memory regions from which DMA transactions are allowed.

Can you add some explanation about why this uses a custom interface instead of hooking into the dma_map_ops?

drivers/soc/apple/sart.c line 71

Quoted 5 lines
drivers/soc/apple/sart.c new file +5 -0
+static void sart2_get_entry(struct apple_sart *sart, int index, u8 *flags,
+                           phys_addr_t *paddr, size_t *size)
+{
+       u32 cfg = readl_relaxed(sart->regs + APPLE_SART2_CONFIG(index));
+       u32 paddr_ = readl_relaxed(sart->regs + APPLE_SART2_PADDR(index));

Why do you use the _relaxed() accessors here and elsewhere in the driver?

drivers/soc/apple/sart.c line 191

Quoted 9 lines
drivers/soc/apple/sart.c new file +9 -0
+struct apple_sart *apple_sart_get(struct device *dev)
+{
+       struct device_node *sart_node;
+       struct platform_device *sart_pdev;
+       struct apple_sart *sart;
+
+       sart_node = of_parse_phandle(dev->of_node, "apple,sart", 0);
+       if (!sart_node)
+               return ERR_PTR(ENODEV);

The error pointers need to take negative values, like 'ERR_PTR(-ENODEV)', here and everywhere else in the driver.

Arnd

#16 lore raw

Re: [PATCH 4/9] soc: apple: Add SART driver

In reply to Sven Peter
Quoted 12 lines
include/linux/soc/apple/sart.h new file +12 -0
+/*
+ * Adds the region [paddr, paddr+size] to the DMA allow list.
+ *
+ * @sart: SART reference
+ * @paddr: Start address of the region to be used for DMA
+ * @size: Size of the region to be used for DMA.
+ */
+int apple_sart_add_allowed_region(struct apple_sart *sart, phys_addr_t paddr,
+				  size_t size);
+
+/*
+ * Removes the region [paddr, paddr+size] from the DMA allow list.

include/linux/soc/apple/sart.h line 53

Quoted 10 lines
include/linux/soc/apple/sart.h new file +10 -0
+ *
+ * Note that exact same paddr and size used for apple_sart_add_allowed_region
+ * have to be passed.
+ *
+ * @sart: SART reference
+ * @paddr: Start address of the region no longer used for DMA
+ * @size: Size of the region no longer used for DMA.
+ */
+int apple_sart_remove_allowed_region(struct apple_sart *sart, phys_addr_t paddr,
+				     size_t size);

Might it be simpler for add_allowed_region to return a handle that remove_allowed_region takes instead of paddr+size? Then remove_allowed_region doesn't have to walk anything, and the requirement to use the same paddr/size is implicit.

#19 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Sven Peter

drivers/soc/apple/rtkit-internal.h line 27

Quoted 12 lines · Sven Peter

Apple SoCs such as the M1 come with multiple embedded co-processors running proprietary firmware. Communication with those is established over a simple mailbox using the RTKit IPC protocol.

drivers/soc/apple/rtkit-internal.h new file +5 -0
+
+#define rtk_err(format, arg...) dev_err(rtk->dev, "RTKit: " format, ##arg)
+#define rtk_warn(format, arg...) dev_warn(rtk->dev, "RTKit: " format, ##arg)
+#define rtk_info(format, arg...) dev_info(rtk->dev, "RTKit: " format, ##arg)
+#define rtk_dbg(format, arg...) dev_dbg(rtk->dev, "RTKit: " format, ##arg)

I generally don't like the custom printing macros, please just open-code the prints where they are used, that makes it easier for other kernel developers to see exactly what is being printed.

drivers/soc/apple/rtkit.c line 20

Quoted 10 lines
drivers/soc/apple/rtkit.c new file +10 -0
+enum { APPLE_RTKIT_WORK_MSG,
+       APPLE_RTKIT_WORK_REINIT,
+};
+
+enum { APPLE_RTKIT_PWR_STATE_OFF = 0x00,
+       APPLE_RTKIT_PWR_STATE_SLEEP = 0x01,
+       APPLE_RTKIT_PWR_STATE_GATED = 0x02,
+       APPLE_RTKIT_PWR_STATE_QUIESCED = 0x10,
+       APPLE_RTKIT_PWR_STATE_ON = 0x20,
+};

This is an odd indentation style, I would insert a newline after the 'enum {'

Quoted 14 lines
drivers/soc/apple/rtkit.c new file +14 -0
+static int apple_rtkit_worker(void *data)
+{
+       struct apple_rtkit *rtk = data;
+       struct apple_rtkit_work work;
+
+       while (!kthread_should_stop()) {
+               wait_event_interruptible(rtk->wq,
+                                        kfifo_len(&rtk->work_fifo) > 0 ||
+                                                kthread_should_stop());
+
+               if (kthread_should_stop())
+                       break;
+
+               while (kfifo_out_spinlocked(&rtk->work_fifo, &work, 1,

drivers/soc/apple/rtkit.c line 530

Quoted 10 lines
drivers/soc/apple/rtkit.c new file +10 -0
+                                           &rtk->work_lock) == 1) {
+                       switch (work.type) {
+                       case APPLE_RTKIT_WORK_MSG:
+                               apple_rtkit_rx(rtk, &work.msg);
+                               break;
+                       case APPLE_RTKIT_WORK_REINIT:
+                               apple_rtkit_do_reinit(rtk);
+                               break;
+                       }
+               }

It looks like you add quite a bit of complexity by using a custom worker thread implementation. Can you explain what this is needed for? Isn't this roughly the same thing that one would get more easily with create_singlethread_workqueue()?

Quoted 1 line

+#if IS_ENABLED(CONFIG_APPLE_RTKIT)

Instead of allowing the interface to be used without CONFIG_APPLE_RTKIT, I think it is sufficient to allow the driver itself to be built with CONFIG_COMPILE_TEST (as you already do), and then have drivers using it marked as 'depends on APPLE_RTKIT' unconditionally.

Quoted 10 lines
include/linux/soc/apple/rtkit.h new file +10 -0
+/*
+ * Initializes the internal state required to handle RTKit. This
+ * should usually be called within _probe.
+ *
+ * @dev: Pointer to the device node this coprocessor is assocated with
+ * @cookie: opaque cookie passed to all functions defined in rtkit_ops
+ * @mbox_name: mailbox name used to communicate with the co-processor
+ * @mbox_idx: mailbox index to be used if mbox_name is NULL
+ * @ops: pointer to rtkit_ops to be used for this co-processor
+ */

include/linux/soc/apple/rtkit.h line 80

Quoted 10 lines
include/linux/soc/apple/rtkit.h new file +10 -0
+struct apple_rtkit *apple_rtkit_init(struct device *dev, void *cookie,
+                                    const char *mbox_name, int mbox_idx,
+                                    const struct apple_rtkit_ops *ops);
+
+/*
+ * Dev-res managed version of apple_rtkit_init.
+ */
+struct apple_rtkit *devm_apple_rtkit_init(struct device *dev, void *cookie,
+                                         const char *mbox_name, int mbox_idx,
+                                         const struct apple_rtkit_ops *ops);

Do we need to export both of these?

Arnd

#34 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Sven Peter

drivers/nvme/host/apple.c line 253

Quoted 12 lines · Sven Peter
drivers/nvme/host/apple.c new file +12 -0
+static int apple_nvme_sart_dma_setup(void *cookie, struct apple_rtkit_shmem *bfr,
+                                    dma_addr_t iova, size_t size)
+{
+       struct apple_nvme *anv = cookie;
+       int ret;
+
+       if (iova)
+               return -EINVAL;
+
+       bfr->buffer = dma_alloc_coherent(anv->dev, size, &iova, GFP_KERNEL);
+       if (!bfr->buffer)
+               return -ENOMEM;

You pass 'iova' as an argument, but then replace it with the address returned by dma_alloc_coherent(). Can you remove the function argument?

drivers/nvme/host/apple.c line 290

Quoted 8 lines
drivers/nvme/host/apple.c new file +8 -0
+static void apple_nvmmu_inval(struct apple_nvme_queue *q, unsigned int tag)
+{
+       struct apple_nvme *anv = queue_to_apple_nvme(q);
+
+       writel(tag, anv->mmio_nvme + APPLE_NVMMU_TCB_INVAL);
+       if (readl_relaxed(anv->mmio_nvme + APPLE_NVMMU_TCB_STAT))
+               dev_warn(anv->dev, "NVMMU TCB invalidation failed\n");
+}

I don't like to see the _relaxed() accessors used without an explanation about why that helps. Please use the non-relaxed version, or make sure it's obvious here why you use it.

drivers/nvme/host/apple.c line 479

Quoted 4 lines
drivers/nvme/host/apple.c new file +4 -0
+bad_sgl:
+       WARN(DO_ONCE(apple_nvme_print_sgl, iod->sg, iod->nents),
+            "Invalid SGL for payload:%d nents:%d\n", blk_rq_payload_bytes(req),
+            iod->nents);

I think you mean WARN_ONCE() here?

Review

Quoted 2 lines
(quoted diff) +2 -0
+       writel_relaxed(0, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL);
+       (void)readl_relaxed(anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL);

What is the purpose of the readl_relaxed() here? It looks like you are trying to flush
the write to the hardware, but then again

a) on Apple hardware, the registers are mapped using PROT_DEVICE_nGnRnE, so MMIO writes are never posted

b) the read is "_relaxed", so there is no barrier, and the result is
unused, so
it would appear that the CPU can just keep executing code anyway.

Since this is all the initialization path, I can't imagine what the relaxation of
the barriers helps with.

drivers/nvme/host/apple.c line 1182

Quoted 11 lines
drivers/nvme/host/apple.c new file +11 -0
+static int apple_nvme_reg_read32(struct nvme_ctrl *ctrl, u32 off, u32 *val)
+{
+       *val = readl_relaxed(ctrl_to_apple_nvme(ctrl)->mmio_nvme + off);
+       return 0;
+}
+
+static int apple_nvme_reg_write32(struct nvme_ctrl *ctrl, u32 off, u32 val)
+{
+       writel_relaxed(val, ctrl_to_apple_nvme(ctrl)->mmio_nvme + off);
+       return 0;
+}

If you have generic register access functions, don't make them use _relaxed internally. If there are instances that need to be _relaxed, add another version of the accessor that spells this out in the caller.

Arnd

#24 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Sven Peter

drivers/soc/apple/rtkit.c line 20

Quoted 6 lines
drivers/soc/apple/rtkit.c new file +6 -0
+enum { APPLE_RTKIT_PWR_STATE_OFF = 0x00,
+	APPLE_RTKIT_PWR_STATE_SLEEP = 0x01,
+	APPLE_RTKIT_PWR_STATE_GATED = 0x02,
+	APPLE_RTKIT_PWR_STATE_QUIESCED = 0x10,
+	APPLE_RTKIT_PWR_STATE_ON = 0x20,
+};

It would be great to get comments added explaining what these states are. It's not obvious how off/sleep/gated/quiesced differ, and it's not obvious from the code (doesn't look like GATED is used here at all?). Are these Apple names or r/e'd names or a mix?

drivers/soc/apple/rtkit.c line 387

Quoted 9 lines
drivers/soc/apple/rtkit.c new file +9 -0
+	if (!rtk->syslog_buffer.size) {
+		rtk_warn(
+			"received syslog message but syslog_buffer.size is zero");
+		goto done;
+	}
+	if (!rtk->syslog_buffer.buffer && !rtk->syslog_buffer.iomem) {
+		rtk_warn("received syslog message but no syslog_buffer.buffer or syslog_buffer.iomem");
+		goto done;
+	}

Nit: Wrapping is inconsistent between these two warns.

#54 lore raw
In reply to Sven Peter
Quoted 3 lines

The driver itself has been successfully used by multiple people as their daily driver for weeks at this point and no major issues have been reported.

FWIW, various versions of your NVMe code have been my daily driver for development since late 2021 now, along with the display driver based on your RTKit library here. I'm not qualified to judge code quality or fitness for mainline, but I can testify that it's functional.

(Not a formal T-b since I haven't tested this exact version of the patch series, though.)

#20 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Arnd Bergmann
Quoted 8 lines · Arnd Bergmann

drivers/soc/apple/rtkit-internal.h line 27

Quoted 4 lines
drivers/soc/apple/rtkit-internal.h new file +4 -0
+#define rtk_err(format, arg...) dev_err(rtk->dev, "RTKit: " format, ##arg)
+#define rtk_warn(format, arg...) dev_warn(rtk->dev, "RTKit: " format, ##arg)
+#define rtk_info(format, arg...) dev_info(rtk->dev, "RTKit: " format, ##arg)
+#define rtk_dbg(format, arg...) dev_dbg(rtk->dev, "RTKit: " format, ##arg)

I generally don't like the custom printing macros, please just open-code the prints where they are used, that makes it easier for other kernel developers to see exactly what is being printed

More to the point, implicitly depending on having something named "rtk" in scope is pretty much inexcusable, and the only thing left after fixing that is what we have pr_fmt for ;)

Robin.

#5 lore raw

Re: [PATCH 2/9] dt-bindings: soc: apple: Add ANS NVMe

In reply to Sven Peter
Quoted 15 lines · Sven Peter

Apple SoCs such as the M1 come with an embedded NVMe coprocessor called ANS2.

---
 .../bindings/soc/apple/apple,nvme-ans.yaml    | 75 +++++++++++++++++++
 1 file changed, 75 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml
Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml new file +0 -0
new file mode 100644
index 000000000000..e1f4c1c572aa

Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml line 4

Quoted 4 lines
Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml new file +4 -0
@@ -0,0 +1,75 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/soc/apple/apple,nvme-ans.yaml#

Do not drop all code in soc/apple, but please use respective subsystems. Apple is not a subsystem, is not special.

Quoted 19 lines
Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml new file +19 -0
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Apple ANS NVM Express host controller
+
+maintainers:
+  - Sven Peter <[email protected]>
+
+properties:
+  compatible:
+    items:
+      - enum:
+          - apple,t8103-nvme-ans2
+          - apple,t6000-nvme-ans2
+      - const: apple,nvme-ans2
+
+  reg:
+    items:
+      - description: NVMe and NVMMU registers
+      - description: ANS2 co-processor control registers

Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml line 33

Quoted 10 lines
Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml new file +10 -0
+
+  reg-names:
+    items:
+      - const: nvme
+      - const: ans
+
+  resets:
+    maxItems: 1
+
+  power-domains: true

maxItems

Best regards,
Krzysztof

#26 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Sven Peter
Quoted 5 lines · Sven Peter

Apple SoCs such as the M1 come with multiple embedded co-processors running proprietary firmware. Communication with those is established over a simple mailbox using the RTKit IPC protocol.

Quoted 8 lines
---
 drivers/soc/apple/Kconfig          |  13 +
 drivers/soc/apple/Makefile         |   3 +
 drivers/soc/apple/rtkit-crashlog.c | 147 +++++
 drivers/soc/apple/rtkit-internal.h |  76 +++
 drivers/soc/apple/rtkit.c          | 842 +++++++++++++++++++++++++++++
 include/linux/soc/apple/rtkit.h    | 203 +++++++
 6 files changed, 1284 insertions(+)

Isn't this some implementation of a mailbox? If so, it should be in drivers/mailbox. Please don't put all stuff in soc/apple, that's not how Linux is organized. To drivers/soc usually we put drivers which do not fit regular subsystems.

Best regards,
Krzysztof

#39 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Sven Peter

drivers/nvme/host/apple.c line 12

Quoted 2 lines
drivers/nvme/host/apple.c new file +2 -0
+
+//#define DEBUG

This should not leak into the driverṡ

Quoted 1 line

+#include <linux/blk-integrity.h>

As far as I can tell this driver does not support metadata or PI, so why is this include needed?

drivers/nvme/host/apple.c line 70

Quoted 3 lines
drivers/nvme/host/apple.c new file +3 -0
+/* NVM Express NVM Command Set Specification, Revision 1.0a, Figure 18 */
+#define NVME_OPCODE_DATA_XFER_HOST_TO_CTRL BIT(0)
+#define NVME_OPCODE_DATA_XFER_CTRL_TO_HOST BIT(1)

Please just use the nvme_is_write helper where you are using these.

Quoted 1 line

+static int apple_nvme_sart_dma_setup(void *cookie, struct apple_rtkit_shmem *bfr,

Please avoid > 80 character lines.

drivers/nvme/host/apple.c line 1199

Quoted 3 lines
drivers/nvme/host/apple.c new file +3 -0
+static void apple_nvme_free_ctrl(struct nvme_ctrl *ctrl)
+{
+}

So where are the apple specific resources free? ->free_ctrl is the callback from the struct device release callback, so without one the resource release can't be tried to the device release.

#49 lore raw

Re: [PATCH 7/9] nvme-apple: Serialize command issue

In reply to Sven Peter
Quoted 11 lines · Sven Peter

From: Jens Axboe <[email protected]>

This controller shouldn't need serialization of command issue since the SQ is replaced by a simple array and commands are issued by writing the array index to a MMIO register.
Without serialization however sometimes commands are still executed correctly and appear in the CQ but never trigger an interrupt.

[sven: added our best guess why this needs to be done]

This really should go into the previous patch.

maintainer
#2 lore raw

Re: [PATCH 1/9] dt-bindings: soc: apple: Add Apple SART

In reply to Sven Peter
Quoted 7 lines · Sven Peter

Apple SoCs such as the M1 come with a simple DMA address filter called SART. Unlike a real IOMMU no pagetables can be configured but instead DMA transactions can be allowed for up to 16 paddr regions.

---
 .../bindings/soc/apple/apple,sart.yaml        | 52 +++++++++++++++++++

Close enough to an IOMMU in terms of its purpose, so put in bindings/iommu/

Quoted 78 lines
 MAINTAINERS                                   |  1 +
 2 files changed, 53 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,sart.yaml
Documentation/devicetree/bindings/soc/apple/apple,sart.yaml new file +52 -0
new file mode 100644
index 000000000000..d8177b3a3fba
@@ -0,0 +1,52 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/soc/apple/apple,sart.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Apple SART DMA address filter
+
+maintainers:
+  - Sven Peter <[email protected]>
+
+description:
+  Apple SART is a simple address filter for DMA transactions. Regions of
+  physical memory must be added to the SART's allow list before any
+  DMA can target these. Unlike a proper IOMMU no remapping can be done and
+  special support in the consumer driver is required since not all DMA
+  transactions of a single device are subject to SART filtering.
+
+  SART1 has first been used since at least the A11 (iPhone 8 and iPhone X)
+  and allows 36 bit of physical address space and filter entries with sizes
+  up to 24 bit.
+
+  SART2, first seen in A14 and M1, allows 36 bit of physical address space
+  and filter entry size up to 36 bit.
+
+  SART3, first seen in M1 Pro/Max, extends both the address space and filter
+  entry size to 42 bit.
+
+properties:
+  compatible:
+    enum:
+      - apple,t6000-sart
+      - apple,t8103-sart
+
+  reg:
+    maxItems: 1
+
+  power-domains:
+    maxItems: 1
+
+required:
+  - compatible
+  - reg
+
+additionalProperties: false
+
+examples:
+  - |
+    sart@7bc50000 {
+      compatible = "apple,t8103-sart";
+      reg = <0x7bc50000 0x4000>;
+    };
MAINTAINERS +1 -0
index cd0f68d4a34a..027c3b4ad61c 100644
@@ -1774,6 +1774,7 @@ F:	Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml
 F:	Documentation/devicetree/bindings/pci/apple,pcie.yaml
 F:	Documentation/devicetree/bindings/pinctrl/apple,pinctrl.yaml
 F:	Documentation/devicetree/bindings/power/apple*
+F:	Documentation/devicetree/bindings/soc/apple/*
 F:	Documentation/devicetree/bindings/watchdog/apple,wdt.yaml
 F:	arch/arm64/boot/dts/apple/
 F:	drivers/i2c/busses/i2c-pasemi-core.c
Signature · 1 line
2.25.1
author
#11 lore raw

Re: [PATCH 4/9] soc: apple: Add SART driver

In reply to Arnd Bergmann

Hi,

Thanks for the review!

Quoted 6 lines · Arnd Bergmann
Quoted 5 lines · Sven Peter

The NVMe co-processor on the Apple M1 uses a DMA address filter called SART for some DMA transactions. This adds a simple driver used to configure the memory regions from which DMA transactions are allowed.

Quoted 6 lines
Quoted 3 lines

Can you add some explanation about why this uses a custom interface instead of hooking into the dma_map_ops?

Sure.
In a perfect world this would just be an IOMMU implementation but since SART can't create any real IOVA space using pagetables it doesn't fit inside that subsytem.

In a slightly less perfect world I could just implement dma_map_ops here but that won't work either because not all DMA buffers of the NVMe device have to go through SART and those allocations happen inside the same device and would use the same dma_map_ops.

The NVMe controller has two separate DMA filters:

- NVMMU, which must be set up for any command that uses PRPs and ensures that the DMA transactions only touch the pages listed inside the PRP structure. NVMMU itself is tightly coupled to the NVMe controller: The list of allowed pages is configured based on command's tag id and even commands that require no DMA transactions must be listed inside NVMMU before they are started.
- SART, which must be set up for some shared memory buffers (e.g. log messages from the NVMe firmware) and for some NVMe debug commands that don't use PRPs.
SART is only loosely coupled to the NVMe controller and could also be used together with other devices. It's also the only thing that changed between M1 and M1 Pro/Max/Ultra and that's why I decided to separate it from the NVMe driver.

I'll add this explanation to the commit message.

Quoted 8 lines

drivers/soc/apple/sart.c line 71

Quoted 6 lines
drivers/soc/apple/sart.c new file +5 -0
+static void sart2_get_entry(struct apple_sart *sart, int index, u8 *flags,
+                           phys_addr_t *paddr, size_t *size)
+{
+       u32 cfg = readl_relaxed(sart->regs + APPLE_SART2_CONFIG(index));
+       u32 paddr_ = readl_relaxed(sart->regs + APPLE_SART2_PADDR(index));

Why do you use the _relaxed() accessors here and elsewhere in the driver?

This device itself doesn't do any DMA transactions so it needs no memory synchronization barriers. Only the consumer (i.e. rtkit and nvme) read/write from/to these buffers (multiple times) and they have the required barriers in place whenever they are used.

These buffers so far are only allocated at probe time though so even using the normal writel/readl here won't hurt performance at all. I can just use those if you prefer or alternatively add a comment why _relaxed is fine here.

This is a bit similar to the discussion for the pinctrl series last year [1].

Quoted 13 lines

drivers/soc/apple/sart.c line 191

Quoted 10 lines
drivers/soc/apple/sart.c new file +9 -0
+struct apple_sart *apple_sart_get(struct device *dev)
+{
+       struct device_node *sart_node;
+       struct platform_device *sart_pdev;
+       struct apple_sart *sart;
+
+       sart_node = of_parse_phandle(dev->of_node, "apple,sart", 0);
+       if (!sart_node)
+               return ERR_PTR(ENODEV);

The error pointers need to take negative values, like 'ERR_PTR(-ENODEV)', here and everywhere else in the driver.

Ouch, that's my second bug of that kind in the past days. I'll fix it here and check the other patches in this series as well.

Thanks,

Sven

[1] https://lore.kernel.org/lkml/[email protected]/

author
#17 lore raw

Re: [PATCH 4/9] soc: apple: Add SART driver

In reply to Alyssa Rosenzweig
Quoted 19 lines · Alyssa Rosenzweig
Quoted 19 lines
include/linux/soc/apple/sart.h new file +19 -0
+/*
+ * Adds the region [paddr, paddr+size] to the DMA allow list.
+ *
+ * @sart: SART reference
+ * @paddr: Start address of the region to be used for DMA
+ * @size: Size of the region to be used for DMA.
+ */
+int apple_sart_add_allowed_region(struct apple_sart *sart, phys_addr_t paddr,
+				  size_t size);
+
+/*
+ * Removes the region [paddr, paddr+size] from the DMA allow list.
+ *
+ * Note that exact same paddr and size used for apple_sart_add_allowed_region
+ * have to be passed.
+ *
+ * @sart: SART reference
+ * @paddr: Start address of the region no longer used for DMA
+ * @size: Size of the region no longer used for DMA.
Quoted 8 lines

include/linux/soc/apple/sart.h line 53

Quoted 3 lines

+ */

include/linux/soc/apple/sart.h new file +2 -0
+int apple_sart_remove_allowed_region(struct apple_sart *sart, phys_addr_t paddr,
+				     size_t size);

Might it be simpler for add_allowed_region to return a handle that remove_allowed_region takes instead of paddr+size? Then remove_allowed_region doesn't have to walk anything, and the requirement to use the same paddr/size is implicit.

I liked that idea and just prototyped it and them remembered why I have the API like it is:

In a perfect world this would be an IOMMU and just implement the IOMMU device ops. In a slightly less perfect world this would implement dma_map_ops and transparently allow using the normal DMA API inside the NVMe driver.
In Apple's world the NVMe driver needs two separate IOMMU-like filters and you can't have two separate dma_map_ops without ugly hacks.

This will usually be used just next to dma_map_coherent and dma_free_coherent and for those you need to keep track of phys_addr, dma_addr and size anyway, e.g. (with the error handling removed here)

	bfr->buffer = dma_alloc_coherent(anv->dev, size, &iova, GFP_KERNEL);
	ret = apple_sart_add_allowed_region(anv->sart, iova, size);

and later then

	apple_sart_remove_allowed_region(anv->sart, bfr->iova, bfr->size);
	dma_free_coherent(anv->dev, bfr->size, bfr->buffer, bfr->iova);

Best,

Sven

author
#50 lore raw

Re: [PATCH 7/9] nvme-apple: Serialize command issue

In reply to Christoph Hellwig
Quoted 9 lines · Christoph Hellwig
Quoted 8 lines · Sven Peter

From: Jens Axboe <[email protected]>

This controller shouldn't need serialization of command issue since the SQ is replaced by a simple array and commands are issued by writing the array index to a MMIO register.
Without serialization however sometimes commands are still executed correctly and appear in the CQ but never trigger an interrupt.

Quoted 5 lines
Quoted 3 lines
[sven: added our best guess why this needs to be done]

This really should go into the previous patch.

Ok, I'll squash it (and the following two patches) into the previous one.

Sven

author
#40 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Christoph Hellwig

Hi,

Thanks for the review!

Quoted 4 lines · Christoph Hellwig

drivers/nvme/host/apple.c line 12

Quoted 2 lines
drivers/nvme/host/apple.c new file +2 -0
+
+//#define DEBUG

This should not leak into the driverṡ

Agreed, I'll remove it.

Quoted 5 lines
Quoted 2 lines

+#include <linux/blk-integrity.h>

As far as I can tell this driver does not support metadata or PI, so why is this include needed?

Yup, you're right, it's not required at all. It's a left-over from when I hadn't realized that this controller doesn't support metadata and still had it implemented.

Quoted 6 lines

drivers/nvme/host/apple.c line 70

Quoted 4 lines
drivers/nvme/host/apple.c new file +3 -0
+/* NVM Express NVM Command Set Specification, Revision 1.0a, Figure 18 */
+#define NVME_OPCODE_DATA_XFER_HOST_TO_CTRL BIT(0)
+#define NVME_OPCODE_DATA_XFER_CTRL_TO_HOST BIT(1)

Please just use the nvme_is_write helper where you are using these.

I didn't realize that helper exists, will use it!

Quoted 4 lines
Quoted 2 lines

+static int apple_nvme_sart_dma_setup(void *cookie, struct apple_rtkit_shmem *bfr,

Please avoid > 80 character lines.

Will fix it.

Quoted 8 lines

drivers/nvme/host/apple.c line 1199

Quoted 4 lines
drivers/nvme/host/apple.c new file +3 -0
+static void apple_nvme_free_ctrl(struct nvme_ctrl *ctrl)
+{
+}

So where are the apple specific resources free? ->free_ctrl is the callback from the struct device release callback, so without one the resource release can't be tried to the device release.

The resources are all devres managed but I only just realized that the nvme_ctrl creates its own struct device that has to be tied to the platform device. I think I'll at least need a get_device in _probe and a put_device here just like in pci.c to tie those two together. I'll also double check to make sure that all resources are indeed devres-managed.

Thanks,

Sven

author
#25 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Alyssa Rosenzweig
Quoted 11 lines · Alyssa Rosenzweig

drivers/soc/apple/rtkit.c line 20

Quoted 6 lines
drivers/soc/apple/rtkit.c new file +6 -0
+enum { APPLE_RTKIT_PWR_STATE_OFF = 0x00,
+	APPLE_RTKIT_PWR_STATE_SLEEP = 0x01,
+	APPLE_RTKIT_PWR_STATE_GATED = 0x02,
+	APPLE_RTKIT_PWR_STATE_QUIESCED = 0x10,
+	APPLE_RTKIT_PWR_STATE_ON = 0x20,
+};

It would be great to get comments added explaining what these states are. It's not obvious how off/sleep/gated/quiesced differ, and it's not obvious from the code (doesn't look like GATED is used here at all?). Are these Apple names or r/e'd names or a mix?

Good point. They come from XNU's serial output, I'll add comments for those where I know exactly what they do. I'll also remove GATED for now since that's not used yet.

Quoted 12 lines

drivers/soc/apple/rtkit.c line 387

Quoted 10 lines
drivers/soc/apple/rtkit.c new file +9 -0
+	if (!rtk->syslog_buffer.size) {
+		rtk_warn(
+			"received syslog message but syslog_buffer.size is zero");
+		goto done;
+	}
+	if (!rtk->syslog_buffer.buffer && !rtk->syslog_buffer.iomem) {
+		rtk_warn("received syslog message but no syslog_buffer.buffer or syslog_buffer.iomem");
+		goto done;
+	}

Nit: Wrapping is inconsistent between these two warns.

Will fix it while getting rid of the rtk_ macros.

Sven

author
#21 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Arnd Bergmann
Quoted 8 lines · Arnd Bergmann
Quoted 6 lines · Sven Peter

Apple SoCs such as the M1 come with multiple embedded co-processors running proprietary firmware. Communication with those is established over a simple mailbox using the RTKit IPC protocol.

Quoted 10 lines

drivers/soc/apple/rtkit-internal.h line 27

Quoted 5 lines
drivers/soc/apple/rtkit-internal.h new file +5 -0
+
+#define rtk_err(format, arg...) dev_err(rtk->dev, "RTKit: " format, ##arg)
+#define rtk_warn(format, arg...) dev_warn(rtk->dev, "RTKit: " format, ##arg)
+#define rtk_info(format, arg...) dev_info(rtk->dev, "RTKit: " format, ##arg)
+#define rtk_dbg(format, arg...) dev_dbg(rtk->dev, "RTKit: " format, ##arg)

I generally don't like the custom printing macros, please just open-code the prints where they are used, that makes it easier for other kernel developers to see exactly what is being printed.

Sure, I'll remove them.

Quoted 4 lines
Quoted 4 lines
drivers/soc/apple/rtkit.c new file +4 -0
+enum { APPLE_RTKIT_WORK_MSG,
+       APPLE_RTKIT_WORK_REINIT,
+};
+
Quoted 8 lines

drivers/soc/apple/rtkit.c line 20

Quoted 6 lines
drivers/soc/apple/rtkit.c new file +6 -0
+enum { APPLE_RTKIT_PWR_STATE_OFF = 0x00,
+       APPLE_RTKIT_PWR_STATE_SLEEP = 0x01,
+       APPLE_RTKIT_PWR_STATE_GATED = 0x02,
+       APPLE_RTKIT_PWR_STATE_QUIESCED = 0x10,
+       APPLE_RTKIT_PWR_STATE_ON = 0x20,
+};

This is an odd indentation style, I would insert a newline after the 'enum {'

Yeah, I blame clang-format and me not double-checking the result for that one. I'll add the newline.

Quoted 22 lines
Quoted 22 lines
drivers/soc/apple/rtkit.c new file +21 -0
+static int apple_rtkit_worker(void *data)
+{
+       struct apple_rtkit *rtk = data;
+       struct apple_rtkit_work work;
+
+       while (!kthread_should_stop()) {
+               wait_event_interruptible(rtk->wq,
+                                        kfifo_len(&rtk->work_fifo) > 0 ||
+                                                kthread_should_stop());
+
+               if (kthread_should_stop())
+                       break;
+
+               while (kfifo_out_spinlocked(&rtk->work_fifo, &work, 1,
+                                           &rtk->work_lock) == 1) {
+                       switch (work.type) {
+                       case APPLE_RTKIT_WORK_MSG:
+                               apple_rtkit_rx(rtk, &work.msg);
+                               break;
+                       case APPLE_RTKIT_WORK_REINIT:
+                               apple_rtkit_do_reinit(rtk);
Quoted 8 lines

drivers/soc/apple/rtkit-crashlog.c line 57

Quoted 3 lines
drivers/soc/apple/rtkit-crashlog.c new file +3 -0
+                               break;
+                       }
+               }

It looks like you add quite a bit of complexity by using a custom worker thread implementation. Can you explain what this is needed for? Isn't this roughly the same thing that one would get more easily with create_singlethread_workqueue()?

I originally had just a workqueue here but I can only put one instance of e.g. APPLE_RTKIT_WORK_MSG onto these. There could however be a new incoming message while the previous one is still being handled and I couldn't figure out a way to handle that with workqueues without introducing a race.

Quoted 8 lines
Quoted 2 lines

+#if IS_ENABLED(CONFIG_APPLE_RTKIT)

Instead of allowing the interface to be used without CONFIG_APPLE_RTKIT, I think it is sufficient to allow the driver itself to be built with CONFIG_COMPILE_TEST (as you already do), and then have drivers using it marked as 'depends on APPLE_RTKIT' unconditionally.

That's indeed much simpler and what I wanted to achieve. I just couldn't figure out how to do it. I'll use your approach!

Quoted 15 lines
Quoted 15 lines
include/linux/soc/apple/rtkit.h new file +14 -0
+/*
+ * Initializes the internal state required to handle RTKit. This
+ * should usually be called within _probe.
+ *
+ * @dev: Pointer to the device node this coprocessor is assocated with
+ * @cookie: opaque cookie passed to all functions defined in rtkit_ops
+ * @mbox_name: mailbox name used to communicate with the co-processor
+ * @mbox_idx: mailbox index to be used if mbox_name is NULL
+ * @ops: pointer to rtkit_ops to be used for this co-processor
+ */
+struct apple_rtkit *apple_rtkit_init(struct device *dev, void *cookie,
+                                    const char *mbox_name, int mbox_idx,
+                                    const struct apple_rtkit_ops *ops);
+
Quoted 8 lines

include/linux/soc/apple/rtkit.h line 80

Quoted 6 lines
include/linux/soc/apple/rtkit.h new file +6 -0
+/*
+ * Dev-res managed version of apple_rtkit_init.
+ */
+struct apple_rtkit *devm_apple_rtkit_init(struct device *dev, void *cookie,
+                                         const char *mbox_name, int mbox_idx,
+                                         const struct apple_rtkit_ops *ops);

Do we need to export both of these?

No, only devm_apple_rtkit_init needs to be exported.

Thanks,

Sven

author
#3 lore raw

Re: [PATCH 1/9] dt-bindings: soc: apple: Add Apple SART

In reply to Rob Herring
Quoted 11 lines · Rob Herring
Quoted 7 lines · Sven Peter

Apple SoCs such as the M1 come with a simple DMA address filter called SART. Unlike a real IOMMU no pagetables can be configured but instead DMA transactions can be allowed for up to 16 paddr regions.

---
 .../bindings/soc/apple/apple,sart.yaml        | 52 +++++++++++++++++++

Close enough to an IOMMU in terms of its purpose, so put in bindings/iommu/

Ok, will put it there. I guess I can also use iommu for the node name then, e.g.

    iommu@7bc50000 {
      compatible = "apple,t8103-sart";
      reg = <0x7bc50000 0x4000>;
    };

Thanks,

Sven

author
#6 lore raw

Re: [PATCH 2/9] dt-bindings: soc: apple: Add ANS NVMe

In reply to Krzysztof Kozlowski

Hi,

thanks for the review!

Quoted 10 lines · Krzysztof Kozlowski
Quoted 9 lines · Sven Peter

Apple SoCs such as the M1 come with an embedded NVMe coprocessor called ANS2.

---
 .../bindings/soc/apple/apple,nvme-ans.yaml    | 75 +++++++++++++++++++
 1 file changed, 75 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml
Quoted 14 lines

Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml line 4

Quoted 10 lines
Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml new file +4 -0
new file mode 100644
index 000000000000..e1f4c1c572aa
@@ -0,0 +1,75 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/soc/apple/apple,nvme-ans.yaml#

Do not drop all code in soc/apple, but please use respective subsystems. Apple is not a subsystem, is not special.

Sure, the code is already inside drivers/nvme/host but I'll also create Documentation/devicetree/bindings/nvme and put the bindings in there as well.

Quoted 23 lines
Quoted 23 lines
Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml new file +23 -0
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Apple ANS NVM Express host controller
+
+maintainers:
+  - Sven Peter <[email protected]>
+
+properties:
+  compatible:
+    items:
+      - enum:
+          - apple,t8103-nvme-ans2
+          - apple,t6000-nvme-ans2
+      - const: apple,nvme-ans2
+
+  reg:
+    items:
+      - description: NVMe and NVMMU registers
+      - description: ANS2 co-processor control registers
+
+  reg-names:
+    items:
+      - const: nvme
Quoted 8 lines

Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml line 33

Quoted 6 lines
Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml new file +6 -0
+      - const: ans
+
+  resets:
+    maxItems: 1
+
+  power-domains: true

maxItems

Ok, I guess I can just use the max number of domains in the HW released so far and we can always increase it when Apple releases a new SoC that requires more power domains then.

Thanks,

Sven

author
#33 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Keith Busch
Quoted 15 lines · Keith Busch
Quoted 14 lines · Sven Peter
drivers/nvme/host/apple.c new file +14 -0
+static bool apple_nvme_poll_cq(struct apple_nvme_queue *q,
+			       struct io_comp_batch *iob)
+{
+	bool found = false;
+
+	while (apple_nvme_cqe_pending(q)) {
+		found = true;
+
+		/*
+		 * load-load control dependency between phase and the rest of
+		 * the cqe requires a full read memory barrier
+		 */
+		dma_rmb();
+		apple_nvme_handle_cqe(q, iob, q->cq_head);
Quoted 8 lines

drivers/nvme/host/apple.c line 633

Quoted 5 lines
drivers/nvme/host/apple.c new file +5 -0
+		apple_nvme_update_cq_head(q);
+	}
+
+	if (found)
+		writel_relaxed(q->cq_head, q->cq_db);

Doesn't a relaxed write mean that a subsequent write can bypass the previous? If so, that sounds like it can corrupt the cq head.

No, writel_relaxed just means there's no synchronization barrier for writes to normal memory and that those could bypass the store to device memory and only become visible later.
The underlying memory (q->cq_db) is still mapped as Device-nGnRnE which prevents reordering of writes to the same endpoint such that the N-th CQ update is still guaranteed to be visible to the device before the N+1-th CQ update.

I'll either add a comment why it's okay to use _relaxed here or just use writel instead since there doesn't seem to be any performance difference.

Sven

author
#35 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Arnd Bergmann
Quoted 18 lines · Arnd Bergmann

drivers/nvme/host/apple.c line 253

Quoted 12 lines · Sven Peter
drivers/nvme/host/apple.c new file +12 -0
+static int apple_nvme_sart_dma_setup(void *cookie, struct apple_rtkit_shmem *bfr,
+                                    dma_addr_t iova, size_t size)
+{
+       struct apple_nvme *anv = cookie;
+       int ret;
+
+       if (iova)
+               return -EINVAL;
+
+       bfr->buffer = dma_alloc_coherent(anv->dev, size, &iova, GFP_KERNEL);
+       if (!bfr->buffer)
+               return -ENOMEM;

You pass 'iova' as an argument, but then replace it with the address returned by dma_alloc_coherent(). Can you remove the function argument?

Yup, will remove it.

Quoted 13 lines

drivers/nvme/host/apple.c line 290

Quoted 9 lines
drivers/nvme/host/apple.c new file +8 -0
+static void apple_nvmmu_inval(struct apple_nvme_queue *q, unsigned int tag)
+{
+       struct apple_nvme *anv = queue_to_apple_nvme(q);
+
+       writel(tag, anv->mmio_nvme + APPLE_NVMMU_TCB_INVAL);
+       if (readl_relaxed(anv->mmio_nvme + APPLE_NVMMU_TCB_STAT))
+               dev_warn(anv->dev, "NVMMU TCB invalidation failed\n");
+}

I don't like to see the _relaxed() accessors used without an explanation about why that helps. Please use the non-relaxed version, or make sure it's obvious here why you use it.

Ok, I'll either use the non-relaxed ones or add a comment whenever I use the relaxed version. In this case here there's no write to any DMA buffers that needs to be visible to the device. That writel there could actually be a writel_relaxed as well. There just used to be a write to a buffer above (which is another good reason to always comment when using the non-relaxed ones, maybe then I would've noticed then and updated it).

Quoted 7 lines

drivers/nvme/host/apple.c line 479

Quoted 5 lines
drivers/nvme/host/apple.c new file +4 -0
+bad_sgl:
+       WARN(DO_ONCE(apple_nvme_print_sgl, iod->sg, iod->nents),
+            "Invalid SGL for payload:%d nents:%d\n", blk_rq_payload_bytes(req),
+            iod->nents);

I think you mean WARN_ONCE() here?

This is taken from pci.c which used to use WARN_ONCE but was replaced in d08774738446e77734777adcf5d1045237b4475a with this construction here. The commit message mentions

The WARN_ONCE macro returns true if the condition is true, not if the warn was raised, so we're printing the scatter list every time it's invalid. This is excessive and makes debugging harder, so this patch prints it just once.

Quoted 11 lines

Review

Quoted 3 lines
(quoted diff) +2 -0
+       writel_relaxed(0, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL);
+       (void)readl_relaxed(anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL);

What is the purpose of the readl_relaxed() here? It looks like you are trying to flush
the write to the hardware, but then again

a) on Apple hardware, the registers are mapped using PROT_DEVICE_nGnRnE, so MMIO writes are never posted

Quoted 7 lines

b) the read is "_relaxed", so there is no barrier, and the result is
unused, so
it would appear that the CPU can just keep executing code anyway.

Since this is all the initialization path, I can't imagine what the relaxation of
the barriers helps with.

Agreed, I've actually tried replacing all non-relaxed ones with the normal accessors (even those inside the hot path) and didn't see any performance difference.
I can use the normal ones here and I'll consider using the non-relaxed ones in the hot path together with a comment why they are safe in those places.

Quoted 16 lines

drivers/nvme/host/apple.c line 1182

Quoted 12 lines
drivers/nvme/host/apple.c new file +11 -0
+static int apple_nvme_reg_read32(struct nvme_ctrl *ctrl, u32 off, u32 *val)
+{
+       *val = readl_relaxed(ctrl_to_apple_nvme(ctrl)->mmio_nvme + off);
+       return 0;
+}
+
+static int apple_nvme_reg_write32(struct nvme_ctrl *ctrl, u32 off, u32 val)
+{
+       writel_relaxed(val, ctrl_to_apple_nvme(ctrl)->mmio_nvme + off);
+       return 0;
+}

If you have generic register access functions, don't make them use _relaxed internally. If there are instances that need to be _relaxed, add another version of the accessor that spells this out in the caller.

Ok, there are used internally by the nvme core and can't do any kind of DMA right now but I agree that it's better to use the non-relaxed ones here to prevent surprises in the future.

Sven

author
#27 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Krzysztof Kozlowski
Quoted 15 lines · Krzysztof Kozlowski
Quoted 5 lines · Sven Peter

Apple SoCs such as the M1 come with multiple embedded co-processors running proprietary firmware. Communication with those is established over a simple mailbox using the RTKit IPC protocol.

Quoted 8 lines
---
 drivers/soc/apple/Kconfig          |  13 +
 drivers/soc/apple/Makefile         |   3 +
 drivers/soc/apple/rtkit-crashlog.c | 147 +++++
 drivers/soc/apple/rtkit-internal.h |  76 +++
 drivers/soc/apple/rtkit.c          | 842 +++++++++++++++++++++++++++++
 include/linux/soc/apple/rtkit.h    | 203 +++++++
 6 files changed, 1284 insertions(+)
Quoted 5 lines

Isn't this some implementation of a mailbox? If so, it should be in drivers/mailbox. Please don't put all stuff in soc/apple, that's not how Linux is organized. To drivers/soc usually we put drivers which do not fit regular subsystems.

I put this into soc/apple because I don't think it fits within the mailbox framework very well.
(It actually uses the mailbox framework for the actual communication with the hardware with a driver that's already upstream.)

Essentially, the mailbox subsystem provides a common API to send and receive messages over indepedent hardware channels and devicetree bindings to describe the relationship between those channels and other drivers.

One of the features that doesn't really fit is that we need to be able to start, shutdown and re-start these co-processors. The NVMe driver actually doesn't need to send/receive any messages except those required to setup the common syslog/crashlog/etc. interfaces.
The mailbox framework would have to be extended to support these specific use cases.

Another thing that doesn't fit is the memory management: These co-processors sometimes need shared memory buffers to e.g. send syslog messages. They always request these buffers with an IPC message but then there are different possibilities:

- For some processor the DMA API can just be used and an IOVA must be sent back. For NVMe these buffers must additionally be allowed in this SART address filter.
- At least one other processor (SMC) does not request such buffers but instead just sends a pointer into MMIO space and the buffer must be accessed using readl/writel. This MMIO memory region is used for both the common buffers (syslog etc.) and for the actual shared buffers used for communication, such that the resource would have to be shared across drivers.
- And yet another coprocessor (for the display controller) requests some buffers with an already existing IOVA that than need to be mapped specifically inside the IOMMU.

Each of these co-processors also provides a single function and most of them don't even have different endpoints. And even those that do (DCP) will just become a single driver since all those endpoints are very much related.

While it's not impossible to do all that by extending and forcing this into the mailbox framework at lest I think that it doesn't fit very well and would just create unneccesarry impedance.

Best,

Sven

maintainer
#36 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Sven Peter
Quoted 22 lines · Sven Peter
Quoted 18 lines · Arnd Bergmann

drivers/nvme/host/apple.c line 253

Quoted 12 lines · Sven Peter
drivers/nvme/host/apple.c new file +12 -0
+static int apple_nvme_sart_dma_setup(void *cookie, struct apple_rtkit_shmem *bfr,
+                                    dma_addr_t iova, size_t size)
+{
+       struct apple_nvme *anv = cookie;
+       int ret;
+
+       if (iova)
+               return -EINVAL;
+
+       bfr->buffer = dma_alloc_coherent(anv->dev, size, &iova, GFP_KERNEL);
+       if (!bfr->buffer)
+               return -ENOMEM;

You pass 'iova' as an argument, but then replace it with the address returned by dma_alloc_coherent(). Can you remove the function argument?

Quoted 1 line

Yup, will remove it.

You can remove it but we will have to add it back once we submit the dcp driver (display co-processor). dcp is initialized during boot and uses a single pre-allocated buffer which needs to be mapped instead of allocated. It seemed easier to make apple_rtkit_ops.shmem_setup() omnipotent than adding a different function pointer for this case.

Janne

author
#37 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

Quoted 23 lines · Janne Grunau
Quoted 22 lines · Sven Peter
Quoted 18 lines · Arnd Bergmann

drivers/nvme/host/apple.c line 253

Quoted 12 lines · Sven Peter
drivers/nvme/host/apple.c new file +12 -0
+static int apple_nvme_sart_dma_setup(void *cookie, struct apple_rtkit_shmem *bfr,
+                                    dma_addr_t iova, size_t size)
+{
+       struct apple_nvme *anv = cookie;
+       int ret;
+
+       if (iova)
+               return -EINVAL;
+
+       bfr->buffer = dma_alloc_coherent(anv->dev, size, &iova, GFP_KERNEL);
+       if (!bfr->buffer)
+               return -ENOMEM;

You pass 'iova' as an argument, but then replace it with the address returned by dma_alloc_coherent(). Can you remove the function argument?

Quoted 7 lines
Quoted 1 line

Yup, will remove it.

You can remove it but we will have to add it back once we submit the dcp driver (display co-processor). dcp is initialized during boot and uses a single pre-allocated buffer which needs to be mapped instead of allocated. It seemed easier to make apple_rtkit_ops.shmem_setup() omnipotent than adding a different function pointer for this case.

Or we can already pass the iova DCP sent us into bfr->iova and this function then has the task to just "do whatever is required so that struct apple_rtkit_shmem *bfr is usable".

Sven

#7 lore raw

Re: [PATCH 2/9] dt-bindings: soc: apple: Add ANS NVMe

In reply to Sven Peter
Quoted 30 lines · Sven Peter

Hi,

thanks for the review!

Quoted 10 lines · Krzysztof Kozlowski
Quoted 9 lines · Sven Peter

Apple SoCs such as the M1 come with an embedded NVMe coprocessor called ANS2.

---
 .../bindings/soc/apple/apple,nvme-ans.yaml    | 75 +++++++++++++++++++
 1 file changed, 75 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml
Quoted 14 lines

Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml line 4

Quoted 10 lines
Documentation/devicetree/bindings/soc/apple/apple,nvme-ans.yaml new file +4 -0
new file mode 100644
index 000000000000..e1f4c1c572aa
@@ -0,0 +1,75 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/soc/apple/apple,nvme-ans.yaml#

Do not drop all code in soc/apple, but please use respective subsystems. Apple is not a subsystem, is not special.

Quoted 3 lines

Sure, the code is already inside drivers/nvme/host but I'll also create Documentation/devicetree/bindings/nvme and put the bindings in there as well.

Yes, please. We have also Documentation/devicetree/bindings/nvmem/ but it seems its entirely different stuff.

Best regards,
Krzysztof

#28 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Sven Peter
Quoted 56 lines · Sven Peter
Quoted 15 lines · Krzysztof Kozlowski
Quoted 5 lines · Sven Peter

Apple SoCs such as the M1 come with multiple embedded co-processors running proprietary firmware. Communication with those is established over a simple mailbox using the RTKit IPC protocol.

Quoted 8 lines
---
 drivers/soc/apple/Kconfig          |  13 +
 drivers/soc/apple/Makefile         |   3 +
 drivers/soc/apple/rtkit-crashlog.c | 147 +++++
 drivers/soc/apple/rtkit-internal.h |  76 +++
 drivers/soc/apple/rtkit.c          | 842 +++++++++++++++++++++++++++++
 include/linux/soc/apple/rtkit.h    | 203 +++++++
 6 files changed, 1284 insertions(+)
Quoted 5 lines

Isn't this some implementation of a mailbox? If so, it should be in drivers/mailbox. Please don't put all stuff in soc/apple, that's not how Linux is organized. To drivers/soc usually we put drivers which do not fit regular subsystems.

I put this into soc/apple because I don't think it fits within the mailbox framework very well.
(It actually uses the mailbox framework for the actual communication with the hardware with a driver that's already upstream.)

Essentially, the mailbox subsystem provides a common API to send and receive messages over indepedent hardware channels and devicetree bindings to describe the relationship between those channels and other drivers.

One of the features that doesn't really fit is that we need to be able to start, shutdown and re-start these co-processors. The NVMe driver actually doesn't need to send/receive any messages except those required to setup the common syslog/crashlog/etc. interfaces.
The mailbox framework would have to be extended to support these specific use cases.

Another thing that doesn't fit is the memory management: These co-processors sometimes need shared memory buffers to e.g. send syslog messages. They always request these buffers with an IPC message but then there are different possibilities:

- For some processor the DMA API can just be used and an IOVA must be sent back. For NVMe these buffers must additionally be allowed in this SART address filter.
- At least one other processor (SMC) does not request such buffers but instead just sends a pointer into MMIO space and the buffer must be accessed using readl/writel. This MMIO memory region is used for both the common buffers (syslog etc.) and for the actual shared buffers used for communication, such that the resource would have to be shared across drivers.
- And yet another coprocessor (for the display controller) requests some buffers with an already existing IOVA that than need to be mapped specifically inside the IOMMU.

Quoted 7 lines

Each of these co-processors also provides a single function and most of them don't even have different endpoints. And even those that do (DCP) will just become a single driver since all those endpoints are very much related.

While it's not impossible to do all that by extending and forcing this into the mailbox framework at lest I think that it doesn't fit very well and would just create unneccesarry impedance.

Thanks for explanation. I don't know the mailbox framework well enough to advise you, so I don't mind keeping it in current location (drivers/soc).

Best regards,
Krzysztof

#22 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Sven Peter
Quoted 31 lines · Sven Peter
Quoted 21 lines · Arnd Bergmann
Quoted 21 lines
drivers/soc/apple/rtkit.c new file +21 -0
+static int apple_rtkit_worker(void *data)
+{
+       struct apple_rtkit *rtk = data;
+       struct apple_rtkit_work work;
+
+       while (!kthread_should_stop()) {
+               wait_event_interruptible(rtk->wq,
+                                        kfifo_len(&rtk->work_fifo) > 0 ||
+                                                kthread_should_stop());
+
+               if (kthread_should_stop())
+                       break;
+
+               while (kfifo_out_spinlocked(&rtk->work_fifo, &work, 1,
+                                           &rtk->work_lock) == 1) {
+                       switch (work.type) {
+                       case APPLE_RTKIT_WORK_MSG:
+                               apple_rtkit_rx(rtk, &work.msg);
+                               break;
+                       case APPLE_RTKIT_WORK_REINIT:
+                               apple_rtkit_do_reinit(rtk);
Quoted 8 lines

drivers/soc/apple/rtkit-crashlog.c line 57

Quoted 3 lines
drivers/soc/apple/rtkit-crashlog.c new file +3 -0
+                               break;
+                       }
+               }

It looks like you add quite a bit of complexity by using a custom worker thread implementation. Can you explain what this is needed for? Isn't this roughly the same thing that one would get more easily with create_singlethread_workqueue()?

Quoted 5 lines

I originally had just a workqueue here but I can only put one instance of e.g. APPLE_RTKIT_WORK_MSG onto these. There could however be a new incoming message while the previous one is still being handled and I couldn't figure out a way to handle that with workqueues without introducing a race.

Are you trying to avoid dynamic allocation of the messages then and have no other place that you can embed it in?

If you kmalloc() a messages that embeds a work_struct, you can enqueue as many of those as you want, but the allocation adds complexity through the need for error handling etc.

I wonder if you can change the mailbox driver to use a threaded irq handler, which I think should ensure that the callback here is run in process context, avoiding the need to defer execution within the rtkit driver.

Arnd

#12 lore raw

Re: [PATCH 4/9] soc: apple: Add SART driver

In reply to Sven Peter
Quoted 39 lines · Sven Peter
Quoted 11 lines · Arnd Bergmann
Quoted 7 lines · Sven Peter

The NVMe co-processor on the Apple M1 uses a DMA address filter called SART for some DMA transactions. This adds a simple driver used to configure the memory regions from which DMA transactions are allowed.

Can you add some explanation about why this uses a custom interface instead of hooking into the dma_map_ops?

Sure.
In a perfect world this would just be an IOMMU implementation but since SART can't create any real IOVA space using pagetables it doesn't fit inside that subsytem.

In a slightly less perfect world I could just implement dma_map_ops here but that won't work either because not all DMA buffers of the NVMe device have to go through SART and those allocations happen inside the same device and would use the same dma_map_ops.

The NVMe controller has two separate DMA filters:

- NVMMU, which must be set up for any command that uses PRPs and ensures that the DMA transactions only touch the pages listed inside the PRP structure. NVMMU itself is tightly coupled to the NVMe controller: The list of allowed pages is configured based on command's tag id and even commands that require no DMA transactions must be listed inside NVMMU before they are started.
- SART, which must be set up for some shared memory buffers (e.g. log messages from the NVMe firmware) and for some NVMe debug commands that don't use PRPs.
SART is only loosely coupled to the NVMe controller and could also be used together with other devices. It's also the only thing that changed between M1 and M1 Pro/Max/Ultra and that's why I decided to separate it from the NVMe driver.

Quoted 1 line

I'll add this explanation to the commit message.

Ok, thanks.

Quoted 13 lines
Quoted 7 lines

drivers/soc/apple/sart.c line 71

Quoted 5 lines
drivers/soc/apple/sart.c new file +5 -0
+static void sart2_get_entry(struct apple_sart *sart, int index, u8 *flags,
+                           phys_addr_t *paddr, size_t *size)
+{
+       u32 cfg = readl_relaxed(sart->regs + APPLE_SART2_CONFIG(index));
+       u32 paddr_ = readl_relaxed(sart->regs + APPLE_SART2_PADDR(index));

Why do you use the _relaxed() accessors here and elsewhere in the driver?

This device itself doesn't do any DMA transactions so it needs no memory synchronization barriers. Only the consumer (i.e. rtkit and nvme) read/write from/to these buffers (multiple times) and they have the required barriers in place whenever they are used.

Quoted 5 lines

These buffers so far are only allocated at probe time though so even using the normal writel/readl here won't hurt performance at all. I can just use those if you prefer or alternatively add a comment why _relaxed is fine here.

This is a bit similar to the discussion for the pinctrl series last year [1].

I think it's better to only use the _relaxed version where it actually helps, with a comment about it, and use the normal version elsewhere, in particular in functions that you have copied from the normal nvme driver. I had tried to compare some of your code with the other version and was rather confused by that.

Arnd

#38 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Sven Peter
Quoted 10 lines · Sven Peter
Quoted 8 lines · Arnd Bergmann

drivers/nvme/host/apple.c line 479

Quoted 4 lines · Sven Peter
drivers/nvme/host/apple.c new file +4 -0
+bad_sgl:
+       WARN(DO_ONCE(apple_nvme_print_sgl, iod->sg, iod->nents),
+            "Invalid SGL for payload:%d nents:%d\n", blk_rq_payload_bytes(req),
+            iod->nents);

I think you mean WARN_ONCE() here?

Quoted 9 lines

This is taken from pci.c which used to use WARN_ONCE but was replaced in d08774738446e77734777adcf5d1045237b4475a with this construction here. The commit message mentions

The WARN_ONCE macro returns true if the condition is true, not if the warn was raised, so we're printing the scatter list every time it's invalid. This is excessive and makes debugging harder, so this patch prints it just once.

Ok, makes sense. If we get more of these in the kernel, we may want to add a helper that makes this more obvious, but it appears that for now these two are the only ones.

It could also be expressed by moving the WARN_ONCE() into the condition above the 'goto', but I don't see a reason to change the other driver and it's better to keep the two consistent.

Quoted 5 lines

Agreed, I've actually tried replacing all non-relaxed ones with the normal accessors (even those inside the hot path) and didn't see any performance difference.
I can use the normal ones here and I'll consider using the non-relaxed ones in the hot path together with a comment why they are safe in those places.

Sounds good. If you find any instances in the hot path that have a corresponding version in the pci.c file, it would be good to keep these two in sync, hopefully making the non-apple case faster as well.

Arnd

author
#23 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Arnd Bergmann
Quoted 32 lines · Arnd Bergmann
Quoted 31 lines · Sven Peter
Quoted 29 lines · Arnd Bergmann
Quoted 14 lines
drivers/soc/apple/rtkit.c new file +14 -0
+static int apple_rtkit_worker(void *data)
+{
+       struct apple_rtkit *rtk = data;
+       struct apple_rtkit_work work;
+
+       while (!kthread_should_stop()) {
+               wait_event_interruptible(rtk->wq,
+                                        kfifo_len(&rtk->work_fifo) > 0 ||
+                                                kthread_should_stop());
+
+               if (kthread_should_stop())
+                       break;
+
+               while (kfifo_out_spinlocked(&rtk->work_fifo, &work, 1,

drivers/soc/apple/rtkit.c line 530

Quoted 10 lines
drivers/soc/apple/rtkit.c new file +10 -0
+                                           &rtk->work_lock) == 1) {
+                       switch (work.type) {
+                       case APPLE_RTKIT_WORK_MSG:
+                               apple_rtkit_rx(rtk, &work.msg);
+                               break;
+                       case APPLE_RTKIT_WORK_REINIT:
+                               apple_rtkit_do_reinit(rtk);
+                               break;
+                       }
+               }

It looks like you add quite a bit of complexity by using a custom worker thread implementation. Can you explain what this is needed for? Isn't this roughly the same thing that one would get more easily with create_singlethread_workqueue()?

Quoted 8 lines
Quoted 5 lines

I originally had just a workqueue here but I can only put one instance of e.g. APPLE_RTKIT_WORK_MSG onto these. There could however be a new incoming message while the previous one is still being handled and I couldn't figure out a way to handle that with workqueues without introducing a race.

Are you trying to avoid dynamic allocation of the messages then and have no other place that you can embed it in?

Yeah, I didn't want to allocate anything because of the added complexity here like you mentioned.

Quoted 9 lines

If you kmalloc() a messages that embeds a work_struct, you can enqueue as many of those as you want, but the allocation adds complexity through the need for error handling etc.

I wonder if you can change the mailbox driver to use a threaded irq handler, which I think should ensure that the callback here is run in process context, avoiding the need to defer execution within the rtkit driver.

Hrm, I just realized that's already the case. mailbox_client.h documents rx_callback as "Atomic callback to provide client the data received" but since we know rtkit will only ever be combined with that specific Apple mailbox we could get away with just ignoring that. It's a small hack but it might be worth it since it would reduce the complexity inside rtkit.

Sven

maintainer
#13 lore raw

Re: [PATCH 4/9] soc: apple: Add SART driver

In reply to Arnd Bergmann
Quoted 61 lines · Arnd Bergmann
Quoted 39 lines · Sven Peter
Quoted 11 lines · Arnd Bergmann
Quoted 7 lines · Sven Peter

The NVMe co-processor on the Apple M1 uses a DMA address filter called SART for some DMA transactions. This adds a simple driver used to configure the memory regions from which DMA transactions are allowed.

Can you add some explanation about why this uses a custom interface instead of hooking into the dma_map_ops?

Sure.
In a perfect world this would just be an IOMMU implementation but since SART can't create any real IOVA space using pagetables it doesn't fit inside that subsytem.

In a slightly less perfect world I could just implement dma_map_ops here but that won't work either because not all DMA buffers of the NVMe device have to go through SART and those allocations happen inside the same device and would use the same dma_map_ops.

The NVMe controller has two separate DMA filters:

- NVMMU, which must be set up for any command that uses PRPs and ensures that the DMA transactions only touch the pages listed inside the PRP structure. NVMMU itself is tightly coupled to the NVMe controller: The list of allowed pages is configured based on command's tag id and even commands that require no DMA transactions must be listed inside NVMMU before they are started.
- SART, which must be set up for some shared memory buffers (e.g. log messages from the NVMe firmware) and for some NVMe debug commands that don't use PRPs.
SART is only loosely coupled to the NVMe controller and could also be used together with other devices. It's also the only thing that changed between M1 and M1 Pro/Max/Ultra and that's why I decided to separate it from the NVMe driver.

Quoted 1 line

I'll add this explanation to the commit message.

Ok, thanks.

Quoted 17 lines
Quoted 7 lines

drivers/soc/apple/sart.c line 71

Quoted 5 lines
drivers/soc/apple/sart.c new file +5 -0
+static void sart2_get_entry(struct apple_sart *sart, int index, u8 *flags,
+                           phys_addr_t *paddr, size_t *size)
+{
+       u32 cfg = readl_relaxed(sart->regs + APPLE_SART2_CONFIG(index));
+       u32 paddr_ = readl_relaxed(sart->regs + APPLE_SART2_PADDR(index));

Why do you use the _relaxed() accessors here and elsewhere in the driver?

This device itself doesn't do any DMA transactions so it needs no memory synchronization barriers. Only the consumer (i.e. rtkit and nvme) read/write from/to these buffers (multiple times) and they have the required barriers in place whenever they are used.

These buffers so far are only allocated at probe time though so even using the normal writel/readl here won't hurt performance at all. I can just use those if you prefer or alternatively add a comment why _relaxed is fine here.

Quoted 7 lines
Quoted 1 line

This is a bit similar to the discussion for the pinctrl series last year [1].

I think it's better to only use the _relaxed version where it actually helps, with a comment about it, and use the normal version elsewhere, in particular in functions that you have copied from the normal nvme driver. I had tried to compare some of your code with the other version and was rather confused by that.

Oh good, I tell folks the opposite (and others do too). We don't accept random explicit barriers without explanation, but implicit ones are okay? The resulting code on arm32 is also pretty horrible with the L2x0 and OMAP sync hooks not that that matters here.

I don't really care too much which way we go, but we should document one rule and follow that.

Rob

#14 lore raw

Re: [PATCH 4/9] soc: apple: Add SART driver

Quoted 70 lines · Rob Herring
Quoted 61 lines · Arnd Bergmann
Quoted 39 lines · Sven Peter
Quoted 11 lines · Arnd Bergmann
Quoted 7 lines · Sven Peter

The NVMe co-processor on the Apple M1 uses a DMA address filter called SART for some DMA transactions. This adds a simple driver used to configure the memory regions from which DMA transactions are allowed.

Can you add some explanation about why this uses a custom interface instead of hooking into the dma_map_ops?

Sure.
In a perfect world this would just be an IOMMU implementation but since SART can't create any real IOVA space using pagetables it doesn't fit inside that subsytem.

In a slightly less perfect world I could just implement dma_map_ops here but that won't work either because not all DMA buffers of the NVMe device have to go through SART and those allocations happen inside the same device and would use the same dma_map_ops.

The NVMe controller has two separate DMA filters:

- NVMMU, which must be set up for any command that uses PRPs and ensures that the DMA transactions only touch the pages listed inside the PRP structure. NVMMU itself is tightly coupled to the NVMe controller: The list of allowed pages is configured based on command's tag id and even commands that require no DMA transactions must be listed inside NVMMU before they are started.
- SART, which must be set up for some shared memory buffers (e.g. log messages from the NVMe firmware) and for some NVMe debug commands that don't use PRPs.
SART is only loosely coupled to the NVMe controller and could also be used together with other devices. It's also the only thing that changed between M1 and M1 Pro/Max/Ultra and that's why I decided to separate it from the NVMe driver.

Quoted 1 line

I'll add this explanation to the commit message.

Ok, thanks.

Quoted 17 lines
Quoted 7 lines

drivers/soc/apple/sart.c line 71

Quoted 5 lines
drivers/soc/apple/sart.c new file +5 -0
+static void sart2_get_entry(struct apple_sart *sart, int index, u8 *flags,
+                           phys_addr_t *paddr, size_t *size)
+{
+       u32 cfg = readl_relaxed(sart->regs + APPLE_SART2_CONFIG(index));
+       u32 paddr_ = readl_relaxed(sart->regs + APPLE_SART2_PADDR(index));

Why do you use the _relaxed() accessors here and elsewhere in the driver?

This device itself doesn't do any DMA transactions so it needs no memory synchronization barriers. Only the consumer (i.e. rtkit and nvme) read/write from/to these buffers (multiple times) and they have the required barriers in place whenever they are used.

These buffers so far are only allocated at probe time though so even using the normal writel/readl here won't hurt performance at all. I can just use those if you prefer or alternatively add a comment why _relaxed is fine here.

Quoted 7 lines
Quoted 1 line

This is a bit similar to the discussion for the pinctrl series last year [1].

I think it's better to only use the _relaxed version where it actually helps, with a comment about it, and use the normal version elsewhere, in particular in functions that you have copied from the normal nvme driver. I had tried to compare some of your code with the other version and was rather confused by that.

Quoted 7 lines

Oh good, I tell folks the opposite (and others do too). We don't accept random explicit barriers without explanation, but implicit ones are okay? The resulting code on arm32 is also pretty horrible with the L2x0 and OMAP sync hooks not that that matters here.

I don't really care too much which way we go, but we should document one rule and follow that.

I'm sure maz@ has an opinion here too :-)

(3... 2... 1... fight!)

Signature · 2 lines
Hector Martin ([email protected])
Public Key: https://mrcn.st/pub
maintainer
#29 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

In reply to Sven Peter
Quoted 27 lines · Sven Peter
Quoted 15 lines · Krzysztof Kozlowski
Quoted 5 lines · Sven Peter

Apple SoCs such as the M1 come with multiple embedded co-processors running proprietary firmware. Communication with those is established over a simple mailbox using the RTKit IPC protocol.

Quoted 8 lines
---
 drivers/soc/apple/Kconfig          |  13 +
 drivers/soc/apple/Makefile         |   3 +
 drivers/soc/apple/rtkit-crashlog.c | 147 +++++
 drivers/soc/apple/rtkit-internal.h |  76 +++
 drivers/soc/apple/rtkit.c          | 842 +++++++++++++++++++++++++++++
 include/linux/soc/apple/rtkit.h    | 203 +++++++
 6 files changed, 1284 insertions(+)
Quoted 5 lines

Isn't this some implementation of a mailbox? If so, it should be in drivers/mailbox. Please don't put all stuff in soc/apple, that's not how Linux is organized. To drivers/soc usually we put drivers which do not fit regular subsystems.

I put this into soc/apple because I don't think it fits within the mailbox framework very well.
(It actually uses the mailbox framework for the actual communication with the hardware with a driver that's already upstream.)

Quoted 6 lines

Essentially, the mailbox subsystem provides a common API to send and receive messages over indepedent hardware channels and devicetree bindings to describe the relationship between those channels and other drivers.

One of the features that doesn't really fit is that we need to be able to start, shutdown and re-start these co-processors. The NVMe driver

remoteproc does that. Did you look at it? Most remoteproc drivers use some combination of mailboxes and shared memory.

Rob

#30 lore raw

Re: [PATCH 5/9] soc: apple: Add RTKit IPC library

Quoted 32 lines · Rob Herring
Quoted 31 lines · Sven Peter
Quoted 15 lines · Krzysztof Kozlowski
Quoted 5 lines · Sven Peter

Apple SoCs such as the M1 come with multiple embedded co-processors running proprietary firmware. Communication with those is established over a simple mailbox using the RTKit IPC protocol.

Quoted 8 lines
---
 drivers/soc/apple/Kconfig          |  13 +
 drivers/soc/apple/Makefile         |   3 +
 drivers/soc/apple/rtkit-crashlog.c | 147 +++++
 drivers/soc/apple/rtkit-internal.h |  76 +++
 drivers/soc/apple/rtkit.c          | 842 +++++++++++++++++++++++++++++
 include/linux/soc/apple/rtkit.h    | 203 +++++++
 6 files changed, 1284 insertions(+)
Quoted 5 lines

Isn't this some implementation of a mailbox? If so, it should be in drivers/mailbox. Please don't put all stuff in soc/apple, that's not how Linux is organized. To drivers/soc usually we put drivers which do not fit regular subsystems.

I put this into soc/apple because I don't think it fits within the mailbox framework very well.
(It actually uses the mailbox framework for the actual communication with the hardware with a driver that's already upstream.)

Essentially, the mailbox subsystem provides a common API to send and receive messages over indepedent hardware channels and devicetree bindings to describe the relationship between those channels and other drivers.

Quoted 5 lines
Quoted 2 lines

One of the features that doesn't really fit is that we need to be able to start, shutdown and re-start these co-processors. The NVMe driver

remoteproc does that. Did you look at it? Most remoteproc drivers use some combination of mailboxes and shared memory.

Remoteproc seems to be mostly about providing a standard interface for loading firmware images and kickstarting somewhat generic remote processors, as well as some high-level stuff for virtio. None of that is useful to us as far as I can tell, because Linux doesn't load the firmware for these things, it is pre-loaded by the bootloader and therefore they might as well be fixed-function hardware as far as we're concerned.

I can certainly see some similarities between the resourceproc API and what we're doing, but I don't see what it would do for us other than cause an impedance mismatch. Does it actually *do* something we can use? Keep in mind these are Apple copros running Apple firmware that will only ever talk to drivers we write for Apple machines, and we don't control the firmware.

Impediance mismatches on first glance:

- The assumption that firmware is loaded by Linux seems to be hard-coded into the subsystem
- Only one boot/shutdown path, while we need different power states and boot modes depending on the specific instance
- The concept of the "resource table"; we have something similar for at least one copro, but it's brokered via exchanged messages after it is booted, and not something we can just look up in the firmware (our plan was to just put the requested regions in the DT reg node and name them; the firmware then *after boot* provides a list of mappings it wants from that list and they can be mapped at that point). At least one other copro does a subset of this an entirely different way altogether. Apple aren't consistent and we can't do anything about that.
- Rproc trace buffers: Apple does syslogs but a different, incompatible way.
- ELF coredumps: even if this were useful for the blobs we get, the blobs loaded by the bootloader themselves are Mach-O binaries, not ELF, so that'd require some funny binary format conversion on one end or the other to be able to line them up for postmortem debugging. And Apple's crashdump format is a custom tag/value type thing.

I'm certainly willing to be convinced to use a kernel subsystem if it actually does something useful for us, but last time we did that when it wasn't entirely clear we should (mailbox, for the hardware underlying these coprocessors) it just resulted in a bunch of headaches because that subsystem is poorly designed and doesn't seem to have bought us anything other than limitations. e.g. it is using suboptimal queueing right now, and we had to switch to the atomic API to make SMC work, which ends up even lower level, and isn't even properly documented and different drivers interpret differently, so now it's just pure added complexity and confusion for ~no gain over just reading/writing the mailbox registers, which would've been *much* simpler (and more performant than introducing additional queuing, since the hardware *does* queuing now which we can't use because mailbox doesn't support it). Remoteproc kind of seems like an even worse fit here...

Oh, and these device producer/consumer relations cannot be computed statically as far as I can tell, so each one we introduce is another special case in distro initramfs image building, since they need to encode magic additional device-specific module dependency information somehow since it isn't available in depmod, but only encoded in DTs which are not necessarily known at initramfs build time.

Signature · 2 lines
Hector Martin ([email protected])
Public Key: https://mrcn.st/pub
#41 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Christoph Hellwig
Quoted 16 lines · Christoph Hellwig

drivers/nvme/host/apple.c line 12

Quoted 2 lines
drivers/nvme/host/apple.c new file +2 -0
+
+//#define DEBUG

This should not leak into the driverṡ

Quoted 1 line

+#include <linux/blk-integrity.h>

As far as I can tell this driver does not support metadata or PI, so why is this include needed?

drivers/nvme/host/apple.c line 70

Quoted 3 lines
drivers/nvme/host/apple.c new file +3 -0
+/* NVM Express NVM Command Set Specification, Revision 1.0a, Figure 18 */
+#define NVME_OPCODE_DATA_XFER_HOST_TO_CTRL BIT(0)
+#define NVME_OPCODE_DATA_XFER_CTRL_TO_HOST BIT(1)

Please just use the nvme_is_write helper where you are using these.

Quoted 3 lines
Quoted 1 line

+static int apple_nvme_sart_dma_setup(void *cookie, struct apple_rtkit_shmem *bfr,

Please avoid > 80 character lines.

The kernel hard limit is 100-character lines, not 80-character lines. Maintainers for existing drivers are certainly free to stick to 80 chars if they like it that way, but I don't see why we should still be enforcing that for new code. See bdc48fa11e46.

And also:
https://lkml.iu.edu/hypermail/linux/kernel/2005.3/08168.html

Quoth Torvalds, addressing you personally:

"If you or Christoph have 80 character lines, you'll get possibly ugly wrapped output. Tough. That's _your_ choice. Your hardware limitations shouldn't be a pain for the rest of us."

Signature · 2 lines
Hector Martin ([email protected])
Public Key: https://mrcn.st/pub
#42 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

Quoted 4 lines · Hector Martin

The kernel hard limit is 100-character lines, not 80-character lines. Maintainers for existing drivers are certainly free to stick to 80 chars if they like it that way, but I don't see why we should still be enforcing that for new code. See bdc48fa11e46.

Because 100 is completely utterly unreadable if is not for individual lines like strings, and that is actually how Linus stated it in CodingStyle.

Your code as-is is completely unreadable and will not go into drivers/nvme/ in that form.

author
#43 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

Quoted 11 lines · Christoph Hellwig
Quoted 4 lines · Hector Martin

The kernel hard limit is 100-character lines, not 80-character lines. Maintainers for existing drivers are certainly free to stick to 80 chars if they like it that way, but I don't see why we should still be enforcing that for new code. See bdc48fa11e46.

Because 100 is completely utterly unreadable if is not for individual lines like strings, and that is actually how Linus stated it in CodingStyle.

Your code as-is is completely unreadable and will not go into drivers/nvme/ in that form.

fwiw, I wrote that code and I just forgot to check the line length after some last minute changes again.
It's already been reduced to 80 chars in my local tree.

Sven

#45 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Christoph Hellwig
Quoted 11 lines · Christoph Hellwig
Quoted 4 lines · Hector Martin

The kernel hard limit is 100-character lines, not 80-character lines. Maintainers for existing drivers are certainly free to stick to 80 chars if they like it that way, but I don't see why we should still be enforcing that for new code. See bdc48fa11e46.

Because 100 is completely utterly unreadable if is not for individual lines like strings, and that is actually how Linus stated it in CodingStyle.

Your code as-is is completely unreadable and will not go into drivers/nvme/ in that form.

That line is 81 characters. I'm sure Sven doesn't mind fixing it, but "your code as-is is completely unreadable" seems uncalled for here, and rather unreasonable.

Signature · 2 lines
Hector Martin ([email protected])
Public Key: https://mrcn.st/pub
#44 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Sven Peter
Quoted 3 lines · Sven Peter

fwiw, I wrote that code and I just forgot to check the line length after some last minute changes again.
It's already been reduced to 80 chars in my local tree.

Awesome!

#46 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

In reply to Christoph Hellwig
Quoted 6 lines · Christoph Hellwig
Quoted 4 lines · Hector Martin

The kernel hard limit is 100-character lines, not 80-character lines. Maintainers for existing drivers are certainly free to stick to 80 chars if they like it that way, but I don't see why we should still be enforcing that for new code. See bdc48fa11e46.

Quoted 6 lines

Because 100 is completely utterly unreadable if is not for individual lines like strings, and that is actually how Linus stated it in CodingStyle.

Your code as-is is completely unreadable and will not go into drivers/nvme/ in that form.

Please reconsider how you phrase these objections. Saying the code is "completely unreadable" because it's _1_ character over your hard limit is just nonsense, and not a very productive way to deal with this.

Signature · 1 line
Jens Axboe
#47 lore raw

Re: [PATCH 6/9] nvme-apple: Add initial Apple SoC NVMe driver

Quoted 3 lines · Jens Axboe

Please reconsider how you phrase these objections. Saying the code is "completely unreadable" because it's _1_ character over your hard limit is just nonsense, and not a very productive way to deal with this.

Agreed and sorry. I actually had a piece of code in mind that formatted all the comments way to long that really tripped me off, but it wans't this one. Too much going on right now.

author
#15 lore raw

Re: [PATCH 4/9] soc: apple: Add SART driver

In reply to Rob Herring
Quoted 70 lines · Rob Herring
Quoted 61 lines · Arnd Bergmann
Quoted 39 lines · Sven Peter
Quoted 11 lines · Arnd Bergmann
Quoted 7 lines · Sven Peter

The NVMe co-processor on the Apple M1 uses a DMA address filter called SART for some DMA transactions. This adds a simple driver used to configure the memory regions from which DMA transactions are allowed.

Can you add some explanation about why this uses a custom interface instead of hooking into the dma_map_ops?

Sure.
In a perfect world this would just be an IOMMU implementation but since SART can't create any real IOVA space using pagetables it doesn't fit inside that subsytem.

In a slightly less perfect world I could just implement dma_map_ops here but that won't work either because not all DMA buffers of the NVMe device have to go through SART and those allocations happen inside the same device and would use the same dma_map_ops.

The NVMe controller has two separate DMA filters:

- NVMMU, which must be set up for any command that uses PRPs and ensures that the DMA transactions only touch the pages listed inside the PRP structure. NVMMU itself is tightly coupled to the NVMe controller: The list of allowed pages is configured based on command's tag id and even commands that require no DMA transactions must be listed inside NVMMU before they are started.
- SART, which must be set up for some shared memory buffers (e.g. log messages from the NVMe firmware) and for some NVMe debug commands that don't use PRPs.
SART is only loosely coupled to the NVMe controller and could also be used together with other devices. It's also the only thing that changed between M1 and M1 Pro/Max/Ultra and that's why I decided to separate it from the NVMe driver.

Quoted 1 line

I'll add this explanation to the commit message.

Ok, thanks.

Quoted 17 lines
Quoted 7 lines

drivers/soc/apple/sart.c line 71

Quoted 5 lines
drivers/soc/apple/sart.c new file +5 -0
+static void sart2_get_entry(struct apple_sart *sart, int index, u8 *flags,
+                           phys_addr_t *paddr, size_t *size)
+{
+       u32 cfg = readl_relaxed(sart->regs + APPLE_SART2_CONFIG(index));
+       u32 paddr_ = readl_relaxed(sart->regs + APPLE_SART2_PADDR(index));

Why do you use the _relaxed() accessors here and elsewhere in the driver?

This device itself doesn't do any DMA transactions so it needs no memory synchronization barriers. Only the consumer (i.e. rtkit and nvme) read/write from/to these buffers (multiple times) and they have the required barriers in place whenever they are used.

These buffers so far are only allocated at probe time though so even using the normal writel/readl here won't hurt performance at all. I can just use those if you prefer or alternatively add a comment why _relaxed is fine here.

Quoted 7 lines
Quoted 1 line

This is a bit similar to the discussion for the pinctrl series last year [1].

I think it's better to only use the _relaxed version where it actually helps, with a comment about it, and use the normal version elsewhere, in particular in functions that you have copied from the normal nvme driver. I had tried to compare some of your code with the other version and was rather confused by that.

Quoted 7 lines

Oh good, I tell folks the opposite (and others do too). We don't accept random explicit barriers without explanation, but implicit ones are okay? The resulting code on arm32 is also pretty horrible with the L2x0 and OMAP sync hooks not that that matters here.

I don't really care too much which way we go, but we should document one rule and follow that.

I don't have a strong opinion either. Arnd's approach is currently documented in Documentation/driver-api/device-io.rst fwiw:

On architectures that require an expensive barrier for serializing against DMA, these "relaxed" versions of the MMIO accessors only serialize against each other, but contain a less expensive barrier operation. A device driver might use these in a particularly performance sensitive fast path, with a comment that explains why the usage in a specific location is safe without the extra barriers.

Sven