source
large_stringclasses
2 values
subject
large_stringclasses
112 values
code
large_stringclasses
112 values
critique
large_stringlengths
61
3.04M
metadata
dict
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/27/26 11:21, Jacob Pan wrote: It's x86 specific: x86_init.iommu.iommu_init = hv_iommu_init oh, you are talking about the config option, yeah, I will move CONFIG_IRQ_REMAP from Kconfig to here. it could, but by convention all public funcs here are hv_iommu_xxx.. and other reviewers might object... We really need virt/mshv/ sub directory... not sure if it's worth creating now for just one function. so maybe we just live with it for now... we do have work item to move some things from drivers/hv to virt/mshv/ .. so this can get added to that whenever that happens. That is correct. It is extra work to support that if there is a good usecase/demand. Well, at the time of this design/coding, my understanding was we'd have mapped devices on l1vh also. But now it looks like that would be bit later than sooner .. unless AI bots start dumping code of course :) :).. I could remove it from the if statement and add it when the support is added, but is harmless and one less thing to remember. Device passthru will fail and will not cause any corruption or data theft issues... can make it u64 if it gives extra peace. not worth all that mumbo jumbo for almost never gonna happen case. no it's just a sequential number with no track of what's used. https://git.kernel.org/pub/scm/linux/kernel/git/hyperv/linux.git branch: hyperv-next All our hyperv/mshv related patch submissions are merged there first by Wei. Thanks, -Mukesh .. deleted ......
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 30 Jan 2026 15:44:37 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Fri, Jan 30, 2026 at 02:51:19PM -0800, Mukesh R wrote: Again, the hypervisor state is not accessible from the kernel core in L1VH. In upstream, it does not matter what the work is focused on. The only thing that matters is that the functionality is merged and available. Once the code is merged upstream, it becomes available to third-party customers. They can use it in any way they see fit. The only product we support with upstream code is L1VH. We should keep it crisp, clear, and easy to debug. This change does not help debugging. It only sweeps the issue under the carpet, with no justification. Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Mon, 2 Feb 2026 08:20:37 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Fri, Jan 30, 2026 at 02:17:24PM -0800, Mukesh R wrote: So, are you saying that the hypervisor does not use these pages and only tracks them? That would make things easier. However, if we later try to map a GPA that is already mapped, will the hypervisor return an error? Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Mon, 2 Feb 2026 08:30:49 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The "qup-memory" interconnect path is optional and may not be defined in all device trees. Unroll the loop-based ICC path initialization to allow specific error handling for each path type. The "qup-core" and "qup-config" paths remain mandatory and will fail probe if missing, while "qup-memory" is now handled as optional and skipped when not present in the device tree. Co-developed-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com> Signed-off-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v1->v2: Bjorn: - Updated commit text. - Used local variable for more readable. --- drivers/soc/qcom/qcom-geni-se.c | 36 +++++++++++++++++---------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index cd1779b6a91a..b6167b968ef6 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -899,30 +899,32 @@ EXPORT_SYMBOL_GPL(geni_se_rx_dma_unprep); int geni_icc_get(struct geni_se *se, const char *icc_ddr) { - int i, err; - const char *icc_names[] = {"qup-core", "qup-config", icc_ddr}; + struct geni_icc_path *icc_paths = se->icc_paths; if (has_acpi_companion(se->dev)) return 0; - for (i = 0; i < ARRAY_SIZE(se->icc_paths); i++) { - if (!icc_names[i]) - continue; - - se->icc_paths[i].path = devm_of_icc_get(se->dev, icc_names[i]); - if (IS_ERR(se->icc_paths[i].path)) - goto err; + icc_paths[GENI_TO_CORE].path = devm_of_icc_get(se->dev, "qup-core"); + if (IS_ERR(icc_paths[GENI_TO_CORE].path)) + return dev_err_probe(se->dev, PTR_ERR(icc_paths[GENI_TO_CORE].path), + "Failed to get 'qup-core' ICC path\n"); + + icc_paths[CPU_TO_GENI].path = devm_of_icc_get(se->dev, "qup-config"); + if (IS_ERR(icc_paths[CPU_TO_GENI].path)) + return dev_err_probe(se->dev, PTR_ERR(icc_paths[CPU_TO_GENI].path), + "Failed to get 'qup-config' ICC path\n"); + + /* The DDR path is optional, depending on protocol and hw capabilities */ + icc_paths[GENI_TO_DDR].path = devm_of_icc_get(se->dev, "qup-memory"); + if (IS_ERR(icc_paths[GENI_TO_DDR].path)) { + if (PTR_ERR(icc_paths[GENI_TO_DDR].path) == -ENODATA) + icc_paths[GENI_TO_DDR].path = NULL; + else + return dev_err_probe(se->dev, PTR_ERR(icc_paths[GENI_TO_DDR].path), + "Failed to get 'qup-memory' ICC path\n"); } return 0; - -err: - err = PTR_ERR(se->icc_paths[i].path); - if (err != -EPROBE_DEFER) - dev_err_ratelimited(se->dev, "Failed to get ICC path '%s': %d\n", - icc_names[i], err); - return err; - } EXPORT_SYMBOL_GPL(geni_icc_get); -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:10 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Add a new function geni_icc_set_bw_ab() that allows callers to set average bandwidth values for all ICC (Interconnect) paths in a single call. This function takes separate parameters for core, config, and DDR average bandwidth values and applies them to the respective ICC paths. This provides a more convenient API for drivers that need to configure specific average bandwidth values. Co-developed-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com> Signed-off-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- drivers/soc/qcom/qcom-geni-se.c | 22 ++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 1 + 2 files changed, 23 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index b6167b968ef6..b0542f836453 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -946,6 +946,28 @@ int geni_icc_set_bw(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_icc_set_bw); +/** + * geni_icc_set_bw_ab() - Set average bandwidth for all ICC paths and apply + * @se: Pointer to the concerned serial engine. + * @core_ab: Average bandwidth in kBps for GENI_TO_CORE path. + * @cfg_ab: Average bandwidth in kBps for CPU_TO_GENI path. + * @ddr_ab: Average bandwidth in kBps for GENI_TO_DDR path. + * + * Sets bandwidth values for all ICC paths and applies them. DDR path is + * optional and only set if it exists. + * + * Return: 0 on success, negative error code on failure. + */ +int geni_icc_set_bw_ab(struct geni_se *se, u32 core_ab, u32 cfg_ab, u32 ddr_ab) +{ + se->icc_paths[GENI_TO_CORE].avg_bw = core_ab; + se->icc_paths[CPU_TO_GENI].avg_bw = cfg_ab; + se->icc_paths[GENI_TO_DDR].avg_bw = ddr_ab; + + return geni_icc_set_bw(se); +} +EXPORT_SYMBOL_GPL(geni_icc_set_bw_ab); + void geni_icc_set_tag(struct geni_se *se, u32 tag) { int i; diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index 0a984e2579fe..980aabea2157 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -528,6 +528,7 @@ void geni_se_rx_dma_unprep(struct geni_se *se, dma_addr_t iova, size_t len); int geni_icc_get(struct geni_se *se, const char *icc_ddr); int geni_icc_set_bw(struct geni_se *se); +int geni_icc_set_bw_ab(struct geni_se *se, u32 core_ab, u32 cfg_ab, u32 ddr_ab); void geni_icc_set_tag(struct geni_se *se, u32 tag); int geni_icc_enable(struct geni_se *se); -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:11 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The GENI Serial Engine drivers (I2C, SPI, and SERIAL) currently duplicate code for initializing shared resources such as clocks and interconnect paths. Introduce a new helper API, geni_se_resources_init(), to centralize this initialization logic, improving modularity and simplifying the probe function. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v1 -> v2: - Updated proper return value for devm_pm_opp_set_clkname() --- drivers/soc/qcom/qcom-geni-se.c | 47 ++++++++++++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 6 ++++ 2 files changed, 53 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index b0542f836453..75e722cd1a94 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -19,6 +19,7 @@ #include <linux/of_platform.h> #include <linux/pinctrl/consumer.h> #include <linux/platform_device.h> +#include <linux/pm_opp.h> #include <linux/soc/qcom/geni-se.h> /** @@ -1012,6 +1013,52 @@ int geni_icc_disable(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_icc_disable); +/** + * geni_se_resources_init() - Initialize resources for a GENI SE device. + * @se: Pointer to the geni_se structure representing the GENI SE device. + * + * This function initializes various resources required by the GENI Serial Engine + * (SE) device, including clock resources (core and SE clocks), interconnect + * paths for communication. + * It retrieves optional and mandatory clock resources, adds an OF-based + * operating performance point (OPP) table, and sets up interconnect paths + * with default bandwidths. The function also sets a flag (`has_opp`) to + * indicate whether OPP support is available for the device. + * + * Return: 0 on success, or a negative errno on failure. + */ +int geni_se_resources_init(struct geni_se *se) +{ + int ret; + + se->core_clk = devm_clk_get_optional(se->dev, "core"); + if (IS_ERR(se->core_clk)) + return dev_err_probe(se->dev, PTR_ERR(se->core_clk), + "Failed to get optional core clk\n"); + + se->clk = devm_clk_get(se->dev, "se"); + if (IS_ERR(se->clk) && !has_acpi_companion(se->dev)) + return dev_err_probe(se->dev, PTR_ERR(se->clk), + "Failed to get SE clk\n"); + + ret = devm_pm_opp_set_clkname(se->dev, "se"); + if (ret) + return ret; + + ret = devm_pm_opp_of_add_table(se->dev); + if (ret && ret != -ENODEV) + return dev_err_probe(se->dev, ret, "Failed to add OPP table\n"); + + se->has_opp = (ret == 0); + + ret = geni_icc_get(se, "qup-memory"); + if (ret) + return ret; + + return geni_icc_set_bw_ab(se, GENI_DEFAULT_BW, GENI_DEFAULT_BW, GENI_DEFAULT_BW); +} +EXPORT_SYMBOL_GPL(geni_se_resources_init); + /** * geni_find_protocol_fw() - Locate and validate SE firmware for a protocol. * @dev: Pointer to the device structure. diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index 980aabea2157..c182dd0f0bde 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -60,18 +60,22 @@ struct geni_icc_path { * @dev: Pointer to the Serial Engine device * @wrapper: Pointer to the parent QUP Wrapper core * @clk: Handle to the core serial engine clock + * @core_clk: Auxiliary clock, which may be required by a protocol * @num_clk_levels: Number of valid clock levels in clk_perf_tbl * @clk_perf_tbl: Table of clock frequency input to serial engine clock * @icc_paths: Array of ICC paths for SE + * @has_opp: Indicates if OPP is supported */ struct geni_se { void __iomem *base; struct device *dev; struct geni_wrapper *wrapper; struct clk *clk; + struct clk *core_clk; unsigned int num_clk_levels; unsigned long *clk_perf_tbl; struct geni_icc_path icc_paths[3]; + bool has_opp; }; /* Common SE registers */ @@ -535,6 +539,8 @@ int geni_icc_enable(struct geni_se *se); int geni_icc_disable(struct geni_se *se); +int geni_se_resources_init(struct geni_se *se); + int geni_load_se_firmware(struct geni_se *se, enum geni_se_protocol_type protocol); #endif #endif -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:12 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Currently, core clk is handled individually in protocol drivers like the I2C driver. Move this clock management to the common clock APIs (geni_se_clks_on/off) that are already present in the common GENI SE driver to maintain consistency across all protocol drivers. Core clk is now properly managed alongside the other clocks (se->clk and wrapper clocks) in the fundamental clock control functions, eliminating the need for individual protocol drivers to handle this clock separately. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- drivers/soc/qcom/qcom-geni-se.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index 75e722cd1a94..2e41595ff912 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -583,6 +583,7 @@ static void geni_se_clks_off(struct geni_se *se) clk_disable_unprepare(se->clk); clk_bulk_disable_unprepare(wrapper->num_clks, wrapper->clks); + clk_disable_unprepare(se->core_clk); } /** @@ -619,7 +620,18 @@ static int geni_se_clks_on(struct geni_se *se) ret = clk_prepare_enable(se->clk); if (ret) - clk_bulk_disable_unprepare(wrapper->num_clks, wrapper->clks); + goto err_bulk_clks; + + ret = clk_prepare_enable(se->core_clk); + if (ret) + goto err_se_clk; + + return 0; + +err_se_clk: + clk_disable_unprepare(se->clk); +err_bulk_clks: + clk_bulk_disable_unprepare(wrapper->num_clks, wrapper->clks); return ret; } -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:13 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The GENI SE protocol drivers (I2C, SPI, UART) implement similar resource activation/deactivation sequences independently, leading to code duplication. Introduce geni_se_resources_activate()/geni_se_resources_deactivate() to power on/off resources.The activate function enables ICC, clocks, and TLMM whereas the deactivate function disables resources in reverse order including OPP rate reset, clocks, ICC and TLMM. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3 -> v4 Konrad - Removed core clk. v2 -> v3 - Added export symbol for new APIs. v1 -> v2 Bjorn - Updated commit message based code changes. - Removed geni_se_resource_state() API. - Utilized code snippet from geni_se_resources_off() --- drivers/soc/qcom/qcom-geni-se.c | 67 ++++++++++++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 4 ++ 2 files changed, 71 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index 2e41595ff912..17ab5bbeb621 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -1025,6 +1025,73 @@ int geni_icc_disable(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_icc_disable); +/** + * geni_se_resources_deactivate() - Deactivate GENI SE device resources + * @se: Pointer to the geni_se structure + * + * Deactivates device resources for power saving: OPP rate to 0, pin control + * to sleep state, turns off clocks, and disables interconnect. Skips ACPI devices. + * + * Return: 0 on success, negative error code on failure + */ +int geni_se_resources_deactivate(struct geni_se *se) +{ + int ret; + + if (has_acpi_companion(se->dev)) + return 0; + + if (se->has_opp) + dev_pm_opp_set_rate(se->dev, 0); + + ret = pinctrl_pm_select_sleep_state(se->dev); + if (ret) + return ret; + + geni_se_clks_off(se); + + return geni_icc_disable(se); +} +EXPORT_SYMBOL_GPL(geni_se_resources_deactivate); + +/** + * geni_se_resources_activate() - Activate GENI SE device resources + * @se: Pointer to the geni_se structure + * + * Activates device resources for operation: enables interconnect, prepares clocks, + * and sets pin control to default state. Includes error cleanup. Skips ACPI devices. + * + * Return: 0 on success, negative error code on failure + */ +int geni_se_resources_activate(struct geni_se *se) +{ + int ret; + + if (has_acpi_companion(se->dev)) + return 0; + + ret = geni_icc_enable(se); + if (ret) + return ret; + + ret = geni_se_clks_on(se); + if (ret) + goto out_icc_disable; + + ret = pinctrl_pm_select_default_state(se->dev); + if (ret) { + geni_se_clks_off(se); + goto out_icc_disable; + } + + return ret; + +out_icc_disable: + geni_icc_disable(se); + return ret; +} +EXPORT_SYMBOL_GPL(geni_se_resources_activate); + /** * geni_se_resources_init() - Initialize resources for a GENI SE device. * @se: Pointer to the geni_se structure representing the GENI SE device. diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index c182dd0f0bde..36a68149345c 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -541,6 +541,10 @@ int geni_icc_disable(struct geni_se *se); int geni_se_resources_init(struct geni_se *se); +int geni_se_resources_activate(struct geni_se *se); + +int geni_se_resources_deactivate(struct geni_se *se); + int geni_load_se_firmware(struct geni_se *se, enum geni_se_protocol_type protocol); #endif #endif -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:14 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The GENI Serial Engine drivers (I2C, SPI, and SERIAL) currently handle the attachment of power domains. This often leads to duplicated code logic across different driver probe functions. Introduce a new helper API, geni_se_domain_attach(), to centralize the logic for attaching "power" and "perf" domains to the GENI SE device. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4 Konrad - Updated function documentation --- drivers/soc/qcom/qcom-geni-se.c | 29 +++++++++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 4 ++++ 2 files changed, 33 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index 17ab5bbeb621..d80ae6c36582 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -19,6 +19,7 @@ #include <linux/of_platform.h> #include <linux/pinctrl/consumer.h> #include <linux/platform_device.h> +#include <linux/pm_domain.h> #include <linux/pm_opp.h> #include <linux/soc/qcom/geni-se.h> @@ -1092,6 +1093,34 @@ int geni_se_resources_activate(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_se_resources_activate); +/** + * geni_se_domain_attach() - Attach power domains to a GENI SE device. + * @se: Pointer to the geni_se structure representing the GENI SE device. + * + * This function attaches the power domains ("power" and "perf") required + * in the SCMI auto-VM environment to the GENI Serial Engine device. It + * initializes se->pd_list with the attached domains. + * + * Return: 0 on success, or a negative error code on failure. + */ +int geni_se_domain_attach(struct geni_se *se) +{ + struct dev_pm_domain_attach_data pd_data = { + .pd_flags = PD_FLAG_DEV_LINK_ON, + .pd_names = (const char*[]) { "power", "perf" }, + .num_pd_names = 2, + }; + int ret; + + ret = dev_pm_domain_attach_list(se->dev, + &pd_data, &se->pd_list); + if (ret <= 0) + return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_GPL(geni_se_domain_attach); + /** * geni_se_resources_init() - Initialize resources for a GENI SE device. * @se: Pointer to the geni_se structure representing the GENI SE device. diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index 36a68149345c..5f75159c5531 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -64,6 +64,7 @@ struct geni_icc_path { * @num_clk_levels: Number of valid clock levels in clk_perf_tbl * @clk_perf_tbl: Table of clock frequency input to serial engine clock * @icc_paths: Array of ICC paths for SE + * @pd_list: Power domain list for managing power domains * @has_opp: Indicates if OPP is supported */ struct geni_se { @@ -75,6 +76,7 @@ struct geni_se { unsigned int num_clk_levels; unsigned long *clk_perf_tbl; struct geni_icc_path icc_paths[3]; + struct dev_pm_domain_list *pd_list; bool has_opp; }; @@ -546,5 +548,7 @@ int geni_se_resources_activate(struct geni_se *se); int geni_se_resources_deactivate(struct geni_se *se); int geni_load_se_firmware(struct geni_se *se, enum geni_se_protocol_type protocol); + +int geni_se_domain_attach(struct geni_se *se); #endif #endif -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:15 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The GENI Serial Engine (SE) drivers (I2C, SPI, and SERIAL) currently manage performance levels and operating points directly. This resulting in code duplication across drivers. such as configuring a specific level or find and apply an OPP based on a clock frequency. Introduce two new helper APIs, geni_se_set_perf_level() and geni_se_set_perf_opp(), addresses this issue by providing a streamlined method for the GENI Serial Engine (SE) drivers to find and set the OPP based on the desired performance level, thereby eliminating redundancy. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- drivers/soc/qcom/qcom-geni-se.c | 50 ++++++++++++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 4 +++ 2 files changed, 54 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index d80ae6c36582..2241d1487031 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -282,6 +282,12 @@ struct se_fw_hdr { #define geni_setbits32(_addr, _v) writel(readl(_addr) | (_v), _addr) #define geni_clrbits32(_addr, _v) writel(readl(_addr) & ~(_v), _addr) +enum domain_idx { + DOMAIN_IDX_POWER, + DOMAIN_IDX_PERF, + DOMAIN_IDX_MAX +}; + /** * geni_se_get_qup_hw_version() - Read the QUP wrapper Hardware version * @se: Pointer to the corresponding serial engine. @@ -1093,6 +1099,50 @@ int geni_se_resources_activate(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_se_resources_activate); +/** + * geni_se_set_perf_level() - Set performance level for GENI SE. + * @se: Pointer to the struct geni_se instance. + * @level: The desired performance level. + * + * Sets the performance level by directly calling dev_pm_opp_set_level + * on the performance device associated with the SE. + * + * Return: 0 on success, or a negative error code on failure. + */ +int geni_se_set_perf_level(struct geni_se *se, unsigned long level) +{ + return dev_pm_opp_set_level(se->pd_list->pd_devs[DOMAIN_IDX_PERF], level); +} +EXPORT_SYMBOL_GPL(geni_se_set_perf_level); + +/** + * geni_se_set_perf_opp() - Set performance OPP for GENI SE by frequency. + * @se: Pointer to the struct geni_se instance. + * @clk_freq: The requested clock frequency. + * + * Finds the nearest operating performance point (OPP) for the given + * clock frequency and applies it to the SE's performance device. + * + * Return: 0 on success, or a negative error code on failure. + */ +int geni_se_set_perf_opp(struct geni_se *se, unsigned long clk_freq) +{ + struct device *perf_dev = se->pd_list->pd_devs[DOMAIN_IDX_PERF]; + struct dev_pm_opp *opp; + int ret; + + opp = dev_pm_opp_find_freq_floor(perf_dev, &clk_freq); + if (IS_ERR(opp)) { + dev_err(se->dev, "failed to find opp for freq %lu\n", clk_freq); + return PTR_ERR(opp); + } + + ret = dev_pm_opp_set_opp(perf_dev, opp); + dev_pm_opp_put(opp); + return ret; +} +EXPORT_SYMBOL_GPL(geni_se_set_perf_opp); + /** * geni_se_domain_attach() - Attach power domains to a GENI SE device. * @se: Pointer to the geni_se structure representing the GENI SE device. diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index 5f75159c5531..c5e6ab85df09 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -550,5 +550,9 @@ int geni_se_resources_deactivate(struct geni_se *se); int geni_load_se_firmware(struct geni_se *se, enum geni_se_protocol_type protocol); int geni_se_domain_attach(struct geni_se *se); + +int geni_se_set_perf_level(struct geni_se *se, unsigned long level); + +int geni_se_set_perf_opp(struct geni_se *se, unsigned long clk_freq); #endif #endif -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:16 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Add DT bindings for the QUP GENI I2C controller on sa8255p platforms. SA8255p platform abstracts resources such as clocks, interconnect and GPIO pins configuration in Firmware. SCMI power and perf protocol are utilized to request resource configurations. SA8255p platform does not require the Serial Engine (SE) common properties as the SE firmware is loaded and managed by the TrustZone (TZ) secure environment. Reviewed-by: Krzysztof Kozlowski <krzysztof.kozlowski@oss.qualcomm.com> Co-developed-by: Nikunj Kela <quic_nkela@quicinc.com> Signed-off-by: Nikunj Kela <quic_nkela@quicinc.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v2->v3: - Added Reviewed-by tag v1->v2: Krzysztof: - Added dma properties in example node - Removed minItems from power-domains property - Added in commit text about common property --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml diff --git a/Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml b/Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml new file mode 100644 index 000000000000..a61e40b5cbc1 --- /dev/null +++ b/Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/i2c/qcom,sa8255p-geni-i2c.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Qualcomm SA8255p QUP GENI I2C Controller + +maintainers: + - Praveen Talari <praveen.talari@oss.qualcomm.com> + +properties: + compatible: + const: qcom,sa8255p-geni-i2c + + reg: + maxItems: 1 + + dmas: + maxItems: 2 + + dma-names: + items: + - const: tx + - const: rx + + interrupts: + maxItems: 1 + + power-domains: + maxItems: 2 + + power-domain-names: + items: + - const: power + - const: perf + +required: + - compatible + - reg + - interrupts + - power-domains + +allOf: + - $ref: /schemas/i2c/i2c-controller.yaml# + +unevaluatedProperties: false + +examples: + - | + #include <dt-bindings/interrupt-controller/arm-gic.h> + #include <dt-bindings/dma/qcom-gpi.h> + + i2c@a90000 { + compatible = "qcom,sa8255p-geni-i2c"; + reg = <0xa90000 0x4000>; + interrupts = <GIC_SPI 357 IRQ_TYPE_LEVEL_HIGH>; + dmas = <&gpi_dma0 0 0 QCOM_GPI_I2C>, + <&gpi_dma0 1 0 QCOM_GPI_I2C>; + dma-names = "tx", "rx"; + power-domains = <&scmi0_pd 0>, <&scmi0_dvfs 0>; + power-domain-names = "power", "perf"; + }; +... -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:17 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Moving the serial engine setup to geni_i2c_init() API for a cleaner probe function and utilizes the PM runtime API to control resources instead of direct clock-related APIs for better resource management. Enables reusability of the serial engine initialization like hibernation and deep sleep features where hardware context is lost. Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4: viken: - Added Acked-by tag - Removed extra space before invoke of geni_i2c_init(). v1->v2: Bjorn: - Updated commit text. --- drivers/i2c/busses/i2c-qcom-geni.c | 158 ++++++++++++++--------------- 1 file changed, 75 insertions(+), 83 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index ae609bdd2ec4..81ed1596ac9f 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -977,10 +977,77 @@ static int setup_gpi_dma(struct geni_i2c_dev *gi2c) return ret; } +static int geni_i2c_init(struct geni_i2c_dev *gi2c) +{ + const struct geni_i2c_desc *desc = NULL; + u32 proto, tx_depth; + bool fifo_disable; + int ret; + + ret = pm_runtime_resume_and_get(gi2c->se.dev); + if (ret < 0) { + dev_err(gi2c->se.dev, "error turning on device :%d\n", ret); + return ret; + } + + proto = geni_se_read_proto(&gi2c->se); + if (proto == GENI_SE_INVALID_PROTO) { + ret = geni_load_se_firmware(&gi2c->se, GENI_SE_I2C); + if (ret) { + dev_err_probe(gi2c->se.dev, ret, "i2c firmware load failed ret: %d\n", ret); + goto err; + } + } else if (proto != GENI_SE_I2C) { + ret = dev_err_probe(gi2c->se.dev, -ENXIO, "Invalid proto %d\n", proto); + goto err; + } + + desc = device_get_match_data(gi2c->se.dev); + if (desc && desc->no_dma_support) { + fifo_disable = false; + gi2c->no_dma = true; + } else { + fifo_disable = readl_relaxed(gi2c->se.base + GENI_IF_DISABLE_RO) & FIFO_IF_DISABLE; + } + + if (fifo_disable) { + /* FIFO is disabled, so we can only use GPI DMA */ + gi2c->gpi_mode = true; + ret = setup_gpi_dma(gi2c); + if (ret) + goto err; + + dev_dbg(gi2c->se.dev, "Using GPI DMA mode for I2C\n"); + } else { + gi2c->gpi_mode = false; + tx_depth = geni_se_get_tx_fifo_depth(&gi2c->se); + + /* I2C Master Hub Serial Elements doesn't have the HW_PARAM_0 register */ + if (!tx_depth && desc) + tx_depth = desc->tx_fifo_depth; + + if (!tx_depth) { + ret = dev_err_probe(gi2c->se.dev, -EINVAL, + "Invalid TX FIFO depth\n"); + goto err; + } + + gi2c->tx_wm = tx_depth - 1; + geni_se_init(&gi2c->se, gi2c->tx_wm, tx_depth); + geni_se_config_packing(&gi2c->se, BITS_PER_BYTE, + PACKING_BYTES_PW, true, true, true); + + dev_dbg(gi2c->se.dev, "i2c fifo/se-dma mode. fifo depth:%d\n", tx_depth); + } + +err: + pm_runtime_put(gi2c->se.dev); + return ret; +} + static int geni_i2c_probe(struct platform_device *pdev) { struct geni_i2c_dev *gi2c; - u32 proto, tx_depth, fifo_disable; int ret; struct device *dev = &pdev->dev; const struct geni_i2c_desc *desc = NULL; @@ -1060,102 +1127,27 @@ static int geni_i2c_probe(struct platform_device *pdev) if (ret) return ret; - ret = clk_prepare_enable(gi2c->core_clk); - if (ret) - return ret; - - ret = geni_se_resources_on(&gi2c->se); - if (ret) { - dev_err_probe(dev, ret, "Error turning on resources\n"); - goto err_clk; - } - proto = geni_se_read_proto(&gi2c->se); - if (proto == GENI_SE_INVALID_PROTO) { - ret = geni_load_se_firmware(&gi2c->se, GENI_SE_I2C); - if (ret) { - dev_err_probe(dev, ret, "i2c firmware load failed ret: %d\n", ret); - goto err_resources; - } - } else if (proto != GENI_SE_I2C) { - ret = dev_err_probe(dev, -ENXIO, "Invalid proto %d\n", proto); - goto err_resources; - } - - if (desc && desc->no_dma_support) { - fifo_disable = false; - gi2c->no_dma = true; - } else { - fifo_disable = readl_relaxed(gi2c->se.base + GENI_IF_DISABLE_RO) & FIFO_IF_DISABLE; - } - - if (fifo_disable) { - /* FIFO is disabled, so we can only use GPI DMA */ - gi2c->gpi_mode = true; - ret = setup_gpi_dma(gi2c); - if (ret) - goto err_resources; - - dev_dbg(dev, "Using GPI DMA mode for I2C\n"); - } else { - gi2c->gpi_mode = false; - tx_depth = geni_se_get_tx_fifo_depth(&gi2c->se); - - /* I2C Master Hub Serial Elements doesn't have the HW_PARAM_0 register */ - if (!tx_depth && desc) - tx_depth = desc->tx_fifo_depth; - - if (!tx_depth) { - ret = dev_err_probe(dev, -EINVAL, - "Invalid TX FIFO depth\n"); - goto err_resources; - } - - gi2c->tx_wm = tx_depth - 1; - geni_se_init(&gi2c->se, gi2c->tx_wm, tx_depth); - geni_se_config_packing(&gi2c->se, BITS_PER_BYTE, - PACKING_BYTES_PW, true, true, true); - - dev_dbg(dev, "i2c fifo/se-dma mode. fifo depth:%d\n", tx_depth); - } - - clk_disable_unprepare(gi2c->core_clk); - ret = geni_se_resources_off(&gi2c->se); - if (ret) { - dev_err_probe(dev, ret, "Error turning off resources\n"); - goto err_dma; - } - - ret = geni_icc_disable(&gi2c->se); - if (ret) - goto err_dma; - gi2c->suspended = 1; pm_runtime_set_suspended(gi2c->se.dev); pm_runtime_set_autosuspend_delay(gi2c->se.dev, I2C_AUTO_SUSPEND_DELAY); pm_runtime_use_autosuspend(gi2c->se.dev); pm_runtime_enable(gi2c->se.dev); + ret = geni_i2c_init(gi2c); + if (ret < 0) { + pm_runtime_disable(gi2c->se.dev); + return ret; + } + ret = i2c_add_adapter(&gi2c->adap); if (ret) { dev_err_probe(dev, ret, "Error adding i2c adapter\n"); pm_runtime_disable(gi2c->se.dev); - goto err_dma; + return ret; } dev_dbg(dev, "Geni-I2C adaptor successfully added\n"); - return ret; - -err_resources: - geni_se_resources_off(&gi2c->se); -err_clk: - clk_disable_unprepare(gi2c->core_clk); - - return ret; - -err_dma: - release_gpi_dma(gi2c); - return ret; } -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:18 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Refactor the resource initialization in geni_i2c_probe() by introducing a new geni_i2c_resources_init() function and utilizing the common geni_se_resources_init() framework and clock frequency mapping, making the probe function cleaner. Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4: - Added Acked-by tag. v1->v2: - Updated commit text. --- drivers/i2c/busses/i2c-qcom-geni.c | 53 ++++++++++++------------------ 1 file changed, 21 insertions(+), 32 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index 81ed1596ac9f..56eebefda75f 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -1045,6 +1045,23 @@ static int geni_i2c_init(struct geni_i2c_dev *gi2c) return ret; } +static int geni_i2c_resources_init(struct geni_i2c_dev *gi2c) +{ + int ret; + + ret = geni_se_resources_init(&gi2c->se); + if (ret) + return ret; + + ret = geni_i2c_clk_map_idx(gi2c); + if (ret) + return dev_err_probe(gi2c->se.dev, ret, "Invalid clk frequency %d Hz\n", + gi2c->clk_freq_out); + + return geni_icc_set_bw_ab(&gi2c->se, GENI_DEFAULT_BW, GENI_DEFAULT_BW, + Bps_to_icc(gi2c->clk_freq_out)); +} + static int geni_i2c_probe(struct platform_device *pdev) { struct geni_i2c_dev *gi2c; @@ -1064,16 +1081,6 @@ static int geni_i2c_probe(struct platform_device *pdev) desc = device_get_match_data(&pdev->dev); - if (desc && desc->has_core_clk) { - gi2c->core_clk = devm_clk_get(dev, "core"); - if (IS_ERR(gi2c->core_clk)) - return PTR_ERR(gi2c->core_clk); - } - - gi2c->se.clk = devm_clk_get(dev, "se"); - if (IS_ERR(gi2c->se.clk) && !has_acpi_companion(dev)) - return PTR_ERR(gi2c->se.clk); - ret = device_property_read_u32(dev, "clock-frequency", &gi2c->clk_freq_out); if (ret) { @@ -1088,16 +1095,15 @@ static int geni_i2c_probe(struct platform_device *pdev) if (gi2c->irq < 0) return gi2c->irq; - ret = geni_i2c_clk_map_idx(gi2c); - if (ret) - return dev_err_probe(dev, ret, "Invalid clk frequency %d Hz\n", - gi2c->clk_freq_out); - gi2c->adap.algo = &geni_i2c_algo; init_completion(&gi2c->done); spin_lock_init(&gi2c->lock); platform_set_drvdata(pdev, gi2c); + ret = geni_i2c_resources_init(gi2c); + if (ret) + return ret; + /* Keep interrupts disabled initially to allow for low-power modes */ ret = devm_request_irq(dev, gi2c->irq, geni_i2c_irq, IRQF_NO_AUTOEN, dev_name(dev), gi2c); @@ -1110,23 +1116,6 @@ static int geni_i2c_probe(struct platform_device *pdev) gi2c->adap.dev.of_node = dev->of_node; strscpy(gi2c->adap.name, "Geni-I2C", sizeof(gi2c->adap.name)); - ret = geni_icc_get(&gi2c->se, desc ? desc->icc_ddr : "qup-memory"); - if (ret) - return ret; - /* - * Set the bus quota for core and cpu to a reasonable value for - * register access. - * Set quota for DDR based on bus speed. - */ - gi2c->se.icc_paths[GENI_TO_CORE].avg_bw = GENI_DEFAULT_BW; - gi2c->se.icc_paths[CPU_TO_GENI].avg_bw = GENI_DEFAULT_BW; - if (!desc || desc->icc_ddr) - gi2c->se.icc_paths[GENI_TO_DDR].avg_bw = Bps_to_icc(gi2c->clk_freq_out); - - ret = geni_icc_set_bw(&gi2c->se); - if (ret) - return ret; - gi2c->suspended = 1; pm_runtime_set_suspended(gi2c->se.dev); pm_runtime_set_autosuspend_delay(gi2c->se.dev, I2C_AUTO_SUSPEND_DELAY); -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:19 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
To manage GENI serial engine resources during runtime power management, drivers currently need to call functions for ICC, clock, and SE resource operations in both suspend and resume paths, resulting in code duplication across drivers. The new geni_se_resources_activate() and geni_se_resources_deactivate() helper APIs addresses this issue by providing a streamlined method to enable or disable all resources based, thereby eliminating redundancy across drivers. Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4: - Added Acked-by tag. v1->v2: Bjorn: - Remove geni_se_resources_state() API. - Used geni_se_resources_activate() and geni_se_resources_deactivate() to enable/disable resources. --- drivers/i2c/busses/i2c-qcom-geni.c | 28 +++++----------------------- 1 file changed, 5 insertions(+), 23 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index 56eebefda75f..4ff84bb0fff5 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -1163,18 +1163,15 @@ static int __maybe_unused geni_i2c_runtime_suspend(struct device *dev) struct geni_i2c_dev *gi2c = dev_get_drvdata(dev); disable_irq(gi2c->irq); - ret = geni_se_resources_off(&gi2c->se); + + ret = geni_se_resources_deactivate(&gi2c->se); if (ret) { enable_irq(gi2c->irq); return ret; - - } else { - gi2c->suspended = 1; } - clk_disable_unprepare(gi2c->core_clk); - - return geni_icc_disable(&gi2c->se); + gi2c->suspended = 1; + return ret; } static int __maybe_unused geni_i2c_runtime_resume(struct device *dev) @@ -1182,28 +1179,13 @@ static int __maybe_unused geni_i2c_runtime_resume(struct device *dev) int ret; struct geni_i2c_dev *gi2c = dev_get_drvdata(dev); - ret = geni_icc_enable(&gi2c->se); + ret = geni_se_resources_activate(&gi2c->se); if (ret) return ret; - ret = clk_prepare_enable(gi2c->core_clk); - if (ret) - goto out_icc_disable; - - ret = geni_se_resources_on(&gi2c->se); - if (ret) - goto out_clk_disable; - enable_irq(gi2c->irq); gi2c->suspended = 0; - return 0; - -out_clk_disable: - clk_disable_unprepare(gi2c->core_clk); -out_icc_disable: - geni_icc_disable(&gi2c->se); - return ret; } -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:20 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
To avoid repeatedly fetching and checking platform data across various functions, store the struct of_device_id data directly in the i2c private structure. This change enhances code maintainability and reduces redundancy. Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4 - Added Acked-by tag. Konrad - Removed icc_ddr from platfrom data struct --- drivers/i2c/busses/i2c-qcom-geni.c | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index 4ff84bb0fff5..8fd62d659c2a 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -77,6 +77,12 @@ enum geni_i2c_err_code { #define XFER_TIMEOUT HZ #define RST_TIMEOUT HZ +struct geni_i2c_desc { + bool has_core_clk; + bool no_dma_support; + unsigned int tx_fifo_depth; +}; + #define QCOM_I2C_MIN_NUM_OF_MSGS_MULTI_DESC 2 /** @@ -122,13 +128,7 @@ struct geni_i2c_dev { bool is_tx_multi_desc_xfer; u32 num_msgs; struct geni_i2c_gpi_multi_desc_xfer i2c_multi_desc_config; -}; - -struct geni_i2c_desc { - bool has_core_clk; - char *icc_ddr; - bool no_dma_support; - unsigned int tx_fifo_depth; + const struct geni_i2c_desc *dev_data; }; struct geni_i2c_err_log { @@ -979,7 +979,6 @@ static int setup_gpi_dma(struct geni_i2c_dev *gi2c) static int geni_i2c_init(struct geni_i2c_dev *gi2c) { - const struct geni_i2c_desc *desc = NULL; u32 proto, tx_depth; bool fifo_disable; int ret; @@ -1002,8 +1001,7 @@ static int geni_i2c_init(struct geni_i2c_dev *gi2c) goto err; } - desc = device_get_match_data(gi2c->se.dev); - if (desc && desc->no_dma_support) { + if (gi2c->dev_data->no_dma_support) { fifo_disable = false; gi2c->no_dma = true; } else { @@ -1023,8 +1021,8 @@ static int geni_i2c_init(struct geni_i2c_dev *gi2c) tx_depth = geni_se_get_tx_fifo_depth(&gi2c->se); /* I2C Master Hub Serial Elements doesn't have the HW_PARAM_0 register */ - if (!tx_depth && desc) - tx_depth = desc->tx_fifo_depth; + if (!tx_depth && gi2c->dev_data->has_core_clk) + tx_depth = gi2c->dev_data->tx_fifo_depth; if (!tx_depth) { ret = dev_err_probe(gi2c->se.dev, -EINVAL, @@ -1067,7 +1065,6 @@ static int geni_i2c_probe(struct platform_device *pdev) struct geni_i2c_dev *gi2c; int ret; struct device *dev = &pdev->dev; - const struct geni_i2c_desc *desc = NULL; gi2c = devm_kzalloc(dev, sizeof(*gi2c), GFP_KERNEL); if (!gi2c) @@ -1079,7 +1076,7 @@ static int geni_i2c_probe(struct platform_device *pdev) if (IS_ERR(gi2c->se.base)) return PTR_ERR(gi2c->se.base); - desc = device_get_match_data(&pdev->dev); + gi2c->dev_data = device_get_match_data(&pdev->dev); ret = device_property_read_u32(dev, "clock-frequency", &gi2c->clk_freq_out); @@ -1218,15 +1215,16 @@ static const struct dev_pm_ops geni_i2c_pm_ops = { NULL) }; +static const struct geni_i2c_desc geni_i2c = {}; + static const struct geni_i2c_desc i2c_master_hub = { .has_core_clk = true, - .icc_ddr = NULL, .no_dma_support = true, .tx_fifo_depth = 16, }; static const struct of_device_id geni_i2c_dt_match[] = { - { .compatible = "qcom,geni-i2c" }, + { .compatible = "qcom,geni-i2c", .data = &geni_i2c }, { .compatible = "qcom,geni-i2c-master-hub", .data = &i2c_master_hub }, {} }; -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:21 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power on/off. The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4: - Added Acked-by tag. V1->v2: - Initialized ret to "0" in resume/suspend callbacks. Bjorn: - Used seperate APIs for the resouces enable/disable. --- drivers/i2c/busses/i2c-qcom-geni.c | 56 ++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 14 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index 8fd62d659c2a..2ad31e412b96 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -81,6 +81,10 @@ struct geni_i2c_desc { bool has_core_clk; bool no_dma_support; unsigned int tx_fifo_depth; + int (*resources_init)(struct geni_se *se); + int (*set_rate)(struct geni_se *se, unsigned long freq); + int (*power_on)(struct geni_se *se); + int (*power_off)(struct geni_se *se); }; #define QCOM_I2C_MIN_NUM_OF_MSGS_MULTI_DESC 2 @@ -203,8 +207,9 @@ static int geni_i2c_clk_map_idx(struct geni_i2c_dev *gi2c) return -EINVAL; } -static void qcom_geni_i2c_conf(struct geni_i2c_dev *gi2c) +static int qcom_geni_i2c_conf(struct geni_se *se, unsigned long freq) { + struct geni_i2c_dev *gi2c = dev_get_drvdata(se->dev); const struct geni_i2c_clk_fld *itr = gi2c->clk_fld; u32 val; @@ -217,6 +222,7 @@ static void qcom_geni_i2c_conf(struct geni_i2c_dev *gi2c) val |= itr->t_low_cnt << LOW_COUNTER_SHFT; val |= itr->t_cycle_cnt; writel_relaxed(val, gi2c->se.base + SE_I2C_SCL_COUNTERS); + return 0; } static void geni_i2c_err_misc(struct geni_i2c_dev *gi2c) @@ -908,7 +914,9 @@ static int geni_i2c_xfer(struct i2c_adapter *adap, return ret; } - qcom_geni_i2c_conf(gi2c); + ret = gi2c->dev_data->set_rate(&gi2c->se, gi2c->clk_freq_out); + if (ret) + return ret; if (gi2c->gpi_mode) ret = geni_i2c_gpi_xfer(gi2c, msgs, num); @@ -1043,8 +1051,9 @@ static int geni_i2c_init(struct geni_i2c_dev *gi2c) return ret; } -static int geni_i2c_resources_init(struct geni_i2c_dev *gi2c) +static int geni_i2c_resources_init(struct geni_se *se) { + struct geni_i2c_dev *gi2c = dev_get_drvdata(se->dev); int ret; ret = geni_se_resources_init(&gi2c->se); @@ -1097,7 +1106,7 @@ static int geni_i2c_probe(struct platform_device *pdev) spin_lock_init(&gi2c->lock); platform_set_drvdata(pdev, gi2c); - ret = geni_i2c_resources_init(gi2c); + ret = gi2c->dev_data->resources_init(&gi2c->se); if (ret) return ret; @@ -1156,15 +1165,17 @@ static void geni_i2c_shutdown(struct platform_device *pdev) static int __maybe_unused geni_i2c_runtime_suspend(struct device *dev) { - int ret; + int ret = 0; struct geni_i2c_dev *gi2c = dev_get_drvdata(dev); disable_irq(gi2c->irq); - ret = geni_se_resources_deactivate(&gi2c->se); - if (ret) { - enable_irq(gi2c->irq); - return ret; + if (gi2c->dev_data->power_off) { + ret = gi2c->dev_data->power_off(&gi2c->se); + if (ret) { + enable_irq(gi2c->irq); + return ret; + } } gi2c->suspended = 1; @@ -1173,12 +1184,14 @@ static int __maybe_unused geni_i2c_runtime_suspend(struct device *dev) static int __maybe_unused geni_i2c_runtime_resume(struct device *dev) { - int ret; + int ret = 0; struct geni_i2c_dev *gi2c = dev_get_drvdata(dev); - ret = geni_se_resources_activate(&gi2c->se); - if (ret) - return ret; + if (gi2c->dev_data->power_on) { + ret = gi2c->dev_data->power_on(&gi2c->se); + if (ret) + return ret; + } enable_irq(gi2c->irq); gi2c->suspended = 0; @@ -1215,17 +1228,32 @@ static const struct dev_pm_ops geni_i2c_pm_ops = { NULL) }; -static const struct geni_i2c_desc geni_i2c = {}; +static const struct geni_i2c_desc geni_i2c = { + .resources_init = geni_i2c_resources_init, + .set_rate = qcom_geni_i2c_conf, + .power_on = geni_se_resources_activate, + .power_off = geni_se_resources_deactivate, +}; static const struct geni_i2c_desc i2c_master_hub = { .has_core_clk = true, .no_dma_support = true, .tx_fifo_depth = 16, + .resources_init = geni_i2c_resources_init, + .set_rate = qcom_geni_i2c_conf, + .power_on = geni_se_resources_activate, + .power_off = geni_se_resources_deactivate, +}; + +static const struct geni_i2c_desc sa8255p_geni_i2c = { + .resources_init = geni_se_domain_attach, + .set_rate = geni_se_set_perf_opp, }; static const struct of_device_id geni_i2c_dt_match[] = { { .compatible = "qcom,geni-i2c", .data = &geni_i2c }, { .compatible = "qcom,geni-i2c-master-hub", .data = &i2c_master_hub }, + { .compatible = "qcom,sa8255p-geni-i2c", .data = &sa8255p_geni_i2c }, {} }; MODULE_DEVICE_TABLE(of, geni_i2c_dt_match); -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:22 +0530", "thread_id": "20260202180922.1692428-6-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH 0/2] arm64: dts: rockchip: fix Ethernet PHY on Theobroma PX30 devices
This removes the reliance on the bootloader setting up the Ethernet PHY for the Linux kernel to be able to use Ethernet. This is due to the HW default of the PHY reset line being active and the MDIO auto-detection mechanism not controlling a PHY's reset line such that we need to hardcode the PHY ID in the compatible property for it to be usable by the kernel, regardless of what the bootloader is doing. We only ever had one PHY (DP83825) for both devices, so it's fine to hardcode this way. Signed-off-by: Quentin Schulz <quentin.schulz@cherry.de> --- Quentin Schulz (2): arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Cobra arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Ringneck arch/arm64/boot/dts/rockchip/px30-cobra.dtsi | 2 +- arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) --- base-commit: 4d310797262f0ddf129e76c2aad2b950adaf1fda change-id: 20260130-px30-eth-phy-676fa181e116 Best regards, -- Quentin Schulz <quentin.schulz@cherry.de>
From: Quentin Schulz <quentin.schulz@cherry.de> When not passing the PHY ID with an ethernet-phy-idX.Y compatible property, the MDIO bus will attempt to auto-detect the PHY by reading its registers and then probing the appropriate driver. For this to work, the PHY needs to be in a working state. Unfortunately, the net subsystem doesn't control the PHY reset GPIO when attempting to auto-detect the PHY. This means the PHY needs to be in a working state when entering the Linux kernel. This historically has been the case for this device, but only because the bootloader was taking care of initializing the Ethernet controller even when not using it. We're attempting to support the removal of the network stack in the bootloader, which means the Linux kernel will be entered with the PHY still in reset and now Ethernet doesn't work anymore. The devices in the field only ever had a TI DP83825, so let's simply bypass the auto-detection mechanism entirely by passing the appropriate PHY IDs via the compatible. Note that this is only an issue since commit e463625af7f9 ("arm64: dts: rockchip: move reset to dedicated eth-phy node on ringneck") as before that commit the reset was done by the MAC controller before starting the MDIO auto-detection mechanism, via the snps,reset-* properties. Cc: stable@vger.kernel.org Fixes: e463625af7f9 ("arm64: dts: rockchip: move reset to dedicated eth-phy node on ringneck") Signed-off-by: Quentin Schulz <quentin.schulz@cherry.de> --- arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi b/arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi index 4203b335a2633..973b4c5880e24 100644 --- a/arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi +++ b/arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi @@ -344,7 +344,7 @@ &io_domains { &mdio { dp83825: ethernet-phy@0 { - compatible = "ethernet-phy-ieee802.3-c22"; + compatible = "ethernet-phy-id2000.a140"; reg = <0x0>; pinctrl-names = "default"; pinctrl-0 = <&phy_rst>; -- 2.52.0
{ "author": "Quentin Schulz <foss+kernel@0leil.net>", "date": "Mon, 02 Feb 2026 11:27:26 +0100", "thread_id": "b2f12140-ee3d-45bc-864e-d51317c83b8d@cherry.de.mbox.gz" }
lkml
[PATCH 0/2] arm64: dts: rockchip: fix Ethernet PHY on Theobroma PX30 devices
This removes the reliance on the bootloader setting up the Ethernet PHY for the Linux kernel to be able to use Ethernet. This is due to the HW default of the PHY reset line being active and the MDIO auto-detection mechanism not controlling a PHY's reset line such that we need to hardcode the PHY ID in the compatible property for it to be usable by the kernel, regardless of what the bootloader is doing. We only ever had one PHY (DP83825) for both devices, so it's fine to hardcode this way. Signed-off-by: Quentin Schulz <quentin.schulz@cherry.de> --- Quentin Schulz (2): arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Cobra arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Ringneck arch/arm64/boot/dts/rockchip/px30-cobra.dtsi | 2 +- arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) --- base-commit: 4d310797262f0ddf129e76c2aad2b950adaf1fda change-id: 20260130-px30-eth-phy-676fa181e116 Best regards, -- Quentin Schulz <quentin.schulz@cherry.de>
From: Quentin Schulz <quentin.schulz@cherry.de> When not passing the PHY ID with an ethernet-phy-idX.Y compatible property, the MDIO bus will attempt to auto-detect the PHY by reading its registers and then probing the appropriate driver. For this to work, the PHY needs to be in a working state. Unfortunately, the net subsystem doesn't control the PHY reset GPIO when attempting to auto-detect the PHY. This means the PHY needs to be in a working state when entering the Linux kernel. This historically has been the case for this device, but only because the bootloader was taking care of initializing the Ethernet controller even when not using it. We're attempting to support the removal of the network stack in the bootloader, which means the Linux kernel will be entered with the PHY still in reset and now Ethernet doesn't work anymore. The devices in the field only ever had a TI DP83825, so let's simply bypass the auto-detection mechanism entirely by passing the appropriate PHY IDs via the compatible. Cc: stable@vger.kernel.org Fixes: bb510ddc9d3e ("arm64: dts: rockchip: add px30-cobra base dtsi and board variants") Signed-off-by: Quentin Schulz <quentin.schulz@cherry.de> --- arch/arm64/boot/dts/rockchip/px30-cobra.dtsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/rockchip/px30-cobra.dtsi b/arch/arm64/boot/dts/rockchip/px30-cobra.dtsi index b7e669d8ba4d1..add917af5de78 100644 --- a/arch/arm64/boot/dts/rockchip/px30-cobra.dtsi +++ b/arch/arm64/boot/dts/rockchip/px30-cobra.dtsi @@ -397,7 +397,7 @@ &io_domains { &mdio { dp83825: ethernet-phy@0 { - compatible = "ethernet-phy-ieee802.3-c22"; + compatible = "ethernet-phy-id2000.a140"; reg = <0x0>; pinctrl-names = "default"; pinctrl-0 = <&phy_rst>; -- 2.52.0
{ "author": "Quentin Schulz <foss+kernel@0leil.net>", "date": "Mon, 02 Feb 2026 11:27:25 +0100", "thread_id": "b2f12140-ee3d-45bc-864e-d51317c83b8d@cherry.de.mbox.gz" }
lkml
[PATCH 0/2] arm64: dts: rockchip: fix Ethernet PHY on Theobroma PX30 devices
This removes the reliance on the bootloader setting up the Ethernet PHY for the Linux kernel to be able to use Ethernet. This is due to the HW default of the PHY reset line being active and the MDIO auto-detection mechanism not controlling a PHY's reset line such that we need to hardcode the PHY ID in the compatible property for it to be usable by the kernel, regardless of what the bootloader is doing. We only ever had one PHY (DP83825) for both devices, so it's fine to hardcode this way. Signed-off-by: Quentin Schulz <quentin.schulz@cherry.de> --- Quentin Schulz (2): arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Cobra arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Ringneck arch/arm64/boot/dts/rockchip/px30-cobra.dtsi | 2 +- arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) --- base-commit: 4d310797262f0ddf129e76c2aad2b950adaf1fda change-id: 20260130-px30-eth-phy-676fa181e116 Best regards, -- Quentin Schulz <quentin.schulz@cherry.de>
On Mon, Feb 02, 2026 at 11:27:25AM +0100, Quentin Schulz wrote: What is the justification for stable? Andrew
{ "author": "Andrew Lunn <andrew@lunn.ch>", "date": "Mon, 2 Feb 2026 14:52:18 +0100", "thread_id": "b2f12140-ee3d-45bc-864e-d51317c83b8d@cherry.de.mbox.gz" }
lkml
[PATCH 0/2] arm64: dts: rockchip: fix Ethernet PHY on Theobroma PX30 devices
This removes the reliance on the bootloader setting up the Ethernet PHY for the Linux kernel to be able to use Ethernet. This is due to the HW default of the PHY reset line being active and the MDIO auto-detection mechanism not controlling a PHY's reset line such that we need to hardcode the PHY ID in the compatible property for it to be usable by the kernel, regardless of what the bootloader is doing. We only ever had one PHY (DP83825) for both devices, so it's fine to hardcode this way. Signed-off-by: Quentin Schulz <quentin.schulz@cherry.de> --- Quentin Schulz (2): arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Cobra arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Ringneck arch/arm64/boot/dts/rockchip/px30-cobra.dtsi | 2 +- arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) --- base-commit: 4d310797262f0ddf129e76c2aad2b950adaf1fda change-id: 20260130-px30-eth-phy-676fa181e116 Best regards, -- Quentin Schulz <quentin.schulz@cherry.de>
Hi Andrew, On 2/2/26 2:52 PM, Andrew Lunn wrote: Bootloader without network stack = no network in Linux. Cheers, Quentin
{ "author": "Quentin Schulz <quentin.schulz@cherry.de>", "date": "Mon, 2 Feb 2026 15:02:08 +0100", "thread_id": "b2f12140-ee3d-45bc-864e-d51317c83b8d@cherry.de.mbox.gz" }
lkml
[PATCH 0/2] arm64: dts: rockchip: fix Ethernet PHY on Theobroma PX30 devices
This removes the reliance on the bootloader setting up the Ethernet PHY for the Linux kernel to be able to use Ethernet. This is due to the HW default of the PHY reset line being active and the MDIO auto-detection mechanism not controlling a PHY's reset line such that we need to hardcode the PHY ID in the compatible property for it to be usable by the kernel, regardless of what the bootloader is doing. We only ever had one PHY (DP83825) for both devices, so it's fine to hardcode this way. Signed-off-by: Quentin Schulz <quentin.schulz@cherry.de> --- Quentin Schulz (2): arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Cobra arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Ringneck arch/arm64/boot/dts/rockchip/px30-cobra.dtsi | 2 +- arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) --- base-commit: 4d310797262f0ddf129e76c2aad2b950adaf1fda change-id: 20260130-px30-eth-phy-676fa181e116 Best regards, -- Quentin Schulz <quentin.schulz@cherry.de>
On Mon, Feb 02, 2026 at 03:02:08PM +0100, Quentin Schulz wrote: I can see this multiple ways.... Changing the bootloader introduces a regression. Hence you cannot change the bootloader. I personally also don't like boot loaders with basic functionality missing. Why cripple the bootloader by removing the network stack? But i also don't like Linux being dependent on the bootloader. Because some vendors ship boards with crippled bootloaders and you need to replace the bootloader. And then hidden vendor initialization is not in the mainline version of the bootloader, and something breaks in Linux. Making Linux more robust is generally ongoing development, not a bug fix. However, it bootloader developers decide to break the contract between the bootloader and the kernel, regressions have been reported, then it would make sense to backport the fix to work around the bootloader breakage. I don't know the internal of uboot too well. Can you remove the IP stack, but leave the drivers? Get the driver to probe and setup the PHY, so you keep the agreed contract with Linux, but you also get the crippled bootloader you want. For the commit message, i would like to see a reasoned argument, based on https://www.kernel.org/doc/html/latest/process/stable-kernel-rules.html why this should be in stable. Andrew
{ "author": "Andrew Lunn <andrew@lunn.ch>", "date": "Mon, 2 Feb 2026 15:55:56 +0100", "thread_id": "b2f12140-ee3d-45bc-864e-d51317c83b8d@cherry.de.mbox.gz" }
lkml
[PATCH 0/2] arm64: dts: rockchip: fix Ethernet PHY on Theobroma PX30 devices
This removes the reliance on the bootloader setting up the Ethernet PHY for the Linux kernel to be able to use Ethernet. This is due to the HW default of the PHY reset line being active and the MDIO auto-detection mechanism not controlling a PHY's reset line such that we need to hardcode the PHY ID in the compatible property for it to be usable by the kernel, regardless of what the bootloader is doing. We only ever had one PHY (DP83825) for both devices, so it's fine to hardcode this way. Signed-off-by: Quentin Schulz <quentin.schulz@cherry.de> --- Quentin Schulz (2): arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Cobra arm64: dts: rockchip: fix Ethernet PHY not found on PX30 Ringneck arch/arm64/boot/dts/rockchip/px30-cobra.dtsi | 2 +- arch/arm64/boot/dts/rockchip/px30-ringneck.dtsi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) --- base-commit: 4d310797262f0ddf129e76c2aad2b950adaf1fda change-id: 20260130-px30-eth-phy-676fa181e116 Best regards, -- Quentin Schulz <quentin.schulz@cherry.de>
On 2/2/26 3:55 PM, Andrew Lunn wrote: Ringneck is a SoM (system-on-module), I don't control what the user wants to do with it. So they may never have the networking stack enabled in the first place (I provide a U-Boot defconfig to use with the devkit, but I don't control what they do with it; it's also supported upstream so if they want to use that, they can). The answer is pretty simple here, no network stack, no bug to exploit there, smaller binary, faster boot. On finished products with secure boot, a crippled bootloader is fine (and desired). It does what it's supposed to do, nothing else. I also don't control what our clients will do with our SoM in their product (and I don't necessarily have feedback either). That's my main concern and only reason for marking this a stable candidate. We shouldn't have to rely on the bootloader doing something. This issue is not related to an API between the bootloader and kernel, so there's no explicit contract. There would be no reason for U-Boot to support having networking drivers compiled in when there's no network stack so I would even go as far as saying if that's the case, it's a bug. If I were to enable a MAC controller and Ethernet PHY drivers with menuconfig, I'd expect them to be working in U-Boot. In any case, I'm not interested in doing that if that even is possible. Audit companies and certification authorities may look into what's compiled in and ask questions about those drivers or stacks. Not compiled in, don't need to argue about them (I have had to do this for every CVE in the kernel in the past, so it's not a theoretical). If I wanted to go this route, I can simply toggle the PHY reset GPIO in U-Boot and be done with it. I still cannot control whether our Ringneck users had the network stack enabled in their bootloader and cannot force them to patch it to either add the network stack or this PHY reset toggling. I want a clean solution if I can have one. Cobra support was upstreamed with this issue, so I could see this as not being a candidate for stable but an improvement according to the standard you stated. Ringneck on the other hand used to work without a network stack in U-Boot before https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=e463625af7f92c4a9f097f7fb87f6baaad6e762a, so I think this is a regression (I don't control the bootloader of the final user, only the default one on our devkit but even then, I don't control what they flash on their setups). Also just to be clear, Theobroma (theobroma-systems.com domain name for mails, "tsd," prefix in compatibles) was acquired by CHERRY (cherry.de domain name for mails) in 2021, we're the manufacturer, vendor and developer of the boards in this patch series. (Not sure if it helps, but I can imagine some confusion with my mail address and the original name of the device manufacturer). Since you haven't answered on patch 2, I'm assuming that """ Note that this is only an issue since commit e463625af7f9 ("arm64: dts: rockchip: move reset to dedicated eth-phy node on ringneck") as before that commit the reset was done by the MAC controller before starting the MDIO auto-detection mechanism, via the snps,reset-* properties. """ is a reasoned argument for making that patch a stable candidate. I don't care too much about stable releases for Cobra as no third party is or will be involved in BSP development so I know for sure which version we're using and that it is appropriately patched (until we migrate to a newer kernel with this patch merged). Also, we're the only one able to change anything on that device due to secure boot so no need to care about hypothetical flashing. So Heiko, if you agree with Andrew here you can either drop the trailer when applying this patch or I can send a v2 dropping the Cc: stable trailer for the Cobra patch. For what it's worth, I agree with what you've said Andrew. I sympathize with the dilemma. Quentin
{ "author": "Quentin Schulz <quentin.schulz@cherry.de>", "date": "Mon, 2 Feb 2026 17:31:58 +0100", "thread_id": "b2f12140-ee3d-45bc-864e-d51317c83b8d@cherry.de.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Add verify-only public key crypto support for ML-DSA so that the X.509/PKCS#7 signature verification code, as used by module signing, amongst other things, can make use of it through the common crypto_sig API. Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org> cc: Eric Biggers <ebiggers@kernel.org> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/Kconfig | 9 +++ crypto/Makefile | 2 + crypto/mldsa.c | 201 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 212 insertions(+) create mode 100644 crypto/mldsa.c diff --git a/crypto/Kconfig b/crypto/Kconfig index 12a87f7cf150..a210575fa5e0 100644 --- a/crypto/Kconfig +++ b/crypto/Kconfig @@ -344,6 +344,15 @@ config CRYPTO_ECRDSA One of the Russian cryptographic standard algorithms (called GOST algorithms). Only signature verification is implemented. +config CRYPTO_MLDSA + tristate "ML-DSA (Module-Lattice-Based Digital Signature Algorithm)" + select CRYPTO_SIG + select CRYPTO_LIB_MLDSA + help + ML-DSA (Module-Lattice-Based Digital Signature Algorithm) (FIPS-204). + + Only signature verification is implemented. + endmenu menu "Block ciphers" diff --git a/crypto/Makefile b/crypto/Makefile index 23d3db7be425..267d5403045b 100644 --- a/crypto/Makefile +++ b/crypto/Makefile @@ -60,6 +60,8 @@ ecdsa_generic-y += ecdsa-p1363.o ecdsa_generic-y += ecdsasignature.asn1.o obj-$(CONFIG_CRYPTO_ECDSA) += ecdsa_generic.o +obj-$(CONFIG_CRYPTO_MLDSA) += mldsa.o + crypto_acompress-y := acompress.o crypto_acompress-y += scompress.o obj-$(CONFIG_CRYPTO_ACOMP2) += crypto_acompress.o diff --git a/crypto/mldsa.c b/crypto/mldsa.c new file mode 100644 index 000000000000..d8de082cc67a --- /dev/null +++ b/crypto/mldsa.c @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * crypto_sig wrapper around ML-DSA library. + */ +#include <linux/init.h> +#include <linux/module.h> +#include <crypto/internal/sig.h> +#include <crypto/mldsa.h> + +struct crypto_mldsa_ctx { + u8 pk[MAX(MAX(MLDSA44_PUBLIC_KEY_SIZE, + MLDSA65_PUBLIC_KEY_SIZE), + MLDSA87_PUBLIC_KEY_SIZE)]; + unsigned int pk_len; + enum mldsa_alg strength; + bool key_set; +}; + +static int crypto_mldsa_sign(struct crypto_sig *tfm, + const void *msg, unsigned int msg_len, + void *sig, unsigned int sig_len) +{ + return -EOPNOTSUPP; +} + +static int crypto_mldsa_verify(struct crypto_sig *tfm, + const void *sig, unsigned int sig_len, + const void *msg, unsigned int msg_len) +{ + const struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + if (unlikely(!ctx->key_set)) + return -EINVAL; + + return mldsa_verify(ctx->strength, sig, sig_len, msg, msg_len, + ctx->pk, ctx->pk_len); +} + +static unsigned int crypto_mldsa_key_size(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + switch (ctx->strength) { + case MLDSA44: + return MLDSA44_PUBLIC_KEY_SIZE; + case MLDSA65: + return MLDSA65_PUBLIC_KEY_SIZE; + case MLDSA87: + return MLDSA87_PUBLIC_KEY_SIZE; + default: + WARN_ON_ONCE(1); + return 0; + } +} + +static int crypto_mldsa_set_pub_key(struct crypto_sig *tfm, + const void *key, unsigned int keylen) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + unsigned int expected_len = crypto_mldsa_key_size(tfm); + + if (keylen != expected_len) + return -EINVAL; + + ctx->pk_len = keylen; + memcpy(ctx->pk, key, keylen); + ctx->key_set = true; + return 0; +} + +static int crypto_mldsa_set_priv_key(struct crypto_sig *tfm, + const void *key, unsigned int keylen) +{ + return -EOPNOTSUPP; +} + +static unsigned int crypto_mldsa_max_size(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + switch (ctx->strength) { + case MLDSA44: + return MLDSA44_SIGNATURE_SIZE; + case MLDSA65: + return MLDSA65_SIGNATURE_SIZE; + case MLDSA87: + return MLDSA87_SIGNATURE_SIZE; + default: + WARN_ON_ONCE(1); + return 0; + } +} + +static int crypto_mldsa44_alg_init(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + ctx->strength = MLDSA44; + ctx->key_set = false; + return 0; +} + +static int crypto_mldsa65_alg_init(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + ctx->strength = MLDSA65; + ctx->key_set = false; + return 0; +} + +static int crypto_mldsa87_alg_init(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + ctx->strength = MLDSA87; + ctx->key_set = false; + return 0; +} + +static void crypto_mldsa_alg_exit(struct crypto_sig *tfm) +{ +} + +static struct sig_alg crypto_mldsa_algs[] = { + { + .sign = crypto_mldsa_sign, + .verify = crypto_mldsa_verify, + .set_pub_key = crypto_mldsa_set_pub_key, + .set_priv_key = crypto_mldsa_set_priv_key, + .key_size = crypto_mldsa_key_size, + .max_size = crypto_mldsa_max_size, + .init = crypto_mldsa44_alg_init, + .exit = crypto_mldsa_alg_exit, + .base.cra_name = "mldsa44", + .base.cra_driver_name = "mldsa44-lib", + .base.cra_ctxsize = sizeof(struct crypto_mldsa_ctx), + .base.cra_module = THIS_MODULE, + .base.cra_priority = 5000, + }, { + .sign = crypto_mldsa_sign, + .verify = crypto_mldsa_verify, + .set_pub_key = crypto_mldsa_set_pub_key, + .set_priv_key = crypto_mldsa_set_priv_key, + .key_size = crypto_mldsa_key_size, + .max_size = crypto_mldsa_max_size, + .init = crypto_mldsa65_alg_init, + .exit = crypto_mldsa_alg_exit, + .base.cra_name = "mldsa65", + .base.cra_driver_name = "mldsa65-lib", + .base.cra_ctxsize = sizeof(struct crypto_mldsa_ctx), + .base.cra_module = THIS_MODULE, + .base.cra_priority = 5000, + }, { + .sign = crypto_mldsa_sign, + .verify = crypto_mldsa_verify, + .set_pub_key = crypto_mldsa_set_pub_key, + .set_priv_key = crypto_mldsa_set_priv_key, + .key_size = crypto_mldsa_key_size, + .max_size = crypto_mldsa_max_size, + .init = crypto_mldsa87_alg_init, + .exit = crypto_mldsa_alg_exit, + .base.cra_name = "mldsa87", + .base.cra_driver_name = "mldsa87-lib", + .base.cra_ctxsize = sizeof(struct crypto_mldsa_ctx), + .base.cra_module = THIS_MODULE, + .base.cra_priority = 5000, + }, +}; + +static int __init mldsa_init(void) +{ + int ret, i; + + for (i = 0; i < ARRAY_SIZE(crypto_mldsa_algs); i++) { + ret = crypto_register_sig(&crypto_mldsa_algs[i]); + if (ret < 0) + goto error; + } + return 0; + +error: + pr_err("Failed to register (%d)\n", ret); + for (i--; i >= 0; i--) + crypto_unregister_sig(&crypto_mldsa_algs[i]); + return ret; +} +module_init(mldsa_init); + +static void mldsa_exit(void) +{ + for (int i = 0; i < ARRAY_SIZE(crypto_mldsa_algs); i++) + crypto_unregister_sig(&crypto_mldsa_algs[i]); +} +module_exit(mldsa_exit); + +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("Crypto API support for ML-DSA signature verification"); +MODULE_ALIAS_CRYPTO("mldsa44"); +MODULE_ALIAS_CRYPTO("mldsa65"); +MODULE_ALIAS_CRYPTO("mldsa87");
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:06 +0000", "thread_id": "20260202170216.2467036-8-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Calculate the SHA256 hash for blacklisting purposes independently of the signature hash (which may be something other than SHA256). This is necessary because when ML-DSA is used, no digest is calculated. Note that this represents a change of behaviour in that the hash used for the blacklist check would previously have been whatever digest was used for, say, RSA-based signatures. It may be that this is inadvisable. Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/x509_parser.h | 2 ++ crypto/asymmetric_keys/x509_public_key.c | 22 +++++++++++++--------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/crypto/asymmetric_keys/x509_parser.h b/crypto/asymmetric_keys/x509_parser.h index 0688c222806b..b7aeebdddb36 100644 --- a/crypto/asymmetric_keys/x509_parser.h +++ b/crypto/asymmetric_keys/x509_parser.h @@ -9,12 +9,14 @@ #include <linux/time.h> #include <crypto/public_key.h> #include <keys/asymmetric-type.h> +#include <crypto/sha2.h> struct x509_certificate { struct x509_certificate *next; struct x509_certificate *signer; /* Certificate that signed this one */ struct public_key *pub; /* Public key details */ struct public_key_signature *sig; /* Signature parameters */ + u8 sha256[SHA256_DIGEST_SIZE]; /* Hash for blacklist purposes */ char *issuer; /* Name of certificate issuer */ char *subject; /* Name of certificate subject */ struct asymmetric_key_id *id; /* Issuer + Serial number */ diff --git a/crypto/asymmetric_keys/x509_public_key.c b/crypto/asymmetric_keys/x509_public_key.c index 12e3341e806b..79cc7b7a0630 100644 --- a/crypto/asymmetric_keys/x509_public_key.c +++ b/crypto/asymmetric_keys/x509_public_key.c @@ -31,6 +31,19 @@ int x509_get_sig_params(struct x509_certificate *cert) pr_devel("==>%s()\n", __func__); + /* Calculate a SHA256 hash of the TBS and check it against the + * blacklist. + */ + sha256(cert->tbs, cert->tbs_size, cert->sha256); + ret = is_hash_blacklisted(cert->sha256, sizeof(cert->sha256), + BLACKLIST_HASH_X509_TBS); + if (ret == -EKEYREJECTED) { + pr_err("Cert %*phN is blacklisted\n", + (int)sizeof(cert->sha256), cert->sha256); + cert->blacklisted = true; + ret = 0; + } + sig->s = kmemdup(cert->raw_sig, cert->raw_sig_size, GFP_KERNEL); if (!sig->s) return -ENOMEM; @@ -69,15 +82,6 @@ int x509_get_sig_params(struct x509_certificate *cert) if (ret < 0) goto error_2; - ret = is_hash_blacklisted(sig->digest, sig->digest_size, - BLACKLIST_HASH_X509_TBS); - if (ret == -EKEYREJECTED) { - pr_err("Cert %*phN is blacklisted\n", - sig->digest_size, sig->digest); - cert->blacklisted = true; - ret = 0; - } - error_2: kfree(desc); error:
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:07 +0000", "thread_id": "20260202170216.2467036-8-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Rename ->digest and ->digest_len to ->m and ->m_size to represent the input to the signature verification algorithm, reflecting that ->digest may no longer actually *be* a digest. Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/asymmetric_type.c | 4 ++-- crypto/asymmetric_keys/pkcs7_verify.c | 28 ++++++++++++------------ crypto/asymmetric_keys/public_key.c | 3 +-- crypto/asymmetric_keys/signature.c | 2 +- crypto/asymmetric_keys/x509_public_key.c | 10 ++++----- include/crypto/public_key.h | 4 ++-- security/integrity/digsig_asymmetric.c | 4 ++-- 7 files changed, 26 insertions(+), 29 deletions(-) diff --git a/crypto/asymmetric_keys/asymmetric_type.c b/crypto/asymmetric_keys/asymmetric_type.c index 348966ea2175..2326743310b1 100644 --- a/crypto/asymmetric_keys/asymmetric_type.c +++ b/crypto/asymmetric_keys/asymmetric_type.c @@ -593,10 +593,10 @@ static int asymmetric_key_verify_signature(struct kernel_pkey_params *params, { struct public_key_signature sig = { .s_size = params->in2_len, - .digest_size = params->in_len, + .m_size = params->in_len, .encoding = params->encoding, .hash_algo = params->hash_algo, - .digest = (void *)in, + .m = (void *)in, .s = (void *)in2, }; diff --git a/crypto/asymmetric_keys/pkcs7_verify.c b/crypto/asymmetric_keys/pkcs7_verify.c index 6d6475e3a9bf..aa085ec6fb1c 100644 --- a/crypto/asymmetric_keys/pkcs7_verify.c +++ b/crypto/asymmetric_keys/pkcs7_verify.c @@ -31,7 +31,7 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, kenter(",%u,%s", sinfo->index, sinfo->sig->hash_algo); /* The digest was calculated already. */ - if (sig->digest) + if (sig->m) return 0; if (!sinfo->sig->hash_algo) @@ -45,11 +45,11 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, return (PTR_ERR(tfm) == -ENOENT) ? -ENOPKG : PTR_ERR(tfm); desc_size = crypto_shash_descsize(tfm) + sizeof(*desc); - sig->digest_size = crypto_shash_digestsize(tfm); + sig->m_size = crypto_shash_digestsize(tfm); ret = -ENOMEM; - sig->digest = kmalloc(sig->digest_size, GFP_KERNEL); - if (!sig->digest) + sig->m = kmalloc(sig->m_size, GFP_KERNEL); + if (!sig->m) goto error_no_desc; desc = kzalloc(desc_size, GFP_KERNEL); @@ -59,11 +59,10 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, desc->tfm = tfm; /* Digest the message [RFC2315 9.3] */ - ret = crypto_shash_digest(desc, pkcs7->data, pkcs7->data_len, - sig->digest); + ret = crypto_shash_digest(desc, pkcs7->data, pkcs7->data_len, sig->m); if (ret < 0) goto error; - pr_devel("MsgDigest = [%*ph]\n", 8, sig->digest); + pr_devel("MsgDigest = [%*ph]\n", 8, sig->m); /* However, if there are authenticated attributes, there must be a * message digest attribute amongst them which corresponds to the @@ -78,14 +77,14 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, goto error; } - if (sinfo->msgdigest_len != sig->digest_size) { + if (sinfo->msgdigest_len != sig->m_size) { pr_warn("Sig %u: Invalid digest size (%u)\n", sinfo->index, sinfo->msgdigest_len); ret = -EBADMSG; goto error; } - if (memcmp(sig->digest, sinfo->msgdigest, + if (memcmp(sig->m, sinfo->msgdigest, sinfo->msgdigest_len) != 0) { pr_warn("Sig %u: Message digest doesn't match\n", sinfo->index); @@ -98,7 +97,8 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, * convert the attributes from a CONT.0 into a SET before we * hash it. */ - memset(sig->digest, 0, sig->digest_size); + memset(sig->m, 0, sig->m_size); + ret = crypto_shash_init(desc); if (ret < 0) @@ -108,10 +108,10 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, if (ret < 0) goto error; ret = crypto_shash_finup(desc, sinfo->authattrs, - sinfo->authattrs_len, sig->digest); + sinfo->authattrs_len, sig->m); if (ret < 0) goto error; - pr_devel("AADigest = [%*ph]\n", 8, sig->digest); + pr_devel("AADigest = [%*ph]\n", 8, sig->m); } error: @@ -138,8 +138,8 @@ int pkcs7_get_digest(struct pkcs7_message *pkcs7, const u8 **buf, u32 *len, if (ret) return ret; - *buf = sinfo->sig->digest; - *len = sinfo->sig->digest_size; + *buf = sinfo->sig->m; + *len = sinfo->sig->m_size; i = match_string(hash_algo_name, HASH_ALGO__LAST, sinfo->sig->hash_algo); diff --git a/crypto/asymmetric_keys/public_key.c b/crypto/asymmetric_keys/public_key.c index e5b177c8e842..a46356e0c08b 100644 --- a/crypto/asymmetric_keys/public_key.c +++ b/crypto/asymmetric_keys/public_key.c @@ -425,8 +425,7 @@ int public_key_verify_signature(const struct public_key *pkey, if (ret) goto error_free_key; - ret = crypto_sig_verify(tfm, sig->s, sig->s_size, - sig->digest, sig->digest_size); + ret = crypto_sig_verify(tfm, sig->s, sig->s_size, sig->m, sig->m_size); error_free_key: kfree_sensitive(key); diff --git a/crypto/asymmetric_keys/signature.c b/crypto/asymmetric_keys/signature.c index 041d04b5c953..f4ec126121b3 100644 --- a/crypto/asymmetric_keys/signature.c +++ b/crypto/asymmetric_keys/signature.c @@ -28,7 +28,7 @@ void public_key_signature_free(struct public_key_signature *sig) for (i = 0; i < ARRAY_SIZE(sig->auth_ids); i++) kfree(sig->auth_ids[i]); kfree(sig->s); - kfree(sig->digest); + kfree(sig->m); kfree(sig); } } diff --git a/crypto/asymmetric_keys/x509_public_key.c b/crypto/asymmetric_keys/x509_public_key.c index 79cc7b7a0630..3854f7ae4ed0 100644 --- a/crypto/asymmetric_keys/x509_public_key.c +++ b/crypto/asymmetric_keys/x509_public_key.c @@ -63,11 +63,11 @@ int x509_get_sig_params(struct x509_certificate *cert) } desc_size = crypto_shash_descsize(tfm) + sizeof(*desc); - sig->digest_size = crypto_shash_digestsize(tfm); + sig->m_size = crypto_shash_digestsize(tfm); ret = -ENOMEM; - sig->digest = kmalloc(sig->digest_size, GFP_KERNEL); - if (!sig->digest) + sig->m = kmalloc(sig->m_size, GFP_KERNEL); + if (!sig->m) goto error; desc = kzalloc(desc_size, GFP_KERNEL); @@ -76,9 +76,7 @@ int x509_get_sig_params(struct x509_certificate *cert) desc->tfm = tfm; - ret = crypto_shash_digest(desc, cert->tbs, cert->tbs_size, - sig->digest); - + ret = crypto_shash_digest(desc, cert->tbs, cert->tbs_size, sig->m); if (ret < 0) goto error_2; diff --git a/include/crypto/public_key.h b/include/crypto/public_key.h index 81098e00c08f..bd38ba4d217d 100644 --- a/include/crypto/public_key.h +++ b/include/crypto/public_key.h @@ -43,9 +43,9 @@ extern void public_key_free(struct public_key *key); struct public_key_signature { struct asymmetric_key_id *auth_ids[3]; u8 *s; /* Signature */ - u8 *digest; + u8 *m; /* Message data to pass to verifier */ u32 s_size; /* Number of bytes in signature */ - u32 digest_size; /* Number of bytes in digest */ + u32 m_size; /* Number of bytes in ->m */ const char *pkey_algo; const char *hash_algo; const char *encoding; diff --git a/security/integrity/digsig_asymmetric.c b/security/integrity/digsig_asymmetric.c index 457c0a396caf..87be85f477d1 100644 --- a/security/integrity/digsig_asymmetric.c +++ b/security/integrity/digsig_asymmetric.c @@ -121,8 +121,8 @@ int asymmetric_verify(struct key *keyring, const char *sig, goto out; } - pks.digest = (u8 *)data; - pks.digest_size = datalen; + pks.m = (u8 *)data; + pks.m_size = datalen; pks.s = hdr->sig; pks.s_size = siglen; ret = verify_signature(key, &pks);
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:08 +0000", "thread_id": "20260202170216.2467036-8-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Allow the data to be verified in a PKCS#7 or CMS message to be passed directly to an asymmetric cipher algorithm (e.g. ML-DSA) if it wants to do whatever passes for hashing/digestion itself. The normal digestion of the data is then skipped as that would be ignored unless another signed info in the message has some other algorithm that needs it. The 'data to be verified' may be the content of the PKCS#7 message or it will be the authenticatedAttributes (signedAttrs if CMS), modified, if those are present. This is done by: (1) Make ->m and ->m_size point to the data to be verified rather than making public_key_verify_signature() access the data directly. This is so that keyctl(KEYCTL_PKEY_VERIFY) will still work. (2) Add a flag, ->algo_takes_data, to indicate that the verification algorithm wants to access the data to be verified directly rather than having it digested first. (3) If the PKCS#7 message has authenticatedAttributes (or CMS signedAttrs), then the digest contained therein will be validated as now, and the modified attrs blob will either be digested or assigned to ->m as appropriate. (4) If present, always copy and modify the authenticatedAttributes (or signedAttrs) then digest that in one go rather than calling the shash update twice (once for the tag and once for the rest). (5) For ML-DSA, point ->m to the TBSCertificate instead of digesting it and using the digest. Note that whilst ML-DSA does allow for an "external mu", CMS doesn't yet have that standardised. Signed-off-by: David Howells <dhowells@redhat.com> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/pkcs7_parser.c | 4 +- crypto/asymmetric_keys/pkcs7_verify.c | 52 ++++++++++++++++-------- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_public_key.c | 10 +++++ include/crypto/public_key.h | 2 + 5 files changed, 51 insertions(+), 20 deletions(-) diff --git a/crypto/asymmetric_keys/pkcs7_parser.c b/crypto/asymmetric_keys/pkcs7_parser.c index 423d13c47545..3cdbab3b9f50 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.c +++ b/crypto/asymmetric_keys/pkcs7_parser.c @@ -599,8 +599,8 @@ int pkcs7_sig_note_set_of_authattrs(void *context, size_t hdrlen, } /* We need to switch the 'CONT 0' to a 'SET OF' when we digest */ - sinfo->authattrs = value - (hdrlen - 1); - sinfo->authattrs_len = vlen + (hdrlen - 1); + sinfo->authattrs = value - hdrlen; + sinfo->authattrs_len = vlen + hdrlen; return 0; } diff --git a/crypto/asymmetric_keys/pkcs7_verify.c b/crypto/asymmetric_keys/pkcs7_verify.c index aa085ec6fb1c..06abb9838f95 100644 --- a/crypto/asymmetric_keys/pkcs7_verify.c +++ b/crypto/asymmetric_keys/pkcs7_verify.c @@ -30,6 +30,16 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, kenter(",%u,%s", sinfo->index, sinfo->sig->hash_algo); + if (!sinfo->authattrs && sig->algo_takes_data) { + /* There's no intermediate digest and the signature algo + * doesn't want the data prehashing. + */ + sig->m = (void *)pkcs7->data; + sig->m_size = pkcs7->data_len; + sig->m_free = false; + return 0; + } + /* The digest was calculated already. */ if (sig->m) return 0; @@ -48,9 +58,10 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, sig->m_size = crypto_shash_digestsize(tfm); ret = -ENOMEM; - sig->m = kmalloc(sig->m_size, GFP_KERNEL); + sig->m = kmalloc(umax(sinfo->authattrs_len, sig->m_size), GFP_KERNEL); if (!sig->m) goto error_no_desc; + sig->m_free = true; desc = kzalloc(desc_size, GFP_KERNEL); if (!desc) @@ -69,8 +80,6 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, * digest we just calculated. */ if (sinfo->authattrs) { - u8 tag; - if (!sinfo->msgdigest) { pr_warn("Sig %u: No messageDigest\n", sinfo->index); ret = -EKEYREJECTED; @@ -96,21 +105,25 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, * as the contents of the digest instead. Note that we need to * convert the attributes from a CONT.0 into a SET before we * hash it. + * + * However, for certain algorithms, such as ML-DSA, the digest + * is integrated into the signing algorithm. In such a case, + * we copy the authattrs, modifying the tag type, and set that + * as the digest. */ - memset(sig->m, 0, sig->m_size); - - - ret = crypto_shash_init(desc); - if (ret < 0) - goto error; - tag = ASN1_CONS_BIT | ASN1_SET; - ret = crypto_shash_update(desc, &tag, 1); - if (ret < 0) - goto error; - ret = crypto_shash_finup(desc, sinfo->authattrs, - sinfo->authattrs_len, sig->m); - if (ret < 0) - goto error; + memcpy(sig->m, sinfo->authattrs, sinfo->authattrs_len); + sig->m[0] = ASN1_CONS_BIT | ASN1_SET; + + if (sig->algo_takes_data) { + sig->m_size = sinfo->authattrs_len; + ret = 0; + } else { + ret = crypto_shash_digest(desc, sig->m, + sinfo->authattrs_len, + sig->m); + if (ret < 0) + goto error; + } pr_devel("AADigest = [%*ph]\n", 8, sig->m); } @@ -137,6 +150,11 @@ int pkcs7_get_digest(struct pkcs7_message *pkcs7, const u8 **buf, u32 *len, ret = pkcs7_digest(pkcs7, sinfo); if (ret) return ret; + if (!sinfo->sig->m_free) { + pr_notice_once("%s: No digest available\n", __func__); + return -EINVAL; /* TODO: MLDSA doesn't necessarily calculate an + * intermediate digest. */ + } *buf = sinfo->sig->m; *len = sinfo->sig->m_size; diff --git a/crypto/asymmetric_keys/signature.c b/crypto/asymmetric_keys/signature.c index f4ec126121b3..a5ac7a53b670 100644 --- a/crypto/asymmetric_keys/signature.c +++ b/crypto/asymmetric_keys/signature.c @@ -28,7 +28,8 @@ void public_key_signature_free(struct public_key_signature *sig) for (i = 0; i < ARRAY_SIZE(sig->auth_ids); i++) kfree(sig->auth_ids[i]); kfree(sig->s); - kfree(sig->m); + if (sig->m_free) + kfree(sig->m); kfree(sig); } } diff --git a/crypto/asymmetric_keys/x509_public_key.c b/crypto/asymmetric_keys/x509_public_key.c index 3854f7ae4ed0..27b4fea37845 100644 --- a/crypto/asymmetric_keys/x509_public_key.c +++ b/crypto/asymmetric_keys/x509_public_key.c @@ -50,6 +50,14 @@ int x509_get_sig_params(struct x509_certificate *cert) sig->s_size = cert->raw_sig_size; + if (sig->algo_takes_data) { + /* The signature algorithm does whatever passes for hashing. */ + sig->m = (u8 *)cert->tbs; + sig->m_size = cert->tbs_size; + sig->m_free = false; + goto out; + } + /* Allocate the hashing algorithm we're going to need and find out how * big the hash operational data will be. */ @@ -69,6 +77,7 @@ int x509_get_sig_params(struct x509_certificate *cert) sig->m = kmalloc(sig->m_size, GFP_KERNEL); if (!sig->m) goto error; + sig->m_free = true; desc = kzalloc(desc_size, GFP_KERNEL); if (!desc) @@ -84,6 +93,7 @@ int x509_get_sig_params(struct x509_certificate *cert) kfree(desc); error: crypto_free_shash(tfm); +out: pr_devel("<==%s() = %d\n", __func__, ret); return ret; } diff --git a/include/crypto/public_key.h b/include/crypto/public_key.h index bd38ba4d217d..4c5199b20338 100644 --- a/include/crypto/public_key.h +++ b/include/crypto/public_key.h @@ -46,6 +46,8 @@ struct public_key_signature { u8 *m; /* Message data to pass to verifier */ u32 s_size; /* Number of bytes in signature */ u32 m_size; /* Number of bytes in ->m */ + bool m_free; /* T if ->m needs freeing */ + bool algo_takes_data; /* T if public key algo operates on data, not a hash */ const char *pkey_algo; const char *hash_algo; const char *encoding;
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:09 +0000", "thread_id": "20260202170216.2467036-8-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Add support for ML-DSA keys and signatures to the CMS/PKCS#7 and X.509 implementations. ML-DSA-44, -65 and -87 are all supported. For X.509 certificates, the TBSCertificate is required to be signed directly; for CMS, direct signing of the data is preferred, though use of SHA512 (and only that) as an intermediate hash of the content is permitted with signedAttrs. Signed-off-by: David Howells <dhowells@redhat.com> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/pkcs7_parser.c | 24 +++++++++++++++++++- crypto/asymmetric_keys/public_key.c | 10 +++++++++ crypto/asymmetric_keys/x509_cert_parser.c | 27 ++++++++++++++++++++++- include/linux/oid_registry.h | 5 +++++ 4 files changed, 64 insertions(+), 2 deletions(-) diff --git a/crypto/asymmetric_keys/pkcs7_parser.c b/crypto/asymmetric_keys/pkcs7_parser.c index 3cdbab3b9f50..594a8f1d9dfb 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.c +++ b/crypto/asymmetric_keys/pkcs7_parser.c @@ -95,11 +95,18 @@ static int pkcs7_check_authattrs(struct pkcs7_message *msg) if (sinfo->authattrs) { want = true; msg->have_authattrs = true; + } else if (sinfo->sig->algo_takes_data) { + sinfo->sig->hash_algo = "none"; } - for (sinfo = sinfo->next; sinfo; sinfo = sinfo->next) + for (sinfo = sinfo->next; sinfo; sinfo = sinfo->next) { if (!!sinfo->authattrs != want) goto inconsistent; + + if (!sinfo->authattrs && + sinfo->sig->algo_takes_data) + sinfo->sig->hash_algo = "none"; + } return 0; inconsistent: @@ -297,6 +304,21 @@ int pkcs7_sig_note_pkey_algo(void *context, size_t hdrlen, ctx->sinfo->sig->pkey_algo = "ecrdsa"; ctx->sinfo->sig->encoding = "raw"; break; + case OID_id_ml_dsa_44: + ctx->sinfo->sig->pkey_algo = "mldsa44"; + ctx->sinfo->sig->encoding = "raw"; + ctx->sinfo->sig->algo_takes_data = true; + break; + case OID_id_ml_dsa_65: + ctx->sinfo->sig->pkey_algo = "mldsa65"; + ctx->sinfo->sig->encoding = "raw"; + ctx->sinfo->sig->algo_takes_data = true; + break; + case OID_id_ml_dsa_87: + ctx->sinfo->sig->pkey_algo = "mldsa87"; + ctx->sinfo->sig->encoding = "raw"; + ctx->sinfo->sig->algo_takes_data = true; + break; default: printk("Unsupported pkey algo: %u\n", ctx->last_oid); return -ENOPKG; diff --git a/crypto/asymmetric_keys/public_key.c b/crypto/asymmetric_keys/public_key.c index a46356e0c08b..09a0b83d5d77 100644 --- a/crypto/asymmetric_keys/public_key.c +++ b/crypto/asymmetric_keys/public_key.c @@ -142,6 +142,16 @@ software_key_determine_akcipher(const struct public_key *pkey, if (strcmp(hash_algo, "streebog256") != 0 && strcmp(hash_algo, "streebog512") != 0) return -EINVAL; + } else if (strcmp(pkey->pkey_algo, "mldsa44") == 0 || + strcmp(pkey->pkey_algo, "mldsa65") == 0 || + strcmp(pkey->pkey_algo, "mldsa87") == 0) { + if (strcmp(encoding, "raw") != 0) + return -EINVAL; + if (!hash_algo) + return -EINVAL; + if (strcmp(hash_algo, "none") != 0 && + strcmp(hash_algo, "sha512") != 0) + return -EINVAL; } else { /* Unknown public key algorithm */ return -ENOPKG; diff --git a/crypto/asymmetric_keys/x509_cert_parser.c b/crypto/asymmetric_keys/x509_cert_parser.c index b37cae914987..2fe094f5caf3 100644 --- a/crypto/asymmetric_keys/x509_cert_parser.c +++ b/crypto/asymmetric_keys/x509_cert_parser.c @@ -257,6 +257,15 @@ int x509_note_sig_algo(void *context, size_t hdrlen, unsigned char tag, case OID_gost2012Signature512: ctx->cert->sig->hash_algo = "streebog512"; goto ecrdsa; + case OID_id_ml_dsa_44: + ctx->cert->sig->pkey_algo = "mldsa44"; + goto ml_dsa; + case OID_id_ml_dsa_65: + ctx->cert->sig->pkey_algo = "mldsa65"; + goto ml_dsa; + case OID_id_ml_dsa_87: + ctx->cert->sig->pkey_algo = "mldsa87"; + goto ml_dsa; } rsa_pkcs1: @@ -274,6 +283,12 @@ int x509_note_sig_algo(void *context, size_t hdrlen, unsigned char tag, ctx->cert->sig->encoding = "x962"; ctx->sig_algo = ctx->last_oid; return 0; +ml_dsa: + ctx->cert->sig->algo_takes_data = true; + ctx->cert->sig->hash_algo = "none"; + ctx->cert->sig->encoding = "raw"; + ctx->sig_algo = ctx->last_oid; + return 0; } /* @@ -300,7 +315,8 @@ int x509_note_signature(void *context, size_t hdrlen, if (strcmp(ctx->cert->sig->pkey_algo, "rsa") == 0 || strcmp(ctx->cert->sig->pkey_algo, "ecrdsa") == 0 || - strcmp(ctx->cert->sig->pkey_algo, "ecdsa") == 0) { + strcmp(ctx->cert->sig->pkey_algo, "ecdsa") == 0 || + strncmp(ctx->cert->sig->pkey_algo, "mldsa", 5) == 0) { /* Discard the BIT STRING metadata */ if (vlen < 1 || *(const u8 *)value != 0) return -EBADMSG; @@ -524,6 +540,15 @@ int x509_extract_key_data(void *context, size_t hdrlen, return -ENOPKG; } break; + case OID_id_ml_dsa_44: + ctx->cert->pub->pkey_algo = "mldsa44"; + break; + case OID_id_ml_dsa_65: + ctx->cert->pub->pkey_algo = "mldsa65"; + break; + case OID_id_ml_dsa_87: + ctx->cert->pub->pkey_algo = "mldsa87"; + break; default: return -ENOPKG; } diff --git a/include/linux/oid_registry.h b/include/linux/oid_registry.h index 6de479ebbe5d..ebce402854de 100644 --- a/include/linux/oid_registry.h +++ b/include/linux/oid_registry.h @@ -145,6 +145,11 @@ enum OID { OID_id_rsassa_pkcs1_v1_5_with_sha3_384, /* 2.16.840.1.101.3.4.3.15 */ OID_id_rsassa_pkcs1_v1_5_with_sha3_512, /* 2.16.840.1.101.3.4.3.16 */ + /* NIST FIPS-204 ML-DSA */ + OID_id_ml_dsa_44, /* 2.16.840.1.101.3.4.3.17 */ + OID_id_ml_dsa_65, /* 2.16.840.1.101.3.4.3.18 */ + OID_id_ml_dsa_87, /* 2.16.840.1.101.3.4.3.19 */ + OID__NR };
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:10 +0000", "thread_id": "20260202170216.2467036-8-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Allow ML-DSA module signing to be enabled. Note that OpenSSL's CMS_*() function suite does not, as of OpenSSL-3.6, support the use of CMS_NOATTR with ML-DSA, so the prohibition against using signedAttrs with module signing has to be removed. The selected digest then applies only to the algorithm used to calculate the digest stored in the messageDigest attribute. The OpenSSL development branch has patches applied that fix this[1], but it appears that that will only be available in OpenSSL-4. [1] https://github.com/openssl/openssl/pull/28923 sign-file won't set CMS_NOATTR if openssl is earlier than v4, resulting in the use of signed attributes. The ML-DSA algorithm takes the raw data to be signed without regard to what digest algorithm is specified in the CMS message. The CMS specified digest algorithm is ignored unless signedAttrs are used; in such a case, only SHA512 is permitted. Signed-off-by: David Howells <dhowells@redhat.com> cc: Jarkko Sakkinen <jarkko@kernel.org> cc: Eric Biggers <ebiggers@kernel.org> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- Documentation/admin-guide/module-signing.rst | 16 ++++---- certs/Kconfig | 40 ++++++++++++++++++++ certs/Makefile | 3 ++ scripts/sign-file.c | 39 ++++++++++++++----- 4 files changed, 82 insertions(+), 16 deletions(-) diff --git a/Documentation/admin-guide/module-signing.rst b/Documentation/admin-guide/module-signing.rst index a8667a777490..7f2f127dc76f 100644 --- a/Documentation/admin-guide/module-signing.rst +++ b/Documentation/admin-guide/module-signing.rst @@ -28,10 +28,12 @@ trusted userspace bits. This facility uses X.509 ITU-T standard certificates to encode the public keys involved. The signatures are not themselves encoded in any industrial standard -type. The built-in facility currently only supports the RSA & NIST P-384 ECDSA -public key signing standard (though it is pluggable and permits others to be -used). The possible hash algorithms that can be used are SHA-2 and SHA-3 of -sizes 256, 384, and 512 (the algorithm is selected by data in the signature). +type. The built-in facility currently only supports the RSA, NIST P-384 ECDSA +and NIST FIPS-204 ML-DSA public key signing standards (though it is pluggable +and permits others to be used). For RSA and ECDSA, the possible hash +algorithms that can be used are SHA-2 and SHA-3 of sizes 256, 384, and 512 (the +algorithm is selected by data in the signature); ML-DSA does its own hashing, +but is allowed to be used with a SHA512 hash for signed attributes. ========================== @@ -146,9 +148,9 @@ into vmlinux) using parameters in the:: file (which is also generated if it does not already exist). -One can select between RSA (``MODULE_SIG_KEY_TYPE_RSA``) and ECDSA -(``MODULE_SIG_KEY_TYPE_ECDSA``) to generate either RSA 4k or NIST -P-384 keypair. +One can select between RSA (``MODULE_SIG_KEY_TYPE_RSA``), ECDSA +(``MODULE_SIG_KEY_TYPE_ECDSA``) and ML-DSA (``MODULE_SIG_KEY_TYPE_MLDSA_*``) to +generate an RSA 4k, a NIST P-384 keypair or an ML-DSA 44, 65 or 87 keypair. It is strongly recommended that you provide your own x509.genkey file. diff --git a/certs/Kconfig b/certs/Kconfig index 78307dc25559..8e39a80c7abe 100644 --- a/certs/Kconfig +++ b/certs/Kconfig @@ -39,6 +39,39 @@ config MODULE_SIG_KEY_TYPE_ECDSA Note: Remove all ECDSA signing keys, e.g. certs/signing_key.pem, when falling back to building Linux 5.14 and older kernels. +config MODULE_SIG_KEY_TYPE_MLDSA_44 + bool "ML-DSA-44" + select CRYPTO_MLDSA + depends on OPENSSL_SUPPORTS_ML_DSA + help + Use an ML-DSA-44 key (NIST FIPS 204) for module signing. ML-DSA + support requires OpenSSL-3.5 minimum; preferably OpenSSL-4+. With + the latter, the entire module body will be signed; with the former, + signedAttrs will be used as it lacks support for CMS_NOATTR with + ML-DSA. + +config MODULE_SIG_KEY_TYPE_MLDSA_65 + bool "ML-DSA-65" + select CRYPTO_MLDSA + depends on OPENSSL_SUPPORTS_ML_DSA + help + Use an ML-DSA-65 key (NIST FIPS 204) for module signing. ML-DSA + support requires OpenSSL-3.5 minimum; preferably OpenSSL-4+. With + the latter, the entire module body will be signed; with the former, + signedAttrs will be used as it lacks support for CMS_NOATTR with + ML-DSA. + +config MODULE_SIG_KEY_TYPE_MLDSA_87 + bool "ML-DSA-87" + select CRYPTO_MLDSA + depends on OPENSSL_SUPPORTS_ML_DSA + help + Use an ML-DSA-87 key (NIST FIPS 204) for module signing. ML-DSA + support requires OpenSSL-3.5 minimum; preferably OpenSSL-4+. With + the latter, the entire module body will be signed; with the former, + signedAttrs will be used as it lacks support for CMS_NOATTR with + ML-DSA. + endchoice config SYSTEM_TRUSTED_KEYRING @@ -154,4 +187,11 @@ config SYSTEM_BLACKLIST_AUTH_UPDATE keyring. The PKCS#7 signature of the description is set in the key payload. Blacklist keys cannot be removed. +config OPENSSL_SUPPORTS_ML_DSA + def_bool $(success, openssl list -key-managers | grep -q ML-DSA-87) + help + Support for ML-DSA-44/65/87 was added in openssl-3.5, so as long + as older versions are supported, the key types may only be + set after testing the installed binary for support. + endmenu diff --git a/certs/Makefile b/certs/Makefile index f6fa4d8d75e0..3ee1960f9f4a 100644 --- a/certs/Makefile +++ b/certs/Makefile @@ -43,6 +43,9 @@ targets += x509_certificate_list ifeq ($(CONFIG_MODULE_SIG_KEY),certs/signing_key.pem) keytype-$(CONFIG_MODULE_SIG_KEY_TYPE_ECDSA) := -newkey ec -pkeyopt ec_paramgen_curve:secp384r1 +keytype-$(CONFIG_MODULE_SIG_KEY_TYPE_MLDSA_44) := -newkey ml-dsa-44 +keytype-$(CONFIG_MODULE_SIG_KEY_TYPE_MLDSA_65) := -newkey ml-dsa-65 +keytype-$(CONFIG_MODULE_SIG_KEY_TYPE_MLDSA_87) := -newkey ml-dsa-87 quiet_cmd_gen_key = GENKEY $@ cmd_gen_key = openssl req -new -nodes -utf8 -$(CONFIG_MODULE_SIG_HASH) -days 36500 \ diff --git a/scripts/sign-file.c b/scripts/sign-file.c index 7070245edfc1..78276b15ab23 100644 --- a/scripts/sign-file.c +++ b/scripts/sign-file.c @@ -27,7 +27,7 @@ #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/err.h> -#if OPENSSL_VERSION_MAJOR >= 3 +#if OPENSSL_VERSION_NUMBER >= 0x30000000L # define USE_PKCS11_PROVIDER # include <openssl/provider.h> # include <openssl/store.h> @@ -315,18 +315,39 @@ int main(int argc, char **argv) ERR(!digest_algo, "EVP_get_digestbyname"); #ifndef USE_PKCS7 + + unsigned int flags = + CMS_NOCERTS | + CMS_PARTIAL | + CMS_BINARY | + CMS_DETACHED | + CMS_STREAM | + CMS_NOSMIMECAP | +#ifdef CMS_NO_SIGNING_TIME + CMS_NO_SIGNING_TIME | +#endif + use_keyid; + +#if OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L + if (EVP_PKEY_is_a(private_key, "ML-DSA-44") || + EVP_PKEY_is_a(private_key, "ML-DSA-65") || + EVP_PKEY_is_a(private_key, "ML-DSA-87")) { + /* ML-DSA + CMS_NOATTR is not supported in openssl-3.5 + * and before. + */ + use_signed_attrs = 0; + } +#endif + + flags |= use_signed_attrs; + /* Load the signature message from the digest buffer. */ - cms = CMS_sign(NULL, NULL, NULL, NULL, - CMS_NOCERTS | CMS_PARTIAL | CMS_BINARY | - CMS_DETACHED | CMS_STREAM); + cms = CMS_sign(NULL, NULL, NULL, NULL, flags); ERR(!cms, "CMS_sign"); - ERR(!CMS_add1_signer(cms, x509, private_key, digest_algo, - CMS_NOCERTS | CMS_BINARY | - CMS_NOSMIMECAP | use_keyid | - use_signed_attrs), + ERR(!CMS_add1_signer(cms, x509, private_key, digest_algo, flags), "CMS_add1_signer"); - ERR(CMS_final(cms, bm, NULL, CMS_NOCERTS | CMS_BINARY) != 1, + ERR(CMS_final(cms, bm, NULL, flags) != 1, "CMS_final"); #else
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:11 +0000", "thread_id": "20260202170216.2467036-8-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Allow the rejection of authenticatedAttributes in PKCS#7 (signedAttrs in CMS) to be waived in the kernel config for ML-DSA when used for module signing. This reflects the issue that openssl < 4.0 cannot do this and openssl-4 has not yet been released. This does not permit RSA, ECDSA or ECRDSA to be so waived (behaviour unchanged). Signed-off-by: David Howells <dhowells@redhat.com> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Jarkko Sakkinen <jarkko@kernel.org> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/Kconfig | 11 +++++++++++ crypto/asymmetric_keys/pkcs7_parser.c | 8 ++++++++ crypto/asymmetric_keys/pkcs7_parser.h | 3 +++ crypto/asymmetric_keys/pkcs7_verify.c | 6 ++++++ 4 files changed, 28 insertions(+) diff --git a/crypto/asymmetric_keys/Kconfig b/crypto/asymmetric_keys/Kconfig index e1345b8f39f1..1dae2232fe9a 100644 --- a/crypto/asymmetric_keys/Kconfig +++ b/crypto/asymmetric_keys/Kconfig @@ -53,6 +53,17 @@ config PKCS7_MESSAGE_PARSER This option provides support for parsing PKCS#7 format messages for signature data and provides the ability to verify the signature. +config PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + bool "Waive rejection of authenticatedAttributes for ML-DSA" + depends on PKCS7_MESSAGE_PARSER + depends on CRYPTO_MLDSA + help + Due to use of CMS_NOATTR with ML-DSA not being supported in + OpenSSL < 4.0 (and thus any released version), enabling this + allows authenticatedAttributes to be used with ML-DSA for + module signing. Use of authenticatedAttributes in this + context is normally rejected. + config PKCS7_TEST_KEY tristate "PKCS#7 testing key type" depends on SYSTEM_DATA_VERIFICATION diff --git a/crypto/asymmetric_keys/pkcs7_parser.c b/crypto/asymmetric_keys/pkcs7_parser.c index 594a8f1d9dfb..db1c90ca6fc1 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.c +++ b/crypto/asymmetric_keys/pkcs7_parser.c @@ -92,9 +92,17 @@ static int pkcs7_check_authattrs(struct pkcs7_message *msg) if (!sinfo) goto inconsistent; +#ifdef CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + msg->authattrs_rej_waivable = true; +#endif + if (sinfo->authattrs) { want = true; msg->have_authattrs = true; +#ifdef CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + if (strncmp(sinfo->sig->pkey_algo, "mldsa", 5) != 0) + msg->authattrs_rej_waivable = false; +#endif } else if (sinfo->sig->algo_takes_data) { sinfo->sig->hash_algo = "none"; } diff --git a/crypto/asymmetric_keys/pkcs7_parser.h b/crypto/asymmetric_keys/pkcs7_parser.h index e17f7ce4fb43..6ef9f335bb17 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.h +++ b/crypto/asymmetric_keys/pkcs7_parser.h @@ -55,6 +55,9 @@ struct pkcs7_message { struct pkcs7_signed_info *signed_infos; u8 version; /* Version of cert (1 -> PKCS#7 or CMS; 3 -> CMS) */ bool have_authattrs; /* T if have authattrs */ +#ifdef CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + bool authattrs_rej_waivable; /* T if authatts rejection can be waived */ +#endif /* Content Data (or NULL) */ enum OID data_type; /* Type of Data */ diff --git a/crypto/asymmetric_keys/pkcs7_verify.c b/crypto/asymmetric_keys/pkcs7_verify.c index 06abb9838f95..519eecfe6778 100644 --- a/crypto/asymmetric_keys/pkcs7_verify.c +++ b/crypto/asymmetric_keys/pkcs7_verify.c @@ -425,6 +425,12 @@ int pkcs7_verify(struct pkcs7_message *pkcs7, return -EKEYREJECTED; } if (pkcs7->have_authattrs) { +#ifdef CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + if (pkcs7->authattrs_rej_waivable) { + pr_warn("Waived invalid module sig (has authattrs)\n"); + break; + } +#endif pr_warn("Invalid module sig (has authattrs)\n"); return -EKEYREJECTED; }
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:12 +0000", "thread_id": "20260202170216.2467036-8-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v2 0/4] Improve Hyper-V memory deposit error handling
This series extends the MSHV driver to properly handle additional memory-related error codes from the Microsoft Hypervisor by depositing memory pages when needed. Currently, when the hypervisor returns HV_STATUS_INSUFFICIENT_MEMORY during partition creation, the driver calls hv_call_deposit_pages() to provide the necessary memory. However, there are other memory-related error codes that indicate the hypervisor needs additional memory resources, but the driver does not attempt to deposit pages for these cases. This series introduces a dedicated helper function macro to identify all memory-related error codes (HV_STATUS_INSUFFICIENT_MEMORY, HV_STATUS_INSUFFICIENT_BUFFERS, HV_STATUS_INSUFFICIENT_DEVICE_DOMAINS, and HV_STATUS_INSUFFICIENT_ROOT_MEMORY) and ensures the driver attempts to deposit pages for all of them via new hv_deposit_memory() helper. With these changes, partition creation becomes more robust by handling all scenarios where the hypervisor requires additional memory deposits. v2: - Rename hv_result_oom() into hv_result_needs_memory() --- Stanislav Kinsburskii (4): mshv: Introduce hv_result_needs_memory() helper function mshv: Introduce hv_deposit_memory helper functions mshv: Handle insufficient contiguous memory hypervisor status mshv: Handle insufficient root memory hypervisor statuses drivers/hv/hv_common.c | 3 ++ drivers/hv/hv_proc.c | 54 +++++++++++++++++++++++++++++++++++--- drivers/hv/mshv_root_hv_call.c | 45 +++++++++++++------------------- drivers/hv/mshv_root_main.c | 5 +--- include/asm-generic/mshyperv.h | 13 +++++++++ include/hyperv/hvgdk_mini.h | 57 +++++++++++++++++++++------------------- include/hyperv/hvhdk_mini.h | 2 + 7 files changed, 119 insertions(+), 60 deletions(-)
Replace direct comparisons of hv_result(status) against HV_STATUS_INSUFFICIENT_MEMORY with a new hv_result_needs_memory() helper function. This improves code readability and provides a consistent and extendable interface for checking out-of-memory conditions in hypercall results. No functional changes intended. Signed-off-by: Stanislav Kinsburskii <skinsburskii@linux.microsoft.com> --- drivers/hv/hv_proc.c | 14 ++++++++++++-- drivers/hv/mshv_root_hv_call.c | 20 ++++++++++---------- drivers/hv/mshv_root_main.c | 2 +- include/asm-generic/mshyperv.h | 3 +++ 4 files changed, 26 insertions(+), 13 deletions(-) diff --git a/drivers/hv/hv_proc.c b/drivers/hv/hv_proc.c index fbb4eb3901bb..e53204b9e05d 100644 --- a/drivers/hv/hv_proc.c +++ b/drivers/hv/hv_proc.c @@ -110,6 +110,16 @@ int hv_call_deposit_pages(int node, u64 partition_id, u32 num_pages) } EXPORT_SYMBOL_GPL(hv_call_deposit_pages); +bool hv_result_needs_memory(u64 status) +{ + switch (hv_result(status)) { + case HV_STATUS_INSUFFICIENT_MEMORY: + return true; + } + return false; +} +EXPORT_SYMBOL_GPL(hv_result_needs_memory); + int hv_call_add_logical_proc(int node, u32 lp_index, u32 apic_id) { struct hv_input_add_logical_processor *input; @@ -137,7 +147,7 @@ int hv_call_add_logical_proc(int node, u32 lp_index, u32 apic_id) input, output); local_irq_restore(flags); - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { if (!hv_result_success(status)) { hv_status_err(status, "cpu %u apic ID: %u\n", lp_index, apic_id); @@ -179,7 +189,7 @@ int hv_call_create_vp(int node, u64 partition_id, u32 vp_index, u32 flags) status = hv_do_hypercall(HVCALL_CREATE_VP, input, NULL); local_irq_restore(irq_flags); - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { if (!hv_result_success(status)) { hv_status_err(status, "vcpu: %u, lp: %u\n", vp_index, flags); diff --git a/drivers/hv/mshv_root_hv_call.c b/drivers/hv/mshv_root_hv_call.c index 598eaff4ff29..89afeeda21dd 100644 --- a/drivers/hv/mshv_root_hv_call.c +++ b/drivers/hv/mshv_root_hv_call.c @@ -115,7 +115,7 @@ int hv_call_create_partition(u64 flags, status = hv_do_hypercall(HVCALL_CREATE_PARTITION, input, output); - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { if (hv_result_success(status)) *partition_id = output->partition_id; local_irq_restore(irq_flags); @@ -147,7 +147,7 @@ int hv_call_initialize_partition(u64 partition_id) status = hv_do_fast_hypercall8(HVCALL_INITIALIZE_PARTITION, *(u64 *)&input); - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { ret = hv_result_to_errno(status); break; } @@ -239,7 +239,7 @@ static int hv_do_map_gpa_hcall(u64 partition_id, u64 gfn, u64 page_struct_count, completed = hv_repcomp(status); - if (hv_result(status) == HV_STATUS_INSUFFICIENT_MEMORY) { + if (hv_result_needs_memory(status)) { ret = hv_call_deposit_pages(NUMA_NO_NODE, partition_id, HV_MAP_GPA_DEPOSIT_PAGES); if (ret) @@ -455,7 +455,7 @@ int hv_call_get_vp_state(u32 vp_index, u64 partition_id, status = hv_do_hypercall(control, input, output); - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { if (hv_result_success(status) && ret_output) memcpy(ret_output, output, sizeof(*output)); @@ -518,7 +518,7 @@ int hv_call_set_vp_state(u32 vp_index, u64 partition_id, status = hv_do_hypercall(control, input, NULL); - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { local_irq_restore(flags); ret = hv_result_to_errno(status); break; @@ -563,7 +563,7 @@ static int hv_call_map_vp_state_page(u64 partition_id, u32 vp_index, u32 type, status = hv_do_hypercall(HVCALL_MAP_VP_STATE_PAGE, input, output); - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { if (hv_result_success(status)) *state_page = pfn_to_page(output->map_location); local_irq_restore(flags); @@ -718,7 +718,7 @@ hv_call_create_port(u64 port_partition_id, union hv_port_id port_id, if (hv_result_success(status)) break; - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { ret = hv_result_to_errno(status); break; } @@ -772,7 +772,7 @@ hv_call_connect_port(u64 port_partition_id, union hv_port_id port_id, if (hv_result_success(status)) break; - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { ret = hv_result_to_errno(status); break; } @@ -843,7 +843,7 @@ static int hv_call_map_stats_page2(enum hv_stats_object_type type, if (!ret) break; - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { hv_status_debug(status, "\n"); break; } @@ -878,7 +878,7 @@ static int hv_call_map_stats_page(enum hv_stats_object_type type, pfn = output->map_location; local_irq_restore(flags); - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) { + if (!hv_result_needs_memory(status)) { ret = hv_result_to_errno(status); if (hv_result_success(status)) break; diff --git a/drivers/hv/mshv_root_main.c b/drivers/hv/mshv_root_main.c index 6a6bf641b352..ee30bfa6bb2e 100644 --- a/drivers/hv/mshv_root_main.c +++ b/drivers/hv/mshv_root_main.c @@ -261,7 +261,7 @@ static int mshv_ioctl_passthru_hvcall(struct mshv_partition *partition, if (hv_result_success(status)) break; - if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) + if (!hv_result_needs_memory(status)) ret = hv_result_to_errno(status); else ret = hv_call_deposit_pages(NUMA_NO_NODE, diff --git a/include/asm-generic/mshyperv.h b/include/asm-generic/mshyperv.h index ecedab554c80..452426d5b2ab 100644 --- a/include/asm-generic/mshyperv.h +++ b/include/asm-generic/mshyperv.h @@ -342,6 +342,8 @@ static inline bool hv_parent_partition(void) { return hv_root_partition() || hv_l1vh_partition(); } + +bool hv_result_needs_memory(u64 status); int hv_call_deposit_pages(int node, u64 partition_id, u32 num_pages); int hv_call_add_logical_proc(int node, u32 lp_index, u32 acpi_id); int hv_call_create_vp(int node, u64 partition_id, u32 vp_index, u32 flags); @@ -350,6 +352,7 @@ int hv_call_create_vp(int node, u64 partition_id, u32 vp_index, u32 flags); static inline bool hv_root_partition(void) { return false; } static inline bool hv_l1vh_partition(void) { return false; } static inline bool hv_parent_partition(void) { return false; } +static inline bool hv_result_needs_memory(u64 status) { return false; } static inline int hv_call_deposit_pages(int node, u64 partition_id, u32 num_pages) { return -EOPNOTSUPP;
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Mon, 02 Feb 2026 17:58:57 +0000", "thread_id": "177005513775.120041.4894134857240187839.stgit@skinsburskii-cloud-desktop.internal.cloudapp.net.mbox.gz" }
lkml
[PATCH v2 0/4] Improve Hyper-V memory deposit error handling
This series extends the MSHV driver to properly handle additional memory-related error codes from the Microsoft Hypervisor by depositing memory pages when needed. Currently, when the hypervisor returns HV_STATUS_INSUFFICIENT_MEMORY during partition creation, the driver calls hv_call_deposit_pages() to provide the necessary memory. However, there are other memory-related error codes that indicate the hypervisor needs additional memory resources, but the driver does not attempt to deposit pages for these cases. This series introduces a dedicated helper function macro to identify all memory-related error codes (HV_STATUS_INSUFFICIENT_MEMORY, HV_STATUS_INSUFFICIENT_BUFFERS, HV_STATUS_INSUFFICIENT_DEVICE_DOMAINS, and HV_STATUS_INSUFFICIENT_ROOT_MEMORY) and ensures the driver attempts to deposit pages for all of them via new hv_deposit_memory() helper. With these changes, partition creation becomes more robust by handling all scenarios where the hypervisor requires additional memory deposits. v2: - Rename hv_result_oom() into hv_result_needs_memory() --- Stanislav Kinsburskii (4): mshv: Introduce hv_result_needs_memory() helper function mshv: Introduce hv_deposit_memory helper functions mshv: Handle insufficient contiguous memory hypervisor status mshv: Handle insufficient root memory hypervisor statuses drivers/hv/hv_common.c | 3 ++ drivers/hv/hv_proc.c | 54 +++++++++++++++++++++++++++++++++++--- drivers/hv/mshv_root_hv_call.c | 45 +++++++++++++------------------- drivers/hv/mshv_root_main.c | 5 +--- include/asm-generic/mshyperv.h | 13 +++++++++ include/hyperv/hvgdk_mini.h | 57 +++++++++++++++++++++------------------- include/hyperv/hvhdk_mini.h | 2 + 7 files changed, 119 insertions(+), 60 deletions(-)
Introduce hv_deposit_memory_node() and hv_deposit_memory() helper functions to handle memory deposition with proper error handling. The new hv_deposit_memory_node() function takes the hypervisor status as a parameter and validates it before depositing pages. It checks for HV_STATUS_INSUFFICIENT_MEMORY specifically and returns an error for unexpected status codes. This is a precursor patch to new out-of-memory error codes support. No functional changes intended. Signed-off-by: Stanislav Kinsburskii <skinsburskii@linux.microsoft.com> --- drivers/hv/hv_proc.c | 22 ++++++++++++++++++++-- drivers/hv/mshv_root_hv_call.c | 25 +++++++++---------------- drivers/hv/mshv_root_main.c | 3 +-- include/asm-generic/mshyperv.h | 10 ++++++++++ 4 files changed, 40 insertions(+), 20 deletions(-) diff --git a/drivers/hv/hv_proc.c b/drivers/hv/hv_proc.c index e53204b9e05d..ffa25cd6e4e9 100644 --- a/drivers/hv/hv_proc.c +++ b/drivers/hv/hv_proc.c @@ -110,6 +110,23 @@ int hv_call_deposit_pages(int node, u64 partition_id, u32 num_pages) } EXPORT_SYMBOL_GPL(hv_call_deposit_pages); +int hv_deposit_memory_node(int node, u64 partition_id, + u64 hv_status) +{ + u32 num_pages; + + switch (hv_result(hv_status)) { + case HV_STATUS_INSUFFICIENT_MEMORY: + num_pages = 1; + break; + default: + hv_status_err(hv_status, "Unexpected!\n"); + return -ENOMEM; + } + return hv_call_deposit_pages(node, partition_id, num_pages); +} +EXPORT_SYMBOL_GPL(hv_deposit_memory_node); + bool hv_result_needs_memory(u64 status) { switch (hv_result(status)) { @@ -155,7 +172,8 @@ int hv_call_add_logical_proc(int node, u32 lp_index, u32 apic_id) } break; } - ret = hv_call_deposit_pages(node, hv_current_partition_id, 1); + ret = hv_deposit_memory_node(node, hv_current_partition_id, + status); } while (!ret); return ret; @@ -197,7 +215,7 @@ int hv_call_create_vp(int node, u64 partition_id, u32 vp_index, u32 flags) } break; } - ret = hv_call_deposit_pages(node, partition_id, 1); + ret = hv_deposit_memory_node(node, partition_id, status); } while (!ret); diff --git a/drivers/hv/mshv_root_hv_call.c b/drivers/hv/mshv_root_hv_call.c index 89afeeda21dd..174431cb5e0e 100644 --- a/drivers/hv/mshv_root_hv_call.c +++ b/drivers/hv/mshv_root_hv_call.c @@ -123,8 +123,7 @@ int hv_call_create_partition(u64 flags, break; } local_irq_restore(irq_flags); - ret = hv_call_deposit_pages(NUMA_NO_NODE, - hv_current_partition_id, 1); + ret = hv_deposit_memory(hv_current_partition_id, status); } while (!ret); return ret; @@ -151,7 +150,7 @@ int hv_call_initialize_partition(u64 partition_id) ret = hv_result_to_errno(status); break; } - ret = hv_call_deposit_pages(NUMA_NO_NODE, partition_id, 1); + ret = hv_deposit_memory(partition_id, status); } while (!ret); return ret; @@ -465,8 +464,7 @@ int hv_call_get_vp_state(u32 vp_index, u64 partition_id, } local_irq_restore(flags); - ret = hv_call_deposit_pages(NUMA_NO_NODE, - partition_id, 1); + ret = hv_deposit_memory(partition_id, status); } while (!ret); return ret; @@ -525,8 +523,7 @@ int hv_call_set_vp_state(u32 vp_index, u64 partition_id, } local_irq_restore(flags); - ret = hv_call_deposit_pages(NUMA_NO_NODE, - partition_id, 1); + ret = hv_deposit_memory(partition_id, status); } while (!ret); return ret; @@ -573,7 +570,7 @@ static int hv_call_map_vp_state_page(u64 partition_id, u32 vp_index, u32 type, local_irq_restore(flags); - ret = hv_call_deposit_pages(NUMA_NO_NODE, partition_id, 1); + ret = hv_deposit_memory(partition_id, status); } while (!ret); return ret; @@ -722,8 +719,7 @@ hv_call_create_port(u64 port_partition_id, union hv_port_id port_id, ret = hv_result_to_errno(status); break; } - ret = hv_call_deposit_pages(NUMA_NO_NODE, port_partition_id, 1); - + ret = hv_deposit_memory(port_partition_id, status); } while (!ret); return ret; @@ -776,8 +772,7 @@ hv_call_connect_port(u64 port_partition_id, union hv_port_id port_id, ret = hv_result_to_errno(status); break; } - ret = hv_call_deposit_pages(NUMA_NO_NODE, - connection_partition_id, 1); + ret = hv_deposit_memory(connection_partition_id, status); } while (!ret); return ret; @@ -848,8 +843,7 @@ static int hv_call_map_stats_page2(enum hv_stats_object_type type, break; } - ret = hv_call_deposit_pages(NUMA_NO_NODE, - hv_current_partition_id, 1); + ret = hv_deposit_memory(hv_current_partition_id, status); } while (!ret); return ret; @@ -885,8 +879,7 @@ static int hv_call_map_stats_page(enum hv_stats_object_type type, return ret; } - ret = hv_call_deposit_pages(NUMA_NO_NODE, - hv_current_partition_id, 1); + ret = hv_deposit_memory(hv_current_partition_id, status); if (ret) return ret; } while (!ret); diff --git a/drivers/hv/mshv_root_main.c b/drivers/hv/mshv_root_main.c index ee30bfa6bb2e..dce255c94f9e 100644 --- a/drivers/hv/mshv_root_main.c +++ b/drivers/hv/mshv_root_main.c @@ -264,8 +264,7 @@ static int mshv_ioctl_passthru_hvcall(struct mshv_partition *partition, if (!hv_result_needs_memory(status)) ret = hv_result_to_errno(status); else - ret = hv_call_deposit_pages(NUMA_NO_NODE, - pt_id, 1); + ret = hv_deposit_memory(pt_id, status); } while (!ret); args.status = hv_result(status); diff --git a/include/asm-generic/mshyperv.h b/include/asm-generic/mshyperv.h index 452426d5b2ab..d37b68238c97 100644 --- a/include/asm-generic/mshyperv.h +++ b/include/asm-generic/mshyperv.h @@ -344,6 +344,7 @@ static inline bool hv_parent_partition(void) } bool hv_result_needs_memory(u64 status); +int hv_deposit_memory_node(int node, u64 partition_id, u64 status); int hv_call_deposit_pages(int node, u64 partition_id, u32 num_pages); int hv_call_add_logical_proc(int node, u32 lp_index, u32 acpi_id); int hv_call_create_vp(int node, u64 partition_id, u32 vp_index, u32 flags); @@ -353,6 +354,10 @@ static inline bool hv_root_partition(void) { return false; } static inline bool hv_l1vh_partition(void) { return false; } static inline bool hv_parent_partition(void) { return false; } static inline bool hv_result_needs_memory(u64 status) { return false; } +static inline int hv_deposit_memory_node(int node, u64 partition_id, u64 status) +{ + return -EOPNOTSUPP; +} static inline int hv_call_deposit_pages(int node, u64 partition_id, u32 num_pages) { return -EOPNOTSUPP; @@ -367,6 +372,11 @@ static inline int hv_call_create_vp(int node, u64 partition_id, u32 vp_index, u3 } #endif /* CONFIG_MSHV_ROOT */ +static inline int hv_deposit_memory(u64 partition_id, u64 status) +{ + return hv_deposit_memory_node(NUMA_NO_NODE, partition_id, status); +} + #if IS_ENABLED(CONFIG_HYPERV_VTL_MODE) u8 __init get_vtl(void); #else
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Mon, 02 Feb 2026 17:59:03 +0000", "thread_id": "177005513775.120041.4894134857240187839.stgit@skinsburskii-cloud-desktop.internal.cloudapp.net.mbox.gz" }
lkml
[PATCH v2 0/4] Improve Hyper-V memory deposit error handling
This series extends the MSHV driver to properly handle additional memory-related error codes from the Microsoft Hypervisor by depositing memory pages when needed. Currently, when the hypervisor returns HV_STATUS_INSUFFICIENT_MEMORY during partition creation, the driver calls hv_call_deposit_pages() to provide the necessary memory. However, there are other memory-related error codes that indicate the hypervisor needs additional memory resources, but the driver does not attempt to deposit pages for these cases. This series introduces a dedicated helper function macro to identify all memory-related error codes (HV_STATUS_INSUFFICIENT_MEMORY, HV_STATUS_INSUFFICIENT_BUFFERS, HV_STATUS_INSUFFICIENT_DEVICE_DOMAINS, and HV_STATUS_INSUFFICIENT_ROOT_MEMORY) and ensures the driver attempts to deposit pages for all of them via new hv_deposit_memory() helper. With these changes, partition creation becomes more robust by handling all scenarios where the hypervisor requires additional memory deposits. v2: - Rename hv_result_oom() into hv_result_needs_memory() --- Stanislav Kinsburskii (4): mshv: Introduce hv_result_needs_memory() helper function mshv: Introduce hv_deposit_memory helper functions mshv: Handle insufficient contiguous memory hypervisor status mshv: Handle insufficient root memory hypervisor statuses drivers/hv/hv_common.c | 3 ++ drivers/hv/hv_proc.c | 54 +++++++++++++++++++++++++++++++++++--- drivers/hv/mshv_root_hv_call.c | 45 +++++++++++++------------------- drivers/hv/mshv_root_main.c | 5 +--- include/asm-generic/mshyperv.h | 13 +++++++++ include/hyperv/hvgdk_mini.h | 57 +++++++++++++++++++++------------------- include/hyperv/hvhdk_mini.h | 2 + 7 files changed, 119 insertions(+), 60 deletions(-)
The HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY status indicates that the hypervisor lacks sufficient contiguous memory for its internal allocations. When this status is encountered, allocate and deposit HV_MAX_CONTIGUOUS_ALLOCATION_PAGES contiguous pages to the hypervisor. HV_MAX_CONTIGUOUS_ALLOCATION_PAGES is defined in the hypervisor headers, a deposit of this size will always satisfy the hypervisor's requirements. Signed-off-by: Stanislav Kinsburskii <skinsburskii@linux.microsoft.com> --- drivers/hv/hv_common.c | 1 + drivers/hv/hv_proc.c | 4 ++++ include/hyperv/hvgdk_mini.h | 1 + include/hyperv/hvhdk_mini.h | 2 ++ 4 files changed, 8 insertions(+) diff --git a/drivers/hv/hv_common.c b/drivers/hv/hv_common.c index 0a3ab7efed46..c7f63c9de503 100644 --- a/drivers/hv/hv_common.c +++ b/drivers/hv/hv_common.c @@ -791,6 +791,7 @@ static const struct hv_status_info hv_status_infos[] = { _STATUS_INFO(HV_STATUS_UNKNOWN_PROPERTY, -EIO), _STATUS_INFO(HV_STATUS_PROPERTY_VALUE_OUT_OF_RANGE, -EIO), _STATUS_INFO(HV_STATUS_INSUFFICIENT_MEMORY, -ENOMEM), + _STATUS_INFO(HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY, -ENOMEM), _STATUS_INFO(HV_STATUS_INVALID_PARTITION_ID, -EINVAL), _STATUS_INFO(HV_STATUS_INVALID_VP_INDEX, -EINVAL), _STATUS_INFO(HV_STATUS_NOT_FOUND, -EIO), diff --git a/drivers/hv/hv_proc.c b/drivers/hv/hv_proc.c index ffa25cd6e4e9..dfa27be66ff7 100644 --- a/drivers/hv/hv_proc.c +++ b/drivers/hv/hv_proc.c @@ -119,6 +119,9 @@ int hv_deposit_memory_node(int node, u64 partition_id, case HV_STATUS_INSUFFICIENT_MEMORY: num_pages = 1; break; + case HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY: + num_pages = HV_MAX_CONTIGUOUS_ALLOCATION_PAGES; + break; default: hv_status_err(hv_status, "Unexpected!\n"); return -ENOMEM; @@ -131,6 +134,7 @@ bool hv_result_needs_memory(u64 status) { switch (hv_result(status)) { case HV_STATUS_INSUFFICIENT_MEMORY: + case HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY: return true; } return false; diff --git a/include/hyperv/hvgdk_mini.h b/include/hyperv/hvgdk_mini.h index 04b18d0e37af..70f22ef44948 100644 --- a/include/hyperv/hvgdk_mini.h +++ b/include/hyperv/hvgdk_mini.h @@ -38,6 +38,7 @@ struct hv_u128 { #define HV_STATUS_INVALID_LP_INDEX 0x41 #define HV_STATUS_INVALID_REGISTER_VALUE 0x50 #define HV_STATUS_OPERATION_FAILED 0x71 +#define HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY 0x75 #define HV_STATUS_TIME_OUT 0x78 #define HV_STATUS_CALL_PENDING 0x79 #define HV_STATUS_VTL_ALREADY_ENABLED 0x86 diff --git a/include/hyperv/hvhdk_mini.h b/include/hyperv/hvhdk_mini.h index c0300910808b..091c03e26046 100644 --- a/include/hyperv/hvhdk_mini.h +++ b/include/hyperv/hvhdk_mini.h @@ -7,6 +7,8 @@ #include "hvgdk_mini.h" +#define HV_MAX_CONTIGUOUS_ALLOCATION_PAGES 8 + /* * Doorbell connection_info flags. */
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Mon, 02 Feb 2026 17:59:09 +0000", "thread_id": "177005513775.120041.4894134857240187839.stgit@skinsburskii-cloud-desktop.internal.cloudapp.net.mbox.gz" }
lkml
[PATCH v2 0/4] Improve Hyper-V memory deposit error handling
This series extends the MSHV driver to properly handle additional memory-related error codes from the Microsoft Hypervisor by depositing memory pages when needed. Currently, when the hypervisor returns HV_STATUS_INSUFFICIENT_MEMORY during partition creation, the driver calls hv_call_deposit_pages() to provide the necessary memory. However, there are other memory-related error codes that indicate the hypervisor needs additional memory resources, but the driver does not attempt to deposit pages for these cases. This series introduces a dedicated helper function macro to identify all memory-related error codes (HV_STATUS_INSUFFICIENT_MEMORY, HV_STATUS_INSUFFICIENT_BUFFERS, HV_STATUS_INSUFFICIENT_DEVICE_DOMAINS, and HV_STATUS_INSUFFICIENT_ROOT_MEMORY) and ensures the driver attempts to deposit pages for all of them via new hv_deposit_memory() helper. With these changes, partition creation becomes more robust by handling all scenarios where the hypervisor requires additional memory deposits. v2: - Rename hv_result_oom() into hv_result_needs_memory() --- Stanislav Kinsburskii (4): mshv: Introduce hv_result_needs_memory() helper function mshv: Introduce hv_deposit_memory helper functions mshv: Handle insufficient contiguous memory hypervisor status mshv: Handle insufficient root memory hypervisor statuses drivers/hv/hv_common.c | 3 ++ drivers/hv/hv_proc.c | 54 +++++++++++++++++++++++++++++++++++--- drivers/hv/mshv_root_hv_call.c | 45 +++++++++++++------------------- drivers/hv/mshv_root_main.c | 5 +--- include/asm-generic/mshyperv.h | 13 +++++++++ include/hyperv/hvgdk_mini.h | 57 +++++++++++++++++++++------------------- include/hyperv/hvhdk_mini.h | 2 + 7 files changed, 119 insertions(+), 60 deletions(-)
When creating guest partition objects, the hypervisor may fail to allocate root partition pages and return an insufficient memory status. In this case, deposit memory using the root partition ID instead. Note: This error should never occur in a guest of L1VH partition context. Signed-off-by: Stanislav Kinsburskii <skinsburskii@linux.microsoft.com> --- drivers/hv/hv_common.c | 2 + drivers/hv/hv_proc.c | 14 ++++++++++ include/hyperv/hvgdk_mini.h | 58 ++++++++++++++++++++++--------------------- 3 files changed, 46 insertions(+), 28 deletions(-) diff --git a/drivers/hv/hv_common.c b/drivers/hv/hv_common.c index c7f63c9de503..cab0d1733607 100644 --- a/drivers/hv/hv_common.c +++ b/drivers/hv/hv_common.c @@ -792,6 +792,8 @@ static const struct hv_status_info hv_status_infos[] = { _STATUS_INFO(HV_STATUS_PROPERTY_VALUE_OUT_OF_RANGE, -EIO), _STATUS_INFO(HV_STATUS_INSUFFICIENT_MEMORY, -ENOMEM), _STATUS_INFO(HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY, -ENOMEM), + _STATUS_INFO(HV_STATUS_INSUFFICIENT_ROOT_MEMORY, -ENOMEM), + _STATUS_INFO(HV_STATUS_INSUFFICIENT_CONTIGUOUS_ROOT_MEMORY, -ENOMEM), _STATUS_INFO(HV_STATUS_INVALID_PARTITION_ID, -EINVAL), _STATUS_INFO(HV_STATUS_INVALID_VP_INDEX, -EINVAL), _STATUS_INFO(HV_STATUS_NOT_FOUND, -EIO), diff --git a/drivers/hv/hv_proc.c b/drivers/hv/hv_proc.c index dfa27be66ff7..935129e0b39d 100644 --- a/drivers/hv/hv_proc.c +++ b/drivers/hv/hv_proc.c @@ -122,6 +122,18 @@ int hv_deposit_memory_node(int node, u64 partition_id, case HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY: num_pages = HV_MAX_CONTIGUOUS_ALLOCATION_PAGES; break; + + case HV_STATUS_INSUFFICIENT_CONTIGUOUS_ROOT_MEMORY: + num_pages = HV_MAX_CONTIGUOUS_ALLOCATION_PAGES; + fallthrough; + case HV_STATUS_INSUFFICIENT_ROOT_MEMORY: + if (!hv_root_partition()) { + hv_status_err(hv_status, "Unexpected root memory deposit\n"); + return -ENOMEM; + } + partition_id = HV_PARTITION_ID_SELF; + break; + default: hv_status_err(hv_status, "Unexpected!\n"); return -ENOMEM; @@ -135,6 +147,8 @@ bool hv_result_needs_memory(u64 status) switch (hv_result(status)) { case HV_STATUS_INSUFFICIENT_MEMORY: case HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY: + case HV_STATUS_INSUFFICIENT_ROOT_MEMORY: + case HV_STATUS_INSUFFICIENT_CONTIGUOUS_ROOT_MEMORY: return true; } return false; diff --git a/include/hyperv/hvgdk_mini.h b/include/hyperv/hvgdk_mini.h index 70f22ef44948..5b74a857ef43 100644 --- a/include/hyperv/hvgdk_mini.h +++ b/include/hyperv/hvgdk_mini.h @@ -14,34 +14,36 @@ struct hv_u128 { } __packed; /* NOTE: when adding below, update hv_result_to_string() */ -#define HV_STATUS_SUCCESS 0x0 -#define HV_STATUS_INVALID_HYPERCALL_CODE 0x2 -#define HV_STATUS_INVALID_HYPERCALL_INPUT 0x3 -#define HV_STATUS_INVALID_ALIGNMENT 0x4 -#define HV_STATUS_INVALID_PARAMETER 0x5 -#define HV_STATUS_ACCESS_DENIED 0x6 -#define HV_STATUS_INVALID_PARTITION_STATE 0x7 -#define HV_STATUS_OPERATION_DENIED 0x8 -#define HV_STATUS_UNKNOWN_PROPERTY 0x9 -#define HV_STATUS_PROPERTY_VALUE_OUT_OF_RANGE 0xA -#define HV_STATUS_INSUFFICIENT_MEMORY 0xB -#define HV_STATUS_INVALID_PARTITION_ID 0xD -#define HV_STATUS_INVALID_VP_INDEX 0xE -#define HV_STATUS_NOT_FOUND 0x10 -#define HV_STATUS_INVALID_PORT_ID 0x11 -#define HV_STATUS_INVALID_CONNECTION_ID 0x12 -#define HV_STATUS_INSUFFICIENT_BUFFERS 0x13 -#define HV_STATUS_NOT_ACKNOWLEDGED 0x14 -#define HV_STATUS_INVALID_VP_STATE 0x15 -#define HV_STATUS_NO_RESOURCES 0x1D -#define HV_STATUS_PROCESSOR_FEATURE_NOT_SUPPORTED 0x20 -#define HV_STATUS_INVALID_LP_INDEX 0x41 -#define HV_STATUS_INVALID_REGISTER_VALUE 0x50 -#define HV_STATUS_OPERATION_FAILED 0x71 -#define HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY 0x75 -#define HV_STATUS_TIME_OUT 0x78 -#define HV_STATUS_CALL_PENDING 0x79 -#define HV_STATUS_VTL_ALREADY_ENABLED 0x86 +#define HV_STATUS_SUCCESS 0x0 +#define HV_STATUS_INVALID_HYPERCALL_CODE 0x2 +#define HV_STATUS_INVALID_HYPERCALL_INPUT 0x3 +#define HV_STATUS_INVALID_ALIGNMENT 0x4 +#define HV_STATUS_INVALID_PARAMETER 0x5 +#define HV_STATUS_ACCESS_DENIED 0x6 +#define HV_STATUS_INVALID_PARTITION_STATE 0x7 +#define HV_STATUS_OPERATION_DENIED 0x8 +#define HV_STATUS_UNKNOWN_PROPERTY 0x9 +#define HV_STATUS_PROPERTY_VALUE_OUT_OF_RANGE 0xA +#define HV_STATUS_INSUFFICIENT_MEMORY 0xB +#define HV_STATUS_INVALID_PARTITION_ID 0xD +#define HV_STATUS_INVALID_VP_INDEX 0xE +#define HV_STATUS_NOT_FOUND 0x10 +#define HV_STATUS_INVALID_PORT_ID 0x11 +#define HV_STATUS_INVALID_CONNECTION_ID 0x12 +#define HV_STATUS_INSUFFICIENT_BUFFERS 0x13 +#define HV_STATUS_NOT_ACKNOWLEDGED 0x14 +#define HV_STATUS_INVALID_VP_STATE 0x15 +#define HV_STATUS_NO_RESOURCES 0x1D +#define HV_STATUS_PROCESSOR_FEATURE_NOT_SUPPORTED 0x20 +#define HV_STATUS_INVALID_LP_INDEX 0x41 +#define HV_STATUS_INVALID_REGISTER_VALUE 0x50 +#define HV_STATUS_OPERATION_FAILED 0x71 +#define HV_STATUS_INSUFFICIENT_ROOT_MEMORY 0x73 +#define HV_STATUS_INSUFFICIENT_CONTIGUOUS_MEMORY 0x75 +#define HV_STATUS_TIME_OUT 0x78 +#define HV_STATUS_CALL_PENDING 0x79 +#define HV_STATUS_INSUFFICIENT_CONTIGUOUS_ROOT_MEMORY 0x83 +#define HV_STATUS_VTL_ALREADY_ENABLED 0x86 /* * The Hyper-V TimeRefCount register and the TSC
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Mon, 02 Feb 2026 17:59:14 +0000", "thread_id": "177005513775.120041.4894134857240187839.stgit@skinsburskii-cloud-desktop.internal.cloudapp.net.mbox.gz" }
lkml
[PATCH 0/3] Axiado AX3000 USB Device Controller
Dear maintainers, This patch series introduces new USB Device Controller driver for Axiado AX3000 SoC and its evaluation board. The driver integrates with the Linux USB subsystem and follows kernel coding standards. This initial submission includes: - Driver implementation under drivers/usb/gadget/udc - Device tree bindings for supported boards - Kconfig and Makefile integration Signed-off-by: Vladimir Moravcevic <vmoravcevic@axiado.com> --- Vladimir Moravcevic (3): dt-bindings: usb: axiado,ax3000-udc: Add Axiado UDC usb: gadget: udc: Add UDC driver for Axiado Device controller IP Corigine MAINTAINERS: Add entries for the Axiado USB UDC .../devicetree/bindings/usb/axiado,ax3000-udc.yaml | 59 + MAINTAINERS | 10 + drivers/usb/gadget/udc/Kconfig | 15 + drivers/usb/gadget/udc/Makefile | 1 + drivers/usb/gadget/udc/crg_udc.c | 4522 ++++++++++++++++++++ drivers/usb/gadget/udc/crg_udc.h | 364 ++ 6 files changed, 4971 insertions(+) --- base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377 change-id: 20260128-axiado-ax3000-usb-device-controller-156d3f1840c9 Best regards, -- Vladimir Moravcevic <vmoravcevic@axiado.com>
Add Axiado ax3000-udc (for USB v2.0 ports) and ax3000-udc-gen3 (for USB v3.0 ports) compatible string for AX3000 SoC. Co-developed-by: Krutik Shah <krutikshah@axiado.com> Signed-off-by: Krutik Shah <krutikshah@axiado.com> Co-developed-by: Prasad Bolisetty <pbolisetty@axiado.com> Signed-off-by: Prasad Bolisetty <pbolisetty@axiado.com> Signed-off-by: Vladimir Moravcevic <vmoravcevic@axiado.com> --- .../devicetree/bindings/usb/axiado,ax3000-udc.yaml | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/Documentation/devicetree/bindings/usb/axiado,ax3000-udc.yaml b/Documentation/devicetree/bindings/usb/axiado,ax3000-udc.yaml new file mode 100644 index 000000000000..15658b5c924f --- /dev/null +++ b/Documentation/devicetree/bindings/usb/axiado,ax3000-udc.yaml @@ -0,0 +1,59 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/usb/axiado,ax3000-udc.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Axiado AX3000 USB Device Controller (Corigine-based) + +maintainers: + - Krutik Shah <krutikshah@axiado.com> + - Prasad Bolisetty <pbolisetty@axiado.com> + - Vladimir Moravcevic <vmoravcevic@axiado.com> + +description: | + Axiado AX3000 USB Device Controller (UDC) is used on + AX3000 SoCs and evaluation boards. This controller is based on a + Corigine USB IP core and provides SuperSpeed (5 Gb/s), High-Speed + (480 Mb/s). It supports control, bulk, interrupt, and isochronous + transfer types across multiple configurable endpoints. The node + describes the memory-mapped register region, interrupt line, and + other required properties for the UDC hardware. + +properties: + compatible: + enum: + - axiado,ax3000-udc # AX3000 UDC (USB 2.0/High-Speed) + - axiado,ax3000-udc-gen3 # AX3000 UDC (USB 3.0/SuperSpeed) + + reg: + maxItems: 1 + description: Base address and size of the UDC register space. + + interrupts: + maxItems: 1 + description: Interrupt line for the UDC. + +required: + - compatible + - reg + - interrupts + +additionalProperties: false + +examples: + - | + #include <dt-bindings/interrupt-controller/arm-gic.h> + #include <dt-bindings/interrupt-controller/irq.h> + + soc { + #address-cells = <2>; + #size-cells = <2>; + + usb@81200000 { + compatible = "axiado,ax3000-udc"; + reg = <0x0 0x81200000 0x0 0x00100000>; + interrupt-parent = <&gic500>; + interrupts = <GIC_SPI 21 IRQ_TYPE_LEVEL_HIGH>; + }; + }; -- 2.34.1
{ "author": "Vladimir Moravcevic <vmoravcevic@axiado.com>", "date": "Mon, 02 Feb 2026 05:16:28 -0800", "thread_id": "202602030223.QlbiPC8d-lkp@intel.com.mbox.gz" }
lkml
[PATCH 0/3] Axiado AX3000 USB Device Controller
Dear maintainers, This patch series introduces new USB Device Controller driver for Axiado AX3000 SoC and its evaluation board. The driver integrates with the Linux USB subsystem and follows kernel coding standards. This initial submission includes: - Driver implementation under drivers/usb/gadget/udc - Device tree bindings for supported boards - Kconfig and Makefile integration Signed-off-by: Vladimir Moravcevic <vmoravcevic@axiado.com> --- Vladimir Moravcevic (3): dt-bindings: usb: axiado,ax3000-udc: Add Axiado UDC usb: gadget: udc: Add UDC driver for Axiado Device controller IP Corigine MAINTAINERS: Add entries for the Axiado USB UDC .../devicetree/bindings/usb/axiado,ax3000-udc.yaml | 59 + MAINTAINERS | 10 + drivers/usb/gadget/udc/Kconfig | 15 + drivers/usb/gadget/udc/Makefile | 1 + drivers/usb/gadget/udc/crg_udc.c | 4522 ++++++++++++++++++++ drivers/usb/gadget/udc/crg_udc.h | 364 ++ 6 files changed, 4971 insertions(+) --- base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377 change-id: 20260128-axiado-ax3000-usb-device-controller-156d3f1840c9 Best regards, -- Vladimir Moravcevic <vmoravcevic@axiado.com>
Add the MAINTAINERS entries for the Axiado USB Device Controller. Co-developed-by: Krutik Shah <krutikshah@axiado.com> Signed-off-by: Krutik Shah <krutikshah@axiado.com> Co-developed-by: Prasad Bolisetty <pbolisetty@axiado.com> Signed-off-by: Prasad Bolisetty <pbolisetty@axiado.com> Signed-off-by: Vladimir Moravcevic <vmoravcevic@axiado.com> --- MAINTAINERS | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 67db88b04537..e63b6b308a3f 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4234,6 +4234,16 @@ S: Maintained F: Documentation/devicetree/bindings/sound/axentia,* F: sound/soc/atmel/tse850-pcm5142.c +AXIADO USB UDC DRIVER +M: Krutik Shah <krutikshah@axiado.com> +M: Prasad Bolisetty <pbolisetty@axiado.com> +M: Vladimir Moravcevic <vmoravcevic@axiado.com> +L: linux-usb@vger.kernel.org +S: Maintained +F: Documentation/devicetree/bindings/usb/axiado,ax3000-udc.yaml +F: drivers/usb/gadget/udc/crg_udc.c +F: drivers/usb/gadget/udc/crg_udc.h + AXIS ARTPEC ARM64 SoC SUPPORT M: Jesper Nilsson <jesper.nilsson@axis.com> M: Lars Persson <lars.persson@axis.com> -- 2.34.1
{ "author": "Vladimir Moravcevic <vmoravcevic@axiado.com>", "date": "Mon, 02 Feb 2026 05:16:30 -0800", "thread_id": "202602030223.QlbiPC8d-lkp@intel.com.mbox.gz" }
lkml
[PATCH 0/3] Axiado AX3000 USB Device Controller
Dear maintainers, This patch series introduces new USB Device Controller driver for Axiado AX3000 SoC and its evaluation board. The driver integrates with the Linux USB subsystem and follows kernel coding standards. This initial submission includes: - Driver implementation under drivers/usb/gadget/udc - Device tree bindings for supported boards - Kconfig and Makefile integration Signed-off-by: Vladimir Moravcevic <vmoravcevic@axiado.com> --- Vladimir Moravcevic (3): dt-bindings: usb: axiado,ax3000-udc: Add Axiado UDC usb: gadget: udc: Add UDC driver for Axiado Device controller IP Corigine MAINTAINERS: Add entries for the Axiado USB UDC .../devicetree/bindings/usb/axiado,ax3000-udc.yaml | 59 + MAINTAINERS | 10 + drivers/usb/gadget/udc/Kconfig | 15 + drivers/usb/gadget/udc/Makefile | 1 + drivers/usb/gadget/udc/crg_udc.c | 4522 ++++++++++++++++++++ drivers/usb/gadget/udc/crg_udc.h | 364 ++ 6 files changed, 4971 insertions(+) --- base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377 change-id: 20260128-axiado-ax3000-usb-device-controller-156d3f1840c9 Best regards, -- Vladimir Moravcevic <vmoravcevic@axiado.com>
Add Corigine USB IP Driver for Axiado AX3000 SoC's USB peripheral (USB 2.0/3.0). The driver is based on the Corigine USB IP core with Axiado-specific enhancements including VBUS detection and USB link stability fixes. The driver supports both USB 2.0 High-Speed and USB 3.0 SuperSpeed modes with control, bulk, interrupt, and isochronous transfer types. Co-developed-by: Krutik Shah <krutikshah@axiado.com> Signed-off-by: Krutik Shah <krutikshah@axiado.com> Co-developed-by: Prasad Bolisetty <pbolisetty@axiado.com> Signed-off-by: Prasad Bolisetty <pbolisetty@axiado.com> Signed-off-by: Vladimir Moravcevic <vmoravcevic@axiado.com> --- drivers/usb/gadget/udc/Kconfig | 15 + drivers/usb/gadget/udc/Makefile | 1 + drivers/usb/gadget/udc/crg_udc.c | 4522 ++++++++++++++++++++++++++++++++++++++ drivers/usb/gadget/udc/crg_udc.h | 364 +++ 4 files changed, 4902 insertions(+) diff --git a/drivers/usb/gadget/udc/Kconfig b/drivers/usb/gadget/udc/Kconfig index 26460340fbc9..b94d113aad99 100644 --- a/drivers/usb/gadget/udc/Kconfig +++ b/drivers/usb/gadget/udc/Kconfig @@ -417,6 +417,21 @@ config USB_ASPEED_UDC dynamically linked module called "aspeed_udc" and force all gadget drivers to also be dynamically linked. +config USB_CRG_UDC + tristate "AXIADO CORIGINE-based AX3000 Device Controller" + depends on ARCH_AXIADO || COMPILE_TEST + depends on USB_GADGET + help + Enables AX3000 USB device controller driver for Axiado + SoCs and evaluation boards. + + Based on the Corigine USB IP core driver with Axiado specific + enhancements. Supports USB 2.0 (High-Speed) and USB 3.0 + (SuperSpeed), including control, bulk, interrupt, and + isochronous transfers. + + Say "y" to build statically, or "m" to build as a module. + source "drivers/usb/gadget/udc/aspeed-vhub/Kconfig" source "drivers/usb/gadget/udc/cdns2/Kconfig" diff --git a/drivers/usb/gadget/udc/Makefile b/drivers/usb/gadget/udc/Makefile index 1b9b1a4f9c57..b17b9c4665a1 100644 --- a/drivers/usb/gadget/udc/Makefile +++ b/drivers/usb/gadget/udc/Makefile @@ -38,3 +38,4 @@ obj-$(CONFIG_USB_ASPEED_UDC) += aspeed_udc.o obj-$(CONFIG_USB_BDC_UDC) += bdc/ obj-$(CONFIG_USB_MAX3420_UDC) += max3420_udc.o obj-$(CONFIG_USB_CDNS2_UDC) += cdns2/ +obj-$(CONFIG_USB_CRG_UDC) += crg_udc.o diff --git a/drivers/usb/gadget/udc/crg_udc.c b/drivers/usb/gadget/udc/crg_udc.c new file mode 100644 index 000000000000..701123dc35bc --- /dev/null +++ b/drivers/usb/gadget/udc/crg_udc.c @@ -0,0 +1,4522 @@ +// SPDX-License-Identifier: (GPL-2.0+ OR MIT) +// +// Copyright (c) 2019 Corigine Inc. +// Copyright (c) 2022-2026 Axiado Corporation. +// + +#include <linux/net.h> +#include <asm/byteorder.h> +#include <linux/errno.h> +#include <linux/io.h> +#include <linux/unaligned.h> +#include <linux/types.h> +#include <linux/bitops.h> +#include <linux/dma-mapping.h> +#include <linux/usb/ch9.h> +#include <linux/usb/gadget.h> +#include <linux/delay.h> +#include <linux/irq.h> +#include <linux/irqreturn.h> +#include <linux/interrupt.h> +#include <linux/ctype.h> +#include <linux/module.h> +#include <linux/sched.h> +#include <linux/kthread.h> +#include <linux/err.h> +#include <linux/wait.h> +#include <linux/kernel.h> +#include <linux/platform_device.h> +#include <linux/of_address.h> +#include <linux/of_gpio.h> +#include <linux/scatterlist.h> +#include "crg_udc.h" + +#define INIT_ZERO -1 +#define UDC_FALSE false + +#define MAX_PACKET_SIZE 1024 + +#define DMA_ADDR_INVALID (~(dma_addr_t)0) + +#define CRG_ERST_SIZE 1 +#define CRG_EVENT_RING_SIZE 256 +#define CRG_NUM_EP_CX 32 + +#define TRB_MAX_BUFFER_SIZE 65536 +#define CRGUDC_CONTROL_EP_TD_RING_SIZE 16 +#define CRGUDC_BULK_EP_TD_RING_SIZE 1024 +#define CRGUDC_ISOC_EP_TD_RING_SIZE 32 +#define CRGUDC_INT_EP_TD_RING_SIZE 8 +#define CRGUDC_ROLE_DEVICE 0x1 + +#define U1_TIMEOUT_VAL 0x70 +#define U2_TIMEOUT_VAL 0x70 + +#define STATE_USB_LINK_STABLE 4 + +/*********Feature switches********************/ +#define U12_FORBIDDEN 1 +#define U12_INITIATE_FORBIDDEN 1 +#define CRG_UDC_INT_EN +#define REINIT_EP0_ON_BUS_RESET +/*********************************************/ + +enum EP_STATE_E { + EP_STATE_DISABLED = 0, + EP_STATE_RUNNING = 1, + EP_STATE_HALTED = 2, + EP_STATE_STOPPED = 3 +}; + +enum EP_TYPE_E { + EP_TYPE_INVALID = 0, + EP_TYPE_ISOCH_OUTBOUND, + EP_TYPE_BULK_OUTBOUND, + EP_TYPE_INTR_OUTBOUND, + EP_TYPE_INVALID2, + EP_TYPE_ISOCH_INBOUND, + EP_TYPE_BULK_INBOUND, + EP_TYPE_INTR_INBOUND +}; + +enum TRB_TYPE_E { + TRB_TYPE_RSVD = 0, + TRB_TYPE_XFER_NORMAL, + TRB_TYPE_RSVD2, + TRB_TYPE_XFER_DATA_STAGE, + TRB_TYPE_XFER_STATUS_STAGE, + TRB_TYPE_XFER_DATA_ISOCH, /* 5*/ + TRB_TYPE_LINK, + TRB_TYPE_RSVD7, + TRB_TYPE_NO_OP, + + TRB_TYPE_EVT_TRANSFER = 32, + TRB_TYPE_EVT_CMD_COMPLETION = 33, + TRB_TYPE_EVT_PORT_STATUS_CHANGE = 34, + TRB_TYPE_EVT_MFINDEX_WRAP = 39, + TRB_TYPE_EVT_SETUP_PKT = 40, +}; + +/*Table 127*/ +enum TRB_CMPL_CODES_E { + CMPL_CODE_INVALID = 0, + CMPL_CODE_SUCCESS, + CMPL_CODE_DATA_BUFFER_ERR, + CMPL_CODE_BABBLE_DETECTED_ERR, + CMPL_CODE_USB_TRANS_ERR, + CMPL_CODE_TRB_ERR, /*5*/ + CMPL_CODE_TRB_STALL, + CMPL_CODE_INVALID_STREAM_TYPE_ERR = 10, + CMPL_CODE_SHORT_PKT = 13, + CMPL_CODE_RING_UNDERRUN, + CMPL_CODE_RING_OVERRUN, /*15*/ + CMPL_CODE_EVENT_RING_FULL_ERR = 21, + CMPL_CODE_STOPPED = 26, + CMPL_CODE_STOPPED_LENGTH_INVALID = 27, + CMPL_CODE_ISOCH_BUFFER_OVERRUN = 31, + /*192-224 vendor defined error*/ + CMPL_CODE_PROTOCOL_STALL = 192, + CMPL_CODE_SETUP_TAG_MISMATCH = 193, + CMPL_CODE_HALTED = 194, + CMPL_CODE_HALTED_LENGTH_INVALID = 195, + CMPL_CODE_DISABLED = 196, + CMPL_CODE_DISABLED_LENGTH_INVALID = 197, +}; + +static const char driver_name[] = "crg_udc"; + +struct buffer_info { + void *vaddr; + dma_addr_t dma; + u32 len; +}; + +struct transfer_trb_s { + __le32 dw0; + __le32 dw1; + +#define TRB_TRANSFER_LEN_MASK 0x0001FFFF +#define TRB_TRANSFER_LEN_SHIFT 0 +#define TRB_TD_SIZE_MASK 0x003E0000 +#define TRB_TD_SIZE_SHIFT 17 +#define TRB_INTR_TARGET_MASK 0xFFC00000 +#define TRB_INTR_TARGET_SHIFT 22 + __le32 dw2; + +#define TRB_CYCLE_BIT_MASK 0x00000001 +#define TRB_CYCLE_BIT_SHIFT 0 +#define TRB_LINK_TOGGLE_CYCLE_MASK 0x00000002 +#define TRB_LINK_TOGGLE_CYCLE_SHIFT 1 +#define TRB_INTR_ON_SHORT_PKT_MASK 0x00000004 +#define TRB_INTR_ON_SHORT_PKT_SHIFT 2 +#define TRB_NO_SNOOP_MASK 0x00000008 +#define TRB_NO_SNOOP_SHIFT 3 +#define TRB_CHAIN_BIT_MASK 0x00000010 +#define TRB_CHAIN_BIT_SHIFT 4 +#define TRB_INTR_ON_COMPLETION_MASK 0x00000020 +#define TRB_INTR_ON_COMPLETION_SHIFT 5 + +#define TRB_APPEND_ZLP_MASK 0x00000080 +#define TRB_APPEND_ZLP_SHIFT 7 + +#define TRB_BLOCK_EVENT_INT_MASK 0x00000200 +#define TRB_BLOCK_EVENT_INT_SHIFT 9 +#define TRB_TYPE_MASK 0x0000FC00 +#define TRB_TYPE_SHIFT 10 +#define DATA_STAGE_TRB_DIR_MASK 0x00010000 +#define DATA_STAGE_TRB_DIR_SHIFT 16 +#define TRB_SETUP_TAG_MASK 0x00060000 +#define TRB_SETUP_TAG_SHIFT 17 +#define STATUS_STAGE_TRB_STALL_MASK 0x00080000 +#define STATUS_STAGE_TRB_STALL_SHIFT 19 +#define STATUS_STAGE_TRB_SET_ADDR_MASK 0x00100000 +#define STATUS_STAGE_TRB_SET_ADDR_SHIFT 20 + +#define ISOC_TRB_FRAME_ID_MASK 0x7FF00000 +#define ISOC_TRB_FRAME_ID_SHIFT 20 +#define ISOC_TRB_SIA_MASK 0x80000000 +#define ISOC_TRB_SIA_SHIFT 31 + __le32 dw3; +}; + +struct event_trb_s { + __le32 dw0; + __le32 dw1; + +#define EVE_TRB_TRAN_LEN_MASK 0x0001FFFF +#define EVE_TRB_TRAN_LEN_SHIFT 0 +#define EVE_TRB_COMPL_CODE_MASK 0xFF000000 +#define EVE_TRB_COMPL_CODE_SHIFT 24 + __le32 dw2; + +#define EVE_TRB_CYCLE_BIT_MASK 0x00000001 +#define EVE_TRB_CYCLE_BIT_SHIFT 0 +#define EVE_TRB_TYPE_MASK 0x0000FC00 +#define EVE_TRB_TYPE_SHIFT 10 +#define EVE_TRB_ENDPOINT_ID_MASK 0x001F0000 +#define EVE_TRB_ENDPOINT_ID_SHIFT 16 +#define EVE_TRB_SETUP_TAG_MASK 0x00600000 +#define EVE_TRB_SETUP_TAG_SHIFT 21 + __le32 dw3; +}; + +struct ep_cx_s { + +#define EP_CX_LOGICAL_EP_NUM_MASK 0x00000078 +#define EP_CX_LOGICAL_EP_NUM_SHIFT 3 + + +#define EP_CX_INTERVAL_MASK 0x00FF0000 +#define EP_CX_INTERVAL_SHIFT 16 + __le32 dw0; + +#define EP_CX_EP_TYPE_MASK 0x00000038 +#define EP_CX_EP_TYPE_SHIFT 3 +#define EP_CX_MAX_BURST_SIZE_MASK 0x0000FF00 +#define EP_CX_MAX_BURST_SIZE_SHIFT 8 +#define EP_CX_MAX_PACKET_SIZE_MASK 0xFFFF0000 +#define EP_CX_MAX_PACKET_SIZE_SHIFT 16 + __le32 dw1; + +#define EP_CX_DEQ_CYC_STATE_MASK 0x00000001 +#define EP_CX_DEQ_CYC_STATE_SHIFT 0 +#define EP_CX_TR_DQPT_LO_MASK 0xFFFFFFF0 +#define EP_CX_TR_DQPT_LO_SHIFT 4 + __le32 dw2; + __le32 dw3; +}; + +struct erst_s { + /* 64-bit event ring segment address */ + __le32 seg_addr_lo; + __le32 seg_addr_hi; + __le32 seg_size; + /* Set to zero */ + __le32 rsvd; +}; + +struct sel_value_s { + u16 u2_pel_value; + u16 u2_sel_value; + u8 u1_pel_value; + u8 u1_sel_value; +}; + +struct crg_udc_request { + struct usb_request usb_req; + struct list_head queue; + bool mapped; + u64 buff_len_left; + u32 trbs_needed; + struct transfer_trb_s *first_trb; + struct transfer_trb_s *last_trb; + bool all_trbs_queued; + bool short_pkt; +}; + +struct crg_udc_ep { + struct usb_ep usb_ep; + + struct buffer_info tran_ring_info; + struct transfer_trb_s *first_trb; + struct transfer_trb_s *last_trb; + + struct transfer_trb_s *enq_pt; + struct transfer_trb_s *deq_pt; + u8 pcs; + + char name[10]; + u8 DCI; + struct list_head queue; + const struct usb_endpoint_descriptor *desc; + const struct usb_ss_ep_comp_descriptor *comp_desc; + bool tran_ring_full; + struct crg_gadget_dev *crg_udc; + + int ep_state; + + unsigned wedge:1; +}; + +#define CRG_RING_NUM 1 + +struct crg_udc_event { + struct buffer_info erst; + struct erst_s *p_erst; + struct buffer_info event_ring; + struct event_trb_s *evt_dq_pt; + u8 CCS; + struct event_trb_s *evt_seg0_last_trb; +}; + +struct crg_setup_packet { + struct usb_ctrlrequest usbctrlreq; + u16 setup_tag; +}; + +struct crg_udc_priv { + bool plat_setup_gen3; +}; + +struct crg_gadget_dev { + void __iomem *mmio_virt_base; + struct resource *udc_res; + resource_size_t udc_res_len; + struct crg_uccr *uccr; + struct crg_uicr *uicr[CRG_RING_NUM]; + + const struct crg_udc_priv *priv; + + /* udc_lock device lock */ + spinlock_t udc_lock; + + struct device *dev; + struct usb_gadget gadget; + struct usb_gadget_driver *gadget_driver; + + int irq; + struct task_struct *vbus_task; + + struct crg_udc_ep udc_ep[32]; + struct buffer_info ep_cx; + struct ep_cx_s *p_epcx; + + struct crg_udc_event udc_event[CRG_RING_NUM]; + + struct crg_udc_request *status_req; + u16 *statusbuf; + struct sel_value_s sel_value; + void (*setup_fn_call_back)(struct crg_gadget_dev *a); + +#define WAIT_FOR_SETUP 0 +#define SETUP_PKT_PROCESS_IN_PROGRESS 1 +#define DATA_STAGE_XFER 2 +#define DATA_STAGE_RECV 3 +#define STATUS_STAGE_XFER 4 +#define STATUS_STAGE_RECV 5 + u8 setup_status; +#define CTRL_REQ_QUEUE_DEPTH 5 + struct crg_setup_packet ctrl_req_queue[CTRL_REQ_QUEUE_DEPTH]; + u8 ctrl_req_enq_idx; + + u8 device_state; + u8 resume_state; + u16 dev_addr; + u8 setup_tag; + u8 set_tm; + + u32 num_enabled_eps; + + int connected; + + unsigned u2_RWE:1; + unsigned feature_u1_enable:1; + unsigned feature_u2_enable:1; + + int setup_tag_mismatch_found; + int portsc_on_reconnecting; +}; + +/*An array should be implemented if we want to support multi + * usb device controller + */ +static DECLARE_WAIT_QUEUE_HEAD(vbus_wait); + +static struct usb_endpoint_descriptor crg_udc_ep0_desc = { + .bLength = USB_DT_ENDPOINT_SIZE, + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 0, + .bmAttributes = USB_ENDPOINT_XFER_CONTROL, + .wMaxPacketSize = cpu_to_le16(64), +}; + +static int get_ep_state(struct crg_gadget_dev *crg_udc, int DCI) +{ + struct crg_udc_ep *udc_ep_ptr; + + if (DCI < 0 || DCI == 1) + return -EINVAL; + + udc_ep_ptr = &crg_udc->udc_ep[DCI]; + + return udc_ep_ptr->ep_state; +} + +/************command related ops**************************/ +static int crg_issue_command(struct crg_gadget_dev *crg_udc, + enum crg_cmd_type type, u32 param0, u32 param1) +{ + struct crg_uccr *uccr = crg_udc->uccr; + u32 status; + bool check_complete = false; + u32 tmp; + + tmp = readl(&uccr->control); + if (tmp & CRG_U3DC_CTRL_RUN) + check_complete = true; + + if (check_complete) { + tmp = readl(&uccr->cmd_control); + if (tmp & CRG_U3DC_CMD_CTRL_ACTIVE) { + dev_err(crg_udc->dev, "%s prev command is not complete!\n", __func__); + return -1; + } + } + /* Ensure that everything is written before issuing new command */ + wmb(); + + writel(param0, &uccr->cmd_param0); + writel(param1, &uccr->cmd_param1); + + /*ignore CMD IOC, in uboot no irq is*/ + tmp = CRG_U3DC_CMD_CTRL_ACTIVE | + CRG_U3DC_CMD_CTRL_TYPE(type); + writel(tmp, &uccr->cmd_control); + + dev_dbg(crg_udc->dev, "%s start, type=%d, par0=0x%x, par1=0x%x\n", + __func__, type, param0, param1); + + if (check_complete) { + do { + tmp = readl(&uccr->cmd_control); + } while (tmp & CRG_U3DC_CMD_CTRL_ACTIVE); + + dev_dbg(crg_udc->dev, "%s successful\n", __func__); + + status = CRG_U3DC_CMD_CTRL_STATUS_GET(tmp); + if (status != 0) { + dev_dbg(crg_udc->dev, "%s fail\n", __func__); + return -EIO; + } + } + + return 0; +} + +static void setup_link_trb(struct transfer_trb_s *link_trb, + bool toggle, ulong next_trb) +{ + u32 dw = 0; + + link_trb->dw0 = cpu_to_le32(lower_32_bits(next_trb)); + link_trb->dw1 = cpu_to_le32(upper_32_bits(next_trb)); + link_trb->dw2 = 0; + + dw = SETF_VAR(TRB_TYPE, dw, TRB_TYPE_LINK); + if (toggle) + dw = SETF_VAR(TRB_LINK_TOGGLE_CYCLE, dw, 1); + else + dw = SETF_VAR(TRB_LINK_TOGGLE_CYCLE, dw, 0); + + link_trb->dw3 = cpu_to_le32(dw); + + /* Ensure that lint trb is updated */ + wmb(); +} + +static dma_addr_t tran_trb_virt_to_dma(struct crg_udc_ep *udc_ep, + struct transfer_trb_s *trb) +{ + unsigned long offset; + int trb_idx; + dma_addr_t dma_addr = 0; + + trb_idx = trb - udc_ep->first_trb; + if (unlikely(trb_idx < 0)) + return 0; + + offset = trb_idx * sizeof(*trb); + if (unlikely(offset > udc_ep->tran_ring_info.len)) + return 0; + dma_addr = udc_ep->tran_ring_info.dma + offset; + return dma_addr; +} + +static struct transfer_trb_s *tran_trb_dma_to_virt + (struct crg_udc_ep *udc_ep, dma_addr_t address) +{ + unsigned long offset; + struct transfer_trb_s *trb_virt; + + if (lower_32_bits(address) & 0xf) + return NULL; + + offset = address - udc_ep->tran_ring_info.dma; + if (unlikely(offset > udc_ep->tran_ring_info.len)) + return NULL; + offset = offset / sizeof(struct transfer_trb_s); + trb_virt = udc_ep->first_trb + offset; + return trb_virt; +} + +static dma_addr_t event_trb_virt_to_dma + (struct crg_udc_event *udc_event, struct event_trb_s *event) +{ + dma_addr_t dma_addr = 0; + unsigned long seg_offset; + + if (!udc_event || !event) + return 0; + + /* update dequeue pointer */ + seg_offset = (void *)event - udc_event->event_ring.vaddr; + dma_addr = udc_event->event_ring.dma + seg_offset; + + return dma_addr; +} + +/* Completes request. Calls gadget completion handler + * caller must have acquired spin lock. + */ +static void req_done(struct crg_udc_ep *udc_ep, + struct crg_udc_request *udc_req, int status) +{ + unsigned long flags = 0; + struct crg_gadget_dev *crg_udc = udc_ep->crg_udc; + + if (likely(udc_req->usb_req.status == -EINPROGRESS)) + udc_req->usb_req.status = status; + + list_del_init(&udc_req->queue); + + + if (udc_req->usb_req.num_mapped_sgs) { + dma_unmap_sg(crg_udc->dev, udc_req->usb_req.sg, + udc_req->usb_req.num_sgs, + (usb_endpoint_dir_in(udc_ep->desc) + ? DMA_TO_DEVICE : DMA_FROM_DEVICE)); + + udc_req->usb_req.num_mapped_sgs = 0; + dev_dbg(crg_udc->dev, "dma_unmap_sg done\n"); + } + + if (udc_req->mapped) { + if (udc_req->usb_req.length) { + dma_unmap_single(crg_udc->dev, udc_req->usb_req.dma, + udc_req->usb_req.length, usb_endpoint_dir_in(udc_ep->desc) + ? DMA_TO_DEVICE : DMA_FROM_DEVICE); + } + udc_req->usb_req.dma = DMA_ADDR_INVALID; + udc_req->mapped = 0; + } + + if (udc_req->usb_req.complete) { + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + udc_req->usb_req.complete(&udc_ep->usb_ep, &udc_req->usb_req); + spin_lock_irqsave(&crg_udc->udc_lock, flags); + } +} + +static void nuke(struct crg_udc_ep *udc_ep, int status) +{ + struct crg_udc_request *req = NULL; + + while (!list_empty(&udc_ep->queue)) { + req = list_entry(udc_ep->queue.next, + struct crg_udc_request, + queue); + + req_done(udc_ep, req, status); + } +} + +static void clear_req_container(struct crg_udc_request *udc_req_ptr) +{ + udc_req_ptr->buff_len_left = 0; + udc_req_ptr->trbs_needed = 0; + udc_req_ptr->all_trbs_queued = 0; + udc_req_ptr->first_trb = NULL; + udc_req_ptr->last_trb = NULL; + udc_req_ptr->short_pkt = 0; +} + +static bool is_pointer_less_than(struct transfer_trb_s *a, + struct transfer_trb_s *b, struct crg_udc_ep *udc_ep) +{ + if (b > a && (udc_ep->enq_pt >= b || udc_ep->enq_pt < a)) + return true; + if (b < a && (udc_ep->enq_pt >= b && udc_ep->enq_pt < a)) + return true; + return false; +} + +/* num_trbs here is the size of the ring. */ +static u32 room_on_ring(struct crg_gadget_dev *crg_udc, u32 num_trbs, + struct transfer_trb_s *p_ring, struct transfer_trb_s *enq_pt, + struct transfer_trb_s *dq_pt) +{ + u32 i = 0; + + if (enq_pt == dq_pt) { + /* ring is empty */ + return num_trbs - 1; + } + + while (enq_pt != dq_pt) { + i++; + + enq_pt++; + + if (GETF(TRB_TYPE, enq_pt->dw3) == TRB_TYPE_LINK) + enq_pt = p_ring; + + if (i > num_trbs) + break; + } + + return i - 1; +} + +static void crg_udc_epcx_setup(struct crg_udc_ep *udc_ep) +{ + struct crg_gadget_dev *crg_udc = udc_ep->crg_udc; + const struct usb_endpoint_descriptor *desc = udc_ep->desc; + const struct usb_ss_ep_comp_descriptor *comp_desc = udc_ep->comp_desc; + u8 DCI = udc_ep->DCI; + struct ep_cx_s *epcx = (struct ep_cx_s *)(crg_udc->p_epcx + DCI - 2); + enum EP_TYPE_E ep_type; + u16 maxburst = 0; + u8 maxstreams = 0; + u16 maxsize; + u32 dw; + + dev_dbg(crg_udc->dev, "crgudc->p_epcx %p, epcx %p\n", crg_udc->p_epcx, epcx); + dev_dbg(crg_udc->dev, "DCI %d, sizeof ep_cx %ld\n", DCI, sizeof(struct ep_cx_s)); + dev_dbg(crg_udc->dev, "desc epaddr = 0x%x\n", desc->bEndpointAddress); + + /*corigine gadget dir should be opposite to host dir*/ + if (usb_endpoint_dir_out(desc)) + ep_type = usb_endpoint_type(desc) + EP_TYPE_INVALID2; + else + ep_type = usb_endpoint_type(desc); + + maxsize = usb_endpoint_maxp(desc) & 0x07ff; /* D[0:10] */ + + if (crg_udc->gadget.speed >= USB_SPEED_SUPER) { + maxburst = comp_desc->bMaxBurst; + + if (usb_endpoint_xfer_bulk(udc_ep->desc)) + maxstreams = comp_desc->bmAttributes & 0x1f; + + } else if ((crg_udc->gadget.speed == USB_SPEED_HIGH || + crg_udc->gadget.speed == USB_SPEED_FULL) && + (usb_endpoint_xfer_int(udc_ep->desc) || + usb_endpoint_xfer_isoc(udc_ep->desc))) { + if (crg_udc->gadget.speed == USB_SPEED_HIGH) + maxburst = (usb_endpoint_maxp(desc) >> 11) & 0x3; + if (maxburst == 0x3) { + dev_err(crg_udc->dev, "invalid maxburst\n"); + maxburst = 0x2; + } + } + + /* fill ep_dw0 */ + dw = 0; + dw = SETF_VAR(EP_CX_LOGICAL_EP_NUM, dw, udc_ep->DCI / 2); + dw = SETF_VAR(EP_CX_INTERVAL, dw, desc->bInterval); + if (maxstreams) { + dev_err(crg_udc->dev, "%s maxstream=%d is not expected\n", + __func__, maxstreams); + } + epcx->dw0 = cpu_to_le32(dw); + + /* fill ep_dw1 */ + dw = 0; + dw = SETF_VAR(EP_CX_EP_TYPE, dw, ep_type); + dw = SETF_VAR(EP_CX_MAX_PACKET_SIZE, dw, maxsize); + dw = SETF_VAR(EP_CX_MAX_BURST_SIZE, dw, maxburst); + epcx->dw1 = cpu_to_le32(dw); + + /* fill ep_dw2 */ + dw = lower_32_bits(udc_ep->tran_ring_info.dma) & EP_CX_TR_DQPT_LO_MASK; + dw = SETF_VAR(EP_CX_DEQ_CYC_STATE, dw, udc_ep->pcs); + epcx->dw2 = cpu_to_le32(dw); + + /* fill ep_dw3 */ + dw = upper_32_bits(udc_ep->tran_ring_info.dma); + epcx->dw3 = cpu_to_le32(dw); + /* Ensure that epcx is updated */ + wmb(); +} + +static void crg_udc_epcx_update_dqptr(struct crg_udc_ep *udc_ep) +{ + struct crg_gadget_dev *crg_udc = udc_ep->crg_udc; + u8 DCI = udc_ep->DCI; + struct ep_cx_s *epcx = (struct ep_cx_s *)(crg_udc->p_epcx + DCI - 2); + u32 dw; + dma_addr_t dqptaddr; + u32 cmd_param0; + + if (DCI == 0) { + dev_err(crg_udc->dev, "%s Cannot update dqptr for ep0\n", __func__); + return; + } + + dqptaddr = tran_trb_virt_to_dma(udc_ep, udc_ep->deq_pt); + + /* fill ep_dw2 */ + dw = lower_32_bits(dqptaddr) & EP_CX_TR_DQPT_LO_MASK; + dw = SETF_VAR(EP_CX_DEQ_CYC_STATE, dw, udc_ep->pcs); + epcx->dw2 = cpu_to_le32(dw); + + /* fill ep_dw3 */ + dw = upper_32_bits(dqptaddr); + epcx->dw3 = cpu_to_le32(dw); + + cmd_param0 = (0x1 << udc_ep->DCI); + /* Ensure that dqptr is updated */ + wmb(); + + crg_issue_command(crg_udc, CRG_CMD_SET_TR_DQPTR, cmd_param0, 0); +} + +static void setup_status_trb(struct crg_gadget_dev *crg_udc, + struct transfer_trb_s *p_trb, + struct usb_request *usb_req, u8 pcs, u8 set_addr, u8 stall) +{ + u32 tmp, dir = 0; + + /* There are some cases where seutp_status_trb() is called with + * usb_req set to NULL. + */ + + p_trb->dw0 = 0; + p_trb->dw1 = 0; + + dev_dbg(crg_udc->dev, "data_buf_ptr_lo = 0x%x, data_buf_ptr_hi = 0x%x\n", + p_trb->dw0, p_trb->dw1); + + tmp = 0; + tmp = SETF_VAR(TRB_INTR_TARGET, tmp, 0); + p_trb->dw2 = tmp; + + tmp = 0; + tmp = SETF_VAR(TRB_CYCLE_BIT, tmp, pcs); + tmp = SETF_VAR(TRB_INTR_ON_COMPLETION, tmp, 1);/*IOC:1*/ + tmp = SETF_VAR(TRB_TYPE, tmp, TRB_TYPE_XFER_STATUS_STAGE); + + dir = (crg_udc->setup_status == STATUS_STAGE_XFER) ? 0 : 1; + tmp = SETF_VAR(DATA_STAGE_TRB_DIR, tmp, dir); + + tmp = SETF_VAR(TRB_SETUP_TAG, tmp, crg_udc->setup_tag); + tmp = SETF_VAR(STATUS_STAGE_TRB_STALL, tmp, stall); + tmp = SETF_VAR(STATUS_STAGE_TRB_SET_ADDR, tmp, set_addr); + + p_trb->dw3 = tmp; + dev_dbg(crg_udc->dev, "trb_dword2 = 0x%x, trb_dword3 = 0x%x\n", + p_trb->dw2, p_trb->dw3); + /* Ensure that status trb is updated */ + wmb(); +} + +static void knock_doorbell(struct crg_gadget_dev *crg_udc, int DCI) +{ + u32 tmp; + struct crg_uccr *uccr; + + uccr = crg_udc->uccr; + /* Ensure evreything is written before notifying the HW */ + wmb(); + + tmp = CRG_U3DC_DB_TARGET(DCI); + dev_dbg(crg_udc->dev, "DOORBELL = 0x%x\n", tmp); + writel(tmp, &uccr->doorbell); +} + +static void setup_datastage_trb(struct crg_gadget_dev *crg_udc, + struct transfer_trb_s *p_trb, struct usb_request *usb_req, + u8 pcs, u32 num_trb, u32 transfer_length, u32 td_size, + u8 IOC, u8 AZP, u8 dir, u8 setup_tag) +{ + u32 tmp; + + dev_dbg(crg_udc->dev, "dma = 0x%llx, ", usb_req->dma); + dev_dbg(crg_udc->dev, "buf = 0x%lx, ", (unsigned long)usb_req->buf); + + p_trb->dw0 = lower_32_bits(usb_req->dma); + p_trb->dw1 = upper_32_bits(usb_req->dma); + + dev_dbg(crg_udc->dev, "data_buf_ptr_lo = 0x%x, data_buf_ptr_hi = 0x%x\n", + p_trb->dw0, p_trb->dw1); + + + /* TRB_Transfer_Length + *For USB_DIR_OUT, this field is the number of data bytes expected from + *xhc. For USB_DIR_IN, this field is the number of data bytes the device + *will send. + */ + tmp = 0; + tmp = SETF_VAR(TRB_TRANSFER_LEN, tmp, transfer_length); + tmp = SETF_VAR(TRB_TD_SIZE, tmp, td_size); + tmp = SETF_VAR(TRB_INTR_TARGET, tmp, 0); + p_trb->dw2 = tmp; + + tmp = 0; + tmp = SETF_VAR(TRB_CYCLE_BIT, tmp, pcs); + tmp = SETF_VAR(TRB_INTR_ON_SHORT_PKT, tmp, 1); + tmp = SETF_VAR(TRB_INTR_ON_COMPLETION, tmp, IOC); + tmp = SETF_VAR(TRB_TYPE, tmp, TRB_TYPE_XFER_DATA_STAGE); + tmp = SETF_VAR(TRB_APPEND_ZLP, tmp, AZP); + tmp = SETF_VAR(DATA_STAGE_TRB_DIR, tmp, dir); + tmp = SETF_VAR(TRB_SETUP_TAG, tmp, setup_tag); + + p_trb->dw3 = tmp; + /* Ensure that datastage trb is updated */ + wmb(); + + dev_dbg(crg_udc->dev, "trb_dword0 = 0x%x, trb_dword1 = 0x%x trb_dword2 = 0x%x, trb_dword3 = 0x%x\n", + p_trb->dw0, p_trb->dw1, p_trb->dw2, p_trb->dw3); +} + +static void setup_trb(struct crg_gadget_dev *crg_udc, + struct transfer_trb_s *p_trb, + struct usb_request *usb_req, u32 xfer_len, + dma_addr_t xfer_buf_addr, u8 td_size, u8 pcs, + u8 trb_type, u8 short_pkt, u8 chain_bit, + u8 intr_on_compl, bool b_setup_stage, u8 usb_dir, + bool b_isoc, u8 tlb_pc, u16 frame_i_d, u8 SIA, u8 AZP) +{ + u32 tmp; + + p_trb->dw0 = lower_32_bits(xfer_buf_addr); + p_trb->dw1 = upper_32_bits(xfer_buf_addr); + + dev_dbg(crg_udc->dev, "data_buf_ptr_lo = 0x%x, data_buf_ptr_hi = 0x%x\n", + p_trb->dw0, p_trb->dw1); + + tmp = 0; + tmp = SETF_VAR(TRB_TRANSFER_LEN, tmp, xfer_len); + tmp = SETF_VAR(TRB_TD_SIZE, tmp, td_size); + tmp = SETF_VAR(TRB_INTR_TARGET, tmp, 0); + + p_trb->dw2 = tmp; + + tmp = 0; + tmp = SETF_VAR(TRB_CYCLE_BIT, tmp, pcs); + tmp = SETF_VAR(TRB_INTR_ON_SHORT_PKT, tmp, short_pkt); + tmp = SETF_VAR(TRB_CHAIN_BIT, tmp, chain_bit); + tmp = SETF_VAR(TRB_INTR_ON_COMPLETION, tmp, intr_on_compl); + tmp = SETF_VAR(TRB_APPEND_ZLP, tmp, AZP); + tmp = SETF_VAR(TRB_TYPE, tmp, trb_type); + + if (b_setup_stage) + tmp = SETF_VAR(DATA_STAGE_TRB_DIR, tmp, usb_dir); + + if (b_isoc) { + tmp = SETF_VAR(ISOC_TRB_FRAME_ID, tmp, frame_i_d); + tmp = SETF_VAR(ISOC_TRB_SIA, tmp, SIA); + } + + p_trb->dw3 = tmp; + /* Ensure that trb is updated */ + wmb(); + dev_dbg(crg_udc->dev, "trb_dword2 = 0x%.8x, trb_dword3 = 0x%.8x\n", + p_trb->dw2, p_trb->dw3); + +} + +static int crg_udc_queue_trbs(struct crg_udc_ep *udc_ep_ptr, + struct crg_udc_request *udc_req_ptr, bool b_isoc, + u32 xfer_ring_size, + u32 num_trbs_needed, u64 buffer_length) +{ + struct crg_gadget_dev *crg_udc = udc_ep_ptr->crg_udc; + struct transfer_trb_s *p_xfer_ring = udc_ep_ptr->first_trb; + u32 num_trbs_ava = 0; + struct usb_request *usb_req = &udc_req_ptr->usb_req; + u64 buff_len_temp = 0; + u32 i, j = 1; + struct transfer_trb_s *enq_pt = udc_ep_ptr->enq_pt; + u8 td_size; + u8 chain_bit = 1; + u8 short_pkt = 0; + u8 intr_on_compl = 0; + u32 count; + bool full_td = true; + u32 intr_rate; + dma_addr_t trb_buf_addr; + bool need_zlp = false; + struct scatterlist *sg = NULL; + u32 num_sgs = 0; + u64 sg_addr = 0; + + dev_dbg(crg_udc->dev, "%s %s\n", __func__, udc_ep_ptr->usb_ep.name); + if (udc_req_ptr->usb_req.num_sgs) { + num_sgs = udc_req_ptr->usb_req.num_sgs; + sg = udc_req_ptr->usb_req.sg; + sg_addr = (u64) sg_dma_address(sg); + buffer_length = sg_dma_len(sg); + + dev_dbg(crg_udc->dev, "num_sgs = %d, num_mapped_sgs = %d\n", + udc_req_ptr->usb_req.num_sgs, + udc_req_ptr->usb_req.num_mapped_sgs); + dev_dbg(crg_udc->dev, + "sg_addr = %p, buffer_length = %llu, num_trbs = %d\n", + (void *)sg_addr, buffer_length, num_trbs_needed); + } + + if (!b_isoc) { + if (udc_req_ptr->usb_req.zero == 1 && + udc_req_ptr->usb_req.length != 0 && + ((udc_req_ptr->usb_req.length % + udc_ep_ptr->usb_ep.maxpacket) == 0)) { + need_zlp = true; + } + } + + td_size = num_trbs_needed; + + num_trbs_ava = room_on_ring(crg_udc, xfer_ring_size, + p_xfer_ring, udc_ep_ptr->enq_pt, udc_ep_ptr->deq_pt); + + /* trb_buf_addr points to the addr of the buffer that we write in + * each TRB. If this function is called to complete the pending TRB + * transfers of a previous request, point it to the buffer that is + * not transferred, or else point it to the starting address of the + * buffer received in usb_request + */ + if (udc_req_ptr->trbs_needed) { + /* Here udc_req_ptr->trbs_needed is used to indicate if we + * are completing a previous req + */ + trb_buf_addr = usb_req->dma + + (usb_req->length - udc_req_ptr->buff_len_left); + } else { + if (sg_addr) + trb_buf_addr = sg_addr; + else + trb_buf_addr = usb_req->dma; + } + + if (num_trbs_ava >= num_trbs_needed) { + count = num_trbs_needed; + } else { + if (b_isoc) { + struct crg_udc_request *udc_req_ptr_temp; + u8 temp = 0; + + list_for_each_entry(udc_req_ptr_temp, + &udc_ep_ptr->queue, queue) { + temp++; + } + + if (temp >= 2) { + dev_err(crg_udc->dev, "%s don't do isoc discard\n", __func__); + /* we already scheduled two mfi in advance. */ + return 0; + } + } + + /* always keep one trb for zlp. */ + count = num_trbs_ava; + full_td = false; + dev_dbg(crg_udc->dev, "TRB Ring Full. Avail: 0x%x Req: 0x%x\n", + num_trbs_ava, num_trbs_needed); + udc_ep_ptr->tran_ring_full = true; + + /*if there is still some trb not queued, + *it means last queued + *trb is not the last trb of TD, so no need zlp + */ + need_zlp = false; + } + + for (i = 0; i < count; i++) { + if ((udc_req_ptr->usb_req.num_sgs) && (buffer_length == 0)) { + sg = sg_next(sg); + if (sg) { + trb_buf_addr = (u64) sg_dma_address(sg); + buffer_length = sg_dma_len(sg); + dev_dbg(crg_udc->dev, + "trb_buf_addr = %p, num_trbs = %d\n", + (void *)trb_buf_addr, num_trbs_needed); + dev_dbg(crg_udc->dev, "buffer_length = %llu\n", + buffer_length); + } else { + dev_err(crg_udc->dev, + "scatterlist ended unexpectedly (i=%d, count=%d)\n", + i, count); + return -EINVAL; + } + } + + if (buffer_length > TRB_MAX_BUFFER_SIZE) + buff_len_temp = TRB_MAX_BUFFER_SIZE; + else + buff_len_temp = buffer_length; + + buffer_length -= buff_len_temp; + + if (usb_endpoint_dir_out(udc_ep_ptr->desc)) + short_pkt = 1; + + if ((buffer_length == 0) && (i == (count - 1))) { + chain_bit = 0; + intr_on_compl = 1; + udc_req_ptr->all_trbs_queued = 1; + } + + +#define BULK_EP_INTERRUPT_RATE 5 +#define ISOC_EP_INTERRUPT_RATE 1 + if (b_isoc) + intr_rate = ISOC_EP_INTERRUPT_RATE; + else + intr_rate = BULK_EP_INTERRUPT_RATE; + + if (!full_td && j == intr_rate) { + intr_on_compl = 1; + j = 0; + } + + if (b_isoc) { + setup_trb(crg_udc, enq_pt, usb_req, buff_len_temp, + trb_buf_addr, td_size - 1, udc_ep_ptr->pcs, + TRB_TYPE_XFER_DATA_ISOCH, short_pkt, chain_bit, + intr_on_compl, 0, 0, 1, 0, 0, 1, 0); + } else { + u8 pcs = udc_ep_ptr->pcs; + + if (udc_ep_ptr->comp_desc && + (usb_ss_max_streams(udc_ep_ptr->comp_desc))) { + dev_err(crg_udc->dev, "%s don't do bulk stream\n", __func__); + } else { + if (udc_req_ptr->all_trbs_queued) { + /*it is the last trb of TD, + * so consider zlp + */ + u8 AZP = 0; + + AZP = (need_zlp ? 1 : 0); + + setup_trb(crg_udc, enq_pt, usb_req, + buff_len_temp, trb_buf_addr, + td_size - 1, pcs, + TRB_TYPE_XFER_NORMAL, short_pkt, + chain_bit, intr_on_compl, + 0, 0, 0, 0, 0, 0, AZP); + + } else { + setup_trb(crg_udc, enq_pt, usb_req, + buff_len_temp, trb_buf_addr, + td_size - 1, pcs, + TRB_TYPE_XFER_NORMAL, short_pkt, + chain_bit, intr_on_compl, + 0, 0, 0, 0, 0, 0, 0); + } + } + } + trb_buf_addr += buff_len_temp; + td_size--; + enq_pt++; + j++; + if (GETF(TRB_TYPE, enq_pt->dw3) == TRB_TYPE_LINK) { + if (GETF(TRB_LINK_TOGGLE_CYCLE, + enq_pt->dw3)) { + enq_pt->dw3 = SETF_VAR(TRB_CYCLE_BIT, + enq_pt->dw3, udc_ep_ptr->pcs); + udc_ep_ptr->pcs ^= 0x1; + /* Ensure that trb cycle bit is updated */ + wmb(); + enq_pt = udc_ep_ptr->first_trb; + } + } + } + + if (!udc_req_ptr->trbs_needed) + udc_req_ptr->first_trb = udc_ep_ptr->enq_pt; + udc_ep_ptr->enq_pt = enq_pt; + udc_req_ptr->buff_len_left = buffer_length; + udc_req_ptr->trbs_needed = td_size; + + if (udc_req_ptr->buff_len_left == 0) { + /* It is actually last trb of a request plus 1 */ + if (udc_ep_ptr->enq_pt == udc_ep_ptr->first_trb) + udc_req_ptr->last_trb = udc_ep_ptr->last_trb - 1; + else + udc_req_ptr->last_trb = udc_ep_ptr->enq_pt - 1; + } + + return 0; +} + +static int crg_udc_queue_ctrl(struct crg_udc_ep *udc_ep_ptr, + struct crg_udc_request *udc_req_ptr, u32 num_of_trbs_needed) +{ + struct crg_gadget_dev *crg_udc = udc_ep_ptr->crg_udc; + u8 ep_state; + struct transfer_trb_s *enq_pt = udc_ep_ptr->enq_pt; + struct transfer_trb_s *dq_pt = udc_ep_ptr->deq_pt; + struct usb_request *usb_req = &udc_req_ptr->usb_req; + struct transfer_trb_s *p_trb; + u32 transfer_length; + u32 td_size = 0; + u8 IOC; + u8 AZP; + u8 dir = 0; + u8 setup_tag = crg_udc->setup_tag; + + ep_state = get_ep_state(crg_udc, 0); + + + /* Need to queue the request even ep is paused or halted */ + if (ep_state != EP_STATE_RUNNING) { + dev_dbg(crg_udc->dev, "EP State = 0x%x\n", ep_state); + return -EINVAL; + } + + if (list_empty(&udc_ep_ptr->queue)) { + /* For control endpoint, we can handle one setup request at a + * time. so if there are TD pending in the transfer ring. + * wait for the sequence number error event. Then put the new + * request to transfer ring + */ + if (enq_pt == dq_pt) { + u32 tmp = 0, i; + bool need_zlp = false; + + dev_dbg(crg_udc->dev, "Setup Data Stage TRBs\n"); + /* Transfer ring is empty + * setup data stage TRBs + */ + udc_req_ptr->first_trb = udc_ep_ptr->enq_pt; + + if (crg_udc->setup_status == DATA_STAGE_XFER) + dir = 0; + else if (crg_udc->setup_status == DATA_STAGE_RECV) + dir = 1; + else + dev_dbg(crg_udc->dev, "unexpected setup_status!%d\n", + crg_udc->setup_status); + + if (udc_req_ptr->usb_req.zero == 1 && + udc_req_ptr->usb_req.length != 0 && + ((udc_req_ptr->usb_req.length % + udc_ep_ptr->usb_ep.maxpacket) == 0)) + need_zlp = true;/*zlp = zero length packet*/ + + + for (i = 0; i < num_of_trbs_needed; i++) { + p_trb = enq_pt; + if (i < (num_of_trbs_needed - 1)) { + transfer_length = TRB_MAX_BUFFER_SIZE; + IOC = 0; + AZP = 0; + } else { + tmp = TRB_MAX_BUFFER_SIZE * i; + transfer_length = (u32)usb_req->length + - tmp; + + IOC = 1; + AZP = (need_zlp ? 1 : 0); + } + + dev_dbg(crg_udc->dev, + "tx_len = 0x%x, tmp = 0x%x\n", + transfer_length, tmp); + + setup_datastage_trb(crg_udc, p_trb, usb_req, + udc_ep_ptr->pcs, i, transfer_length, + td_size, IOC, AZP, dir, setup_tag); + udc_req_ptr->all_trbs_queued = 1; + enq_pt++; + + if (GETF(TRB_TYPE, enq_pt->dw3) == + TRB_TYPE_LINK) { + if (GETF(TRB_LINK_TOGGLE_CYCLE, + enq_pt->dw3)) { + enq_pt->dw3 = SETF_VAR(TRB_CYCLE_BIT, + enq_pt->dw3, + udc_ep_ptr->pcs); + udc_ep_ptr->pcs ^= 0x1; + } + /* Ensure that trb cycle bit is updated */ + wmb(); + enq_pt = udc_ep_ptr->first_trb; + } + } + + udc_ep_ptr->enq_pt = enq_pt; + + tmp = 0; + + knock_doorbell(crg_udc, 0); + + if (udc_ep_ptr->enq_pt == udc_ep_ptr->first_trb) + udc_req_ptr->last_trb = + udc_ep_ptr->last_trb - 1; + else + udc_req_ptr->last_trb = udc_ep_ptr->enq_pt - 1; + } else { + /* we process one setup request at a time, so ring + * should already be empty. + */ + dev_err(crg_udc->dev, "Eq = 0x%p != Dq = 0x%p\n", + enq_pt, dq_pt); + } + } else { + dev_err(crg_udc->dev, "udc_ep_ptr->queue not empty\n"); + /* New setup packet came + * Drop the this req.. + */ + return -EINVAL; + } + + return 0; +} + +static void build_ep0_status(struct crg_udc_ep *udc_ep_ptr, + bool default_value, u32 status, + struct crg_udc_request *udc_req_ptr, u8 set_addr, u8 stall) +{ + struct crg_gadget_dev *crg_udc = udc_ep_ptr->crg_udc; + struct transfer_trb_s *enq_pt = udc_ep_ptr->enq_pt; + + if (default_value) { + udc_req_ptr = crg_udc->status_req; + udc_req_ptr->usb_req.length = 0; + udc_req_ptr->usb_req.status = status; + udc_req_ptr->usb_req.actual = 0; + udc_req_ptr->usb_req.complete = NULL; + } else { + udc_req_ptr->usb_req.status = status; + udc_req_ptr->usb_req.actual = 0; + } + + setup_status_trb(crg_udc, enq_pt, &udc_req_ptr->usb_req, + udc_ep_ptr->pcs, set_addr, stall); + + enq_pt++; + + /* check if we are at end of trb segment. If so, update + * pcs and enq for next segment + */ + if (GETF(TRB_TYPE, enq_pt->dw3) == TRB_TYPE_LINK) { + if (GETF(TRB_LINK_TOGGLE_CYCLE, enq_pt->dw3)) { + enq_pt->dw3 = SETF_VAR + (TRB_CYCLE_BIT, enq_pt->dw3, udc_ep_ptr->pcs); + udc_ep_ptr->pcs ^= 0x1; + } + enq_pt = udc_ep_ptr->first_trb; + } + udc_ep_ptr->enq_pt = enq_pt; + + knock_doorbell(crg_udc, 0); + + list_add_tail(&udc_req_ptr->queue, &udc_ep_ptr->queue); +} + +static void ep0_req_complete(struct crg_udc_ep *udc_ep_ptr) +{ + struct crg_gadget_dev *crg_udc = udc_ep_ptr->crg_udc; + + switch (crg_udc->setup_status) { + case DATA_STAGE_XFER: + crg_udc->setup_status = STATUS_STAGE_RECV; + build_ep0_status(udc_ep_ptr, true, -EINPROGRESS, NULL, 0, 0); + break; + case DATA_STAGE_RECV: + crg_udc->setup_status = STATUS_STAGE_XFER; + build_ep0_status(udc_ep_ptr, true, -EINPROGRESS, NULL, 0, 0); + break; + default: + if (crg_udc->setup_fn_call_back) + crg_udc->setup_fn_call_back(crg_udc); + + crg_udc->setup_status = WAIT_FOR_SETUP; + break; + } +} + +static void handle_cmpl_code_success(struct crg_gadget_dev *crg_udc, + struct event_trb_s *event, struct crg_udc_ep *udc_ep_ptr) +{ + u64 trb_pt; + struct transfer_trb_s *p_trb; + struct crg_udc_request *udc_req_ptr; + u32 trb_transfer_length; + + trb_pt = (u64)event->dw0 + ((u64)(event->dw1) << 32); + p_trb = tran_trb_dma_to_virt(udc_ep_ptr, trb_pt); + + dev_dbg(crg_udc->dev, "trb_pt = 0x%lx, p_trb = 0x%p\n", (unsigned long)trb_pt, p_trb); + dev_dbg(crg_udc->dev, "trb dw0 = 0x%x\n", p_trb->dw0); + dev_dbg(crg_udc->dev, "trb dw1 = 0x%x\n", p_trb->dw1); + dev_dbg(crg_udc->dev, "trb dw2 = 0x%x\n", p_trb->dw2); + dev_dbg(crg_udc->dev, "trb dw3 = 0x%x\n", p_trb->dw3); + + if (!GETF(TRB_CHAIN_BIT, p_trb->dw3)) { + /* chain bit is not set, which means it + * is the end of a TD + */ + udc_req_ptr = list_entry(udc_ep_ptr->queue.next, + struct crg_udc_request, queue); + + dev_dbg(crg_udc->dev, "udc_req_ptr = 0x%p\n", udc_req_ptr); + + trb_transfer_length = GETF(EVE_TRB_TRAN_LEN, + event->dw2); + udc_req_ptr->usb_req.actual = udc_req_ptr->usb_req.length - + trb_transfer_length; + dev_dbg(crg_udc->dev, "Actual data xfer = 0x%x, tx_len = 0x%x\n", + udc_req_ptr->usb_req.actual, trb_transfer_length); + + dev_dbg(crg_udc->dev, "udc_req_ptr->usb_req.buf = 0x%p\n", + udc_req_ptr->usb_req.buf); + /* Ensure that req_ptr is updated */ + wmb(); + req_done(udc_ep_ptr, udc_req_ptr, 0); + if (!udc_ep_ptr->desc) { + dev_dbg(crg_udc->dev, "udc_ep_ptr->desc is NULL\n"); + } else { + if (usb_endpoint_xfer_control(udc_ep_ptr->desc)) + ep0_req_complete(udc_ep_ptr); + } + } +} + +static void update_dequeue_pt(struct event_trb_s *event, + struct crg_udc_ep *udc_ep) +{ + u32 deq_pt_lo = event->dw0; + u32 deq_pt_hi = event->dw1; + u64 dq_pt_addr = (u64)deq_pt_lo + ((u64)deq_pt_hi << 32); + struct transfer_trb_s *deq_pt; + + deq_pt = tran_trb_dma_to_virt(udc_ep, dq_pt_addr); + deq_pt++; + + if (GETF(TRB_TYPE, deq_pt->dw3) == TRB_TYPE_LINK) + deq_pt = udc_ep->first_trb; + + udc_ep->deq_pt = deq_pt; +} + +static void advance_dequeue_pt(struct crg_udc_ep *udc_ep) +{ + struct crg_udc_request *udc_req; + + if (!list_empty(&udc_ep->queue)) { + udc_req = list_entry(udc_ep->queue.next, + struct crg_udc_request, + queue); + + if (udc_req->first_trb) + udc_ep->deq_pt = udc_req->first_trb; + else + udc_ep->deq_pt = udc_ep->enq_pt; + } else + udc_ep->deq_pt = udc_ep->enq_pt; +} + +static bool is_request_dequeued(struct crg_gadget_dev *crg_udc, + struct crg_udc_ep *udc_ep, struct event_trb_s *event) +{ + struct crg_udc_request *udc_req; + u32 trb_pt_lo = event->dw0; + u32 trb_pt_hi = event->dw1; + u64 trb_addr = (u64)trb_pt_lo + ((u64)trb_pt_hi << 32); + struct transfer_trb_s *trb_pt; + bool status = true; + + if (udc_ep->DCI == 0) + return false; + + trb_pt = tran_trb_dma_to_virt(udc_ep, trb_addr); + list_for_each_entry(udc_req, &udc_ep->queue, queue) { + if (trb_pt == udc_req->last_trb || + trb_pt == udc_req->first_trb) { + status = false; + break; + } + + if (is_pointer_less_than(trb_pt, udc_req->last_trb, udc_ep) && + is_pointer_less_than(udc_req->first_trb, trb_pt, + udc_ep)) { + status = false; + break; + } + } + + return status; +} + +static unsigned int count_trbs(u64 addr, u64 len) +{ + unsigned int num_trbs; + + num_trbs = DIV_ROUND_UP(len + (addr & (TRB_MAX_BUFFER_SIZE - 1)), + TRB_MAX_BUFFER_SIZE); + if (num_trbs == 0) + num_trbs++; + + return num_trbs; +} + +static unsigned int count_sg_trbs_needed(struct usb_request *usb_req) +{ + struct scatterlist *sg; + unsigned int i, len, full_len, num_trbs = 0; + + full_len = usb_req->length; + + for_each_sg(usb_req->sg, sg, usb_req->num_mapped_sgs, i) { + len = sg_dma_len(sg); + num_trbs += count_trbs(sg_dma_address(sg), len); + len = min_t(unsigned int, len, full_len); + full_len -= len; + if (full_len == 0) + break; + } + + return num_trbs; +} + + +static int crg_udc_build_td(struct crg_udc_ep *udc_ep_ptr, + struct crg_udc_request *udc_req_ptr) +{ + int status = 0; + struct crg_gadget_dev *crg_udc = udc_ep_ptr->crg_udc; + u32 num_trbs_needed; + u64 buffer_length; + u32 tmp; + + dev_dbg(crg_udc->dev, "udc_req buf = 0x%p\n", udc_req_ptr->usb_req.buf); + + if (udc_req_ptr->trbs_needed) { + /* If this is called to complete pending TRB transfers + * of previous Request + */ + buffer_length = udc_req_ptr->buff_len_left; + num_trbs_needed = udc_req_ptr->trbs_needed; + } else { + buffer_length = (u64)udc_req_ptr->usb_req.length; + + if (udc_req_ptr->usb_req.num_sgs) + num_trbs_needed = count_sg_trbs_needed(&udc_req_ptr->usb_req); + else { + num_trbs_needed = (u32)(buffer_length / TRB_MAX_BUFFER_SIZE); + + if (buffer_length == 0 || + (buffer_length % TRB_MAX_BUFFER_SIZE)) + num_trbs_needed += 1; + } + } + + dev_dbg(crg_udc->dev, "buf_len = %ld, num_trb_needed = %d\n", + (unsigned long)buffer_length, num_trbs_needed); + + if (usb_endpoint_xfer_control(udc_ep_ptr->desc)) { + dev_dbg(crg_udc->dev, "crg_udc_queue_ctrl control\n"); + status = crg_udc_queue_ctrl(udc_ep_ptr, + udc_req_ptr, num_trbs_needed); + } else if (usb_endpoint_xfer_isoc(udc_ep_ptr->desc)) { + dev_dbg(crg_udc->dev, "crg_udc_queue_trbs isoc\n"); + status = crg_udc_queue_trbs(udc_ep_ptr, udc_req_ptr, 1, + CRGUDC_ISOC_EP_TD_RING_SIZE, + num_trbs_needed, buffer_length); + + tmp = udc_ep_ptr->DCI; + tmp = CRG_U3DC_DB_TARGET(tmp); + dev_dbg(crg_udc->dev, "DOORBELL = 0x%x\n", tmp); + + knock_doorbell(crg_udc, udc_ep_ptr->DCI); + } else if (usb_endpoint_xfer_bulk(udc_ep_ptr->desc)) { + dev_dbg(crg_udc->dev, "crg_udc_queue_trbs bulk\n"); + status = crg_udc_queue_trbs(udc_ep_ptr, udc_req_ptr, 0, + CRGUDC_BULK_EP_TD_RING_SIZE, + num_trbs_needed, buffer_length); + tmp = udc_ep_ptr->DCI; + tmp = CRG_U3DC_DB_TARGET(tmp); + if (udc_ep_ptr->comp_desc && + usb_ss_max_streams(udc_ep_ptr->comp_desc)) { + /* hold the doorbell if stream_rejected is set */ + dev_err(crg_udc->dev, "%s, WANT TO have bulk stream\n", __func__); + } + + knock_doorbell(crg_udc, udc_ep_ptr->DCI); + } else { + /* interrupt endpoint */ + status = crg_udc_queue_trbs(udc_ep_ptr, udc_req_ptr, 0, + CRGUDC_INT_EP_TD_RING_SIZE, + num_trbs_needed, buffer_length); + tmp = udc_ep_ptr->DCI; + tmp = CRG_U3DC_DB_TARGET(tmp); + + knock_doorbell(crg_udc, udc_ep_ptr->DCI); + } + + return status; +} + +/* This function will go through the list of the USB requests for the + * given endpoint and schedule any unscheduled trb's to the xfer ring + */ +static void queue_pending_trbs(struct crg_udc_ep *udc_ep_ptr) +{ + struct crg_udc_request *udc_req_ptr; + /* schedule trbs till there arent any pending unscheduled ones + * or the ring is full again + */ + + list_for_each_entry(udc_req_ptr, &udc_ep_ptr->queue, queue) { + if (udc_req_ptr->all_trbs_queued == 0) + crg_udc_build_td(udc_ep_ptr, udc_req_ptr); + + if (udc_ep_ptr->tran_ring_full) + break; + } +} + +static void squeeze_xfer_ring(struct crg_udc_ep *udc_ep_ptr, + struct crg_udc_request *udc_req_ptr) +{ + struct transfer_trb_s *temp = udc_req_ptr->first_trb; + struct crg_udc_request *next_req; + + /* All the incompleted Requests are recorded in crg_udc_ep.queue by SW*/ + /* 1. Clear all the queued-in-ring trbs from the deleted point */ + /* 2. Re-queue in ring the Requests that are after the deleted Request*/ + while (temp != udc_ep_ptr->enq_pt) { + temp->dw0 = 0; + temp->dw1 = 0; + temp->dw2 = 0; + temp->dw3 = 0; + + temp++; + + if (GETF(TRB_TYPE, temp->dw3) == TRB_TYPE_LINK) + temp = udc_ep_ptr->first_trb; + } + + /* Update the new enq_ptr starting from the deleted req */ + udc_ep_ptr->enq_pt = udc_req_ptr->first_trb; + + if (udc_ep_ptr->tran_ring_full) + udc_ep_ptr->tran_ring_full = false; + + next_req = list_entry(udc_req_ptr->queue.next, + struct crg_udc_request, queue); + + list_for_each_entry_from(next_req, &udc_ep_ptr->queue, queue) { + next_req->usb_req.status = -EINPROGRESS; + next_req->usb_req.actual = 0; + + /* clear the values of the nv_udc_request container **/ + clear_req_container(next_req); + + if (udc_ep_ptr->tran_ring_full) + break; + + /* push the request to the transfer ring */ + crg_udc_build_td(udc_ep_ptr, next_req); + } +} + +static int set_ep0_halt(struct crg_gadget_dev *crg_udc) +{ + struct crg_udc_ep *udc_ep_ptr = &crg_udc->udc_ep[0]; + int ep_state; + + ep_state = get_ep_state(crg_udc, udc_ep_ptr->DCI); + if (ep_state == EP_STATE_HALTED || + ep_state == EP_STATE_DISABLED) { + return 0; + } + + build_ep0_status(udc_ep_ptr, true, -EINVAL, NULL, 0, 1); + + udc_ep_ptr->ep_state = EP_STATE_HALTED; + + return 0; +} + +static int set_ep_halt(struct crg_gadget_dev *crg_udc, int DCI) +{ + struct crg_uccr *uccr = crg_udc->uccr; + struct crg_udc_ep *udc_ep_ptr = &crg_udc->udc_ep[DCI]; + u32 param0; + u32 tmp; + + dev_dbg(crg_udc->dev, "%s DCI=%d !!\n", __func__, DCI); + + if (DCI == 0) + return 0; + + if (udc_ep_ptr->ep_state == EP_STATE_DISABLED || + udc_ep_ptr->ep_state == EP_STATE_HALTED) + return 0; + + param0 = (0x1 << DCI); + crg_issue_command(crg_udc, CRG_CMD_SET_HALT, param0, 0); + do { + tmp = readl(&uccr->ep_running); + } while ((tmp & param0) != 0); + + /* clean up the request queue */ + nuke(udc_ep_ptr, -ECONNRESET); + + udc_ep_ptr->deq_pt = udc_ep_ptr->enq_pt; + udc_ep_ptr->tran_ring_full = false; + udc_ep_ptr->ep_state = EP_STATE_HALTED; + + return 0; +} + +static int ep_halt(struct crg_udc_ep *udc_ep_ptr, + int halt, int ignore_wedge) +{ + struct crg_gadget_dev *crg_udc = udc_ep_ptr->crg_udc; + struct crg_uccr *uccr = crg_udc->uccr; + int ep_state; + bool reset_seq_only = false; + int do_halt; + u32 param0; + u32 tmp; + struct crg_udc_request *udc_req_ptr; + + if (!udc_ep_ptr->desc) { + dev_err(crg_udc->dev, "NULL desc\n"); + return -EINVAL; + } + + if (udc_ep_ptr->desc->bmAttributes == USB_ENDPOINT_XFER_ISOC) { + dev_err(crg_udc->dev, "Isoc ep, halt not supported\n"); + return -EOPNOTSUPP; + } + + if (udc_ep_ptr->DCI == 0) + return 0; + + ep_state = get_ep_state(crg_udc, udc_ep_ptr->DCI); + + if (ep_state == EP_STATE_DISABLED) + return 0; + + if (ep_state == EP_STATE_HALTED) { + if (halt != 0) + return 0; + + /* want unhalt an halted ep */ + if (udc_ep_ptr->wedge && !ignore_wedge) { + do_halt = -1; + reset_seq_only = true; + } else { + do_halt = 0; + } + + } else { + /* ep state == running or stopped */ + if (halt != 0) { + /* want halt a running ep */ + do_halt = 1; + } else { + /* reset a running ep */ + do_halt = 0; + reset_seq_only = true; + } + } + + param0 = (0x1 << udc_ep_ptr->DCI); + if (do_halt == 1) { + /* setting ep to halt */ + dev_dbg(crg_udc->dev, "HALT EP DCI = %d\n", udc_ep_ptr->DCI); + crg_issue_command(crg_udc, CRG_CMD_SET_HALT, param0, 0); + do { + tmp = readl(&uccr->ep_running); + } while ((tmp & param0) != 0); + + if (crg_udc->gadget.speed >= USB_SPEED_SUPER) { + /* clean up the request queue */ + nuke(udc_ep_ptr, -ECONNRESET); + + udc_ep_ptr->deq_pt = udc_ep_ptr->enq_pt; + udc_ep_ptr->tran_ring_full = false; + + dev_dbg(crg_udc->dev, "update deq_pt tp enq_pt 0x%p\n", + udc_ep_ptr->deq_pt); + } + /* clean up the request queue */ + udc_ep_ptr->ep_state = EP_STATE_HALTED; + } else if (do_halt == 0) { + /* clearing ep halt state */ + dev_dbg(crg_udc->dev, "Clear EP HALT DCI = %d\n", udc_ep_ptr->DCI); + /* reset sequence number */ + crg_issue_command(crg_udc, CRG_CMD_RESET_SEQNUM, param0, 0); + + if (!reset_seq_only) { + /* Clear halt for a halted EP.*/ + /* NOTE: we must CLEAR_HALT first, then SET_TR_DQPTR*/ + crg_issue_command(crg_udc, + CRG_CMD_CLEAR_HALT, param0, 0); + crg_udc_epcx_update_dqptr(udc_ep_ptr); + + dev_dbg(crg_udc->dev, + "crg_udc_epcx_update_dqptr , PCS = %d\n", + udc_ep_ptr->pcs); + } + + udc_ep_ptr->wedge = 0; + udc_ep_ptr->ep_state = EP_STATE_RUNNING; + /* set endpoint to running state */ + /* clear pause for the endpoint */ + if (!list_empty(&udc_ep_ptr->queue)) { + tmp = udc_ep_ptr->DCI; + tmp = CRG_U3DC_DB_TARGET(tmp); + + list_for_each_entry(udc_req_ptr, &udc_ep_ptr->queue, + queue) { + struct transfer_trb_s *tmp_ptr = + udc_ep_ptr->deq_pt; + + tmp_ptr--; + tmp_ptr = udc_ep_ptr->deq_pt + 1; + if (GETF(TRB_TYPE, tmp_ptr->dw3) == TRB_TYPE_LINK) { + udc_ep_ptr->pcs ^= 0x1; + crg_udc_epcx_update_dqptr(udc_ep_ptr); + udc_ep_ptr->pcs ^= 0x1; + } + } + knock_doorbell(crg_udc, udc_ep_ptr->DCI); + } + } else { + /* wedged EP deny CLEAR HALT */ + dev_dbg(crg_udc->dev, "wedged EP deny CLEAR HALT DCI = %d\n", udc_ep_ptr->DCI); + /* reset sequence number */ + if (reset_seq_only) + crg_issue_command(crg_udc, + CRG_CMD_RESET_SEQNUM, param0, 0); + } + + return 0; +} + +/************ep related ops*******************************/ +static int crg_udc_ep_disable(struct usb_ep *ep) +{ + struct crg_udc_ep *udc_ep; + struct crg_gadget_dev *crg_udc; + struct ep_cx_s *p_ep_cx; + int ep_state; + struct crg_uccr *uccr; + unsigned long flags = 0; + + if (!ep) + return -EINVAL; + + udc_ep = container_of(ep, struct crg_udc_ep, usb_ep); + crg_udc = udc_ep->crg_udc; + + if (udc_ep->DCI == 0) + return 0; + + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + uccr = crg_udc->uccr; + p_ep_cx = (struct ep_cx_s *)crg_udc->p_epcx + udc_ep->DCI - 2; + + ep_state = get_ep_state(crg_udc, udc_ep->DCI); + if (ep_state == EP_STATE_DISABLED) { + /* get here if ep is already disabled */ + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EINVAL; + } + + dev_dbg(crg_udc->dev, "EPDCI = 0x%x\n", udc_ep->DCI); + + /*Maybe we need to halt ep before ep disable*/ + + writel(0x1 << udc_ep->DCI, &uccr->ep_enable); + + /* clean up the request queue */ + nuke(udc_ep, -ESHUTDOWN); + + /* decrement ep counters */ + crg_udc->num_enabled_eps--; + + udc_ep->desc = NULL; + + /* clean up the endpoint context */ + memset(p_ep_cx, 0, sizeof(struct ep_cx_s)); + + dev_dbg(crg_udc->dev, "num_enabled_eps = %d\n", crg_udc->num_enabled_eps); + + /* If device state was changed to default by port + * reset, should not overwrite it again + */ + if (crg_udc->num_enabled_eps == 0 && + crg_udc->device_state == USB_STATE_CONFIGURED) { + dev_dbg(crg_udc->dev, "Device State USB_STATE_CONFIGURED\n"); + dev_dbg(crg_udc->dev, "Set Device State to addressed\n"); + crg_udc->device_state = USB_STATE_ADDRESS; + + } + + udc_ep->ep_state = EP_STATE_DISABLED; + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + + return 0; +} + +static int crg_udc_ep_enable(struct usb_ep *ep, + const struct usb_endpoint_descriptor *desc) +{ + struct crg_udc_ep *udc_ep; + struct crg_gadget_dev *crg_udc; + u32 param0; + unsigned long flags = 0; + struct ep_cx_s *epcx; + struct crg_uccr *uccr; + + if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) + return -EINVAL; + + udc_ep = container_of(ep, struct crg_udc_ep, usb_ep); + + /*ep0 is always running*/ + if (udc_ep->DCI == 0) + return 0; + + crg_udc = udc_ep->crg_udc; + uccr = crg_udc->uccr; + + if (!crg_udc->gadget_driver) + return -ESHUTDOWN; + + dev_dbg(crg_udc->dev, "%s DCI = %d\n", __func__, udc_ep->DCI); + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + /*crg ep context start from ep1*/ + if (get_ep_state(crg_udc, udc_ep->DCI) != EP_STATE_DISABLED) { + dev_dbg(crg_udc->dev, "%s disable first\n", __func__); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + crg_udc_ep_disable(ep); + spin_lock_irqsave(&crg_udc->udc_lock, flags); + } + + udc_ep->desc = desc; + udc_ep->comp_desc = ep->comp_desc; + + /* setup endpoint context for regular endpoint + * the endpoint context for control endpoint has been + * setted up in probe function + */ + if (udc_ep->DCI) { + dev_dbg(crg_udc->dev, "ep_enable udc_ep->DCI = %d\n", udc_ep->DCI); + + /* setup transfer ring */ + if (!udc_ep->tran_ring_info.vaddr) { + dma_addr_t dma; + u32 ring_size = 0; + void *vaddr; + size_t len; + + if (usb_endpoint_xfer_bulk(desc)) + ring_size = CRGUDC_BULK_EP_TD_RING_SIZE; + else if (usb_endpoint_xfer_isoc(desc)) + ring_size = CRGUDC_ISOC_EP_TD_RING_SIZE; + else if (usb_endpoint_xfer_int(desc)) + ring_size = CRGUDC_INT_EP_TD_RING_SIZE; + len = ring_size * sizeof(struct transfer_trb_s); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + vaddr = dma_alloc_coherent(crg_udc->dev, len, + &dma, GFP_ATOMIC); + if (!vaddr) + return -ENOMEM; + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + udc_ep->tran_ring_info.vaddr = vaddr; + udc_ep->tran_ring_info.dma = dma; + udc_ep->tran_ring_info.len = len; + udc_ep->first_trb = vaddr; + udc_ep->last_trb = udc_ep->first_trb + ring_size - 1; + } + memset(udc_ep->first_trb, 0, udc_ep->tran_ring_info.len); + /* Ensure that transfer ring is updated */ + wmb(); + setup_link_trb(udc_ep->last_trb, true, + udc_ep->tran_ring_info.dma); + + udc_ep->enq_pt = udc_ep->first_trb; + udc_ep->deq_pt = udc_ep->first_trb; + udc_ep->pcs = 1; + udc_ep->tran_ring_full = false; + crg_udc->num_enabled_eps++; + crg_udc_epcx_setup(udc_ep); + } + + dev_dbg(crg_udc->dev, "num_enabled_eps = %d\n", crg_udc->num_enabled_eps); + + epcx = (struct ep_cx_s *)(crg_udc->p_epcx + udc_ep->DCI - 2); + + param0 = (0x1 << udc_ep->DCI); + crg_issue_command(crg_udc, CRG_CMD_CONFIG_EP, param0, 0); + + dev_dbg(crg_udc->dev, "config ep and start, DCI=%d\n", udc_ep->DCI); + if (crg_udc->device_state == USB_STATE_ADDRESS) + crg_udc->device_state = USB_STATE_CONFIGURED; + + udc_ep->wedge = 0; + udc_ep->ep_state = EP_STATE_RUNNING; + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + + return 0; +} + +static struct usb_request * +crg_udc_alloc_request(struct usb_ep *_ep, gfp_t gfp_flags) +{ + struct crg_udc_request *udc_req_ptr = NULL; + + udc_req_ptr = kzalloc(sizeof(*udc_req_ptr), gfp_flags); + + + if (!udc_req_ptr) + return NULL; + + udc_req_ptr->usb_req.dma = DMA_ADDR_INVALID; + INIT_LIST_HEAD(&udc_req_ptr->queue); + + return &udc_req_ptr->usb_req; +} + +static void crg_udc_free_request(struct usb_ep *_ep, struct usb_request *_req) +{ + struct crg_udc_request *udc_req_ptr = NULL; + + if (!_ep || !_req) + return; + + udc_req_ptr = container_of(_req, struct crg_udc_request, usb_req); + kfree(udc_req_ptr); +} + +static int +crg_udc_ep_queue(struct usb_ep *_ep, struct usb_request *_req, + gfp_t gfp_flags) +{ + struct crg_udc_request *udc_req_ptr; + struct crg_udc_ep *udc_ep_ptr; + struct crg_gadget_dev *crg_udc; + int status; + unsigned long flags = 0; + int dma_data_dir = 0; + + + if (!_req || !_ep) + return -EINVAL; + + udc_req_ptr = container_of(_req, struct crg_udc_request, usb_req); + if (!udc_req_ptr) + return -EINVAL; + + udc_ep_ptr = container_of(_ep, struct crg_udc_ep, usb_ep); + if (!udc_ep_ptr) + return -EINVAL; + + crg_udc = udc_ep_ptr->crg_udc; + if (!crg_udc) + return -EINVAL; + + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + if (!udc_ep_ptr->first_trb || + !udc_req_ptr->usb_req.complete || + (!udc_req_ptr->usb_req.buf && !udc_req_ptr->usb_req.num_sgs) || + !list_empty(&udc_req_ptr->queue)) { + dev_dbg(crg_udc->dev, "%s, invalid usbrequest\n", __func__); + if (!udc_ep_ptr->first_trb) + dev_err(crg_udc->dev, "%s, no first_trb\n", __func__); + + if (!udc_req_ptr->usb_req.complete) + dev_err(crg_udc->dev, "%s, no complete\n", __func__); + + if (!udc_req_ptr->usb_req.buf) + dev_err(crg_udc->dev, "%s, no req buf\n", __func__); + + if (!list_empty(&udc_req_ptr->queue)) + dev_err(crg_udc->dev, "%s, list not empty\n", __func__); + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EINVAL; + } + dev_dbg(crg_udc->dev, "enqueue EPDCI = 0x%x\n", udc_ep_ptr->DCI); + dev_dbg(crg_udc->dev, "udc_req buf = 0x%p\n", udc_req_ptr->usb_req.buf); + + if (!udc_ep_ptr->desc) { + dev_dbg(crg_udc->dev, "udc_ep_ptr->Desc is null\n"); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EINVAL; + } + /* Ensure that req_ptr is updated */ + wmb(); + /* Clearing the Values of the UDC_REQUEST container */ + clear_req_container(udc_req_ptr); + udc_req_ptr->mapped = 0; + + if (usb_endpoint_xfer_control(udc_ep_ptr->desc) && + _req->length == 0) { + crg_udc->setup_status = STATUS_STAGE_XFER; + status = -EINPROGRESS; + dev_dbg(crg_udc->dev, "udc_req_ptr = 0x%p\n", udc_req_ptr); + + build_ep0_status(&crg_udc->udc_ep[0], false, status, + udc_req_ptr, 0, 0); + dev_dbg(crg_udc->dev, "act status request for control endpoint\n"); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return 0; + } + + /* request length is possible to be 0. Like SCSI blank command */ + dev_dbg(crg_udc->dev, "request length=%d\n", _req->length); + + if (udc_req_ptr->usb_req.num_sgs) { + int n; + + dev_dbg(crg_udc->dev, "udc_req_ptr->usb_req.num_sgs = %d\n", + udc_req_ptr->usb_req.num_sgs); + dev_dbg(crg_udc->dev, "udc_req_ptr->usb_req.sg->length = %d\n", + udc_req_ptr->usb_req.sg->length); + dma_data_dir = (usb_endpoint_dir_in(udc_ep_ptr->desc) + ? DMA_TO_DEVICE : DMA_FROM_DEVICE); + n = dma_map_sg(crg_udc->dev, udc_req_ptr->usb_req.sg, + udc_req_ptr->usb_req.num_sgs, dma_data_dir); + if (n <= 0) { + dev_err(crg_udc->dev, "dma_map_sg fail, ret is %d\n", n); + dump_stack(); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EINVAL; + } + if (n != udc_req_ptr->usb_req.num_sgs) { + dev_err(crg_udc->dev, "URB_DMA_SG_COMBINED we not support\n"); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EAGAIN; + } + udc_req_ptr->usb_req.num_mapped_sgs = n; + dev_dbg(crg_udc->dev, "dma_map_sg done , usb_req.num_mapped_sgs = %d\n", n); + + + } else if (udc_req_ptr->usb_req.sg) { + dev_err(crg_udc->dev, "num_sgs = 0, but udc_req_ptr->usb_req.sg is not NULL\n"); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EINVAL; + + } else { + if (udc_req_ptr->usb_req.dma == DMA_ADDR_INVALID && _req->length != 0) { + if (usb_endpoint_xfer_control(udc_ep_ptr->desc)) { + if (crg_udc->setup_status == DATA_STAGE_XFER || + crg_udc->setup_status == STATUS_STAGE_XFER) + dma_data_dir = DMA_TO_DEVICE; + + if (crg_udc->setup_status == DATA_STAGE_RECV || + crg_udc->setup_status == STATUS_STAGE_RECV) + dma_data_dir = DMA_FROM_DEVICE; + } else { + dma_data_dir = (usb_endpoint_dir_in(udc_ep_ptr->desc) + ? DMA_TO_DEVICE : DMA_FROM_DEVICE); + } + udc_req_ptr->usb_req.dma = + dma_map_single(crg_udc->dev, udc_req_ptr->usb_req.buf, + udc_req_ptr->usb_req.length, + dma_data_dir); + + + udc_req_ptr->mapped = 1; + + dev_dbg(crg_udc->dev, "dma_map_single and mapped is 1\n"); + } + } + + udc_req_ptr->usb_req.status = -EINPROGRESS; + udc_req_ptr->usb_req.actual = 0; + + /* If the transfer ring for this particular end point is full, + * then simply queue the request and return + */ + if (udc_ep_ptr->tran_ring_full) { + status = 0; + } else { + /* push the request to the transfer ring if possible. */ + status = crg_udc_build_td(udc_ep_ptr, udc_req_ptr); + } + if (!status) + list_add_tail(&udc_req_ptr->queue, &udc_ep_ptr->queue); + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + + return status; +} + +static int +crg_udc_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req) +{ + struct crg_udc_ep *udc_ep_ptr; + struct crg_gadget_dev *crg_udc; + struct crg_uccr *uccr; + u32 tmp = 0; + struct crg_udc_request *udc_req; + struct ep_cx_s *p_ep_cx; + int old_ep_state; + struct transfer_trb_s *pause_pt; + u32 deq_pt_lo, deq_pt_hi; + u64 dq_pt_addr; + u8 DCI; + unsigned long flags = 0; + + if (!_ep || !_req) + return -EINVAL; + + udc_ep_ptr = container_of(_ep, struct crg_udc_ep, usb_ep); + crg_udc = udc_ep_ptr->crg_udc; + uccr = crg_udc->uccr; + DCI = udc_ep_ptr->DCI; + + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + dev_dbg(crg_udc->dev, "%s EPDCI = 0x%x\n", __func__, DCI); + old_ep_state = get_ep_state(crg_udc, DCI); + if (DCI != 0 && old_ep_state == EP_STATE_RUNNING) { + u32 param0; + + dev_dbg(crg_udc->dev, "%s, EP_STATE_RUNNING\n", __func__); + param0 = (0x1 << DCI); + /* stop the DMA from HW first */ + crg_issue_command(crg_udc, CRG_CMD_STOP_EP, param0, 0); + do { + tmp = readl(&uccr->ep_running); + } while ((tmp & param0) != 0); + udc_ep_ptr->ep_state = EP_STATE_STOPPED; + } + + list_for_each_entry(udc_req, &udc_ep_ptr->queue, queue) { + if (&udc_req->usb_req == _req) + break; + } + + if (&udc_req->usb_req != _req) { + dev_dbg(crg_udc->dev, "did not find the request in request queue\n"); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EINVAL; + } + /* Request hasn't been queued to transfer ring yet + * dequeue it from sw queue only + */ + if (!udc_req->first_trb) { + req_done(udc_ep_ptr, udc_req, -ECONNRESET); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return 0; + } + + /* ep0 cannot be stopped. So if request has already been queued to + * transfer ring, it cannot be dequeued + */ + if (DCI == 0) { + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EINVAL; + } + + p_ep_cx = crg_udc->p_epcx + DCI - 2; + deq_pt_lo = p_ep_cx->dw2 & EP_CX_TR_DQPT_LO_MASK; + deq_pt_hi = p_ep_cx->dw3; + dq_pt_addr = (u64)deq_pt_lo + ((u64)deq_pt_hi << 32); + pause_pt = tran_trb_dma_to_virt(udc_ep_ptr, dq_pt_addr); + + dev_dbg(crg_udc->dev, "dequeue pause_pt = 0x%p, first_trb = 0x%p\n", + pause_pt, udc_req->first_trb); + dev_dbg(crg_udc->dev, "dequeue deq_pt = 0x%p, enq_pt = 0x%p\n", + udc_ep_ptr->deq_pt, udc_ep_ptr->enq_pt); + + if (is_pointer_less_than(pause_pt, udc_req->first_trb, udc_ep_ptr)) { + dev_dbg(crg_udc->dev, "squeeze_xfer_ring\n"); + /* HW hasn't process the request yet */ + squeeze_xfer_ring(udc_ep_ptr, udc_req); + req_done(udc_ep_ptr, udc_req, -ECONNRESET); + } else if (udc_req->last_trb && + is_pointer_less_than(udc_req->last_trb, pause_pt, udc_ep_ptr)) { + /* Request has been completed by HW + * There must be transfer events pending in event ring, and + * it will be processed later once interrupt context gets spin + * lock. + * Gadget driver free the request without checking the return + * value of usb_ep_dequeue, so we have to complete the request + * here and drop the transfer event later. + */ + dev_dbg(crg_udc->dev, " Request has been complete by HW, reject request\n"); + req_done(udc_ep_ptr, udc_req, -ECONNRESET); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EINVAL; + + } else { + /* Request has been partially completed by HW */ + + dev_dbg(crg_udc->dev, " Request has been partially completed by HW\n"); + /*udc_req->usb_req.actual = actual_data_xfered(udc_ep, udc_req);*/ + + dev_dbg(crg_udc->dev, "%s, complete requests\n", __func__); + req_done(udc_ep_ptr, udc_req, -ECONNRESET); + + advance_dequeue_pt(udc_ep_ptr); + crg_udc_epcx_update_dqptr(udc_ep_ptr); + + /* For big TD, we generated completion event every 5 TRBS. + * So, we do not need to update sw dequeue pointer here. + * Wait for interrupt context to update it. + * Do not need to queue more trbs also. + */ + } + + dev_dbg(crg_udc->dev, "End dequeue deq_pt = 0x%p, enq_pt = 0x%p\n", + udc_ep_ptr->deq_pt, udc_ep_ptr->enq_pt); + + /* knock doorbell and resume data transfer */ + if (old_ep_state == EP_STATE_RUNNING) { + tmp = DCI; + tmp = CRG_U3DC_DB_TARGET(tmp); + + knock_doorbell(crg_udc, udc_ep_ptr->DCI); + + udc_ep_ptr->ep_state = EP_STATE_RUNNING; + } + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + + return 0; +} + +static int crg_udc_ep_set_halt(struct usb_ep *_ep, int value) +{ + struct crg_udc_ep *udc_ep_ptr; + int status; + unsigned long flags = 0; + struct crg_gadget_dev *crg_udc; + + if (!_ep) + return -EINVAL; + + udc_ep_ptr = container_of(_ep, struct crg_udc_ep, usb_ep); + crg_udc = udc_ep_ptr->crg_udc; + + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + if (value && usb_endpoint_dir_in(udc_ep_ptr->desc) && + !list_empty(&udc_ep_ptr->queue)) { + dev_err(crg_udc->dev, "set_halt: list not empty\n"); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + return -EAGAIN; + } + + status = ep_halt(udc_ep_ptr, value, 1); + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + + return status; +} + +static int crg_udc_ep_set_wedge(struct usb_ep *_ep) +{ + struct crg_udc_ep *udc_ep_ptr; + int status; + unsigned long flags = 0; + struct crg_gadget_dev *crg_udc; + + if (!_ep) + return -EINVAL; + + udc_ep_ptr = container_of(_ep, struct crg_udc_ep, usb_ep); + crg_udc = udc_ep_ptr->crg_udc; + + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + udc_ep_ptr->wedge = 1; + + status = ep_halt(udc_ep_ptr, 1, 1); + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + + return status; +} + +static struct usb_ep_ops crg_udc_ep_ops = { + .enable = crg_udc_ep_enable, + .disable = crg_udc_ep_disable, + .alloc_request = crg_udc_alloc_request, + .free_request = crg_udc_free_request, + .queue = crg_udc_ep_queue, + .dequeue = crg_udc_ep_dequeue, + .set_halt = crg_udc_ep_set_halt, + .set_wedge = crg_udc_ep_set_wedge, +}; + +static void crg_ep_struct_setup(struct crg_gadget_dev *crg_udc, + u32 DCI, const char *name) +{ + struct crg_udc_ep *ep = &crg_udc->udc_ep[DCI]; + + ep->DCI = DCI; + + if (ep->DCI > 1) { + strscpy_pad(ep->name, name, sizeof(ep->name) - 1); + ep->usb_ep.name = ep->name; + ep->usb_ep.maxpacket = 1024; + ep->usb_ep.max_streams = 16; + + ep->usb_ep.caps.type_iso = 1; + ep->usb_ep.caps.type_bulk = 1; + ep->usb_ep.caps.type_int = 1; + ep->usb_ep.caps.dir_in = 1; + ep->usb_ep.caps.type_control = 1; + + ep->usb_ep.caps.type_iso = 1; + ep->usb_ep.caps.type_bulk = 1; + ep->usb_ep.caps.type_int = 1; + ep->usb_ep.caps.type_control = 1; + if (ep->DCI % 2) + ep->usb_ep.caps.dir_out = 1; + else + ep->usb_ep.caps.dir_in = 1; + usb_ep_set_maxpacket_limit(&ep->usb_ep, MAX_PACKET_SIZE); + } else { + strscpy(ep->name, "ep0", sizeof(ep->name) - 1); + ep->usb_ep.name = ep->name; + ep->usb_ep.maxpacket = 512; + ep->usb_ep.caps.type_control = 1; + ep->usb_ep.caps.dir_in = 1; + ep->usb_ep.caps.dir_out = 1; + } + + dev_dbg(crg_udc->dev, "ep = 0x%p, ep name = %s maxpacket = %d DCI=%d\n", + ep, ep->name, ep->usb_ep.maxpacket, ep->DCI); + ep->usb_ep.ops = &crg_udc_ep_ops; + ep->crg_udc = crg_udc; + + INIT_LIST_HEAD(&ep->queue); + if (ep->DCI > 1) + list_add_tail(&ep->usb_ep.ep_list, &crg_udc->gadget.ep_list); +} + + +static void enable_setup_event(struct crg_gadget_dev *crg_udc) +{ + struct crg_uccr *uccr = crg_udc->uccr; + u32 val; + + dev_dbg(crg_udc->dev, "before setup en config1[0x%p]=0x%x\n", + &uccr->config1, readl(&uccr->config1)); + + val = readl(&uccr->config1); + val |= CRG_U3DC_CFG1_SETUP_EVENT_EN; + writel(val, &uccr->config1); + dev_dbg(crg_udc->dev, "update config1[0x%p]=0x%x\n", + &uccr->config1, readl(&uccr->config1)); +} + +static int is_event_ring_x_empty(struct crg_gadget_dev *crg_udc, int index) +{ + struct event_trb_s *event; + struct crg_udc_event *udc_event; + + udc_event = &crg_udc->udc_event[index]; + if (udc_event->evt_dq_pt) { + event = (struct event_trb_s *)udc_event->evt_dq_pt; + + if (GETF(EVE_TRB_CYCLE_BIT, event->dw3) != + udc_event->CCS) + return 1; + } + + return 0; +} + +static int is_event_rings_empty(struct crg_gadget_dev *crg_udc) +{ + int i; + + for (i = 0; i < CRG_RING_NUM; i++) { + if (!is_event_ring_x_empty(crg_udc, i)) { + dev_err(crg_udc->dev, "%s evt ring not empty\n", __func__); + return 0; + } + } + return 1; +} + +static int enable_setup(struct crg_gadget_dev *crg_udc) +{ + enable_setup_event(crg_udc); + crg_udc->device_state = USB_STATE_DEFAULT; + crg_udc->setup_status = WAIT_FOR_SETUP; + dev_dbg(crg_udc->dev, "%s ready to receive setup events\n", __func__); + + return 0; +} + +static int prepare_for_setup(struct crg_gadget_dev *crg_udc) +{ + struct crg_udc_ep *udc_ep0_ptr; + +#ifdef REINIT_EP0_ON_BUS_RESET + dma_addr_t dqptaddr; + u32 cmd_param0; + u32 cmd_param1; +#endif + + if (!is_event_rings_empty(crg_udc) || + crg_udc->portsc_on_reconnecting == 1) + return -EBUSY; + + udc_ep0_ptr = &crg_udc->udc_ep[0]; +/* If we reinit ep0 on bus reset, we just make ep0 dequeue pointer align + * with enqueue pointer, all remaining xfer trbs became dumb ones which + * will not produce xfer event anymore. + * + * If we considering the opposite solution, we should wait all ep0 xfer + * trbs be completed(with some err complete code) + */ +#ifdef REINIT_EP0_ON_BUS_RESET + /* Complete any reqs on EP0 queue */ + nuke(udc_ep0_ptr, -ESHUTDOWN); + + crg_udc->ctrl_req_enq_idx = 0; + memset(crg_udc->ctrl_req_queue, 0, + sizeof(struct crg_setup_packet) * CTRL_REQ_QUEUE_DEPTH); + + /*context related ops*/ + dqptaddr = tran_trb_virt_to_dma(udc_ep0_ptr, udc_ep0_ptr->enq_pt); + cmd_param0 = (lower_32_bits(dqptaddr) & + CRG_CMD0_0_DQPTRLO_MASK) | + CRG_CMD0_0_DCS(udc_ep0_ptr->pcs); + cmd_param1 = upper_32_bits(dqptaddr); + crg_issue_command(crg_udc, + CRG_CMD_INIT_EP0, cmd_param0, cmd_param1); + + /* TRY this solution*/ + udc_ep0_ptr->deq_pt = udc_ep0_ptr->enq_pt; + udc_ep0_ptr->tran_ring_full = false; +#else + if (!list_empty(&udc_ep0_ptr->queue)) { + dev_err(crg_udc->dev, "%s remaining ep0 xfer trbs on reset!\n", __func__); + return -EBUSY; + } +#endif + + enable_setup(crg_udc); + + return 0; +} + +static void update_ep0_maxpacketsize(struct crg_gadget_dev *crg_udc) +{ + u16 maxpacketsize = 0; + struct crg_udc_ep *udc_ep0 = &crg_udc->udc_ep[0]; + u32 param0; + + if (crg_udc->gadget.speed >= USB_SPEED_SUPER) + maxpacketsize = 512; + else + maxpacketsize = 64; + + param0 = CRG_CMD1_0_MPS(maxpacketsize); + crg_issue_command(crg_udc, CRG_CMD_UPDATE_EP0_CFG, param0, 0); + + crg_udc_ep0_desc.wMaxPacketSize = cpu_to_le16(maxpacketsize); + udc_ep0->usb_ep.maxpacket = maxpacketsize; +} + +static int init_event_ring(struct crg_gadget_dev *crg_udc, int index) +{ + struct crg_uicr *uicr = crg_udc->uicr[index]; + struct crg_udc_event *udc_event = &crg_udc->udc_event[index]; + + int ret; + u32 buff_length; + dma_addr_t mapping; + + buff_length = CRG_ERST_SIZE * sizeof(struct erst_s); + if (!udc_event->erst.vaddr) { + udc_event->erst.vaddr = + dma_alloc_coherent(crg_udc->dev, buff_length, + &mapping, GFP_KERNEL); + + if (!udc_event->erst.vaddr) { + ret = -ENOMEM; + return ret; + } + } else { + mapping = udc_event->erst.dma; + } + + udc_event->erst.len = buff_length; + udc_event->erst.dma = mapping; + udc_event->p_erst = udc_event->erst.vaddr; + + buff_length = CRG_EVENT_RING_SIZE * sizeof(struct event_trb_s); + if (!udc_event->event_ring.vaddr) { + udc_event->event_ring.vaddr = + dma_alloc_coherent(crg_udc->dev, buff_length, + &mapping, GFP_KERNEL); + + if (!udc_event->event_ring.vaddr) { + ret = -ENOMEM; + return ret; + } + } else { + mapping = udc_event->event_ring.dma; + } + + udc_event->event_ring.len = buff_length; + udc_event->event_ring.dma = mapping; + udc_event->evt_dq_pt = udc_event->event_ring.vaddr; + + udc_event->evt_seg0_last_trb = + (struct event_trb_s *)(udc_event->event_ring.vaddr) + + (CRG_EVENT_RING_SIZE - 1); + + udc_event->CCS = 1; + + udc_event->p_erst->seg_addr_lo = + lower_32_bits(udc_event->event_ring.dma); + udc_event->p_erst->seg_addr_hi = + upper_32_bits(udc_event->event_ring.dma); + udc_event->p_erst->seg_size = cpu_to_le32(CRG_EVENT_RING_SIZE); + udc_event->p_erst->rsvd = 0; + /* Ensure that event ring is updated */ + wmb(); + /*clear the event ring, to avoid hw unexpected ops + *because of dirty data + */ + memset(udc_event->event_ring.vaddr, 0, buff_length); + + /*hw related ops ERSTBA && ERSTSZ && ERDP*/ + /* Ensure that event ring is clear */ + wmb(); + + /**************************/ + writel(CRG_ERST_SIZE, &uicr->erstsz); + writel(lower_32_bits(udc_event->erst.dma), &uicr->erstbalo); + writel(upper_32_bits(udc_event->erst.dma), &uicr->erstbahi); + writel(lower_32_bits(udc_event->event_ring.dma) | CRG_U3DC_ERDPLO_EHB, + &uicr->erdplo); + writel(upper_32_bits(udc_event->event_ring.dma), &uicr->erdphi); + + writel((CRG_U3DC_IMAN_INT_EN | CRG_U3DC_IMAN_INT_PEND), &uicr->iman); + writel((0L << 0) | (4000L << 0), &uicr->imod); + + return 0; +} + +static int init_device_context(struct crg_gadget_dev *crg_udc) +{ + struct crg_uccr *uccr = crg_udc->uccr; + int ret; + u32 buff_length; + dma_addr_t mapping; + + /*ep0 is not included in ep contexts in crg udc*/ + buff_length = (CRG_NUM_EP_CX - 2) * sizeof(struct ep_cx_s); + + if (!crg_udc->ep_cx.vaddr) { + crg_udc->ep_cx.vaddr = + dma_alloc_coherent(crg_udc->dev, buff_length, + &mapping, GFP_KERNEL); + /* Ensure that ep_cx.vaddr is updated */ + wmb(); + if (!crg_udc->ep_cx.vaddr) { + ret = -ENOMEM; + return ret; + } + } else { + mapping = crg_udc->ep_cx.dma; + } + + crg_udc->p_epcx = crg_udc->ep_cx.vaddr; + crg_udc->ep_cx.len = buff_length; + crg_udc->ep_cx.dma = mapping; + + /*hw ops DCBAPLO DCBAPHI*/ + writel(lower_32_bits(crg_udc->ep_cx.dma), &uccr->dcbaplo); + writel(upper_32_bits(crg_udc->ep_cx.dma), &uccr->dcbaphi); + + dev_dbg(crg_udc->dev, "dcbaplo[0x%p]=0x%x\n", &uccr->dcbaplo, readl(&uccr->dcbaplo)); + dev_dbg(crg_udc->dev, "dcbaphi[0x%p]=0x%x\n", &uccr->dcbaphi, readl(&uccr->dcbaphi)); + + return 0; +} + +static int reset_data_struct(struct crg_gadget_dev *crg_udc) +{ + u32 tmp; + int i; + struct crg_uccr *uccr = crg_udc->uccr; + u32 val; + + val = readl(&uccr->control); + val &= (~(CRG_U3DC_CTRL_INT_EN | CRG_U3DC_CTRL_RUN)); + writel(val, &uccr->control); + + dev_dbg(crg_udc->dev, "capability[0x%p]=0x%x\n", &uccr->capability, + readl(&uccr->capability)); + + switch (crg_udc->gadget.max_speed) { + case USB_SPEED_FULL: + tmp = CRG_U3DC_CFG0_MAXSPEED_FS; + break; + case USB_SPEED_HIGH: + tmp = CRG_U3DC_CFG0_MAXSPEED_HS; + break; + case USB_SPEED_SUPER: + tmp = CRG_U3DC_CFG0_MAXSPEED_SS; + break; + case USB_SPEED_SUPER_PLUS: + tmp = CRG_U3DC_CFG0_MAXSPEED_SSP; + break; + case USB_SPEED_UNKNOWN: + default: + return -EINVAL; + } + writel(tmp, &uccr->config0); + + for (i = 0; i < CRG_RING_NUM; i++) + init_event_ring(crg_udc, i); + + init_device_context(crg_udc); + + if (!crg_udc->status_req) { + crg_udc->status_req = + container_of(crg_udc_alloc_request(&crg_udc->udc_ep[0].usb_ep, + GFP_ATOMIC), struct crg_udc_request, + usb_req); + } + + /*other hw ops*/ + return 0; +} + +static int init_ep0(struct crg_gadget_dev *crg_udc) +{ + struct crg_udc_ep *udc_ep_ptr = &crg_udc->udc_ep[0]; + u32 cmd_param0; + u32 cmd_param1; + + /* setup transfer ring */ + if (!udc_ep_ptr->tran_ring_info.vaddr) { + dma_addr_t dma; + u32 ring_size = CRGUDC_CONTROL_EP_TD_RING_SIZE; + void *vaddr; + size_t len; + + len = ring_size * sizeof(struct transfer_trb_s); + vaddr = dma_alloc_coherent(crg_udc->dev, len, + &dma, GFP_KERNEL); + if (!vaddr) + return -ENOMEM; + + udc_ep_ptr->tran_ring_info.vaddr = vaddr; + udc_ep_ptr->tran_ring_info.dma = dma; + udc_ep_ptr->tran_ring_info.len = len; + udc_ep_ptr->first_trb = vaddr; + udc_ep_ptr->last_trb = udc_ep_ptr->first_trb + ring_size - 1; + } + + memset(udc_ep_ptr->first_trb, 0, udc_ep_ptr->tran_ring_info.len); + /* Ensure that transfer ring is updated */ + wmb(); + udc_ep_ptr->enq_pt = udc_ep_ptr->first_trb; + udc_ep_ptr->deq_pt = udc_ep_ptr->first_trb; + udc_ep_ptr->pcs = 1; + udc_ep_ptr->tran_ring_full = false; + + setup_link_trb(udc_ep_ptr->last_trb, + true, udc_ep_ptr->tran_ring_info.dma); + + /*context related ops*/ + cmd_param0 = (lower_32_bits(udc_ep_ptr->tran_ring_info.dma) & + CRG_CMD0_0_DQPTRLO_MASK) | + CRG_CMD0_0_DCS(udc_ep_ptr->pcs); + cmd_param1 = upper_32_bits(udc_ep_ptr->tran_ring_info.dma); + + dev_dbg(crg_udc->dev, "ep0 ring dma addr = 0x%llx\n", udc_ep_ptr->tran_ring_info.dma); + + dev_dbg(crg_udc->dev, "ep0 ring vaddr = 0x%p\n", udc_ep_ptr->tran_ring_info.vaddr); + + dev_dbg(crg_udc->dev, "INIT EP0 CMD, par0=0x%x, par1=0x%x\n", cmd_param0, cmd_param1); + + crg_issue_command(crg_udc, CRG_CMD_INIT_EP0, cmd_param0, cmd_param1); + + udc_ep_ptr->ep_state = EP_STATE_RUNNING; + + return 0; +} + +static int EP0_Start(struct crg_gadget_dev *crg_udc) +{ + crg_udc->udc_ep[0].desc = &crg_udc_ep0_desc; + + return 0; +} + +static void crg_udc_start(struct crg_gadget_dev *crg_udc) +{ + struct crg_uccr *uccr; + u32 val; + + uccr = crg_udc->uccr; + + /*****interrupt related*****/ + val = readl(&uccr->config1); + val |= (CRG_U3DC_CFG1_CSC_EVENT_EN | + CRG_U3DC_CFG1_PEC_EVENT_EN | + CRG_U3DC_CFG1_PPC_EVENT_EN | + CRG_U3DC_CFG1_PRC_EVENT_EN | + CRG_U3DC_CFG1_PLC_EVENT_EN | + CRG_U3DC_CFG1_CEC_EVENT_EN); + writel(val, &uccr->config1); + dev_dbg(crg_udc->dev, "config1[0x%p]=0x%x\n", &uccr->config1, readl(&uccr->config1)); + dev_dbg(crg_udc->dev, "config0[0x%p]=0x%x\n", &uccr->config0, readl(&uccr->config0)); + + val = readl(&uccr->control); + val |= (CRG_U3DC_CTRL_SYSERR_EN | + CRG_U3DC_CTRL_INT_EN); + writel(val, &uccr->control); + /*****interrupt related end*****/ + + val = readl(&uccr->control); + val |= CRG_U3DC_CTRL_RUN; + writel(val, &uccr->control); + dev_dbg(crg_udc->dev, "%s, control=0x%x\n", __func__, readl(&uccr->control)); +} + +static void crg_udc_clear_portpm(struct crg_gadget_dev *crg_udc) +{ + struct crg_uccr *uccr = crg_udc->uccr; + u32 tmp; + + tmp = readl(&uccr->u3portpmsc); + + tmp &= (~CRG_U3DC_U3PORTPM_U1IEN); + tmp = SETF_VAR(CRG_U3DC_U3PORTPM_U1TMOUT, tmp, 0); + tmp &= (~CRG_U3DC_U3PORTPM_U2IEN); + tmp = SETF_VAR(CRG_U3DC_U3PORTPM_U2TMOUT, tmp, 0); + + writel(tmp, &uccr->u3portpmsc); + + crg_udc->feature_u1_enable = 0; + crg_udc->feature_u2_enable = 0; +} + +static void crg_udc_reinit(struct crg_gadget_dev *crg_udc) +{ + struct crg_uccr *uccr = crg_udc->uccr; + u32 i, tmp; + unsigned long flags = 0; + struct crg_udc_ep *udc_ep_ptr; + + crg_udc->setup_status = WAIT_FOR_SETUP; + /* Base on Figure 9-1, default USB_STATE is attached */ + crg_udc->device_state = USB_STATE_RECONNECTING; + + /* halt all the endpoints */ + + dev_dbg(crg_udc->dev, "ep_enable=0x%x\n", readl(&uccr->ep_enable)); + dev_dbg(crg_udc->dev, "ep_running=0x%x\n", readl(&uccr->ep_running)); + + /* disable all the endpoints */ + tmp = readl(&uccr->ep_enable); + writel(tmp, &uccr->ep_enable); + for (i = 0; i < 50; i++) { + tmp = readl(&uccr->ep_enable); + if (tmp == 0) + break; + } + + dev_dbg(crg_udc->dev, "i=%d\n", i); + dev_dbg(crg_udc->dev, "after ep_enable=0x%x\n", readl(&uccr->ep_enable)); + + for (i = 2; i < 32; i++) { + udc_ep_ptr = &crg_udc->udc_ep[i]; + udc_ep_ptr->usb_ep.enabled = 0; + if (udc_ep_ptr->desc) + nuke(udc_ep_ptr, -ESHUTDOWN); + udc_ep_ptr->tran_ring_full = false; + udc_ep_ptr->ep_state = EP_STATE_DISABLED; + } + crg_udc->num_enabled_eps = 0; + +/* we don't handle ep0 here, we init_ep0 when event ring is empty*/ + + if (crg_udc->dev_addr != 0) { + u32 param0; + + param0 = CRG_CMD2_0_DEV_ADDR(0); + crg_issue_command(crg_udc, CRG_CMD_SET_ADDR, param0, 0); + crg_udc->dev_addr = 0; + } + + crg_udc_clear_portpm(crg_udc); + + if (crg_udc->gadget_driver) { + dev_dbg(crg_udc->dev, "calling disconnect\n"); + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + crg_udc->gadget_driver->disconnect(&crg_udc->gadget); + spin_lock_irqsave(&crg_udc->udc_lock, flags); + } +} + +static int crg_udc_reset(struct crg_gadget_dev *crg_udc) +{ + struct crg_uccr *uccr = crg_udc->uccr; + u32 i, tmp, count; + struct crg_udc_ep *udc_ep_ptr; + u32 val; + + dev_dbg(crg_udc->dev, "capability = %x\n", readl(&uccr->capability)); + + count = 0; + val = readl(&uccr->control); + val |= CRG_U3DC_CTRL_SWRST; + writel(val, &uccr->control); + do { + mdelay(10); + tmp = readl(&uccr->control); + count++; + + if (count == 50) { + dev_err(crg_udc->dev, "reset error\n"); + return -1; + } + } while ((tmp & CRG_U3DC_CTRL_SWRST) != 0); + + crg_udc_clear_portpm(crg_udc); + + crg_udc->setup_status = WAIT_FOR_SETUP; + /* Base on Figure 9-1, default USB_STATE is attached */ + crg_udc->device_state = USB_STATE_ATTACHED; + crg_udc->dev_addr = 0; + + /* Complete any reqs on EP1-EP15 queue */ + for (i = 2; i < 32; i++) { + udc_ep_ptr = &crg_udc->udc_ep[i]; + + if (udc_ep_ptr->desc) + nuke(udc_ep_ptr, -ESHUTDOWN); + udc_ep_ptr->tran_ring_full = false; + udc_ep_ptr->ep_state = EP_STATE_DISABLED; + } + crg_udc->num_enabled_eps = 0; + + /* Complete any reqs on EP0 queue */ + udc_ep_ptr = &crg_udc->udc_ep[0]; + if (udc_ep_ptr->desc) + nuke(udc_ep_ptr, -ESHUTDOWN); + + crg_udc->ctrl_req_enq_idx = 0; + memset(crg_udc->ctrl_req_queue, 0, + sizeof(struct crg_setup_packet) * CTRL_REQ_QUEUE_DEPTH); + + return 0; +} + +/************controller related ops*******************************/ +#define gadget_to_udc(g) (container_of(g, struct crg_gadget_dev, gadget)) +int g_dnl_board_usb_cable_connected(struct crg_gadget_dev *crg_udc); + +static int crg_gadget_pullup(struct usb_gadget *g, int is_on) +{ + struct crg_gadget_dev *crg_udc; + + /* No need to call g_dnl_board_usb_cable_connected upon stop + * controller or pull down D- event. + */ + if (is_on) { + crg_udc = gadget_to_udc(g); + g_dnl_board_usb_cable_connected(crg_udc); + } + return 0; +} + +static int crg_vbus_detect_thread(void *data); + +static void crg_vbus_detect(struct crg_gadget_dev *crg_udc, int enable) +{ + if (enable) { + if (crg_udc->vbus_task) { + dev_err(crg_udc->dev, + "vbus task already run, wake up vbus_wait\n"); + wake_up_interruptible(&vbus_wait); + return; + } + /* Enable the VBUS */ + writel((readl(crg_udc->mmio_virt_base + + CRG_UDC_VENDOR_REG) | + CRG_UDC_VBUS_DETECT), + crg_udc->mmio_virt_base + CRG_UDC_VENDOR_REG); + crg_udc->vbus_task = kthread_run(crg_vbus_detect_thread, + (void *)crg_udc, + "corigine_vbus_thread"); + if (IS_ERR(crg_udc->vbus_task)) { + dev_err(crg_udc->dev, + "Unable to create corigine_vbus_thread.\n"); + crg_udc->vbus_task = NULL; + return; + } + } else { + if (crg_udc->vbus_task) { + /* Disable VBUS to stop controller */ + writel((readl(crg_udc->mmio_virt_base + + CRG_UDC_VENDOR_REG) & + ~(CRG_UDC_VBUS_DETECT)), + crg_udc->mmio_virt_base + CRG_UDC_VENDOR_REG); + wake_up_interruptible(&vbus_wait); + kthread_stop(crg_udc->vbus_task); + crg_udc->vbus_task = NULL; + return; + } + } +} + +static int crg_gadget_start(struct usb_gadget *g, + struct usb_gadget_driver *driver) +{ + struct crg_gadget_dev *crg_udc; + + crg_udc = gadget_to_udc(g); + crg_udc->gadget_driver = driver; + + dev_dbg(crg_udc->dev, "%s %d gadget speed=%d, max speed=%d\n", + __func__, __LINE__, g->speed, g->max_speed); + dev_dbg(crg_udc->dev, "%s %d driver speed=%d\n", + __func__, __LINE__, driver->max_speed); + crg_vbus_detect(crg_udc, 1); + return 0; +} + +static int crg_gadget_stop(struct usb_gadget *g) +{ + struct crg_gadget_dev *crg_udc; + unsigned long flags = 0; + + crg_udc = gadget_to_udc(g); + + crg_udc->device_state = USB_STATE_ATTACHED; + crg_vbus_detect(crg_udc, 0); + + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + crg_udc_reset(crg_udc); + + reset_data_struct(crg_udc); + crg_udc->connected = 0; + crg_udc->gadget_driver = NULL; + crg_udc->gadget.speed = USB_SPEED_UNKNOWN; + + init_ep0(crg_udc); + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + + return 0; +} + +static const struct usb_gadget_ops crg_gadget_ops = { + .pullup = crg_gadget_pullup, + .udc_start = crg_gadget_start, + .udc_stop = crg_gadget_stop, +}; + +static int init_ep_info(struct crg_gadget_dev *crg_udc) +{ + int i; + + /*udc_ep[0] is reserved, */ + crg_ep_struct_setup(crg_udc, 0, NULL); + + for (i = 1; i < CRG_NUM_EP_CX / 2; i++) { + char name[14]; + + sprintf(name, "ep%din", i); + crg_ep_struct_setup(crg_udc, i * 2, name); + sprintf(name, "ep%dout", i); + crg_ep_struct_setup(crg_udc, i * 2 + 1, name); + } + + return 0; +} + +static void queue_setup_pkt(struct crg_gadget_dev *crg_udc, + struct usb_ctrlrequest *setup_pkt, + u16 setup_tag) +{ + if (crg_udc->ctrl_req_enq_idx == CTRL_REQ_QUEUE_DEPTH) { + dev_err(crg_udc->dev, "ctrl request queque is full\n"); + return; + } + + memcpy(&crg_udc->ctrl_req_queue[crg_udc->ctrl_req_enq_idx].usbctrlreq, + setup_pkt, sizeof(struct usb_ctrlrequest)); + crg_udc->ctrl_req_queue[crg_udc->ctrl_req_enq_idx].setup_tag = + setup_tag; + + crg_udc->ctrl_req_enq_idx++; +} + +static inline u32 index2DCI(u16 index) +{ + if (index == 0) + return 0; + + return (index & USB_ENDPOINT_NUMBER_MASK) * 2 + ((index & + USB_DIR_IN) ? 0 : 1); +} + +static void get_status_cmpl(struct usb_ep *ep, struct usb_request *req) +{ + kfree(req->buf); +} + +static void getstatusrequest(struct crg_gadget_dev *crg_udc, + u8 RequestType, u16 value, u16 index, u16 length) +{ + u32 status_val = 0; + u32 status = -EINPROGRESS; + struct crg_udc_ep *udc_ep_ptr; + struct crg_udc_request *udc_req_ptr = crg_udc->status_req; + + if (!udc_req_ptr) + return; + udc_req_ptr->usb_req.buf = kzalloc(sizeof(u16), GFP_ATOMIC); + dev_dbg(crg_udc->dev, "udc_req_ptr->usb_req.buf = 0x%p\n", udc_req_ptr->usb_req.buf); + if (!udc_req_ptr->usb_req.buf) + return; + + if (value || length > 2 || !length) { + status = -EINVAL; + goto get_status_error; + } + + dev_dbg(crg_udc->dev, "Get status request RequestType = 0x%x Index=%x\n", + RequestType, index); + if ((RequestType & USB_RECIP_MASK) == USB_RECIP_DEVICE) { + dev_dbg(crg_udc->dev, "Get status request Device request\n"); + if (index) { + status = -EINVAL; + goto get_status_error; + } + + if (crg_udc->gadget.speed == USB_SPEED_HIGH || + crg_udc->gadget.speed == USB_SPEED_FULL) { + if (crg_udc->u2_RWE) + status_val |= BIT(USB_DEVICE_REMOTE_WAKEUP); + } + + if (crg_udc->gadget.speed >= USB_SPEED_SUPER) { + if (crg_udc->feature_u1_enable) + status_val |= BIT(USB_DEV_STAT_U1_ENABLED); + if (crg_udc->feature_u2_enable) + status_val |= BIT(USB_DEV_STAT_U2_ENABLED); + } + + status_val |= USB_DEVICE_SELF_POWERED; + dev_dbg(crg_udc->dev, "Status = 0x%x\n", status_val); + + } else if ((RequestType & USB_RECIP_MASK) == USB_RECIP_INTERFACE) { + dev_dbg(crg_udc->dev, "Get status request Interface request\n"); + status_val = 0; + } else if ((RequestType & USB_RECIP_MASK) == USB_RECIP_ENDPOINT) { + u32 DCI; + + DCI = index2DCI(index); + + dev_dbg(crg_udc->dev, "Get status request endpoint request DCI = %d\n", DCI); + + if (DCI == 1) { + status_val = 0; + dev_dbg(crg_udc->dev, "Get status request INVALID! DCI = %d\n", DCI); + goto get_status_error; + } + /* if device state is address state, index should be 0 + * if device state is configured state, index should be an + * endpoint configured. + */ + + dev_dbg(crg_udc->dev, "crg_udc->device_state = %d\n", crg_udc->device_state); + if (crg_udc->device_state == USB_STATE_ADDRESS && DCI != 0) { + status = -EINVAL; + goto get_status_error; + } + + if (crg_udc->device_state == USB_STATE_CONFIGURED) { + if (get_ep_state(crg_udc, DCI) == EP_STATE_DISABLED) { + status = -EINVAL; + goto get_status_error; + } + + if (get_ep_state(crg_udc, DCI) == EP_STATE_HALTED) { + status_val = BIT(USB_ENDPOINT_HALT); + dev_dbg(crg_udc->dev, "endpoint was halted = 0x%lx\n", + (unsigned long)status_val); + } + } + } + +get_status_error: + if (status != -EINPROGRESS) { + udc_req_ptr->usb_req.length = 0; + } else { + *(u16 *)udc_req_ptr->usb_req.buf = cpu_to_le16(status_val); + dev_dbg(crg_udc->dev, "usb_req.buf = 0x%x\n", + *((u16 *)udc_req_ptr->usb_req.buf)); + + dev_dbg(crg_udc->dev, "usb_req.buf addr = 0x%p\n", + (udc_req_ptr->usb_req.buf)); + + udc_req_ptr->usb_req.length = 2; + } + udc_req_ptr->usb_req.status = status; + udc_req_ptr->usb_req.actual = 0; + udc_req_ptr->usb_req.complete = get_status_cmpl; + + if (udc_req_ptr->usb_req.dma == DMA_ADDR_INVALID) { + udc_req_ptr->usb_req.dma = + dma_map_single(crg_udc->dev, udc_req_ptr->usb_req.buf, + udc_req_ptr->usb_req.length, + DMA_FROM_DEVICE); + udc_req_ptr->mapped = 1; + } + dev_dbg(crg_udc->dev, "status_val = 0x%x, cpu_to_le16(status_val) = 0x%x\n", + status_val, cpu_to_le16(status_val)); + dev_dbg(crg_udc->dev, "udc_req_ptr->usb_req.buf = 0x%p, value = 0x%x\n", + udc_req_ptr->usb_req.buf, *(u16 *)(udc_req_ptr->usb_req.buf)); + dev_dbg(crg_udc->dev, "udc_req_ptr->usb_req.dma = 0x%llx\n", + udc_req_ptr->usb_req.dma); + + udc_ep_ptr = &crg_udc->udc_ep[0]; + + crg_udc->setup_status = DATA_STAGE_XFER; + status = crg_udc_build_td(udc_ep_ptr, udc_req_ptr); + + dev_dbg(crg_udc->dev, "getstatus databuf eqpt = 0x%p\n", udc_ep_ptr->enq_pt); + + if (!status) + list_add_tail(&udc_req_ptr->queue, &udc_ep_ptr->queue); +} + +static void set_address_cmpl(struct crg_gadget_dev *crg_udc) +{ + if (crg_udc->device_state == USB_STATE_DEFAULT && + crg_udc->dev_addr != 0) { + crg_udc->device_state = USB_STATE_ADDRESS; + dev_dbg(crg_udc->dev, "USB State Addressed\n"); + + } else if (crg_udc->device_state == USB_STATE_ADDRESS) { + if (crg_udc->dev_addr == 0) + crg_udc->device_state = USB_STATE_DEFAULT; + } +} + +static void setaddressrequest(struct crg_gadget_dev *crg_udc, + u16 value, u16 index, u16 length) +{ + int status = -EINPROGRESS; + u8 status_set_addr = 0; + + if (value > 127 || index != 0 || length != 0) { + status = -EINVAL; + goto set_address_error; + } + + if ((crg_udc->device_state == USB_STATE_DEFAULT && value != 0) || + crg_udc->device_state == USB_STATE_ADDRESS) { + u32 param0; + + crg_udc->dev_addr = value; + + param0 = CRG_CMD2_0_DEV_ADDR(value); + crg_issue_command(crg_udc, CRG_CMD_SET_ADDR, param0, 0); + status_set_addr = 1; + } else { + status = -EINVAL; + } + +set_address_error: + dev_dbg(crg_udc->dev, "build_ep0_status for Address Device\n"); + + crg_udc->setup_status = STATUS_STAGE_XFER; + crg_udc->setup_fn_call_back = &set_address_cmpl; + build_ep0_status(&crg_udc->udc_ep[0], + true, status, NULL, status_set_addr, 0); +} + +static void set_sel_cmpl(struct usb_ep *ep, struct usb_request *req) +{ + struct crg_udc_ep *udc_ep; + struct crg_gadget_dev *crg_udc; + struct sel_value_s *sel_value; + + udc_ep = container_of(ep, struct crg_udc_ep, usb_ep); + crg_udc = udc_ep->crg_udc; + + if (req->buf) { + sel_value = req->buf; + crg_udc->sel_value.u2_pel_value = sel_value->u2_pel_value; + crg_udc->sel_value.u2_sel_value = sel_value->u2_sel_value; + crg_udc->sel_value.u1_pel_value = sel_value->u1_pel_value; + crg_udc->sel_value.u1_sel_value = sel_value->u1_sel_value; + + kfree(req->buf); + } + + dev_dbg(crg_udc->dev, "u1_sel_value = 0x%x, u2_sel_value = 0x%x\n", + crg_udc->sel_value.u1_sel_value, + crg_udc->sel_value.u2_sel_value); +} + +static void setselrequest(struct crg_gadget_dev *crg_udc, + u16 value, u16 index, u16 length, u64 data) +{ + int status = -EINPROGRESS; + struct crg_udc_request *udc_req_ptr = crg_udc->status_req; + struct crg_udc_ep *udc_ep_ptr = &crg_udc->udc_ep[0]; + + if (!udc_req_ptr) + return; + + if (crg_udc->device_state == USB_STATE_DEFAULT) + status = -EINVAL; + + if (index != 0 || value != 0 || length != 6) + status = -EINVAL; + + if (status != -EINPROGRESS) { + } else { + udc_req_ptr->usb_req.length = length; + udc_req_ptr->usb_req.buf = + kzalloc(sizeof(*udc_req_ptr->usb_req.buf), GFP_ATOMIC); + } + + udc_req_ptr->usb_req.status = -EINPROGRESS; + udc_req_ptr->usb_req.actual = 0; + udc_req_ptr->usb_req.complete = set_sel_cmpl; + + if (udc_req_ptr->usb_req.dma == DMA_ADDR_INVALID) { + udc_req_ptr->usb_req.dma = + dma_map_single(crg_udc->dev, udc_req_ptr->usb_req.buf, + udc_req_ptr->usb_req.length, + DMA_TO_DEVICE); + udc_req_ptr->mapped = 1; + } + + status = crg_udc_build_td(udc_ep_ptr, udc_req_ptr); + + if (!status) + list_add_tail(&udc_req_ptr->queue, &udc_ep_ptr->queue); +} + +static void set_test_mode_cmpl(struct crg_gadget_dev *crg_udc) +{ + if (crg_udc->set_tm != 0) { + u32 tmp; + struct crg_uccr *uccr = crg_udc->uccr; + + tmp = readl(&uccr->u2portpmsc); + tmp = SETF_VAR(CRG_U3DC_U2PORTPM_TM, tmp, crg_udc->set_tm); + writel(tmp, &uccr->u2portpmsc); + + crg_udc->set_tm = 0; + } +} + +static bool setfeaturesrequest(struct crg_gadget_dev *crg_udc, + u8 RequestType, u8 bRequest, u16 value, u16 index, u16 length) +{ + int status = -EINPROGRESS; + u8 DCI; + struct crg_udc_ep *udc_ep_ptr; + u32 tmp; + bool set_feat = 0; + struct crg_uccr *uccr = crg_udc->uccr; + + if (length != 0) { + status = -EINVAL; + goto set_feature_error; + } + + if (crg_udc->device_state == USB_STATE_DEFAULT) { + status = -EINVAL; + goto set_feature_error; + } + + set_feat = (bRequest == USB_REQ_SET_FEATURE) ? 1 : 0; + if ((RequestType & (USB_RECIP_MASK | USB_TYPE_MASK)) == + (USB_RECIP_ENDPOINT | USB_TYPE_STANDARD)) { + dev_dbg(crg_udc->dev, "Halt/Unhalt EP\n"); + if (crg_udc->device_state == USB_STATE_ADDRESS) { + if (index != 0) { + status = -EINVAL; + goto set_feature_error; + } + } + + DCI = index2DCI(index); + + if (DCI == 1) { + dev_dbg(crg_udc->dev, "setfeat INVALID DCI = 0x%x !!\n", DCI); + goto set_feature_error; + } + + udc_ep_ptr = &crg_udc->udc_ep[DCI]; + dev_dbg(crg_udc->dev, "halt/Unhalt endpoint DCI = 0x%x\n", DCI); + + status = ep_halt(udc_ep_ptr, + (bRequest == USB_REQ_SET_FEATURE) ? 1 : 0, + 0); + + if (status < 0) + goto set_feature_error; + } else if ((RequestType & (USB_RECIP_MASK | USB_TYPE_MASK)) == + (USB_RECIP_DEVICE | USB_TYPE_STANDARD)) { + switch (value) { + case USB_DEVICE_REMOTE_WAKEUP: + dev_dbg(crg_udc->dev, "USB_DEVICE_REMOTE_WAKEUP called\n"); + /* REMOTE_WAKEUP selector is not used by USB3.0 */ + if (crg_udc->device_state < USB_STATE_DEFAULT || + crg_udc->gadget.speed >= USB_SPEED_SUPER) { + status = -EINVAL; + goto set_feature_error; + } + dev_dbg(crg_udc->dev, "%s_Feature RemoteWake\n", + set_feat ? "Set" : "Clear"); + + /*TODO corigine hardware ops needed*/ + crg_udc->u2_RWE = set_feat; + + break; + case USB_DEVICE_U1_ENABLE: + case USB_DEVICE_U2_ENABLE: + { + u32 timeout_val; + + dev_dbg(crg_udc->dev, "USB_DEVICE_U12_ENABLE called\n"); + if (crg_udc->device_state != USB_STATE_CONFIGURED) { + dev_err(crg_udc->dev, "%s u12 enable fail, usb state=%d\n", + __func__, crg_udc->device_state); + status = -EINVAL; + goto set_feature_error; + } + + if (index & 0xff) { + status = -EINVAL; + goto set_feature_error; + } + + if (set_feat == 1 && U12_FORBIDDEN > 0) { + status = -EINVAL; + goto set_feature_error; + } + + tmp = readl(&uccr->u3portpmsc); + /*TODO corigine hardware ops needed*/ + if (value == USB_DEVICE_U1_ENABLE) { +#if (U12_INITIATE_FORBIDDEN == 0) + tmp &= (~CRG_U3DC_U3PORTPM_U1IEN); + tmp |= (set_feat << + CRG_U3DC_U3PORTPM_U1IEN_SHIFT); +#endif + if (U12_FORBIDDEN == 0) + timeout_val = set_feat ? + U1_TIMEOUT_VAL : 0; + else + timeout_val = 0; + + tmp = SETF_VAR(CRG_U3DC_U3PORTPM_U1TMOUT, + tmp, timeout_val); + + crg_udc->feature_u1_enable = set_feat; + } + + if (value == USB_DEVICE_U2_ENABLE) { +#if (U12_INITIATE_FORBIDDEN == 0) + tmp &= (~CRG_U3DC_U3PORTPM_U2IEN); + tmp |= (set_feat << + CRG_U3DC_U3PORTPM_U2IEN_SHIFT); +#endif + if (U12_FORBIDDEN == 0) + timeout_val = set_feat ? U1_TIMEOUT_VAL : 0; + else + timeout_val = 0; + + tmp = SETF_VAR(CRG_U3DC_U3PORTPM_U2TMOUT, + tmp, timeout_val); + + crg_udc->feature_u2_enable = set_feat; + } + writel(tmp, &uccr->u3portpmsc); + + break; + } + case USB_DEVICE_TEST_MODE: + { + u32 u_pattern; + + dev_dbg(crg_udc->dev, "USB_DEVICE_TEST_MODE called\n"); + if (crg_udc->gadget.speed > USB_SPEED_HIGH) + goto set_feature_error; + + if (crg_udc->device_state < USB_STATE_DEFAULT) + goto set_feature_error; + + u_pattern = index >> 8; + /* TESTMODE is only defined for high speed device */ + if (crg_udc->gadget.speed == USB_SPEED_HIGH) { + dev_dbg(crg_udc->dev, "high speed test mode enter\n"); + crg_udc->set_tm = u_pattern; + crg_udc->setup_fn_call_back = + &set_test_mode_cmpl; + } + break; + } + + default: + goto set_feature_error; + } + + } else if ((RequestType & (USB_RECIP_MASK | USB_TYPE_MASK)) == + (USB_RECIP_INTERFACE | USB_TYPE_STANDARD)) { + if (crg_udc->device_state != USB_STATE_CONFIGURED) { + dev_err(crg_udc->dev, "%s interface u12 enable fail, usb state=%d\n", + __func__, crg_udc->device_state); + status = -EINVAL; + goto set_feature_error; + } + + /* Suspend Option */ + if (value == USB_INTRF_FUNC_SUSPEND) { + if (index & USB_INTR_FUNC_SUSPEND_OPT_MASK & + USB_INTRF_FUNC_SUSPEND_LP) { + if (index & USB_INTRF_FUNC_SUSPEND_RW) + dev_dbg(crg_udc->dev, "Interface En Remote Wakeup\n"); + else + dev_dbg(crg_udc->dev, "Interface Dis RemoteWakeup\n"); + + /* Do not need to return status stage here + * Pass to composite gadget driver to process + * the request + */ + return false; + } + } + } + + crg_udc->setup_status = STATUS_STAGE_XFER; + build_ep0_status(&crg_udc->udc_ep[0], true, status, NULL, 0, 0); + return true; + +set_feature_error: + set_ep0_halt(crg_udc); + return true; +} + +static bool setconfigurationrequest(struct crg_gadget_dev *crg_udc, u16 value) +{ + if (crg_udc->device_state <= USB_STATE_DEFAULT) + goto set_config_error; + + /*return false means need further process by composite gadget driver*/ + return false; + +set_config_error: + set_ep0_halt(crg_udc); + return true; +} + +static void set_isoch_delay(struct crg_gadget_dev *crg_udc, + u16 value, u16 index, u16 length) +{ + int status = -EINPROGRESS; + + if (value > 65535 || index != 0 || length != 0) + status = -EINVAL; + + /*need further ops for isoch delay*/ + + crg_udc->setup_status = STATUS_STAGE_XFER; + build_ep0_status(&crg_udc->udc_ep[0], true, status, NULL, 0, 0); +} + +static void crg_handle_setup_pkt(struct crg_gadget_dev *crg_udc, + struct usb_ctrlrequest *setup_pkt, u8 setup_tag) +{ + u16 wValue = setup_pkt->wValue; + u16 wIndex = setup_pkt->wIndex; + u16 wLength = setup_pkt->wLength; + u64 wData = 0; + unsigned long flags = 0; + + dev_dbg(crg_udc->dev, "bRequest=0x%x, wValue=0x%.4x, wIndex=0x%x, wLength=%d\n", + setup_pkt->bRequest, wValue, wIndex, wLength); + + /* EP0 come backs to running when new setup packet comes*/ + crg_udc->udc_ep[0].ep_state = EP_STATE_RUNNING; + + crg_udc->setup_tag = setup_tag; + crg_udc->setup_status = SETUP_PKT_PROCESS_IN_PROGRESS; + crg_udc->setup_fn_call_back = NULL; + + if ((setup_pkt->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) { + switch (setup_pkt->bRequest) { + case USB_REQ_GET_STATUS: + dev_dbg(crg_udc->dev, "USB_REQ_GET_STATUS\n"); + if ((setup_pkt->bRequestType & (USB_DIR_IN | + USB_TYPE_MASK)) + != (USB_DIR_IN | USB_TYPE_STANDARD)) { + crg_udc->setup_status = WAIT_FOR_SETUP; + return; + } + + getstatusrequest(crg_udc, setup_pkt->bRequestType, + wValue, wIndex, wLength); + return; + case USB_REQ_SET_ADDRESS: + dev_dbg(crg_udc->dev, "USB_REQ_SET_ADDRESS\n"); + if (setup_pkt->bRequestType != (USB_DIR_OUT | + USB_RECIP_DEVICE | + USB_TYPE_STANDARD)) { + crg_udc->setup_status = WAIT_FOR_SETUP; + return; + } + + setaddressrequest(crg_udc, wValue, wIndex, wLength); + return; + case USB_REQ_SET_SEL: + dev_dbg(crg_udc->dev, "USB_REQ_SET_SEL\n"); + + if (setup_pkt->bRequestType != (USB_DIR_OUT | + USB_RECIP_DEVICE | + USB_TYPE_STANDARD)) { + crg_udc->setup_status = WAIT_FOR_SETUP; + return; + } + + crg_udc->setup_status = DATA_STAGE_RECV; + setselrequest(crg_udc, wValue, wIndex, wLength, wData); + return; + case USB_REQ_SET_ISOCH_DELAY: + if (setup_pkt->bRequestType != (USB_DIR_OUT | + USB_RECIP_DEVICE | + USB_TYPE_STANDARD)) + break; + + dev_dbg(crg_udc->dev, "USB_REQ_SET_ISOCH_DELAY\n"); + set_isoch_delay(crg_udc, wValue, wIndex, wLength); + return; + + case USB_REQ_CLEAR_FEATURE: + case USB_REQ_SET_FEATURE: + dev_dbg(crg_udc->dev, "USB_REQ_CLEAR/SET_FEATURE\n"); + + /* Need composite gadget driver + * to process the function remote wakeup request + */ + if (setfeaturesrequest(crg_udc, setup_pkt->bRequestType, + setup_pkt->bRequest, + wValue, wIndex, wLength)) { + /* Get here if request has been processed.*/ + return; + } + break; + case USB_REQ_SET_CONFIGURATION: + /*In theory we need to clear RUN bit before + *status stage of deconfig request sent. + *But seeing problem if we do it before all the + *endpoints belonging to the configuration + *disabled. + */ + dev_dbg(crg_udc->dev, "USB_REQ_SET_CONFIGURATION\n"); + dev_dbg(crg_udc->dev, "CONFIGURATION wValue=%d\n", wValue); + + if (setconfigurationrequest(crg_udc, wValue)) { + /* Get here if request has been processed. + * Or error happens + */ + return; + } + + if (crg_udc->device_state == USB_STATE_ADDRESS) + crg_udc->device_state = USB_STATE_CONFIGURED; + dev_dbg(crg_udc->dev, "USB_REQ_SET_CONFIGURATION: device_state is %d\n", + crg_udc->device_state); + break; + default: + dev_dbg(crg_udc->dev, "USB_REQ default bRequest=%d, bRequestType=%d\n", + setup_pkt->bRequest, setup_pkt->bRequestType); + } + } + + if (wLength) { + /* data phase from gadget like GET_CONFIGURATION + * call the setup routine of gadget driver. + * remember the request direction. + */ + crg_udc->setup_status = + (setup_pkt->bRequestType & USB_DIR_IN) ? + DATA_STAGE_XFER : DATA_STAGE_RECV; + } + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + if (crg_udc->gadget_driver->setup(&crg_udc->gadget, setup_pkt) < 0) { + spin_lock_irqsave(&crg_udc->udc_lock, flags); + set_ep0_halt(crg_udc); + return; + } + spin_lock_irqsave(&crg_udc->udc_lock, flags); +} + +static int crg_handle_xfer_event(struct crg_gadget_dev *crg_udc, + struct event_trb_s *event) +{ + u8 DCI = GETF(EVE_TRB_ENDPOINT_ID, event->dw3); + struct crg_udc_ep *udc_ep_ptr = &crg_udc->udc_ep[DCI]; + /*Corigine ep contexts start from ep1*/ + u16 comp_code; + struct crg_udc_request *udc_req_ptr; + bool trbs_dequeued = false; + + if (!udc_ep_ptr->first_trb || + get_ep_state(crg_udc, DCI) == EP_STATE_DISABLED) + return -ENODEV; + + comp_code = GETF(EVE_TRB_COMPL_CODE, event->dw2); + if (comp_code == CMPL_CODE_STOPPED || + comp_code == CMPL_CODE_STOPPED_LENGTH_INVALID || + comp_code == CMPL_CODE_DISABLED || + comp_code == CMPL_CODE_DISABLED_LENGTH_INVALID || + comp_code == CMPL_CODE_HALTED || + comp_code == CMPL_CODE_HALTED_LENGTH_INVALID) { + dev_dbg(crg_udc->dev, "comp_code = %d(STOPPED/HALTED/DISABLED)\n", comp_code); + } else { + update_dequeue_pt(event, udc_ep_ptr); + } + + dev_dbg(crg_udc->dev, "%s ep%d dqpt=0x%p, eqpt=0x%p\n", __func__, + DCI, udc_ep_ptr->deq_pt, udc_ep_ptr->enq_pt); + dev_dbg(crg_udc->dev, "comp_code = %d\n", comp_code); + + if (is_request_dequeued(crg_udc, udc_ep_ptr, event)) { + trbs_dequeued = true; + dev_dbg(crg_udc->dev, "WARNING: Drop the transfer event\n"); + goto queue_more_trbs; + } + + comp_code = GETF(EVE_TRB_COMPL_CODE, event->dw2); + + switch (comp_code) { + case CMPL_CODE_SUCCESS: + { + dev_dbg(crg_udc->dev, "%s Complete SUCCESS\n", __func__); + handle_cmpl_code_success(crg_udc, event, udc_ep_ptr); + + trbs_dequeued = true; + break; + } + case CMPL_CODE_SHORT_PKT: + { + u32 trb_transfer_length; + + dev_dbg(crg_udc->dev, "handle_exfer_event CMPL_CODE_SHORT_PKT\n"); + if (usb_endpoint_dir_out(udc_ep_ptr->desc)) { + + trb_transfer_length = GETF(EVE_TRB_TRAN_LEN, + event->dw2); + udc_req_ptr = list_entry(udc_ep_ptr->queue.next, + struct crg_udc_request, queue); + + udc_req_ptr->usb_req.actual = + udc_req_ptr->usb_req.length - + trb_transfer_length; + /* Ensure that req_ptr is updated */ + wmb(); + if (udc_req_ptr->usb_req.actual != 512 && + udc_req_ptr->usb_req.actual != 31) { + u64 trb_pt; + struct transfer_trb_s *p_trb; + + dev_dbg(crg_udc->dev, "Actual Data transferred = %d\n", + udc_req_ptr->usb_req.actual); + + trb_pt = (u64)event->dw0 + + ((u64)(event->dw1) << 32); + + p_trb = tran_trb_dma_to_virt(udc_ep_ptr, trb_pt); + + dev_dbg(crg_udc->dev, "event dw0 = 0x%x\n", event->dw0); + dev_dbg(crg_udc->dev, "event dw1 = 0x%x\n", event->dw1); + dev_dbg(crg_udc->dev, "event dw2 = 0x%x\n", event->dw2); + dev_dbg(crg_udc->dev, "event dw3 = 0x%x\n", event->dw3); + + dev_dbg(crg_udc->dev, "trb_pt = 0x%lx, p_trb = 0x%p\n", + (unsigned long)trb_pt, p_trb); + + dev_dbg(crg_udc->dev, "trb dw0 = 0x%x\n", p_trb->dw0); + dev_dbg(crg_udc->dev, "trb dw1 = 0x%x\n", p_trb->dw1); + dev_dbg(crg_udc->dev, "trb dw2 = 0x%x\n", p_trb->dw2); + dev_dbg(crg_udc->dev, "trb dw3 = 0x%x\n", p_trb->dw3); + } + req_done(udc_ep_ptr, udc_req_ptr, 0); + } else { + dev_dbg(crg_udc->dev, "ep dir in\n"); + } + + trbs_dequeued = true; + + /* Advance the dequeue pointer to next TD */ + advance_dequeue_pt(udc_ep_ptr); + + break; + } + + case CMPL_CODE_PROTOCOL_STALL: + { + dev_dbg(crg_udc->dev, "%s CMPL_CODE_PROTOCOL_STALL\n", __func__); + + udc_req_ptr = list_entry(udc_ep_ptr->queue.next, + struct crg_udc_request, queue); + req_done(udc_ep_ptr, udc_req_ptr, -EINVAL); + trbs_dequeued = true; + crg_udc->setup_status = WAIT_FOR_SETUP; + advance_dequeue_pt(udc_ep_ptr); + break; + } + + case CMPL_CODE_SETUP_TAG_MISMATCH: + { + u32 enq_idx = crg_udc->ctrl_req_enq_idx; + struct usb_ctrlrequest *setup_pkt; + struct crg_setup_packet *crg_setup_pkt; + u16 setup_tag; + + dev_err(crg_udc->dev, "%s SETUP TAG MISMATCH\n", __func__); + dev_dbg(crg_udc->dev, "NOW setup tag = 0x%x\n", crg_udc->setup_tag); + + /* skip seqnum err event until last one arrives. */ + if (udc_ep_ptr->deq_pt == udc_ep_ptr->enq_pt) { + udc_req_ptr = list_entry(udc_ep_ptr->queue.next, + struct crg_udc_request, + queue); + + if (udc_req_ptr) + req_done(udc_ep_ptr, udc_req_ptr, -EINVAL); + + /* drop all the queued setup packet, only + * process the latest one. + */ + crg_udc->setup_status = WAIT_FOR_SETUP; + if (enq_idx) { + crg_setup_pkt = + &crg_udc->ctrl_req_queue[enq_idx - 1]; + setup_pkt = &crg_setup_pkt->usbctrlreq; + setup_tag = crg_setup_pkt->setup_tag; + crg_handle_setup_pkt(crg_udc, setup_pkt, + setup_tag); + /* flash the queue after the latest + * setup pkt got handled.. + */ + memset(crg_udc->ctrl_req_queue, 0, + sizeof(struct crg_setup_packet) + * CTRL_REQ_QUEUE_DEPTH); + crg_udc->ctrl_req_enq_idx = 0; + } + } else { + dev_dbg(crg_udc->dev, "setuptag mismatch skp dpt!=ept: 0x%p, 0x%p\n", + udc_ep_ptr->deq_pt, udc_ep_ptr->enq_pt); + } + + crg_udc->setup_tag_mismatch_found = 1; + dev_dbg(crg_udc->dev, "%s SETUP TAG MISMATCH END\n", __func__); + break; + } + + case CMPL_CODE_BABBLE_DETECTED_ERR: + case CMPL_CODE_INVALID_STREAM_TYPE_ERR: + case CMPL_CODE_RING_UNDERRUN: + case CMPL_CODE_RING_OVERRUN: + case CMPL_CODE_ISOCH_BUFFER_OVERRUN: + case CMPL_CODE_USB_TRANS_ERR: + case CMPL_CODE_TRB_ERR: + { + dev_err(crg_udc->dev, "XFER event err, comp_code = 0x%x\n", comp_code); + set_ep_halt(crg_udc, DCI); + break; + } + + case CMPL_CODE_STOPPED: + case CMPL_CODE_STOPPED_LENGTH_INVALID: + /* Any ep stop ops should deal with stopped trbs itselves + * Event handler didn't know whether the stopped trb should + * be discarded or continued. So we do nothing here + */ + dev_err(crg_udc->dev, "STOP, comp_code = 0x%x\n", comp_code); + break; + default: + dev_dbg(crg_udc->dev, "CRG UNKNOWN comp_code = 0x%x\n", comp_code); + dev_dbg(crg_udc->dev, "EPDCI = 0x%x\n", udc_ep_ptr->DCI); + break; + } + + dev_dbg(crg_udc->dev, "%s 2 ep%d dqpt=0x%p, eqpt=0x%p\n", __func__, + DCI, udc_ep_ptr->deq_pt, udc_ep_ptr->enq_pt); + +queue_more_trbs: + /* If there are some trbs dequeued by HW and the ring + * was full before, then schedule any pending TRB's + */ + if (trbs_dequeued && udc_ep_ptr->tran_ring_full) { + udc_ep_ptr->tran_ring_full = false; + queue_pending_trbs(udc_ep_ptr); + } + return 0; +} + +int g_dnl_board_usb_cable_connected(struct crg_gadget_dev *crg_udc) +{ + struct crg_uccr *uccr; + u32 tmp, tmp_cfg0; + static bool pp = UDC_FALSE; + static int cnt = INIT_ZERO; + + uccr = crg_udc->uccr; + crg_udc_start(crg_udc); + + if (cnt < STATE_USB_LINK_STABLE) { + tmp = readl(crg_udc->mmio_virt_base + CRG_UDC_VENDOR_REG); + writel(tmp | 1 << 26, + crg_udc->mmio_virt_base + CRG_UDC_VENDOR_REG); + + tmp = readl(&uccr->control); + tmp |= CRG_U3DC_CTRL_RUN; + dev_dbg(crg_udc->dev, "tmp1 = 0x%x\n", tmp); + writel(tmp, &uccr->control); + tmp = readl(&uccr->control); + dev_dbg(crg_udc->dev, "control = 0x%x\n", tmp); + mdelay(10); + pp = (readl(crg_udc->mmio_virt_base + + CRG_UDC_VENDOR_REG) >> 26) & 1; + tmp = readl(&uccr->control); + tmp &= ~CRG_U3DC_CTRL_RUN; + writel(tmp, &uccr->control); + tmp = readl(&uccr->control); + dev_dbg(crg_udc->dev, "control2 = 0x%x\n", tmp); + cnt++; + } else { + pp = (readl(crg_udc->mmio_virt_base + + CRG_UDC_VENDOR_REG) >> 26) & 1; + dev_dbg(crg_udc->dev, "pp = %d\n", pp); + if (pp) { + if (crg_udc->device_state < USB_STATE_POWERED) { + tmp_cfg0 = readl(&uccr->config0); + tmp_cfg0 &= (~0xf0); + tmp_cfg0 |= 0xf0; + writel(tmp_cfg0, &uccr->config0); + + mdelay(3); + crg_udc_start(crg_udc); + crg_udc->device_state = USB_STATE_POWERED; + return 1; + } else + return 1; + + } else { + cnt = 0; + return 0; + } + } + tmp = readl(&uccr->portsc); + if (tmp & CRG_U3DC_PORTSC_PP) { + mdelay(100); + tmp = readl(&uccr->portsc); + if (tmp & CRG_U3DC_PORTSC_PP) { + if (crg_udc->device_state < USB_STATE_POWERED) { + u32 tmp_cfg0; + + dev_dbg(crg_udc->dev, "%s powered, portsc[0x%p]=0x%x\n", __func__, + &uccr->portsc, tmp); + + /*set usb 3 disable count to 15*/ + tmp_cfg0 = readl(&uccr->config0); + tmp_cfg0 &= (~0xf0); + tmp_cfg0 |= 0xf0; + writel(tmp_cfg0, &uccr->config0); + + mdelay(3); + crg_udc_start(crg_udc); + + dev_dbg(crg_udc->dev, "%s device state powered\n", __func__); + crg_udc->device_state = USB_STATE_POWERED; + } + } + return 1; + } + + dev_dbg(crg_udc->dev, "%s no power, portsc[0x%p]=0x%x\n", __func__, + &uccr->portsc, tmp); + + return 0; +} + +static int crg_handle_port_status(struct crg_gadget_dev *crg_udc) +{ + struct crg_uccr *uccr = crg_udc->uccr; + u32 portsc_val; + u32 tmp; + u32 speed; + unsigned long flags = 0; + + /* handle Port Reset */ + portsc_val = readl(&uccr->portsc); + writel(portsc_val, &uccr->portsc); + + tmp = readl(&uccr->portsc); + dev_dbg(crg_udc->dev, "%s RAW,portsc[0x%p]=0x%x\n", __func__, + &uccr->portsc, portsc_val); + + if (portsc_val & CRG_U3DC_PORTSC_PRC) { + mdelay(3); + + tmp = readl(&uccr->portsc); + if (tmp & CRG_U3DC_PORTSC_PRC) { + dev_dbg(crg_udc->dev, "PRC is still set\n"); + } else if (tmp & CRG_U3DC_PORTSC_PR) { + /* first port status change event for port reset*/ + dev_dbg(crg_udc->dev, "PRC is not set, but PR is set!!!!!!!!\n"); + } else { + if (CRG_U3DC_PORTSC_PLS_GET(tmp) != 0 || + (!(tmp & CRG_U3DC_PORTSC_PED))) { + dev_dbg(crg_udc->dev, + "portsc[0x%p]=0x%x no PED\n", + &uccr->portsc, tmp); + return 0; + } + + switch (CRG_U3DC_PORTSC_SPEED_GET(tmp)) { + case CRG_U3DC_PORTSC_SPEED_SSP: + speed = USB_SPEED_SUPER_PLUS; + break; + case CRG_U3DC_PORTSC_SPEED_SS: + speed = USB_SPEED_SUPER; + break; + case CRG_U3DC_PORTSC_SPEED_HS: + speed = USB_SPEED_HIGH; + break; + + case CRG_U3DC_PORTSC_SPEED_FS: + speed = USB_SPEED_FULL; + break; + + case CRG_U3DC_PORTSC_SPEED_LS: + speed = USB_SPEED_LOW; + break; + default: + speed = USB_SPEED_UNKNOWN; + return 0; + } + + if (crg_udc->device_state >= USB_STATE_DEFAULT) + crg_udc_reinit(crg_udc); + + crg_udc->gadget.speed = speed; + dev_dbg(crg_udc->dev, "gadget speed = 0x%x\n", crg_udc->gadget.speed); + + update_ep0_maxpacketsize(crg_udc); + + crg_udc->connected = 1; + + if (crg_udc->device_state < USB_STATE_RECONNECTING) + enable_setup(crg_udc); + + dev_dbg(crg_udc->dev, "PORTSC = 0x%x\n", readl(&uccr->portsc)); + } + } + /* handle Port Reset end */ + + /* handle Port Connection Change*/ + tmp = readl(&uccr->portsc); + if ((tmp & (CRG_U3DC_PORTSC_CCS | CRG_U3DC_PORTSC_PP)) == + (CRG_U3DC_PORTSC_CCS | CRG_U3DC_PORTSC_PP)) { + dev_dbg(crg_udc->dev, "connect int checked\n"); + dev_dbg(crg_udc->dev, "portsc[0x%p]=0x%x\n", &uccr->portsc, tmp); + + if (CRG_U3DC_PORTSC_PLS_GET(tmp) != 0 || + (!(tmp & CRG_U3DC_PORTSC_PED))) + return 0; + + switch (CRG_U3DC_PORTSC_SPEED_GET(tmp)) { + case CRG_U3DC_PORTSC_SPEED_SSP: + speed = USB_SPEED_SUPER_PLUS; + break; + case CRG_U3DC_PORTSC_SPEED_SS: + speed = USB_SPEED_SUPER; + break; + case CRG_U3DC_PORTSC_SPEED_HS: + speed = USB_SPEED_HIGH; + break; + + case CRG_U3DC_PORTSC_SPEED_FS: + speed = USB_SPEED_FULL; + break; + + case CRG_U3DC_PORTSC_SPEED_LS: + default: + speed = USB_SPEED_UNKNOWN; + return 0; + } + crg_udc->gadget.speed = speed; + + update_ep0_maxpacketsize(crg_udc); + + crg_udc->connected = 1; + + if (crg_udc->device_state < USB_STATE_RECONNECTING) + enable_setup(crg_udc); + + dev_dbg(crg_udc->dev, "connect speed = %d\n", speed); + + } else if (!(tmp & CRG_U3DC_PORTSC_CCS)) { + int cable_connected; + + int ccs_drop_ignore = 0; + + if ((CRG_U3DC_PORTSC_PLS_GET(tmp) == 0x0) && + (CRG_U3DC_PORTSC_SPEED_GET(tmp) < + CRG_U3DC_PORTSC_SPEED_SS)) { + ccs_drop_ignore = 1; + dev_err(crg_udc->dev, "ccs glitch detect on HS/FS!\n"); + } + + if (!ccs_drop_ignore) + crg_udc->gadget.speed = USB_SPEED_UNKNOWN; + + mdelay(150); + cable_connected = + g_dnl_board_usb_cable_connected(crg_udc); + if (cable_connected && !ccs_drop_ignore) { + crg_udc->device_state = USB_STATE_POWERED; + dev_dbg(crg_udc->dev, "do warm reset\n"); + crg_udc_reinit(crg_udc); + crg_udc->connected = 0; + } else if (!cable_connected) { + dev_dbg(crg_udc->dev, "cable disconnected, rst controller\n"); + + crg_udc_reset(crg_udc); + if (crg_udc->gadget_driver->disconnect) { + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + crg_udc->gadget_driver->disconnect(&crg_udc->gadget); + spin_lock_irqsave(&crg_udc->udc_lock, flags); + } + + reset_data_struct(crg_udc); + crg_udc->connected = 0; + init_ep0(crg_udc); + + crg_udc->device_state = USB_STATE_ATTACHED; + + wake_up_interruptible(&vbus_wait); + return -ECONNRESET; + } + } + /* handle Port Connection Change end*/ + + if (portsc_val & CRG_U3DC_PORTSC_PLC) { + tmp = readl(&uccr->portsc); + if (CRG_U3DC_PORTSC_PLS_GET(tmp) == 0xf) { + tmp = SETF_VAR(CRG_U3DC_PORTSC_PLS, tmp, 0x0); + writel(tmp, &uccr->portsc); + dev_dbg(crg_udc->dev, "pls to 0, write portsc 0x%x\n", tmp); + } else if (CRG_U3DC_PORTSC_PLS_GET(tmp) == 0x3) { + if (crg_udc->gadget_driver->disconnect) { + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + crg_udc->gadget_driver->disconnect(&crg_udc->gadget); + spin_lock_irqsave(&crg_udc->udc_lock, flags); + } + } + } + + return 0; +} + +static int crg_udc_handle_event(struct crg_gadget_dev *crg_udc, + struct event_trb_s *event) +{ + int ret; + + switch (GETF(EVE_TRB_TYPE, event->dw3)) { + case TRB_TYPE_EVT_PORT_STATUS_CHANGE: + if (crg_udc->device_state == USB_STATE_RECONNECTING) { + crg_udc->portsc_on_reconnecting = 1; + break; + } + /* 1.Port Reset 2.Port Connection Change 3.Port Link Change */ + ret = crg_handle_port_status(crg_udc); + if (ret) + return ret; + + break; + case TRB_TYPE_EVT_TRANSFER: + if (crg_udc->device_state < USB_STATE_RECONNECTING) { + dev_err(crg_udc->dev, + "Xfer compl event rcved when dev state=%d !\n", + crg_udc->device_state); + break; + } + + crg_handle_xfer_event(crg_udc, event); + break; + case TRB_TYPE_EVT_SETUP_PKT: + { + struct usb_ctrlrequest *setup_pkt; + u8 setup_tag; + + dev_dbg(crg_udc->dev, "handle_setup_pkt(%d)\n", + crg_udc->device_state); + + setup_pkt = (struct usb_ctrlrequest *)&event->dw0; + + setup_tag = GETF(EVE_TRB_SETUP_TAG, event->dw3); + dev_dbg(crg_udc->dev, "setup_pkt = 0x%p, setup_tag = 0x%x\n", + setup_pkt, setup_tag); + if (crg_udc->setup_status != WAIT_FOR_SETUP) { + /*previous setup packet hasn't + * completed yet. Just ignore the prev setup + */ + dev_err(crg_udc->dev, "consecutive setup\n"); + queue_setup_pkt(crg_udc, setup_pkt, setup_tag); + break; + } + + crg_handle_setup_pkt(crg_udc, setup_pkt, setup_tag); + + break; + } + default: + dev_dbg(crg_udc->dev, "unexpect TRB_TYPE = 0x%x", + GETF(EVE_TRB_TYPE, event->dw3)); + break; + } + + return 0; +} + +static int process_event_ring(struct crg_gadget_dev *crg_udc, int index) +{ + struct event_trb_s *event; + struct crg_udc_event *udc_event; + struct crg_uicr *uicr = crg_udc->uicr[index]; + dma_addr_t tmp; + u32 val; + dma_addr_t erdp; + int ret; + + if (!uicr) + return IRQ_NONE; + + tmp = readl(&uicr->iman); + if ((tmp & (CRG_U3DC_IMAN_INT_EN | CRG_U3DC_IMAN_INT_PEND)) != + (CRG_U3DC_IMAN_INT_EN | CRG_U3DC_IMAN_INT_PEND)) { + } + + val = readl(&uicr->iman); + val |= CRG_U3DC_IMAN_INT_PEND; + writel(val, &uicr->iman); + + udc_event = &crg_udc->udc_event[index]; + while (udc_event->evt_dq_pt) { + /* rmb */ + rmb(); + event = (struct event_trb_s *)udc_event->evt_dq_pt; + + if (GETF(EVE_TRB_CYCLE_BIT, event->dw3) != + udc_event->CCS) + break; + + ret = crg_udc_handle_event(crg_udc, event); + if (ret == -ECONNRESET) + return ret; + + if (event == udc_event->evt_seg0_last_trb) { + udc_event->CCS = udc_event->CCS ? 0 : 1; + udc_event->evt_dq_pt = udc_event->event_ring.vaddr; + } else { + udc_event->evt_dq_pt++; + } + } + + /* update dequeue pointer */ + erdp = event_trb_virt_to_dma(udc_event, udc_event->evt_dq_pt); + tmp = upper_32_bits(erdp); + writel(upper_32_bits(erdp), &uicr->erdphi); + tmp = lower_32_bits(erdp); + tmp |= CRG_U3DC_ERDPLO_EHB; + writel(lower_32_bits(erdp | CRG_U3DC_ERDPLO_EHB), &uicr->erdplo); + + return 0; +} + +static int crg_gadget_handle_interrupt(struct crg_gadget_dev *crg_udc) +{ + struct crg_uccr *uccr = crg_udc->uccr; + u32 tmp_status; + unsigned long flags = 0; + + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + /******************************/ + + tmp_status = readl(&uccr->status); + + if (tmp_status & CRG_U3DC_STATUS_SYS_ERR) { + dev_err(crg_udc->dev, "%s System error happens!!!\n", __func__); + /*Handle system error*/ + writel(CRG_U3DC_STATUS_SYS_ERR, &uccr->status); + } + + if (tmp_status & CRG_U3DC_STATUS_EINT) { + int i; + + writel(CRG_U3DC_STATUS_EINT, &uccr->status); + + /*process event rings*/ + for (i = 0; i < CRG_RING_NUM; i++) + process_event_ring(crg_udc, i); + } + + if (crg_udc->device_state == USB_STATE_RECONNECTING && + crg_udc->portsc_on_reconnecting == 1 && + is_event_rings_empty(crg_udc)) { + crg_udc->portsc_on_reconnecting = 0; + crg_handle_port_status(crg_udc); + } + + if (crg_udc->device_state == USB_STATE_RECONNECTING && + crg_udc->connected == 1) { + dev_dbg(crg_udc->dev, "check if ready for setup\n"); + prepare_for_setup(crg_udc); + } + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + + return 0; +} + +static irqreturn_t crg_udc_common_irq(int irq, void *dev) +{ + int retval = 0; + + retval = crg_gadget_handle_interrupt(dev); + + return IRQ_HANDLED; +} + +static int crg_gadget_irq_init(struct platform_device *pdev, struct crg_gadget_dev *crg_udc) +{ + int irq = 0; + int retval = 0; + + irq = platform_get_irq(pdev, 0); + if (irq < 0) + return -ENODEV; + + crg_udc->irq = irq; + + retval = request_irq(irq, crg_udc_common_irq, + IRQF_SHARED, "crg_udc", + crg_udc); + if (retval) { + dev_err(crg_udc->dev, "request of irq%d failed\n", irq); + retval = -EBUSY; + } + + return 0; +} + +static int crg_vbus_detect_thread(void *data) +{ + struct crg_gadget_dev *crg_udc = (struct crg_gadget_dev *)data; + unsigned long flags = 0; + int cable_connected = 0; + + while (1) { + if (kthread_should_stop()) + break; + + dev_dbg(crg_udc->dev, "crg_udc->device_state is %d\n", + crg_udc->device_state); + + spin_lock_irqsave(&crg_udc->udc_lock, flags); + + cable_connected = g_dnl_board_usb_cable_connected(crg_udc); + + spin_unlock_irqrestore(&crg_udc->udc_lock, flags); + + if (cable_connected) { + wait_event_interruptible + (vbus_wait, crg_udc->device_state < USB_STATE_POWERED); + } else { + dev_dbg(crg_udc->dev, "wait for vbus\n"); + msleep(1000); + } + } + + return 0; +} + + +static const struct crg_udc_priv ax3000_plat_setup_gen2 = { + .plat_setup_gen3 = false, +}; + +static const struct crg_udc_priv ax3000_plat_setup_gen3 = { + .plat_setup_gen3 = true, +}; + +/** + * crg_gadget_probe - Initializes gadget driver + * + * + * Returns 0 on success otherwise negative errno. + */ + +static const struct of_device_id of_crg_udc_match[] = { + { + .compatible = "axiado,ax3000-udc", + .data = &ax3000_plat_setup_gen2 + }, + { + .compatible = "axiado,ax3000-udc-gen3", + .data = &ax3000_plat_setup_gen3 + }, + { }, +}; +MODULE_DEVICE_TABLE(of, of_crg_udc_match); + +static int crg_udc_probe(struct platform_device *pdev) +{ + int ret; + int i; + struct crg_gadget_dev *crg_udc; + static int udc_gcnt = INIT_ZERO; + char udc_gname[10] = {""}; + const struct crg_udc_priv *priv; + + priv = of_device_get_match_data(&pdev->dev); + sprintf(udc_gname, "gadget-%d", udc_gcnt); + crg_udc = devm_kzalloc(&pdev->dev, sizeof(*crg_udc), GFP_KERNEL); + if (!crg_udc) + return -ENOMEM; + crg_udc->dev = &pdev->dev; + + spin_lock_init(&crg_udc->udc_lock); + platform_set_drvdata(pdev, crg_udc); + + dev_set_name(&crg_udc->gadget.dev, udc_gname); + crg_udc->gadget.ops = &crg_gadget_ops; + crg_udc->gadget.ep0 = &crg_udc->udc_ep[0].usb_ep; + crg_udc->gadget.dev.parent = &pdev->dev; + INIT_LIST_HEAD(&crg_udc->gadget.ep_list); + if (priv->plat_setup_gen3) { + crg_udc->gadget.max_speed = USB_SPEED_SUPER; + crg_udc->gadget.speed = USB_SPEED_SUPER; + } else { + crg_udc->gadget.max_speed = USB_SPEED_HIGH; + crg_udc->gadget.speed = USB_SPEED_HIGH; + } + crg_udc->gadget.name = udc_gname; + crg_udc->gadget.sg_supported = true; + dev_dbg(crg_udc->dev, "%s sg support\n", __func__); + crg_udc->connected = 0; + crg_udc->dev_addr = 0; + + crg_udc->udc_res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!crg_udc->udc_res) { + dev_err(&pdev->dev, "missing memory resource\n"); + return -ENODEV; + } + + crg_udc->mmio_virt_base = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(crg_udc->mmio_virt_base)) { + dev_err(&pdev->dev, "mmio ioremap failed\n"); + return PTR_ERR(crg_udc->mmio_virt_base); + } + + /* set controller device role*/ + writel((readl(crg_udc->mmio_virt_base + CRG_UDC_MODE_REG) | + CRGUDC_ROLE_DEVICE), + crg_udc->mmio_virt_base + CRG_UDC_MODE_REG); + for (i = 0; i < CRG_RING_NUM; i++) { + crg_udc->uicr[i] = crg_udc->mmio_virt_base + + CRG_UICR_OFFSET + i * CRG_UICR_STRIDE; + + dev_dbg(crg_udc->dev, "crg_udc->uicr[%d] = %p\n", i, + crg_udc->uicr[i]); + } + crg_udc->uccr = crg_udc->mmio_virt_base + CRG_UCCR_OFFSET; + + crg_udc_reset(crg_udc); + + crg_udc_clear_portpm(crg_udc); + + ret = reset_data_struct(crg_udc); + if (ret) { + dev_err(crg_udc->dev, "reset_data_struct error\n"); + goto err0; + } + + init_ep_info(crg_udc); + init_ep0(crg_udc); + + EP0_Start(crg_udc); + + crg_gadget_irq_init(pdev, crg_udc); + + ret = usb_add_gadget_udc(&pdev->dev, &crg_udc->gadget); + if (ret) + goto err0; + + udc_gcnt++; + + return 0; + +err0: + return -1; +} + +static void crg_udc_remove(struct platform_device *pdev) +{ + struct crg_gadget_dev *crg_udc = platform_get_drvdata(pdev); + u32 tmp = 0; + + dev_dbg(crg_udc->dev, "%s %d called\n", __func__, __LINE__); + + crg_udc->device_state = USB_STATE_ATTACHED; + crg_vbus_detect(crg_udc, 0); + + usb_del_gadget_udc(&crg_udc->gadget); + + /* set controller host role*/ + tmp = readl(crg_udc->mmio_virt_base + CRG_UDC_MODE_REG) & ~0x1; + writel(tmp, crg_udc->mmio_virt_base + CRG_UDC_MODE_REG); + + if (crg_udc->irq) + free_irq(crg_udc->irq, crg_udc); + + platform_set_drvdata(pdev, 0); + + dev_dbg(crg_udc->dev, "%s %d gadget remove\n", __func__, __LINE__); + +} + +static void crg_udc_shutdown(struct platform_device *pdev) +{ + struct crg_gadget_dev *crg_udc = platform_get_drvdata(pdev); + + dev_dbg(crg_udc->dev, "%s %d called\n", __func__, __LINE__); + + crg_udc->device_state = USB_STATE_ATTACHED; + crg_vbus_detect(crg_udc, 0); + usb_del_gadget_udc(&crg_udc->gadget); + + if (crg_udc->irq) + free_irq(crg_udc->irq, crg_udc); + /* + * Clear the drvdata pointer. + */ + platform_set_drvdata(pdev, 0); +} + +#ifdef CONFIG_PM +static int crg_udc_suspend(struct device *dev) +{ + return 0; +} + +static int crg_udc_resume(struct device *dev) +{ + + + return 0; +} +#else +#define crg_udc_suspend NULL +#define crg_udc_resume NULL +#endif + +static const struct dev_pm_ops crg_udc_pm_ops = { + .suspend = crg_udc_suspend, + .resume = crg_udc_resume, +}; + +static struct platform_driver crg_udc_driver = { + .probe = crg_udc_probe, + .remove = crg_udc_remove, + .shutdown = crg_udc_shutdown, + .driver = { + .name = "crg_udc", + .owner = THIS_MODULE, + .pm = &crg_udc_pm_ops, + .of_match_table = of_match_ptr(of_crg_udc_match), + }, +}; + +static void crg_gadget_exit(void) +{ + platform_driver_unregister(&crg_udc_driver); +} + +static int crg_gadget_init(void) +{ + + return platform_driver_register(&crg_udc_driver); +} + +module_init(crg_gadget_init); +module_exit(crg_gadget_exit); + +MODULE_DESCRIPTION("Corigine USB Device Controller"); +MODULE_LICENSE("GPL"); diff --git a/drivers/usb/gadget/udc/crg_udc.h b/drivers/usb/gadget/udc/crg_udc.h new file mode 100644 index 000000000000..bb0cd724582c --- /dev/null +++ b/drivers/usb/gadget/udc/crg_udc.h @@ -0,0 +1,364 @@ +/* SPDX-License-Identifier: (GPL-2.0+ OR MIT) */ +/* + * Copyright (c) 2019 Corigine, Inc. + * Copyright (c) 2022-2026 Axiado Corporation. + */ + +#ifndef __CRG_UDC_H__ +#define __CRG_UDC_H__ + +#define CRG_UCCR_OFFSET (0x2400) +#define CRG_UICR_OFFSET (0x2500) +#define CRG_UICR_STRIDE (0x20) + +/* corigine usb 3.1 device core register macros */ +struct crg_uccr { + u32 capability; /*0x00*/ + u32 resv0[3]; + + u32 config0; /*0x10*/ + u32 config1; + u32 resv1[2]; + + u32 control; /*0x20*/ + u32 status; + u32 dcbaplo; + u32 dcbaphi; + u32 portsc; + u32 u3portpmsc; + u32 u2portpmsc; + u32 u3portli; + + u32 doorbell; /*0x40*/ + u32 mfindex; + u32 speed_select; + u32 resv3[5]; + + u32 ep_enable; /*0x60*/ + u32 ep_running; + u32 resv4[2]; + + u32 cmd_param0; /*0x70*/ + u32 cmd_param1; + u32 cmd_control; + u32 resv5[1]; + + u32 odb_capability; /*0x80*/ + u32 resv6[3]; + u32 odb_config[8]; + + u32 debug0; /*0xB0*/ +}; + +struct crg_uicr { + u32 iman; + u32 imod; + u32 erstsz; + u32 resv0; + + u32 erstbalo; /*0x10*/ + u32 erstbahi; + u32 erdplo; + u32 erdphi; +}; + +#define SETF_VAR(field, var, fieldval) \ + (((var) & ~(field ## _MASK)) | \ + (((fieldval) << field ## _SHIFT) & (field ## _MASK))) + +#define GETF(field, val) \ + (((val) & (field ## _MASK)) >> (field ## _SHIFT)) + +#define MAKEF_VAR(field, fieldval) \ + (((fieldval) << field ## _SHIFT) & (field ## _MASK)) + +/* interrupt registers array */ +#define CRG_U3DC_IRS_BASE (0x100L) +#define CRG_U3DC_IRS_IMAN(x) \ + (CRG_U3DC_IRS_BASE + (x) * 0x20L + 0x00L) +#define CRG_U3DC_IRS_IMOD(x) \ + (CRG_U3DC_IRS_BASE + (x) * 0x20L + 0x04L) +#define CRG_U3DC_IRS_ERSTSZ(x) \ + (CRG_U3DC_IRS_BASE + (x) * 0x20L + 0x08L) +#define CRG_U3DC_IRS_ERSTBALO(x) \ + (CRG_U3DC_IRS_BASE + (x) * 0x20L + 0x10L) +#define CRG_U3DC_IRS_ERSTBAHI(x) \ + (CRG_U3DC_IRS_BASE + (x) * 0x20L + 0x14L) +#define CRG_U3DC_IRS_ERDPLO(x) \ + (CRG_U3DC_IRS_BASE + (x) * 0x20L + 0x18L) +#define CRG_U3DC_IRS_ERDPHI(x) \ + (CRG_U3DC_IRS_BASE + (x) * 0x20L + 0x20L) + +/* reg config 0 & 1*/ +#define CRG_U3DC_CFG0_MAXSPEED_MASK (0xfL << 0) +#define CRG_U3DC_CFG0_MAXSPEED_FS (0x1L << 0) +#define CRG_U3DC_CFG0_MAXSPEED_HS (0x3L << 0) +#define CRG_U3DC_CFG0_MAXSPEED_SS (0x4L << 0) +#define CRG_U3DC_CFG0_MAXSPEED_SSP (0x5L << 0) + +#define CRG_U3DC_CFG1_CSC_EVENT_EN BIT(0) +#define CRG_U3DC_CFG1_PEC_EVENT_EN BIT(1) +#define CRG_U3DC_CFG1_PPC_EVENT_EN BIT(3) +#define CRG_U3DC_CFG1_PRC_EVENT_EN BIT(4) +#define CRG_U3DC_CFG1_PLC_EVENT_EN BIT(5) +#define CRG_U3DC_CFG1_CEC_EVENT_EN BIT(6) + +#define CRG_U3DC_CFG1_U3_ENTRY_EN BIT(8) +#define CRG_U3DC_CFG1_L1_ENTRY_EN BIT(9) +#define CRG_U3DC_CFG1_U3_RESUME_EN BIT(10) +#define CRG_U3DC_CFG1_L1_RESUME_EN BIT(11) +#define CRG_U3DC_CFG1_INACTIVE_PLC_EN BIT(12) +#define CRG_U3DC_CFG1_U3_RESUME_NORESP_PLC_EN BIT(13) +#define CRG_U3DC_CFG1_U2_RESUME_NORESP_PLC_EN BIT(14) + +#define CRG_U3DC_CFG1_SETUP_EVENT_EN BIT(16) + +/* ctrl register*/ +#define CRG_U3DC_CTRL_RUN BIT(0) +#define CRG_U3DC_CTRL_STOP (0) +#define CRG_U3DC_CTRL_SWRST BIT(1) +#define CRG_U3DC_CTRL_INT_EN BIT(2) +#define CRG_U3DC_CTRL_SYSERR_EN BIT(3) +#define CRG_U3DC_CTRL_EWE BIT(10) +#define CRG_U3DC_CTRL_KP_CNCT BIT(11) + +/*status register*/ +#define CRG_U3DC_STATUS_DEV_CTRL_HALT BIT(0) +#define CRG_U3DC_STATUS_SYS_ERR BIT(2) +#define CRG_U3DC_STATUS_EINT BIT(3) + +/*portsc register*/ +#define CRG_U3DC_PORTSC_CCS BIT(0) +#define CRG_U3DC_PORTSC_PED BIT(1) +#define CRG_U3DC_PORTSC_PP BIT(3) +#define CRG_U3DC_PORTSC_PR BIT(4) + +#define CRG_U3DC_PORTSC_PLS_SHIFT (5) +#define CRG_U3DC_PORTSC_PLS_MASK (0xf << CRG_U3DC_PORTSC_PLS_SHIFT) +#define CRG_U3DC_PORTSC_PLS(fv) (MAKEF_VAR(CRG_U3DC_PORTSC_PLS, (fv))) +#define CRG_U3DC_PORTSC_PLS_GET(v) (GETF(CRG_U3DC_PORTSC_PLS, (v))) + +#define CRG_U3DC_PORTSC_SPEED_SHIFT (10) +#define CRG_U3DC_PORTSC_SPEED_MASK \ + (0xf << CRG_U3DC_PORTSC_SPEED_SHIFT) +#define CRG_U3DC_PORTSC_SPEED(fv) \ + (MAKEF_VAR(CRG_U3DC_PORTSC_SPEED, (fv))) +#define CRG_U3DC_PORTSC_SPEED_GET(v) \ + (GETF(CRG_U3DC_PORTSC_SPEED, (v))) +#define CRG_U3DC_PORTSC_SPEED_FS (0x1) +#define CRG_U3DC_PORTSC_SPEED_LS (0x2) +#define CRG_U3DC_PORTSC_SPEED_HS (0x3) +#define CRG_U3DC_PORTSC_SPEED_SS (0x4) +#define CRG_U3DC_PORTSC_SPEED_SSP (0x5) + +#define CRG_U3DC_PORTSC_LWS BIT(16) +#define CRG_U3DC_PORTSC_CSC BIT(17) +#define CRG_U3DC_PORTSC_PEC BIT(18) +#define CRG_U3DC_PORTSC_PPC BIT(20) +#define CRG_U3DC_PORTSC_PRC BIT(21) +#define CRG_U3DC_PORTSC_PLC BIT(22) +#define CRG_U3DC_PORTSC_CEC BIT(23) +#define CRG_U3DC_PORTSC_WCE BIT(25) +#define CRG_U3DC_PORTSC_WDE BIT(26) +#define CRG_U3DC_PORTSC_WPR BIT(31) + +#define PORTSC_W1C_MASK (CRG_U3DC_PORTSC_CSC | \ + CRG_U3DC_PORTSC_PEC | \ + CRG_U3DC_PORTSC_PPC | \ + CRG_U3DC_PORTSC_PRC | \ + CRG_U3DC_PORTSC_PLC | \ + CRG_U3DC_PORTSC_CEC) +#define PORTSC_WRITE_MASK (~PORTSC_W1C_MASK) + +/* u3portpmsc */ +#define CRG_U3DC_U3PORTPM_U1TMOUT_SHIFT (0) +#define CRG_U3DC_U3PORTPM_U1TMOUT_MASK \ + (0xff << CRG_U3DC_U3PORTPM_U1TMOUT_SHIFT) +#define CRG_U3DC_U3PORTPM_U1TMOUT(fv) \ + (MAKEF_VAR(CRG_U3DC_U3PORTPM_U1TMOUT, (fv))) + +#define CRG_U3DC_U3PORTPM_U2TMOUT_SHIFT (8) +#define CRG_U3DC_U3PORTPM_U2TMOUT_MASK \ + (0xff << CRG_U3DC_U3PORTPM_U2TMOUT_SHIFT) +#define CRG_U3DC_U3PORTPM_U2TMOUT(fv) \ + (MAKEF_VAR(CRG_U3DC_U3PORTPM_U2TMOUT, (fv))) + +#define CRG_U3DC_U3PORTPM_FLA BIT(16) + +#define CRG_U3DC_U3PORTPM_U1IEN_SHIFT (20) +#define CRG_U3DC_U3PORTPM_U1IEN \ + (1L << CRG_U3DC_U3PORTPM_U1IEN_SHIFT) + +#define CRG_U3DC_U3PORTPM_U2IEN_SHIFT (21) +#define CRG_U3DC_U3PORTPM_U2IEN \ + (1L << CRG_U3DC_U3PORTPM_U2IEN_SHIFT) + +#define CRG_U3DC_U3PORTPM_U1AEN_SHIFT (22) +#define CRG_U3DC_U3PORTPM_U1AEN \ + (1L << CRG_U3DC_U3PORTPM_U1AEN_SHIFT) + +#define CRG_U3DC_U3PORTPM_U2AEN_SHIFT (23) +#define CRG_U3DC_U3PORTPM_U2AEN \ + (1L << CRG_U3DC_U3PORTPM_U2AEN_SHIFT) + +#define CRG_U3DC_U3PORTPM_U1U2TMOUT_SHIFT (24) +#define CRG_U3DC_U3PORTPM_U1U2TMOUT_MASK \ + (0xff << CRG_U3DC_U3PORTPM_U1U2TMOUT_SHIFT) + +/* u2portpmsc */ +#define CRG_U3DC_U2PORTPM_RJ_TH_SHIFT (0) +#define CRG_U3DC_U2PORTPM_RJ_TH_MASK \ + (0xf << CRG_U3DC_U2PORTPM_RJ_TH_SHIFT) +#define CRG_U3DC_U2PORTPM_RJ_TH(fv) \ + (MAKEF_VAR(CRG_U3DC_U2PORTPM_RJ_TH, (fv))) + +#define CRG_U3DC_U2PORTPM_DS_TH_SHIFT (4) +#define CRG_U3DC_U2PORTPM_DS_TH_MASK \ + (0xf << CRG_U3DC_U2PORTPM_DS_TH_SHIFT) +#define CRG_U3DC_U2PORTPM_DS_TH(fv) \ + (MAKEF_VAR(CRG_U3DC_U2PORTPM_DS_TH, (fv))) + +#define CRG_U3DC_U2PORTPM_LPM_EN BIT(8) +#define CRG_U3DC_U2PORTPM_RJ_TH_EN BIT(9) +#define CRG_U3DC_U2PORTPM_DS_EN BIT(10) +#define CRG_U3DC_U2PORTPM_SLP_EN BIT(11) +#define CRG_U3DC_U2PORTPM_LPM_FACK BIT(12) +#define CRG_U3DC_U2PORTPM_L1_AEX BIT(13) +#define CRG_U3DC_U2PORTPM_H_B_SHIFT (16) +#define CRG_U3DC_U2PORTPM_H_B_MASK \ + (0xf << CRG_U3DC_U2PORTPM_H_B_SHIFT) +#define CRG_U3DC_U2PORTPM_H_B(fv) \ + (MAKEF_VAR(CRG_U3DC_U2PORTPM_H_B, (fv))) + +#define CRG_U3DC_U2PORTPM_RWE BIT(20) + +#define CRG_U3DC_U2PORTPM_TM_SHIFT (28) +#define CRG_U3DC_U2PORTPM_TM_MASK \ + (0xf << CRG_U3DC_U2PORTPM_TM_SHIFT) +#define CRG_U3DC_U2PORTPM_TM(fv) \ + (MAKEF_VAR(CRG_U3DC_U2PORTPM_TM, (fv))) + +/* doorbell register*/ +#define CRG_U3DC_DB_TARGET_SHIFT (0) +#define CRG_U3DC_DB_TARGET_MASK \ + (0x1f << CRG_U3DC_DB_TARGET_SHIFT) +#define CRG_U3DC_DB_TARGET(fv) \ + (MAKEF_VAR(CRG_U3DC_DB_TARGET, (fv))) + +/* odb registers*/ +#define CRG_U3DC_ODBCFG_2N_OFFSET_SHIFT (0) +#define CRG_U3DC_ODBCFG_2N_OFFSET_MASK \ + (0x3ff << CRG_U3DC_ODBCFG_2N_OFFSET_SHIFT) +#define CRG_U3DC_ODBCFG_2N_OFFSET(fv) \ + (MAKEF_VAR(CRG_U3DC_ODBCFG_2N_OFFSET, (fv))) + +#define CRG_U3DC_ODBCFG_2N_SIZE_SHIFT (10) +#define CRG_U3DC_ODBCFG_2N_SIZE_MASK \ + (0x7 << CRG_U3DC_ODBCFG_2N_SIZE_SHIFT) +#define CRG_U3DC_ODBCFG_2N_SIZE(fv) \ + (MAKEF_VAR(CRG_U3DC_ODBCFG_2N_SIZE, (fv))) + +#define CRG_U3DC_ODBCFG_2N1_OFFSET_SHIFT (16) +#define CRG_U3DC_ODBCFG_2N1_OFFSET_MASK \ + (0x3ff << CRG_U3DC_ODBCFG_2N1_OFFSET_SHIFT) +#define CRG_U3DC_ODBCFG_2N1_OFFSET(fv) \ + (MAKEF_VAR(CRG_U3DC_ODBCFG_2N1_OFFSET, (fv))) + +#define CRG_U3DC_ODBCFG_2N1_SIZE_SHIFT (26) +#define CRG_U3DC_ODBCFG_2N1_SIZE_MASK \ + (0x7 << CRG_U3DC_ODBCFG_2N1_SIZE_SHIFT) +#define CRG_U3DC_ODBCFG_2N1_SIZE(fv) \ + (MAKEF_VAR(CRG_U3DC_ODBCFG_2N1_SIZE, (fv))) + +/* command control register*/ +#define CRG_U3DC_CMD_CTRL_ACTIVE_SHIFT (0) +#define CRG_U3DC_CMD_CTRL_ACTIVE \ + (1L << CRG_U3DC_CMD_CTRL_ACTIVE_SHIFT) +#define CRG_U3DC_CMD_CTRL_IOC_SHIFT (1) +#define CRG_U3DC_CMD_CTRL_IOC_EN \ + (1L << CRG_U3DC_CMD_CTRL_IOC_SHIFT) + +#define CRG_U3DC_CMD_CTRL_TYPE_SHIFT (4) +#define CRG_U3DC_CMD_CTRL_TYPE_MASK \ + (0xf << CRG_U3DC_CMD_CTRL_TYPE_SHIFT) +#define CRG_U3DC_CMD_CTRL_TYPE(fv) \ + (MAKEF_VAR(CRG_U3DC_CMD_CTRL_TYPE, (fv))) + +#define CRG_U3DC_CMD_CTRL_STATUS_SHIFT (16) +#define CRG_U3DC_CMD_CTRL_STATUS_MASK \ + (0xf << CRG_U3DC_CMD_CTRL_STATUS_SHIFT) +#define CRG_U3DC_CMD_CTRL_STATUS(fv) \ + (MAKEF_VAR(CRG_U3DC_CMD_CTRL_STATUS, (fv))) +#define CRG_U3DC_CMD_CTRL_STATUS_GET(v) \ + (GETF(CRG_U3DC_CMD_CTRL_STATUS, (v))) + +#define CRG_U3DC_CMD_INIT_EP0 (0L) +#define CRG_U3DC_CMD_UPDATE_EP0 (1L) +#define CRG_U3DC_CMD_SET_ADDRESS (2L) +#define CRG_U3DC_CMD_SEND_DEV_NOTIFY (3L) +#define CRG_U3DC_CMD_CONFIG_EP (4L) +#define CRG_U3DC_CMD_SET_HALT (5L) +#define CRG_U3DC_CMD_CLR_HALT (6L) +#define CRG_U3DC_CMD_RST_SEQNUM (7L) +#define CRG_U3DC_CMD_STOP_EP (8L) +#define CRG_U3DC_CMD_SET_TR_DQPTR (9L) +#define CRG_U3DC_CMD_FORCE_FLOW_CTRL (10L) +#define CRG_U3DC_CMD_REQ_LDM_EXCHAG (11L) + +/* int register*/ +/* iman bits*/ +#define CRG_U3DC_IMAN_INT_PEND BIT(0) +#define CRG_U3DC_IMAN_INT_EN BIT(1) + +/* erdp bits*/ +#define CRG_U3DC_ERDPLO_EHB BIT(3) +#define CRG_U3DC_ERDPLO_ADDRLO(fv) ((fv) & 0xfffffff0) + +/*command params*/ +/*command0 init ep0*/ +#define CRG_CMD0_0_DQPTRLO_SHIFT (4) +#define CRG_CMD0_0_DQPTRLO_MASK \ + (0x0fffffff << CRG_CMD0_0_DQPTRLO_SHIFT) + +#define CRG_CMD0_0_DCS_SHIFT (0) +#define CRG_CMD0_0_DCS_MASK (0x1 << CRG_CMD0_0_DCS_SHIFT) +#define CRG_CMD0_0_DCS(fv) (MAKEF_VAR(CRG_CMD0_0_DCS, (fv))) + +/*command1 update ep0 */ +#define CRG_CMD1_0_MPS_SHIFT (16) +#define CRG_CMD1_0_MPS_MASK (0xffff << CRG_CMD1_0_MPS_SHIFT) +#define CRG_CMD1_0_MPS(fv) (MAKEF_VAR(CRG_CMD1_0_MPS, (fv))) + +/*command2 set addr */ +#define CRG_CMD2_0_DEV_ADDR_SHIFT (0) +#define CRG_CMD2_0_DEV_ADDR_MASK (0xff << CRG_CMD2_0_DEV_ADDR_SHIFT) +#define CRG_CMD2_0_DEV_ADDR(fv) (MAKEF_VAR(CRG_CMD2_0_DEV_ADDR, (fv))) + +#define CRG_UDC_MODE_REG 0x20fc +/* Vendor specific register */ +#define CRG_UDC_VENDOR_REG 0x210c +#define CRG_UDC_VBUS_DETECT BIT(26) +/*command type*/ +enum crg_cmd_type { + CRG_CMD_INIT_EP0 = 0, + CRG_CMD_UPDATE_EP0_CFG = 1, + CRG_CMD_SET_ADDR = 2, + CRG_CMD_SEND_DEV_NOTIFICATION = 3, + CRG_CMD_CONFIG_EP = 4, + CRG_CMD_SET_HALT = 5, + CRG_CMD_CLEAR_HALT = 6, + CRG_CMD_RESET_SEQNUM = 7, + CRG_CMD_STOP_EP = 8, + CRG_CMD_SET_TR_DQPTR = 9, + CRG_CMD_FORCE_FLOW_CONTROL = 10, + CRG_CMD_REQ_LDM_EXCHANGE = 11 +}; + +struct crg_gadget_dev; + +struct crg_udc_platdata { + int num_out_eps; + int num_in_eps; +}; + +#endif /* __CRG_UDC_H__ */ -- 2.34.1
{ "author": "Vladimir Moravcevic <vmoravcevic@axiado.com>", "date": "Mon, 02 Feb 2026 05:16:29 -0800", "thread_id": "202602030223.QlbiPC8d-lkp@intel.com.mbox.gz" }
lkml
[PATCH 0/3] Axiado AX3000 USB Device Controller
Dear maintainers, This patch series introduces new USB Device Controller driver for Axiado AX3000 SoC and its evaluation board. The driver integrates with the Linux USB subsystem and follows kernel coding standards. This initial submission includes: - Driver implementation under drivers/usb/gadget/udc - Device tree bindings for supported boards - Kconfig and Makefile integration Signed-off-by: Vladimir Moravcevic <vmoravcevic@axiado.com> --- Vladimir Moravcevic (3): dt-bindings: usb: axiado,ax3000-udc: Add Axiado UDC usb: gadget: udc: Add UDC driver for Axiado Device controller IP Corigine MAINTAINERS: Add entries for the Axiado USB UDC .../devicetree/bindings/usb/axiado,ax3000-udc.yaml | 59 + MAINTAINERS | 10 + drivers/usb/gadget/udc/Kconfig | 15 + drivers/usb/gadget/udc/Makefile | 1 + drivers/usb/gadget/udc/crg_udc.c | 4522 ++++++++++++++++++++ drivers/usb/gadget/udc/crg_udc.h | 364 ++ 6 files changed, 4971 insertions(+) --- base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377 change-id: 20260128-axiado-ax3000-usb-device-controller-156d3f1840c9 Best regards, -- Vladimir Moravcevic <vmoravcevic@axiado.com>
Hi Vladimir, kernel test robot noticed the following build warnings: [auto build test WARNING on 63804fed149a6750ffd28610c5c1c98cce6bd377] url: https://github.com/intel-lab-lkp/linux/commits/Vladimir-Moravcevic/dt-bindings-usb-axiado-ax3000-udc-Add-Axiado-UDC/20260202-211951 base: 63804fed149a6750ffd28610c5c1c98cce6bd377 patch link: https://lore.kernel.org/r/20260202-axiado-ax3000-usb-device-controller-v1-2-45ce0a8b014f%40axiado.com patch subject: [PATCH 2/3] usb: gadget: udc: Add UDC driver for Axiado Device controller IP Corigine config: alpha-allyesconfig (https://download.01.org/0day-ci/archive/20260203/202602030131.VCTzZ4me-lkp@intel.com/config) compiler: alpha-linux-gcc (GCC) 15.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260203/202602030131.VCTzZ4me-lkp@intel.com/reproduce) If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags | Reported-by: kernel test robot <lkp@intel.com> | Closes: https://lore.kernel.org/oe-kbuild-all/202602030131.VCTzZ4me-lkp@intel.com/ All warnings (new ones prefixed by >>): drivers/usb/gadget/udc/crg_udc.c: In function 'crg_udc_queue_trbs': 881 | u32 num_sgs = 0; | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c: In function 'crg_udc_ep_enable': 1812 | struct crg_uccr *uccr; | ^~~~ 1811 | struct ep_cx_s *epcx; | ^~~~ drivers/usb/gadget/udc/crg_udc.c: In function 'crg_udc_common_irq': 4250 | int retval = 0; | ^~~~~~ drivers/usb/gadget/udc/crg_udc.c: At top level: 126 | static const char driver_name[] = "crg_udc"; | ^~~~~~~~~~~ -- vim +/num_sgs +881 drivers/usb/gadget/udc/crg_udc.c 858 859 static int crg_udc_queue_trbs(struct crg_udc_ep *udc_ep_ptr, 860 struct crg_udc_request *udc_req_ptr, bool b_isoc, 861 u32 xfer_ring_size, 862 u32 num_trbs_needed, u64 buffer_length) 863 { 864 struct crg_gadget_dev *crg_udc = udc_ep_ptr->crg_udc; 865 struct transfer_trb_s *p_xfer_ring = udc_ep_ptr->first_trb; 866 u32 num_trbs_ava = 0; 867 struct usb_request *usb_req = &udc_req_ptr->usb_req; 868 u64 buff_len_temp = 0; 869 u32 i, j = 1; 870 struct transfer_trb_s *enq_pt = udc_ep_ptr->enq_pt; 871 u8 td_size; 872 u8 chain_bit = 1; 873 u8 short_pkt = 0; 874 u8 intr_on_compl = 0; 875 u32 count; 876 bool full_td = true; 877 u32 intr_rate; 878 dma_addr_t trb_buf_addr; 879 bool need_zlp = false; 880 struct scatterlist *sg = NULL; > 881 u32 num_sgs = 0; 882 u64 sg_addr = 0; 883 884 dev_dbg(crg_udc->dev, "%s %s\n", __func__, udc_ep_ptr->usb_ep.name); 885 if (udc_req_ptr->usb_req.num_sgs) { 886 num_sgs = udc_req_ptr->usb_req.num_sgs; 887 sg = udc_req_ptr->usb_req.sg; 888 sg_addr = (u64) sg_dma_address(sg); 889 buffer_length = sg_dma_len(sg); 890 891 dev_dbg(crg_udc->dev, "num_sgs = %d, num_mapped_sgs = %d\n", 892 udc_req_ptr->usb_req.num_sgs, 893 udc_req_ptr->usb_req.num_mapped_sgs); 894 dev_dbg(crg_udc->dev, 895 "sg_addr = %p, buffer_length = %llu, num_trbs = %d\n", 896 (void *)sg_addr, buffer_length, num_trbs_needed); 897 } 898 899 if (!b_isoc) { 900 if (udc_req_ptr->usb_req.zero == 1 && 901 udc_req_ptr->usb_req.length != 0 && 902 ((udc_req_ptr->usb_req.length % 903 udc_ep_ptr->usb_ep.maxpacket) == 0)) { 904 need_zlp = true; 905 } 906 } 907 908 td_size = num_trbs_needed; 909 910 num_trbs_ava = room_on_ring(crg_udc, xfer_ring_size, 911 p_xfer_ring, udc_ep_ptr->enq_pt, udc_ep_ptr->deq_pt); 912 913 /* trb_buf_addr points to the addr of the buffer that we write in 914 * each TRB. If this function is called to complete the pending TRB 915 * transfers of a previous request, point it to the buffer that is 916 * not transferred, or else point it to the starting address of the 917 * buffer received in usb_request 918 */ 919 if (udc_req_ptr->trbs_needed) { 920 /* Here udc_req_ptr->trbs_needed is used to indicate if we 921 * are completing a previous req 922 */ 923 trb_buf_addr = usb_req->dma + 924 (usb_req->length - udc_req_ptr->buff_len_left); 925 } else { 926 if (sg_addr) 927 trb_buf_addr = sg_addr; 928 else 929 trb_buf_addr = usb_req->dma; 930 } 931 932 if (num_trbs_ava >= num_trbs_needed) { 933 count = num_trbs_needed; 934 } else { 935 if (b_isoc) { 936 struct crg_udc_request *udc_req_ptr_temp; 937 u8 temp = 0; 938 939 list_for_each_entry(udc_req_ptr_temp, 940 &udc_ep_ptr->queue, queue) { 941 temp++; 942 } 943 944 if (temp >= 2) { 945 dev_err(crg_udc->dev, "%s don't do isoc discard\n", __func__); 946 /* we already scheduled two mfi in advance. */ 947 return 0; 948 } 949 } 950 951 /* always keep one trb for zlp. */ 952 count = num_trbs_ava; 953 full_td = false; 954 dev_dbg(crg_udc->dev, "TRB Ring Full. Avail: 0x%x Req: 0x%x\n", 955 num_trbs_ava, num_trbs_needed); 956 udc_ep_ptr->tran_ring_full = true; 957 958 /*if there is still some trb not queued, 959 *it means last queued 960 *trb is not the last trb of TD, so no need zlp 961 */ 962 need_zlp = false; 963 } 964 965 for (i = 0; i < count; i++) { 966 if ((udc_req_ptr->usb_req.num_sgs) && (buffer_length == 0)) { 967 sg = sg_next(sg); 968 if (sg) { 969 trb_buf_addr = (u64) sg_dma_address(sg); 970 buffer_length = sg_dma_len(sg); 971 dev_dbg(crg_udc->dev, 972 "trb_buf_addr = %p, num_trbs = %d\n", 973 (void *)trb_buf_addr, num_trbs_needed); 974 dev_dbg(crg_udc->dev, "buffer_length = %llu\n", 975 buffer_length); 976 } else { 977 dev_err(crg_udc->dev, 978 "scatterlist ended unexpectedly (i=%d, count=%d)\n", 979 i, count); 980 return -EINVAL; 981 } 982 } 983 984 if (buffer_length > TRB_MAX_BUFFER_SIZE) 985 buff_len_temp = TRB_MAX_BUFFER_SIZE; 986 else 987 buff_len_temp = buffer_length; 988 989 buffer_length -= buff_len_temp; 990 991 if (usb_endpoint_dir_out(udc_ep_ptr->desc)) 992 short_pkt = 1; 993 994 if ((buffer_length == 0) && (i == (count - 1))) { 995 chain_bit = 0; 996 intr_on_compl = 1; 997 udc_req_ptr->all_trbs_queued = 1; 998 } 999 1000 -- 0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
{ "author": "kernel test robot <lkp@intel.com>", "date": "Tue, 3 Feb 2026 01:37:05 +0800", "thread_id": "202602030223.QlbiPC8d-lkp@intel.com.mbox.gz" }
lkml
[PATCH 0/3] Axiado AX3000 USB Device Controller
Dear maintainers, This patch series introduces new USB Device Controller driver for Axiado AX3000 SoC and its evaluation board. The driver integrates with the Linux USB subsystem and follows kernel coding standards. This initial submission includes: - Driver implementation under drivers/usb/gadget/udc - Device tree bindings for supported boards - Kconfig and Makefile integration Signed-off-by: Vladimir Moravcevic <vmoravcevic@axiado.com> --- Vladimir Moravcevic (3): dt-bindings: usb: axiado,ax3000-udc: Add Axiado UDC usb: gadget: udc: Add UDC driver for Axiado Device controller IP Corigine MAINTAINERS: Add entries for the Axiado USB UDC .../devicetree/bindings/usb/axiado,ax3000-udc.yaml | 59 + MAINTAINERS | 10 + drivers/usb/gadget/udc/Kconfig | 15 + drivers/usb/gadget/udc/Makefile | 1 + drivers/usb/gadget/udc/crg_udc.c | 4522 ++++++++++++++++++++ drivers/usb/gadget/udc/crg_udc.h | 364 ++ 6 files changed, 4971 insertions(+) --- base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377 change-id: 20260128-axiado-ax3000-usb-device-controller-156d3f1840c9 Best regards, -- Vladimir Moravcevic <vmoravcevic@axiado.com>
Hi Vladimir, kernel test robot noticed the following build warnings: [auto build test WARNING on 63804fed149a6750ffd28610c5c1c98cce6bd377] url: https://github.com/intel-lab-lkp/linux/commits/Vladimir-Moravcevic/dt-bindings-usb-axiado-ax3000-udc-Add-Axiado-UDC/20260202-211951 base: 63804fed149a6750ffd28610c5c1c98cce6bd377 patch link: https://lore.kernel.org/r/20260202-axiado-ax3000-usb-device-controller-v1-2-45ce0a8b014f%40axiado.com patch subject: [PATCH 2/3] usb: gadget: udc: Add UDC driver for Axiado Device controller IP Corigine config: nios2-allmodconfig (https://download.01.org/0day-ci/archive/20260203/202602030223.QlbiPC8d-lkp@intel.com/config) compiler: nios2-linux-gcc (GCC) 11.5.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260203/202602030223.QlbiPC8d-lkp@intel.com/reproduce) If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags | Reported-by: kernel test robot <lkp@intel.com> | Closes: https://lore.kernel.org/oe-kbuild-all/202602030223.QlbiPC8d-lkp@intel.com/ All warnings (new ones prefixed by >>): In file included from include/linux/printk.h:621, from include/asm-generic/bug.h:31, from ./arch/nios2/include/generated/asm/bug.h:1, from include/linux/bug.h:5, from include/linux/random.h:6, from include/linux/net.h:18, from drivers/usb/gadget/udc/crg_udc.c:7: drivers/usb/gadget/udc/crg_udc.c: In function 'crg_udc_epcx_setup': 624 | dev_dbg(crg_udc->dev, "DCI %d, sizeof ep_cx %ld\n", DCI, sizeof(struct ep_cx_s)); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ include/linux/dynamic_debug.h:231:29: note: in definition of macro '__dynamic_func_call_cls' 231 | func(&id, ##__VA_ARGS__); \ | ^~~~~~~~~~~ include/linux/dynamic_debug.h:261:9: note: in expansion of macro '_dynamic_func_call_cls' 261 | _dynamic_func_call_cls(_DPRINTK_CLASS_DFLT, fmt, func, ##__VA_ARGS__) | ^~~~~~~~~~~~~~~~~~~~~~ include/linux/dynamic_debug.h:284:9: note: in expansion of macro '_dynamic_func_call' 284 | _dynamic_func_call(fmt, __dynamic_dev_dbg, \ | ^~~~~~~~~~~~~~~~~~ include/linux/dev_printk.h:165:9: note: in expansion of macro 'dynamic_dev_dbg' 165 | dynamic_dev_dbg(dev, dev_fmt(fmt), ##__VA_ARGS__) | ^~~~~~~~~~~~~~~ include/linux/dev_printk.h:165:30: note: in expansion of macro 'dev_fmt' 165 | dynamic_dev_dbg(dev, dev_fmt(fmt), ##__VA_ARGS__) | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c:624:9: note: in expansion of macro 'dev_dbg' 624 | dev_dbg(crg_udc->dev, "DCI %d, sizeof ep_cx %ld\n", DCI, sizeof(struct ep_cx_s)); | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c:624:55: note: format string is defined here 624 | dev_dbg(crg_udc->dev, "DCI %d, sizeof ep_cx %ld\n", DCI, sizeof(struct ep_cx_s)); | ~~^ | | | long int | %d In file included from include/linux/printk.h:621, from include/asm-generic/bug.h:31, from ./arch/nios2/include/generated/asm/bug.h:1, from include/linux/bug.h:5, from include/linux/random.h:6, from include/linux/net.h:18, from drivers/usb/gadget/udc/crg_udc.c:7: drivers/usb/gadget/udc/crg_udc.c: In function 'setup_datastage_trb': 774 | dev_dbg(crg_udc->dev, "dma = 0x%llx, ", usb_req->dma); | ^~~~~~~~~~~~~~~~ include/linux/dynamic_debug.h:231:29: note: in definition of macro '__dynamic_func_call_cls' 231 | func(&id, ##__VA_ARGS__); \ | ^~~~~~~~~~~ include/linux/dynamic_debug.h:261:9: note: in expansion of macro '_dynamic_func_call_cls' 261 | _dynamic_func_call_cls(_DPRINTK_CLASS_DFLT, fmt, func, ##__VA_ARGS__) | ^~~~~~~~~~~~~~~~~~~~~~ include/linux/dynamic_debug.h:284:9: note: in expansion of macro '_dynamic_func_call' 284 | _dynamic_func_call(fmt, __dynamic_dev_dbg, \ | ^~~~~~~~~~~~~~~~~~ include/linux/dev_printk.h:165:9: note: in expansion of macro 'dynamic_dev_dbg' 165 | dynamic_dev_dbg(dev, dev_fmt(fmt), ##__VA_ARGS__) | ^~~~~~~~~~~~~~~ include/linux/dev_printk.h:165:30: note: in expansion of macro 'dev_fmt' 165 | dynamic_dev_dbg(dev, dev_fmt(fmt), ##__VA_ARGS__) | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c:774:9: note: in expansion of macro 'dev_dbg' 774 | dev_dbg(crg_udc->dev, "dma = 0x%llx, ", usb_req->dma); | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c:774:43: note: format string is defined here 774 | dev_dbg(crg_udc->dev, "dma = 0x%llx, ", usb_req->dma); | ~~~^ | | | long long unsigned int | %x In file included from include/linux/printk.h:621, from include/asm-generic/bug.h:31, from ./arch/nios2/include/generated/asm/bug.h:1, from include/linux/bug.h:5, from include/linux/random.h:6, from include/linux/net.h:18, from drivers/usb/gadget/udc/crg_udc.c:7: drivers/usb/gadget/udc/crg_udc.c: In function 'crg_udc_queue_trbs': 896 | (void *)sg_addr, buffer_length, num_trbs_needed); | ^ include/linux/dynamic_debug.h:231:29: note: in definition of macro '__dynamic_func_call_cls' 231 | func(&id, ##__VA_ARGS__); \ | ^~~~~~~~~~~ include/linux/dynamic_debug.h:261:9: note: in expansion of macro '_dynamic_func_call_cls' 261 | _dynamic_func_call_cls(_DPRINTK_CLASS_DFLT, fmt, func, ##__VA_ARGS__) | ^~~~~~~~~~~~~~~~~~~~~~ include/linux/dynamic_debug.h:284:9: note: in expansion of macro '_dynamic_func_call' 284 | _dynamic_func_call(fmt, __dynamic_dev_dbg, \ | ^~~~~~~~~~~~~~~~~~ include/linux/dev_printk.h:165:9: note: in expansion of macro 'dynamic_dev_dbg' 165 | dynamic_dev_dbg(dev, dev_fmt(fmt), ##__VA_ARGS__) | ^~~~~~~~~~~~~~~ drivers/usb/gadget/udc/crg_udc.c:894:17: note: in expansion of macro 'dev_dbg' 894 | dev_dbg(crg_udc->dev, | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c:881:13: warning: variable 'num_sgs' set but not used [-Wunused-but-set-variable] 881 | u32 num_sgs = 0; | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c: In function 'crg_udc_ep_enable': drivers/usb/gadget/udc/crg_udc.c:1812:26: warning: variable 'uccr' set but not used [-Wunused-but-set-variable] 1812 | struct crg_uccr *uccr; | ^~~~ drivers/usb/gadget/udc/crg_udc.c:1811:25: warning: variable 'epcx' set but not used [-Wunused-but-set-variable] 1811 | struct ep_cx_s *epcx; | ^~~~ In file included from include/linux/printk.h:621, from include/asm-generic/bug.h:31, from ./arch/nios2/include/generated/asm/bug.h:1, from include/linux/bug.h:5, from include/linux/random.h:6, from include/linux/net.h:18, from drivers/usb/gadget/udc/crg_udc.c:7: drivers/usb/gadget/udc/crg_udc.c: In function 'init_ep0': drivers/usb/gadget/udc/crg_udc.c:2681:31: warning: format '%llx' expects argument of type 'long long unsigned int', but argument 4 has type 'dma_addr_t' {aka 'unsigned int'} [-Wformat=] 2681 | dev_dbg(crg_udc->dev, "ep0 ring dma addr = 0x%llx\n", udc_ep_ptr->tran_ring_info.dma); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ include/linux/dynamic_debug.h:231:29: note: in definition of macro '__dynamic_func_call_cls' 231 | func(&id, ##__VA_ARGS__); \ | ^~~~~~~~~~~ include/linux/dynamic_debug.h:261:9: note: in expansion of macro '_dynamic_func_call_cls' 261 | _dynamic_func_call_cls(_DPRINTK_CLASS_DFLT, fmt, func, ##__VA_ARGS__) | ^~~~~~~~~~~~~~~~~~~~~~ include/linux/dynamic_debug.h:284:9: note: in expansion of macro '_dynamic_func_call' 284 | _dynamic_func_call(fmt, __dynamic_dev_dbg, \ | ^~~~~~~~~~~~~~~~~~ include/linux/dev_printk.h:165:9: note: in expansion of macro 'dynamic_dev_dbg' 165 | dynamic_dev_dbg(dev, dev_fmt(fmt), ##__VA_ARGS__) | ^~~~~~~~~~~~~~~ include/linux/dev_printk.h:165:30: note: in expansion of macro 'dev_fmt' 165 | dynamic_dev_dbg(dev, dev_fmt(fmt), ##__VA_ARGS__) | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c:2681:9: note: in expansion of macro 'dev_dbg' 2681 | dev_dbg(crg_udc->dev, "ep0 ring dma addr = 0x%llx\n", udc_ep_ptr->tran_ring_info.dma); | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c:2681:57: note: format string is defined here 2681 | dev_dbg(crg_udc->dev, "ep0 ring dma addr = 0x%llx\n", udc_ep_ptr->tran_ring_info.dma); | ~~~^ | | | long long unsigned int | %x In file included from include/linux/printk.h:621, from include/asm-generic/bug.h:31, from ./arch/nios2/include/generated/asm/bug.h:1, from include/linux/bug.h:5, from include/linux/random.h:6, from include/linux/net.h:18, from drivers/usb/gadget/udc/crg_udc.c:7: drivers/usb/gadget/udc/crg_udc.c: In function 'getstatusrequest': drivers/usb/gadget/udc/crg_udc.c:3131:31: warning: format '%llx' expects argument of type 'long long unsigned int', but argument 4 has type 'dma_addr_t' {aka 'unsigned int'} [-Wformat=] 3131 | dev_dbg(crg_udc->dev, "udc_req_ptr->usb_req.dma = 0x%llx\n", | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ include/linux/dynamic_debug.h:231:29: note: in definition of macro '__dynamic_func_call_cls' 231 | func(&id, ##__VA_ARGS__); \ | ^~~~~~~~~~~ include/linux/dynamic_debug.h:261:9: note: in expansion of macro '_dynamic_func_call_cls' 261 | _dynamic_func_call_cls(_DPRINTK_CLASS_DFLT, fmt, func, ##__VA_ARGS__) | ^~~~~~~~~~~~~~~~~~~~~~ include/linux/dynamic_debug.h:284:9: note: in expansion of macro '_dynamic_func_call' 284 | _dynamic_func_call(fmt, __dynamic_dev_dbg, \ | ^~~~~~~~~~~~~~~~~~ include/linux/dev_printk.h:165:9: note: in expansion of macro 'dynamic_dev_dbg' 165 | dynamic_dev_dbg(dev, dev_fmt(fmt), ##__VA_ARGS__) | ^~~~~~~~~~~~~~~ include/linux/dev_printk.h:165:30: note: in expansion of macro 'dev_fmt' 165 | dynamic_dev_dbg(dev, dev_fmt(fmt), ##__VA_ARGS__) | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c:3131:9: note: in expansion of macro 'dev_dbg' 3131 | dev_dbg(crg_udc->dev, "udc_req_ptr->usb_req.dma = 0x%llx\n", | ^~~~~~~ drivers/usb/gadget/udc/crg_udc.c:3131:64: note: format string is defined here 3131 | dev_dbg(crg_udc->dev, "udc_req_ptr->usb_req.dma = 0x%llx\n", | ~~~^ | | | long long unsigned int | %x drivers/usb/gadget/udc/crg_udc.c: In function 'crg_udc_common_irq': drivers/usb/gadget/udc/crg_udc.c:4250:13: warning: variable 'retval' set but not used [-Wunused-but-set-variable] 4250 | int retval = 0; vim +624 drivers/usb/gadget/udc/crg_udc.c 609 610 static void crg_udc_epcx_setup(struct crg_udc_ep *udc_ep) 611 { 612 struct crg_gadget_dev *crg_udc = udc_ep->crg_udc; 613 const struct usb_endpoint_descriptor *desc = udc_ep->desc; 614 const struct usb_ss_ep_comp_descriptor *comp_desc = udc_ep->comp_desc; 615 u8 DCI = udc_ep->DCI; 616 struct ep_cx_s *epcx = (struct ep_cx_s *)(crg_udc->p_epcx + DCI - 2); 617 enum EP_TYPE_E ep_type; 618 u16 maxburst = 0; 619 u8 maxstreams = 0; 620 u16 maxsize; 621 u32 dw; 622 623 dev_dbg(crg_udc->dev, "crgudc->p_epcx %p, epcx %p\n", crg_udc->p_epcx, epcx); > 624 dev_dbg(crg_udc->dev, "DCI %d, sizeof ep_cx %ld\n", DCI, sizeof(struct ep_cx_s)); 625 dev_dbg(crg_udc->dev, "desc epaddr = 0x%x\n", desc->bEndpointAddress); 626 627 /*corigine gadget dir should be opposite to host dir*/ 628 if (usb_endpoint_dir_out(desc)) 629 ep_type = usb_endpoint_type(desc) + EP_TYPE_INVALID2; 630 else 631 ep_type = usb_endpoint_type(desc); 632 633 maxsize = usb_endpoint_maxp(desc) & 0x07ff; /* D[0:10] */ 634 635 if (crg_udc->gadget.speed >= USB_SPEED_SUPER) { 636 maxburst = comp_desc->bMaxBurst; 637 638 if (usb_endpoint_xfer_bulk(udc_ep->desc)) 639 maxstreams = comp_desc->bmAttributes & 0x1f; 640 641 } else if ((crg_udc->gadget.speed == USB_SPEED_HIGH || 642 crg_udc->gadget.speed == USB_SPEED_FULL) && 643 (usb_endpoint_xfer_int(udc_ep->desc) || 644 usb_endpoint_xfer_isoc(udc_ep->desc))) { 645 if (crg_udc->gadget.speed == USB_SPEED_HIGH) 646 maxburst = (usb_endpoint_maxp(desc) >> 11) & 0x3; 647 if (maxburst == 0x3) { 648 dev_err(crg_udc->dev, "invalid maxburst\n"); 649 maxburst = 0x2; 650 } 651 } 652 653 /* fill ep_dw0 */ 654 dw = 0; 655 dw = SETF_VAR(EP_CX_LOGICAL_EP_NUM, dw, udc_ep->DCI / 2); 656 dw = SETF_VAR(EP_CX_INTERVAL, dw, desc->bInterval); 657 if (maxstreams) { 658 dev_err(crg_udc->dev, "%s maxstream=%d is not expected\n", 659 __func__, maxstreams); 660 } 661 epcx->dw0 = cpu_to_le32(dw); 662 663 /* fill ep_dw1 */ 664 dw = 0; 665 dw = SETF_VAR(EP_CX_EP_TYPE, dw, ep_type); 666 dw = SETF_VAR(EP_CX_MAX_PACKET_SIZE, dw, maxsize); 667 dw = SETF_VAR(EP_CX_MAX_BURST_SIZE, dw, maxburst); 668 epcx->dw1 = cpu_to_le32(dw); 669 670 /* fill ep_dw2 */ 671 dw = lower_32_bits(udc_ep->tran_ring_info.dma) & EP_CX_TR_DQPT_LO_MASK; 672 dw = SETF_VAR(EP_CX_DEQ_CYC_STATE, dw, udc_ep->pcs); 673 epcx->dw2 = cpu_to_le32(dw); 674 675 /* fill ep_dw3 */ 676 dw = upper_32_bits(udc_ep->tran_ring_info.dma); 677 epcx->dw3 = cpu_to_le32(dw); 678 /* Ensure that epcx is updated */ 679 wmb(); 680 } 681 682 static void crg_udc_epcx_update_dqptr(struct crg_udc_ep *udc_ep) 683 { 684 struct crg_gadget_dev *crg_udc = udc_ep->crg_udc; 685 u8 DCI = udc_ep->DCI; 686 struct ep_cx_s *epcx = (struct ep_cx_s *)(crg_udc->p_epcx + DCI - 2); 687 u32 dw; 688 dma_addr_t dqptaddr; 689 u32 cmd_param0; 690 691 if (DCI == 0) { 692 dev_err(crg_udc->dev, "%s Cannot update dqptr for ep0\n", __func__); 693 return; 694 } 695 696 dqptaddr = tran_trb_virt_to_dma(udc_ep, udc_ep->deq_pt); 697 698 /* fill ep_dw2 */ 699 dw = lower_32_bits(dqptaddr) & EP_CX_TR_DQPT_LO_MASK; 700 dw = SETF_VAR(EP_CX_DEQ_CYC_STATE, dw, udc_ep->pcs); 701 epcx->dw2 = cpu_to_le32(dw); 702 703 /* fill ep_dw3 */ 704 dw = upper_32_bits(dqptaddr); 705 epcx->dw3 = cpu_to_le32(dw); 706 707 cmd_param0 = (0x1 << udc_ep->DCI); 708 /* Ensure that dqptr is updated */ 709 wmb(); 710 711 crg_issue_command(crg_udc, CRG_CMD_SET_TR_DQPTR, cmd_param0, 0); 712 } 713 714 static void setup_status_trb(struct crg_gadget_dev *crg_udc, 715 struct transfer_trb_s *p_trb, 716 struct usb_request *usb_req, u8 pcs, u8 set_addr, u8 stall) 717 { 718 u32 tmp, dir = 0; 719 720 /* There are some cases where seutp_status_trb() is called with 721 * usb_req set to NULL. 722 */ 723 724 p_trb->dw0 = 0; 725 p_trb->dw1 = 0; 726 727 dev_dbg(crg_udc->dev, "data_buf_ptr_lo = 0x%x, data_buf_ptr_hi = 0x%x\n", 728 p_trb->dw0, p_trb->dw1); 729 730 tmp = 0; 731 tmp = SETF_VAR(TRB_INTR_TARGET, tmp, 0); 732 p_trb->dw2 = tmp; 733 734 tmp = 0; 735 tmp = SETF_VAR(TRB_CYCLE_BIT, tmp, pcs); 736 tmp = SETF_VAR(TRB_INTR_ON_COMPLETION, tmp, 1);/*IOC:1*/ 737 tmp = SETF_VAR(TRB_TYPE, tmp, TRB_TYPE_XFER_STATUS_STAGE); 738 739 dir = (crg_udc->setup_status == STATUS_STAGE_XFER) ? 0 : 1; 740 tmp = SETF_VAR(DATA_STAGE_TRB_DIR, tmp, dir); 741 742 tmp = SETF_VAR(TRB_SETUP_TAG, tmp, crg_udc->setup_tag); 743 tmp = SETF_VAR(STATUS_STAGE_TRB_STALL, tmp, stall); 744 tmp = SETF_VAR(STATUS_STAGE_TRB_SET_ADDR, tmp, set_addr); 745 746 p_trb->dw3 = tmp; 747 dev_dbg(crg_udc->dev, "trb_dword2 = 0x%x, trb_dword3 = 0x%x\n", 748 p_trb->dw2, p_trb->dw3); 749 /* Ensure that status trb is updated */ 750 wmb(); 751 } 752 753 static void knock_doorbell(struct crg_gadget_dev *crg_udc, int DCI) 754 { 755 u32 tmp; 756 struct crg_uccr *uccr; 757 758 uccr = crg_udc->uccr; 759 /* Ensure evreything is written before notifying the HW */ 760 wmb(); 761 762 tmp = CRG_U3DC_DB_TARGET(DCI); 763 dev_dbg(crg_udc->dev, "DOORBELL = 0x%x\n", tmp); 764 writel(tmp, &uccr->doorbell); 765 } 766 767 static void setup_datastage_trb(struct crg_gadget_dev *crg_udc, 768 struct transfer_trb_s *p_trb, struct usb_request *usb_req, 769 u8 pcs, u32 num_trb, u32 transfer_length, u32 td_size, 770 u8 IOC, u8 AZP, u8 dir, u8 setup_tag) 771 { 772 u32 tmp; 773 > 774 dev_dbg(crg_udc->dev, "dma = 0x%llx, ", usb_req->dma); 775 dev_dbg(crg_udc->dev, "buf = 0x%lx, ", (unsigned long)usb_req->buf); 776 777 p_trb->dw0 = lower_32_bits(usb_req->dma); 778 p_trb->dw1 = upper_32_bits(usb_req->dma); 779 780 dev_dbg(crg_udc->dev, "data_buf_ptr_lo = 0x%x, data_buf_ptr_hi = 0x%x\n", 781 p_trb->dw0, p_trb->dw1); 782 783 784 /* TRB_Transfer_Length 785 *For USB_DIR_OUT, this field is the number of data bytes expected from 786 *xhc. For USB_DIR_IN, this field is the number of data bytes the device 787 *will send. 788 */ 789 tmp = 0; 790 tmp = SETF_VAR(TRB_TRANSFER_LEN, tmp, transfer_length); 791 tmp = SETF_VAR(TRB_TD_SIZE, tmp, td_size); 792 tmp = SETF_VAR(TRB_INTR_TARGET, tmp, 0); 793 p_trb->dw2 = tmp; 794 795 tmp = 0; 796 tmp = SETF_VAR(TRB_CYCLE_BIT, tmp, pcs); 797 tmp = SETF_VAR(TRB_INTR_ON_SHORT_PKT, tmp, 1); 798 tmp = SETF_VAR(TRB_INTR_ON_COMPLETION, tmp, IOC); 799 tmp = SETF_VAR(TRB_TYPE, tmp, TRB_TYPE_XFER_DATA_STAGE); 800 tmp = SETF_VAR(TRB_APPEND_ZLP, tmp, AZP); 801 tmp = SETF_VAR(DATA_STAGE_TRB_DIR, tmp, dir); 802 tmp = SETF_VAR(TRB_SETUP_TAG, tmp, setup_tag); 803 804 p_trb->dw3 = tmp; 805 /* Ensure that datastage trb is updated */ 806 wmb(); 807 808 dev_dbg(crg_udc->dev, "trb_dword0 = 0x%x, trb_dword1 = 0x%x trb_dword2 = 0x%x, trb_dword3 = 0x%x\n", 809 p_trb->dw0, p_trb->dw1, p_trb->dw2, p_trb->dw3); 810 } 811 -- 0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
{ "author": "kernel test robot <lkp@intel.com>", "date": "Tue, 3 Feb 2026 02:20:11 +0800", "thread_id": "202602030223.QlbiPC8d-lkp@intel.com.mbox.gz" }
lkml
[PATCH 0/2] Add HPET NMI Watchdog support
The current NMI watchdog relies on performance counters and consistently occupies one on each CPU. When running virtual machines, we want to pass performance counters to virtual machines so they can make use of them. In addition the host system wants to use performance counters to check the system to identify when anything looks abnormal, such as split locks. That makes PMCs a precious resource. So any PMC we can free up is a PMC we can use for something useful. That made me look at the NMI watchdog. The PMC based NMI watchdog implementation does not actually need any performance counting. It just needs a per-CPU NMI timer source. X86 systems can make anything that emits an interrupt descriptor (IOAPIC, MSI(-X), etc) become an NMI source. So any time goes. Including the HPET. And while they can't really operate per-CPU, in almost all cases you only really want the NMI on *all* CPUs, rather than per-CPU. So I took a stab at building an HPET based NMI watchdog. In my (QEMU based) testing, it's fully functional and can successfully detect when CPUs get stuck. It even survives suspend/resume cycles. For now, its enablement is a config time option because the hardlockup framework does not support dynamic switching of multiple detectors. That's ok for our use case. But maybe something for the interested reader to tackle eventually :). You can enable the HPET watchdog by default by setting CONFIG_HARDLOCKUP_DETECTOR_HPET_DEFAULT=y or passing "hpet=watchdog" to the kernel command line. When active, it will emit a kernel log message to indicate it works: [ 0.179176] hpet: HPET watchdog initialized on timer 0, GSI 2 The HPET can only be in either watchdog or generic mode. I am a bit worried about IO-APIC pin allocation logic, so I opted to reuse the generic timer pin. And that means I'm effectively breaking the normal interrupt delivery path. so the easy way out was to say when watchdog is active, PIT and HPET are not available as timer sources. Which is ok on modern systems. There are way too many (unreliable) timer sources on x86 already. Trimming a few surely won't hurt. I'm open to inputs on how to make the HPET multi-purpose though, in case anyone feels strongly about it. Alex Alexander Graf (2): x86/ioapic: Add NMI delivery configuration helper hpet: Add HPET-based NMI watchdog support .../admin-guide/kernel-parameters.txt | 5 +- arch/x86/Kconfig | 19 ++ arch/x86/include/asm/io_apic.h | 2 + arch/x86/kernel/apic/io_apic.c | 32 ++++ arch/x86/kernel/hpet.c | 172 ++++++++++++++++++ arch/x86/kernel/i8253.c | 9 + drivers/char/hpet.c | 3 + include/linux/hpet.h | 14 ++ 8 files changed, 255 insertions(+), 1 deletion(-) -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
To implement an HPET based NMI watchdog, the HPET code will need to reconfigure an IOAPIC pin to NMI mode. Add a function that allows driver code to configure an IOAPIC pin for NMI delivery mode. (Disclaimer: Some of this code was written with the help of Kiro, an AI coding assistant) Signed-off-by: Alexander Graf <graf@amazon.com> --- arch/x86/include/asm/io_apic.h | 2 ++ arch/x86/kernel/apic/io_apic.c | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/arch/x86/include/asm/io_apic.h b/arch/x86/include/asm/io_apic.h index 0d806513c4b3..58cfb338bf39 100644 --- a/arch/x86/include/asm/io_apic.h +++ b/arch/x86/include/asm/io_apic.h @@ -158,6 +158,8 @@ extern void mp_save_irq(struct mpc_intsrc *m); extern void disable_ioapic_support(void); +extern int ioapic_set_nmi(u32 gsi, bool broadcast); + extern void __init io_apic_init_mappings(void); extern unsigned int native_io_apic_read(unsigned int apic, unsigned int reg); extern void native_restore_boot_irq_mode(void); diff --git a/arch/x86/kernel/apic/io_apic.c b/arch/x86/kernel/apic/io_apic.c index 28f934f05a85..006f328929cd 100644 --- a/arch/x86/kernel/apic/io_apic.c +++ b/arch/x86/kernel/apic/io_apic.c @@ -2951,6 +2951,38 @@ int mp_irqdomain_ioapic_idx(struct irq_domain *domain) return (int)(long)domain->host_data; } +/** + * ioapic_set_nmi - Configure an IOAPIC pin for NMI delivery + * @gsi: Global System Interrupt number + * @broadcast: true to broadcast to all CPUs, false to send to CPU 0 only + * + * Configures the specified GSI for NMI delivery mode. + * + * Returns 0 on success, negative error code on failure. + */ +int ioapic_set_nmi(u32 gsi, bool broadcast) +{ + struct IO_APIC_route_entry entry = { }; + int ioapic_idx, pin; + + ioapic_idx = mp_find_ioapic(gsi); + if (ioapic_idx < 0) + return -ENODEV; + + pin = mp_find_ioapic_pin(ioapic_idx, gsi); + if (pin < 0) + return -ENODEV; + + entry.delivery_mode = APIC_DELIVERY_MODE_NMI; + entry.destid_0_7 = broadcast ? 0xFF : 0; + entry.dest_mode_logical = 0; + entry.masked = 0; + + ioapic_write_entry(ioapic_idx, pin, entry); + + return 0; +} + const struct irq_domain_ops mp_ioapic_irqdomain_ops = { .alloc = mp_irqdomain_alloc, .free = mp_irqdomain_free, -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
{ "author": "Alexander Graf <graf@amazon.com>", "date": "Mon, 2 Feb 2026 17:43:15 +0000", "thread_id": "e38c5244-9e8f-467c-b3aa-8098f288a2c3@amazon.com.mbox.gz" }
lkml
[PATCH 0/2] Add HPET NMI Watchdog support
The current NMI watchdog relies on performance counters and consistently occupies one on each CPU. When running virtual machines, we want to pass performance counters to virtual machines so they can make use of them. In addition the host system wants to use performance counters to check the system to identify when anything looks abnormal, such as split locks. That makes PMCs a precious resource. So any PMC we can free up is a PMC we can use for something useful. That made me look at the NMI watchdog. The PMC based NMI watchdog implementation does not actually need any performance counting. It just needs a per-CPU NMI timer source. X86 systems can make anything that emits an interrupt descriptor (IOAPIC, MSI(-X), etc) become an NMI source. So any time goes. Including the HPET. And while they can't really operate per-CPU, in almost all cases you only really want the NMI on *all* CPUs, rather than per-CPU. So I took a stab at building an HPET based NMI watchdog. In my (QEMU based) testing, it's fully functional and can successfully detect when CPUs get stuck. It even survives suspend/resume cycles. For now, its enablement is a config time option because the hardlockup framework does not support dynamic switching of multiple detectors. That's ok for our use case. But maybe something for the interested reader to tackle eventually :). You can enable the HPET watchdog by default by setting CONFIG_HARDLOCKUP_DETECTOR_HPET_DEFAULT=y or passing "hpet=watchdog" to the kernel command line. When active, it will emit a kernel log message to indicate it works: [ 0.179176] hpet: HPET watchdog initialized on timer 0, GSI 2 The HPET can only be in either watchdog or generic mode. I am a bit worried about IO-APIC pin allocation logic, so I opted to reuse the generic timer pin. And that means I'm effectively breaking the normal interrupt delivery path. so the easy way out was to say when watchdog is active, PIT and HPET are not available as timer sources. Which is ok on modern systems. There are way too many (unreliable) timer sources on x86 already. Trimming a few surely won't hurt. I'm open to inputs on how to make the HPET multi-purpose though, in case anyone feels strongly about it. Alex Alexander Graf (2): x86/ioapic: Add NMI delivery configuration helper hpet: Add HPET-based NMI watchdog support .../admin-guide/kernel-parameters.txt | 5 +- arch/x86/Kconfig | 19 ++ arch/x86/include/asm/io_apic.h | 2 + arch/x86/kernel/apic/io_apic.c | 32 ++++ arch/x86/kernel/hpet.c | 172 ++++++++++++++++++ arch/x86/kernel/i8253.c | 9 + drivers/char/hpet.c | 3 + include/linux/hpet.h | 14 ++ 8 files changed, 255 insertions(+), 1 deletion(-) -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
The current NMI watchdog relies on performance counters and consistently occupies one on each CPU. When running virtual machines, we want to pass performance counters to virtual machines so they can make use of them. In addition the host system wants to use performance counters to check the system to identify when anything looks abnormal, such as split locks. That makes PMCs a precious resource. So any PMC we can free up is a PMC we can use for something useful. That made me look at the NMI watchdog. The PMC based NMI watchdog implementation does not actually need any performance counting. It just needs a per-CPU NMI timer source. X86 systems can make anything that emits an interrupt descriptor (IOAPIC, MSI(-X), etc) become an NMI source. So any time goes. Including the HPET. And while they can't really operate per-CPU, in almost all cases you only really want the NMI on *all* CPUs, rather than per-CPU. So I took a stab at building an HPET based NMI watchdog. In my (QEMU based) testing, it's fully functional and can successfully detect when CPUs get stuck. It even survives suspend/resume cycles. For now, its enablement is a config time option because the hardlockup framework does not support dynamic switching of multiple detectors. That's ok for our use case. But maybe something for the interested reader to tackle eventually :). You can enable the HPET watchdog by default by setting CONFIG_HARDLOCKUP_DETECTOR_HPET_DEFAULT=y or passing "hpet=watchdog" to the kernel command line. When active, it will emit a kernel log message to indicate it works: [ 0.179176] hpet: HPET watchdog initialized on timer 0, GSI 2 The HPET can only be in either watchdog or generic mode. I am a bit worried about IO-APIC pin allocation logic, so I opted to reuse the generic timer pin. And that means I'm effectively breaking the normal interrupt delivery path. so the easy way out was to say when watchdog is active, PIT and HPET are not available as timer sources. Which is ok on modern systems. There are way too many (unreliable) timer sources on x86 already. Trimming a few surely won't hurt. I'm open to inputs on how to make the HPET multi-purpose though, in case anyone feels strongly about it. Alex Alexander Graf (2): x86/ioapic: Add NMI delivery configuration helper hpet: Add HPET-based NMI watchdog support .../admin-guide/kernel-parameters.txt | 5 +- arch/x86/Kconfig | 19 ++ arch/x86/include/asm/io_apic.h | 2 + arch/x86/kernel/apic/io_apic.c | 32 ++++ arch/x86/kernel/hpet.c | 172 ++++++++++++++++++ arch/x86/kernel/i8253.c | 9 + drivers/char/hpet.c | 3 + include/linux/hpet.h | 14 ++ 8 files changed, 255 insertions(+), 1 deletion(-) -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
{ "author": "Alexander Graf <graf@amazon.com>", "date": "Mon, 2 Feb 2026 17:48:01 +0000", "thread_id": "e38c5244-9e8f-467c-b3aa-8098f288a2c3@amazon.com.mbox.gz" }
lkml
[PATCH 0/2] Add HPET NMI Watchdog support
The current NMI watchdog relies on performance counters and consistently occupies one on each CPU. When running virtual machines, we want to pass performance counters to virtual machines so they can make use of them. In addition the host system wants to use performance counters to check the system to identify when anything looks abnormal, such as split locks. That makes PMCs a precious resource. So any PMC we can free up is a PMC we can use for something useful. That made me look at the NMI watchdog. The PMC based NMI watchdog implementation does not actually need any performance counting. It just needs a per-CPU NMI timer source. X86 systems can make anything that emits an interrupt descriptor (IOAPIC, MSI(-X), etc) become an NMI source. So any time goes. Including the HPET. And while they can't really operate per-CPU, in almost all cases you only really want the NMI on *all* CPUs, rather than per-CPU. So I took a stab at building an HPET based NMI watchdog. In my (QEMU based) testing, it's fully functional and can successfully detect when CPUs get stuck. It even survives suspend/resume cycles. For now, its enablement is a config time option because the hardlockup framework does not support dynamic switching of multiple detectors. That's ok for our use case. But maybe something for the interested reader to tackle eventually :). You can enable the HPET watchdog by default by setting CONFIG_HARDLOCKUP_DETECTOR_HPET_DEFAULT=y or passing "hpet=watchdog" to the kernel command line. When active, it will emit a kernel log message to indicate it works: [ 0.179176] hpet: HPET watchdog initialized on timer 0, GSI 2 The HPET can only be in either watchdog or generic mode. I am a bit worried about IO-APIC pin allocation logic, so I opted to reuse the generic timer pin. And that means I'm effectively breaking the normal interrupt delivery path. so the easy way out was to say when watchdog is active, PIT and HPET are not available as timer sources. Which is ok on modern systems. There are way too many (unreliable) timer sources on x86 already. Trimming a few surely won't hurt. I'm open to inputs on how to make the HPET multi-purpose though, in case anyone feels strongly about it. Alex Alexander Graf (2): x86/ioapic: Add NMI delivery configuration helper hpet: Add HPET-based NMI watchdog support .../admin-guide/kernel-parameters.txt | 5 +- arch/x86/Kconfig | 19 ++ arch/x86/include/asm/io_apic.h | 2 + arch/x86/kernel/apic/io_apic.c | 32 ++++ arch/x86/kernel/hpet.c | 172 ++++++++++++++++++ arch/x86/kernel/i8253.c | 9 + drivers/char/hpet.c | 3 + include/linux/hpet.h | 14 ++ 8 files changed, 255 insertions(+), 1 deletion(-) -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
On 02.02.26 18:43, Alexander Graf wrote: Sorry for the resend. I caught an issue while sending out the series, hit ctrl-c before thinking and suddenly had a half sent series. Discard this one. Happy review on the real, full one :) Alex Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
{ "author": "Alexander Graf <graf@amazon.com>", "date": "Mon, 2 Feb 2026 18:49:13 +0100", "thread_id": "e38c5244-9e8f-467c-b3aa-8098f288a2c3@amazon.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Add verify-only public key crypto support for ML-DSA so that the X.509/PKCS#7 signature verification code, as used by module signing, amongst other things, can make use of it through the common crypto_sig API. Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org> cc: Eric Biggers <ebiggers@kernel.org> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/Kconfig | 9 +++ crypto/Makefile | 2 + crypto/mldsa.c | 201 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 212 insertions(+) create mode 100644 crypto/mldsa.c diff --git a/crypto/Kconfig b/crypto/Kconfig index 12a87f7cf150..a210575fa5e0 100644 --- a/crypto/Kconfig +++ b/crypto/Kconfig @@ -344,6 +344,15 @@ config CRYPTO_ECRDSA One of the Russian cryptographic standard algorithms (called GOST algorithms). Only signature verification is implemented. +config CRYPTO_MLDSA + tristate "ML-DSA (Module-Lattice-Based Digital Signature Algorithm)" + select CRYPTO_SIG + select CRYPTO_LIB_MLDSA + help + ML-DSA (Module-Lattice-Based Digital Signature Algorithm) (FIPS-204). + + Only signature verification is implemented. + endmenu menu "Block ciphers" diff --git a/crypto/Makefile b/crypto/Makefile index 23d3db7be425..267d5403045b 100644 --- a/crypto/Makefile +++ b/crypto/Makefile @@ -60,6 +60,8 @@ ecdsa_generic-y += ecdsa-p1363.o ecdsa_generic-y += ecdsasignature.asn1.o obj-$(CONFIG_CRYPTO_ECDSA) += ecdsa_generic.o +obj-$(CONFIG_CRYPTO_MLDSA) += mldsa.o + crypto_acompress-y := acompress.o crypto_acompress-y += scompress.o obj-$(CONFIG_CRYPTO_ACOMP2) += crypto_acompress.o diff --git a/crypto/mldsa.c b/crypto/mldsa.c new file mode 100644 index 000000000000..d8de082cc67a --- /dev/null +++ b/crypto/mldsa.c @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * crypto_sig wrapper around ML-DSA library. + */ +#include <linux/init.h> +#include <linux/module.h> +#include <crypto/internal/sig.h> +#include <crypto/mldsa.h> + +struct crypto_mldsa_ctx { + u8 pk[MAX(MAX(MLDSA44_PUBLIC_KEY_SIZE, + MLDSA65_PUBLIC_KEY_SIZE), + MLDSA87_PUBLIC_KEY_SIZE)]; + unsigned int pk_len; + enum mldsa_alg strength; + bool key_set; +}; + +static int crypto_mldsa_sign(struct crypto_sig *tfm, + const void *msg, unsigned int msg_len, + void *sig, unsigned int sig_len) +{ + return -EOPNOTSUPP; +} + +static int crypto_mldsa_verify(struct crypto_sig *tfm, + const void *sig, unsigned int sig_len, + const void *msg, unsigned int msg_len) +{ + const struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + if (unlikely(!ctx->key_set)) + return -EINVAL; + + return mldsa_verify(ctx->strength, sig, sig_len, msg, msg_len, + ctx->pk, ctx->pk_len); +} + +static unsigned int crypto_mldsa_key_size(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + switch (ctx->strength) { + case MLDSA44: + return MLDSA44_PUBLIC_KEY_SIZE; + case MLDSA65: + return MLDSA65_PUBLIC_KEY_SIZE; + case MLDSA87: + return MLDSA87_PUBLIC_KEY_SIZE; + default: + WARN_ON_ONCE(1); + return 0; + } +} + +static int crypto_mldsa_set_pub_key(struct crypto_sig *tfm, + const void *key, unsigned int keylen) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + unsigned int expected_len = crypto_mldsa_key_size(tfm); + + if (keylen != expected_len) + return -EINVAL; + + ctx->pk_len = keylen; + memcpy(ctx->pk, key, keylen); + ctx->key_set = true; + return 0; +} + +static int crypto_mldsa_set_priv_key(struct crypto_sig *tfm, + const void *key, unsigned int keylen) +{ + return -EOPNOTSUPP; +} + +static unsigned int crypto_mldsa_max_size(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + switch (ctx->strength) { + case MLDSA44: + return MLDSA44_SIGNATURE_SIZE; + case MLDSA65: + return MLDSA65_SIGNATURE_SIZE; + case MLDSA87: + return MLDSA87_SIGNATURE_SIZE; + default: + WARN_ON_ONCE(1); + return 0; + } +} + +static int crypto_mldsa44_alg_init(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + ctx->strength = MLDSA44; + ctx->key_set = false; + return 0; +} + +static int crypto_mldsa65_alg_init(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + ctx->strength = MLDSA65; + ctx->key_set = false; + return 0; +} + +static int crypto_mldsa87_alg_init(struct crypto_sig *tfm) +{ + struct crypto_mldsa_ctx *ctx = crypto_sig_ctx(tfm); + + ctx->strength = MLDSA87; + ctx->key_set = false; + return 0; +} + +static void crypto_mldsa_alg_exit(struct crypto_sig *tfm) +{ +} + +static struct sig_alg crypto_mldsa_algs[] = { + { + .sign = crypto_mldsa_sign, + .verify = crypto_mldsa_verify, + .set_pub_key = crypto_mldsa_set_pub_key, + .set_priv_key = crypto_mldsa_set_priv_key, + .key_size = crypto_mldsa_key_size, + .max_size = crypto_mldsa_max_size, + .init = crypto_mldsa44_alg_init, + .exit = crypto_mldsa_alg_exit, + .base.cra_name = "mldsa44", + .base.cra_driver_name = "mldsa44-lib", + .base.cra_ctxsize = sizeof(struct crypto_mldsa_ctx), + .base.cra_module = THIS_MODULE, + .base.cra_priority = 5000, + }, { + .sign = crypto_mldsa_sign, + .verify = crypto_mldsa_verify, + .set_pub_key = crypto_mldsa_set_pub_key, + .set_priv_key = crypto_mldsa_set_priv_key, + .key_size = crypto_mldsa_key_size, + .max_size = crypto_mldsa_max_size, + .init = crypto_mldsa65_alg_init, + .exit = crypto_mldsa_alg_exit, + .base.cra_name = "mldsa65", + .base.cra_driver_name = "mldsa65-lib", + .base.cra_ctxsize = sizeof(struct crypto_mldsa_ctx), + .base.cra_module = THIS_MODULE, + .base.cra_priority = 5000, + }, { + .sign = crypto_mldsa_sign, + .verify = crypto_mldsa_verify, + .set_pub_key = crypto_mldsa_set_pub_key, + .set_priv_key = crypto_mldsa_set_priv_key, + .key_size = crypto_mldsa_key_size, + .max_size = crypto_mldsa_max_size, + .init = crypto_mldsa87_alg_init, + .exit = crypto_mldsa_alg_exit, + .base.cra_name = "mldsa87", + .base.cra_driver_name = "mldsa87-lib", + .base.cra_ctxsize = sizeof(struct crypto_mldsa_ctx), + .base.cra_module = THIS_MODULE, + .base.cra_priority = 5000, + }, +}; + +static int __init mldsa_init(void) +{ + int ret, i; + + for (i = 0; i < ARRAY_SIZE(crypto_mldsa_algs); i++) { + ret = crypto_register_sig(&crypto_mldsa_algs[i]); + if (ret < 0) + goto error; + } + return 0; + +error: + pr_err("Failed to register (%d)\n", ret); + for (i--; i >= 0; i--) + crypto_unregister_sig(&crypto_mldsa_algs[i]); + return ret; +} +module_init(mldsa_init); + +static void mldsa_exit(void) +{ + for (int i = 0; i < ARRAY_SIZE(crypto_mldsa_algs); i++) + crypto_unregister_sig(&crypto_mldsa_algs[i]); +} +module_exit(mldsa_exit); + +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("Crypto API support for ML-DSA signature verification"); +MODULE_ALIAS_CRYPTO("mldsa44"); +MODULE_ALIAS_CRYPTO("mldsa65"); +MODULE_ALIAS_CRYPTO("mldsa87");
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:06 +0000", "thread_id": "20260202170216.2467036-7-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Calculate the SHA256 hash for blacklisting purposes independently of the signature hash (which may be something other than SHA256). This is necessary because when ML-DSA is used, no digest is calculated. Note that this represents a change of behaviour in that the hash used for the blacklist check would previously have been whatever digest was used for, say, RSA-based signatures. It may be that this is inadvisable. Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/x509_parser.h | 2 ++ crypto/asymmetric_keys/x509_public_key.c | 22 +++++++++++++--------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/crypto/asymmetric_keys/x509_parser.h b/crypto/asymmetric_keys/x509_parser.h index 0688c222806b..b7aeebdddb36 100644 --- a/crypto/asymmetric_keys/x509_parser.h +++ b/crypto/asymmetric_keys/x509_parser.h @@ -9,12 +9,14 @@ #include <linux/time.h> #include <crypto/public_key.h> #include <keys/asymmetric-type.h> +#include <crypto/sha2.h> struct x509_certificate { struct x509_certificate *next; struct x509_certificate *signer; /* Certificate that signed this one */ struct public_key *pub; /* Public key details */ struct public_key_signature *sig; /* Signature parameters */ + u8 sha256[SHA256_DIGEST_SIZE]; /* Hash for blacklist purposes */ char *issuer; /* Name of certificate issuer */ char *subject; /* Name of certificate subject */ struct asymmetric_key_id *id; /* Issuer + Serial number */ diff --git a/crypto/asymmetric_keys/x509_public_key.c b/crypto/asymmetric_keys/x509_public_key.c index 12e3341e806b..79cc7b7a0630 100644 --- a/crypto/asymmetric_keys/x509_public_key.c +++ b/crypto/asymmetric_keys/x509_public_key.c @@ -31,6 +31,19 @@ int x509_get_sig_params(struct x509_certificate *cert) pr_devel("==>%s()\n", __func__); + /* Calculate a SHA256 hash of the TBS and check it against the + * blacklist. + */ + sha256(cert->tbs, cert->tbs_size, cert->sha256); + ret = is_hash_blacklisted(cert->sha256, sizeof(cert->sha256), + BLACKLIST_HASH_X509_TBS); + if (ret == -EKEYREJECTED) { + pr_err("Cert %*phN is blacklisted\n", + (int)sizeof(cert->sha256), cert->sha256); + cert->blacklisted = true; + ret = 0; + } + sig->s = kmemdup(cert->raw_sig, cert->raw_sig_size, GFP_KERNEL); if (!sig->s) return -ENOMEM; @@ -69,15 +82,6 @@ int x509_get_sig_params(struct x509_certificate *cert) if (ret < 0) goto error_2; - ret = is_hash_blacklisted(sig->digest, sig->digest_size, - BLACKLIST_HASH_X509_TBS); - if (ret == -EKEYREJECTED) { - pr_err("Cert %*phN is blacklisted\n", - sig->digest_size, sig->digest); - cert->blacklisted = true; - ret = 0; - } - error_2: kfree(desc); error:
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:07 +0000", "thread_id": "20260202170216.2467036-7-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Rename ->digest and ->digest_len to ->m and ->m_size to represent the input to the signature verification algorithm, reflecting that ->digest may no longer actually *be* a digest. Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/asymmetric_type.c | 4 ++-- crypto/asymmetric_keys/pkcs7_verify.c | 28 ++++++++++++------------ crypto/asymmetric_keys/public_key.c | 3 +-- crypto/asymmetric_keys/signature.c | 2 +- crypto/asymmetric_keys/x509_public_key.c | 10 ++++----- include/crypto/public_key.h | 4 ++-- security/integrity/digsig_asymmetric.c | 4 ++-- 7 files changed, 26 insertions(+), 29 deletions(-) diff --git a/crypto/asymmetric_keys/asymmetric_type.c b/crypto/asymmetric_keys/asymmetric_type.c index 348966ea2175..2326743310b1 100644 --- a/crypto/asymmetric_keys/asymmetric_type.c +++ b/crypto/asymmetric_keys/asymmetric_type.c @@ -593,10 +593,10 @@ static int asymmetric_key_verify_signature(struct kernel_pkey_params *params, { struct public_key_signature sig = { .s_size = params->in2_len, - .digest_size = params->in_len, + .m_size = params->in_len, .encoding = params->encoding, .hash_algo = params->hash_algo, - .digest = (void *)in, + .m = (void *)in, .s = (void *)in2, }; diff --git a/crypto/asymmetric_keys/pkcs7_verify.c b/crypto/asymmetric_keys/pkcs7_verify.c index 6d6475e3a9bf..aa085ec6fb1c 100644 --- a/crypto/asymmetric_keys/pkcs7_verify.c +++ b/crypto/asymmetric_keys/pkcs7_verify.c @@ -31,7 +31,7 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, kenter(",%u,%s", sinfo->index, sinfo->sig->hash_algo); /* The digest was calculated already. */ - if (sig->digest) + if (sig->m) return 0; if (!sinfo->sig->hash_algo) @@ -45,11 +45,11 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, return (PTR_ERR(tfm) == -ENOENT) ? -ENOPKG : PTR_ERR(tfm); desc_size = crypto_shash_descsize(tfm) + sizeof(*desc); - sig->digest_size = crypto_shash_digestsize(tfm); + sig->m_size = crypto_shash_digestsize(tfm); ret = -ENOMEM; - sig->digest = kmalloc(sig->digest_size, GFP_KERNEL); - if (!sig->digest) + sig->m = kmalloc(sig->m_size, GFP_KERNEL); + if (!sig->m) goto error_no_desc; desc = kzalloc(desc_size, GFP_KERNEL); @@ -59,11 +59,10 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, desc->tfm = tfm; /* Digest the message [RFC2315 9.3] */ - ret = crypto_shash_digest(desc, pkcs7->data, pkcs7->data_len, - sig->digest); + ret = crypto_shash_digest(desc, pkcs7->data, pkcs7->data_len, sig->m); if (ret < 0) goto error; - pr_devel("MsgDigest = [%*ph]\n", 8, sig->digest); + pr_devel("MsgDigest = [%*ph]\n", 8, sig->m); /* However, if there are authenticated attributes, there must be a * message digest attribute amongst them which corresponds to the @@ -78,14 +77,14 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, goto error; } - if (sinfo->msgdigest_len != sig->digest_size) { + if (sinfo->msgdigest_len != sig->m_size) { pr_warn("Sig %u: Invalid digest size (%u)\n", sinfo->index, sinfo->msgdigest_len); ret = -EBADMSG; goto error; } - if (memcmp(sig->digest, sinfo->msgdigest, + if (memcmp(sig->m, sinfo->msgdigest, sinfo->msgdigest_len) != 0) { pr_warn("Sig %u: Message digest doesn't match\n", sinfo->index); @@ -98,7 +97,8 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, * convert the attributes from a CONT.0 into a SET before we * hash it. */ - memset(sig->digest, 0, sig->digest_size); + memset(sig->m, 0, sig->m_size); + ret = crypto_shash_init(desc); if (ret < 0) @@ -108,10 +108,10 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, if (ret < 0) goto error; ret = crypto_shash_finup(desc, sinfo->authattrs, - sinfo->authattrs_len, sig->digest); + sinfo->authattrs_len, sig->m); if (ret < 0) goto error; - pr_devel("AADigest = [%*ph]\n", 8, sig->digest); + pr_devel("AADigest = [%*ph]\n", 8, sig->m); } error: @@ -138,8 +138,8 @@ int pkcs7_get_digest(struct pkcs7_message *pkcs7, const u8 **buf, u32 *len, if (ret) return ret; - *buf = sinfo->sig->digest; - *len = sinfo->sig->digest_size; + *buf = sinfo->sig->m; + *len = sinfo->sig->m_size; i = match_string(hash_algo_name, HASH_ALGO__LAST, sinfo->sig->hash_algo); diff --git a/crypto/asymmetric_keys/public_key.c b/crypto/asymmetric_keys/public_key.c index e5b177c8e842..a46356e0c08b 100644 --- a/crypto/asymmetric_keys/public_key.c +++ b/crypto/asymmetric_keys/public_key.c @@ -425,8 +425,7 @@ int public_key_verify_signature(const struct public_key *pkey, if (ret) goto error_free_key; - ret = crypto_sig_verify(tfm, sig->s, sig->s_size, - sig->digest, sig->digest_size); + ret = crypto_sig_verify(tfm, sig->s, sig->s_size, sig->m, sig->m_size); error_free_key: kfree_sensitive(key); diff --git a/crypto/asymmetric_keys/signature.c b/crypto/asymmetric_keys/signature.c index 041d04b5c953..f4ec126121b3 100644 --- a/crypto/asymmetric_keys/signature.c +++ b/crypto/asymmetric_keys/signature.c @@ -28,7 +28,7 @@ void public_key_signature_free(struct public_key_signature *sig) for (i = 0; i < ARRAY_SIZE(sig->auth_ids); i++) kfree(sig->auth_ids[i]); kfree(sig->s); - kfree(sig->digest); + kfree(sig->m); kfree(sig); } } diff --git a/crypto/asymmetric_keys/x509_public_key.c b/crypto/asymmetric_keys/x509_public_key.c index 79cc7b7a0630..3854f7ae4ed0 100644 --- a/crypto/asymmetric_keys/x509_public_key.c +++ b/crypto/asymmetric_keys/x509_public_key.c @@ -63,11 +63,11 @@ int x509_get_sig_params(struct x509_certificate *cert) } desc_size = crypto_shash_descsize(tfm) + sizeof(*desc); - sig->digest_size = crypto_shash_digestsize(tfm); + sig->m_size = crypto_shash_digestsize(tfm); ret = -ENOMEM; - sig->digest = kmalloc(sig->digest_size, GFP_KERNEL); - if (!sig->digest) + sig->m = kmalloc(sig->m_size, GFP_KERNEL); + if (!sig->m) goto error; desc = kzalloc(desc_size, GFP_KERNEL); @@ -76,9 +76,7 @@ int x509_get_sig_params(struct x509_certificate *cert) desc->tfm = tfm; - ret = crypto_shash_digest(desc, cert->tbs, cert->tbs_size, - sig->digest); - + ret = crypto_shash_digest(desc, cert->tbs, cert->tbs_size, sig->m); if (ret < 0) goto error_2; diff --git a/include/crypto/public_key.h b/include/crypto/public_key.h index 81098e00c08f..bd38ba4d217d 100644 --- a/include/crypto/public_key.h +++ b/include/crypto/public_key.h @@ -43,9 +43,9 @@ extern void public_key_free(struct public_key *key); struct public_key_signature { struct asymmetric_key_id *auth_ids[3]; u8 *s; /* Signature */ - u8 *digest; + u8 *m; /* Message data to pass to verifier */ u32 s_size; /* Number of bytes in signature */ - u32 digest_size; /* Number of bytes in digest */ + u32 m_size; /* Number of bytes in ->m */ const char *pkey_algo; const char *hash_algo; const char *encoding; diff --git a/security/integrity/digsig_asymmetric.c b/security/integrity/digsig_asymmetric.c index 457c0a396caf..87be85f477d1 100644 --- a/security/integrity/digsig_asymmetric.c +++ b/security/integrity/digsig_asymmetric.c @@ -121,8 +121,8 @@ int asymmetric_verify(struct key *keyring, const char *sig, goto out; } - pks.digest = (u8 *)data; - pks.digest_size = datalen; + pks.m = (u8 *)data; + pks.m_size = datalen; pks.s = hdr->sig; pks.s_size = siglen; ret = verify_signature(key, &pks);
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:08 +0000", "thread_id": "20260202170216.2467036-7-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Allow the data to be verified in a PKCS#7 or CMS message to be passed directly to an asymmetric cipher algorithm (e.g. ML-DSA) if it wants to do whatever passes for hashing/digestion itself. The normal digestion of the data is then skipped as that would be ignored unless another signed info in the message has some other algorithm that needs it. The 'data to be verified' may be the content of the PKCS#7 message or it will be the authenticatedAttributes (signedAttrs if CMS), modified, if those are present. This is done by: (1) Make ->m and ->m_size point to the data to be verified rather than making public_key_verify_signature() access the data directly. This is so that keyctl(KEYCTL_PKEY_VERIFY) will still work. (2) Add a flag, ->algo_takes_data, to indicate that the verification algorithm wants to access the data to be verified directly rather than having it digested first. (3) If the PKCS#7 message has authenticatedAttributes (or CMS signedAttrs), then the digest contained therein will be validated as now, and the modified attrs blob will either be digested or assigned to ->m as appropriate. (4) If present, always copy and modify the authenticatedAttributes (or signedAttrs) then digest that in one go rather than calling the shash update twice (once for the tag and once for the rest). (5) For ML-DSA, point ->m to the TBSCertificate instead of digesting it and using the digest. Note that whilst ML-DSA does allow for an "external mu", CMS doesn't yet have that standardised. Signed-off-by: David Howells <dhowells@redhat.com> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/pkcs7_parser.c | 4 +- crypto/asymmetric_keys/pkcs7_verify.c | 52 ++++++++++++++++-------- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_public_key.c | 10 +++++ include/crypto/public_key.h | 2 + 5 files changed, 51 insertions(+), 20 deletions(-) diff --git a/crypto/asymmetric_keys/pkcs7_parser.c b/crypto/asymmetric_keys/pkcs7_parser.c index 423d13c47545..3cdbab3b9f50 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.c +++ b/crypto/asymmetric_keys/pkcs7_parser.c @@ -599,8 +599,8 @@ int pkcs7_sig_note_set_of_authattrs(void *context, size_t hdrlen, } /* We need to switch the 'CONT 0' to a 'SET OF' when we digest */ - sinfo->authattrs = value - (hdrlen - 1); - sinfo->authattrs_len = vlen + (hdrlen - 1); + sinfo->authattrs = value - hdrlen; + sinfo->authattrs_len = vlen + hdrlen; return 0; } diff --git a/crypto/asymmetric_keys/pkcs7_verify.c b/crypto/asymmetric_keys/pkcs7_verify.c index aa085ec6fb1c..06abb9838f95 100644 --- a/crypto/asymmetric_keys/pkcs7_verify.c +++ b/crypto/asymmetric_keys/pkcs7_verify.c @@ -30,6 +30,16 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, kenter(",%u,%s", sinfo->index, sinfo->sig->hash_algo); + if (!sinfo->authattrs && sig->algo_takes_data) { + /* There's no intermediate digest and the signature algo + * doesn't want the data prehashing. + */ + sig->m = (void *)pkcs7->data; + sig->m_size = pkcs7->data_len; + sig->m_free = false; + return 0; + } + /* The digest was calculated already. */ if (sig->m) return 0; @@ -48,9 +58,10 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, sig->m_size = crypto_shash_digestsize(tfm); ret = -ENOMEM; - sig->m = kmalloc(sig->m_size, GFP_KERNEL); + sig->m = kmalloc(umax(sinfo->authattrs_len, sig->m_size), GFP_KERNEL); if (!sig->m) goto error_no_desc; + sig->m_free = true; desc = kzalloc(desc_size, GFP_KERNEL); if (!desc) @@ -69,8 +80,6 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, * digest we just calculated. */ if (sinfo->authattrs) { - u8 tag; - if (!sinfo->msgdigest) { pr_warn("Sig %u: No messageDigest\n", sinfo->index); ret = -EKEYREJECTED; @@ -96,21 +105,25 @@ static int pkcs7_digest(struct pkcs7_message *pkcs7, * as the contents of the digest instead. Note that we need to * convert the attributes from a CONT.0 into a SET before we * hash it. + * + * However, for certain algorithms, such as ML-DSA, the digest + * is integrated into the signing algorithm. In such a case, + * we copy the authattrs, modifying the tag type, and set that + * as the digest. */ - memset(sig->m, 0, sig->m_size); - - - ret = crypto_shash_init(desc); - if (ret < 0) - goto error; - tag = ASN1_CONS_BIT | ASN1_SET; - ret = crypto_shash_update(desc, &tag, 1); - if (ret < 0) - goto error; - ret = crypto_shash_finup(desc, sinfo->authattrs, - sinfo->authattrs_len, sig->m); - if (ret < 0) - goto error; + memcpy(sig->m, sinfo->authattrs, sinfo->authattrs_len); + sig->m[0] = ASN1_CONS_BIT | ASN1_SET; + + if (sig->algo_takes_data) { + sig->m_size = sinfo->authattrs_len; + ret = 0; + } else { + ret = crypto_shash_digest(desc, sig->m, + sinfo->authattrs_len, + sig->m); + if (ret < 0) + goto error; + } pr_devel("AADigest = [%*ph]\n", 8, sig->m); } @@ -137,6 +150,11 @@ int pkcs7_get_digest(struct pkcs7_message *pkcs7, const u8 **buf, u32 *len, ret = pkcs7_digest(pkcs7, sinfo); if (ret) return ret; + if (!sinfo->sig->m_free) { + pr_notice_once("%s: No digest available\n", __func__); + return -EINVAL; /* TODO: MLDSA doesn't necessarily calculate an + * intermediate digest. */ + } *buf = sinfo->sig->m; *len = sinfo->sig->m_size; diff --git a/crypto/asymmetric_keys/signature.c b/crypto/asymmetric_keys/signature.c index f4ec126121b3..a5ac7a53b670 100644 --- a/crypto/asymmetric_keys/signature.c +++ b/crypto/asymmetric_keys/signature.c @@ -28,7 +28,8 @@ void public_key_signature_free(struct public_key_signature *sig) for (i = 0; i < ARRAY_SIZE(sig->auth_ids); i++) kfree(sig->auth_ids[i]); kfree(sig->s); - kfree(sig->m); + if (sig->m_free) + kfree(sig->m); kfree(sig); } } diff --git a/crypto/asymmetric_keys/x509_public_key.c b/crypto/asymmetric_keys/x509_public_key.c index 3854f7ae4ed0..27b4fea37845 100644 --- a/crypto/asymmetric_keys/x509_public_key.c +++ b/crypto/asymmetric_keys/x509_public_key.c @@ -50,6 +50,14 @@ int x509_get_sig_params(struct x509_certificate *cert) sig->s_size = cert->raw_sig_size; + if (sig->algo_takes_data) { + /* The signature algorithm does whatever passes for hashing. */ + sig->m = (u8 *)cert->tbs; + sig->m_size = cert->tbs_size; + sig->m_free = false; + goto out; + } + /* Allocate the hashing algorithm we're going to need and find out how * big the hash operational data will be. */ @@ -69,6 +77,7 @@ int x509_get_sig_params(struct x509_certificate *cert) sig->m = kmalloc(sig->m_size, GFP_KERNEL); if (!sig->m) goto error; + sig->m_free = true; desc = kzalloc(desc_size, GFP_KERNEL); if (!desc) @@ -84,6 +93,7 @@ int x509_get_sig_params(struct x509_certificate *cert) kfree(desc); error: crypto_free_shash(tfm); +out: pr_devel("<==%s() = %d\n", __func__, ret); return ret; } diff --git a/include/crypto/public_key.h b/include/crypto/public_key.h index bd38ba4d217d..4c5199b20338 100644 --- a/include/crypto/public_key.h +++ b/include/crypto/public_key.h @@ -46,6 +46,8 @@ struct public_key_signature { u8 *m; /* Message data to pass to verifier */ u32 s_size; /* Number of bytes in signature */ u32 m_size; /* Number of bytes in ->m */ + bool m_free; /* T if ->m needs freeing */ + bool algo_takes_data; /* T if public key algo operates on data, not a hash */ const char *pkey_algo; const char *hash_algo; const char *encoding;
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:09 +0000", "thread_id": "20260202170216.2467036-7-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Add support for ML-DSA keys and signatures to the CMS/PKCS#7 and X.509 implementations. ML-DSA-44, -65 and -87 are all supported. For X.509 certificates, the TBSCertificate is required to be signed directly; for CMS, direct signing of the data is preferred, though use of SHA512 (and only that) as an intermediate hash of the content is permitted with signedAttrs. Signed-off-by: David Howells <dhowells@redhat.com> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/pkcs7_parser.c | 24 +++++++++++++++++++- crypto/asymmetric_keys/public_key.c | 10 +++++++++ crypto/asymmetric_keys/x509_cert_parser.c | 27 ++++++++++++++++++++++- include/linux/oid_registry.h | 5 +++++ 4 files changed, 64 insertions(+), 2 deletions(-) diff --git a/crypto/asymmetric_keys/pkcs7_parser.c b/crypto/asymmetric_keys/pkcs7_parser.c index 3cdbab3b9f50..594a8f1d9dfb 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.c +++ b/crypto/asymmetric_keys/pkcs7_parser.c @@ -95,11 +95,18 @@ static int pkcs7_check_authattrs(struct pkcs7_message *msg) if (sinfo->authattrs) { want = true; msg->have_authattrs = true; + } else if (sinfo->sig->algo_takes_data) { + sinfo->sig->hash_algo = "none"; } - for (sinfo = sinfo->next; sinfo; sinfo = sinfo->next) + for (sinfo = sinfo->next; sinfo; sinfo = sinfo->next) { if (!!sinfo->authattrs != want) goto inconsistent; + + if (!sinfo->authattrs && + sinfo->sig->algo_takes_data) + sinfo->sig->hash_algo = "none"; + } return 0; inconsistent: @@ -297,6 +304,21 @@ int pkcs7_sig_note_pkey_algo(void *context, size_t hdrlen, ctx->sinfo->sig->pkey_algo = "ecrdsa"; ctx->sinfo->sig->encoding = "raw"; break; + case OID_id_ml_dsa_44: + ctx->sinfo->sig->pkey_algo = "mldsa44"; + ctx->sinfo->sig->encoding = "raw"; + ctx->sinfo->sig->algo_takes_data = true; + break; + case OID_id_ml_dsa_65: + ctx->sinfo->sig->pkey_algo = "mldsa65"; + ctx->sinfo->sig->encoding = "raw"; + ctx->sinfo->sig->algo_takes_data = true; + break; + case OID_id_ml_dsa_87: + ctx->sinfo->sig->pkey_algo = "mldsa87"; + ctx->sinfo->sig->encoding = "raw"; + ctx->sinfo->sig->algo_takes_data = true; + break; default: printk("Unsupported pkey algo: %u\n", ctx->last_oid); return -ENOPKG; diff --git a/crypto/asymmetric_keys/public_key.c b/crypto/asymmetric_keys/public_key.c index a46356e0c08b..09a0b83d5d77 100644 --- a/crypto/asymmetric_keys/public_key.c +++ b/crypto/asymmetric_keys/public_key.c @@ -142,6 +142,16 @@ software_key_determine_akcipher(const struct public_key *pkey, if (strcmp(hash_algo, "streebog256") != 0 && strcmp(hash_algo, "streebog512") != 0) return -EINVAL; + } else if (strcmp(pkey->pkey_algo, "mldsa44") == 0 || + strcmp(pkey->pkey_algo, "mldsa65") == 0 || + strcmp(pkey->pkey_algo, "mldsa87") == 0) { + if (strcmp(encoding, "raw") != 0) + return -EINVAL; + if (!hash_algo) + return -EINVAL; + if (strcmp(hash_algo, "none") != 0 && + strcmp(hash_algo, "sha512") != 0) + return -EINVAL; } else { /* Unknown public key algorithm */ return -ENOPKG; diff --git a/crypto/asymmetric_keys/x509_cert_parser.c b/crypto/asymmetric_keys/x509_cert_parser.c index b37cae914987..2fe094f5caf3 100644 --- a/crypto/asymmetric_keys/x509_cert_parser.c +++ b/crypto/asymmetric_keys/x509_cert_parser.c @@ -257,6 +257,15 @@ int x509_note_sig_algo(void *context, size_t hdrlen, unsigned char tag, case OID_gost2012Signature512: ctx->cert->sig->hash_algo = "streebog512"; goto ecrdsa; + case OID_id_ml_dsa_44: + ctx->cert->sig->pkey_algo = "mldsa44"; + goto ml_dsa; + case OID_id_ml_dsa_65: + ctx->cert->sig->pkey_algo = "mldsa65"; + goto ml_dsa; + case OID_id_ml_dsa_87: + ctx->cert->sig->pkey_algo = "mldsa87"; + goto ml_dsa; } rsa_pkcs1: @@ -274,6 +283,12 @@ int x509_note_sig_algo(void *context, size_t hdrlen, unsigned char tag, ctx->cert->sig->encoding = "x962"; ctx->sig_algo = ctx->last_oid; return 0; +ml_dsa: + ctx->cert->sig->algo_takes_data = true; + ctx->cert->sig->hash_algo = "none"; + ctx->cert->sig->encoding = "raw"; + ctx->sig_algo = ctx->last_oid; + return 0; } /* @@ -300,7 +315,8 @@ int x509_note_signature(void *context, size_t hdrlen, if (strcmp(ctx->cert->sig->pkey_algo, "rsa") == 0 || strcmp(ctx->cert->sig->pkey_algo, "ecrdsa") == 0 || - strcmp(ctx->cert->sig->pkey_algo, "ecdsa") == 0) { + strcmp(ctx->cert->sig->pkey_algo, "ecdsa") == 0 || + strncmp(ctx->cert->sig->pkey_algo, "mldsa", 5) == 0) { /* Discard the BIT STRING metadata */ if (vlen < 1 || *(const u8 *)value != 0) return -EBADMSG; @@ -524,6 +540,15 @@ int x509_extract_key_data(void *context, size_t hdrlen, return -ENOPKG; } break; + case OID_id_ml_dsa_44: + ctx->cert->pub->pkey_algo = "mldsa44"; + break; + case OID_id_ml_dsa_65: + ctx->cert->pub->pkey_algo = "mldsa65"; + break; + case OID_id_ml_dsa_87: + ctx->cert->pub->pkey_algo = "mldsa87"; + break; default: return -ENOPKG; } diff --git a/include/linux/oid_registry.h b/include/linux/oid_registry.h index 6de479ebbe5d..ebce402854de 100644 --- a/include/linux/oid_registry.h +++ b/include/linux/oid_registry.h @@ -145,6 +145,11 @@ enum OID { OID_id_rsassa_pkcs1_v1_5_with_sha3_384, /* 2.16.840.1.101.3.4.3.15 */ OID_id_rsassa_pkcs1_v1_5_with_sha3_512, /* 2.16.840.1.101.3.4.3.16 */ + /* NIST FIPS-204 ML-DSA */ + OID_id_ml_dsa_44, /* 2.16.840.1.101.3.4.3.17 */ + OID_id_ml_dsa_65, /* 2.16.840.1.101.3.4.3.18 */ + OID_id_ml_dsa_87, /* 2.16.840.1.101.3.4.3.19 */ + OID__NR };
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:10 +0000", "thread_id": "20260202170216.2467036-7-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Allow ML-DSA module signing to be enabled. Note that OpenSSL's CMS_*() function suite does not, as of OpenSSL-3.6, support the use of CMS_NOATTR with ML-DSA, so the prohibition against using signedAttrs with module signing has to be removed. The selected digest then applies only to the algorithm used to calculate the digest stored in the messageDigest attribute. The OpenSSL development branch has patches applied that fix this[1], but it appears that that will only be available in OpenSSL-4. [1] https://github.com/openssl/openssl/pull/28923 sign-file won't set CMS_NOATTR if openssl is earlier than v4, resulting in the use of signed attributes. The ML-DSA algorithm takes the raw data to be signed without regard to what digest algorithm is specified in the CMS message. The CMS specified digest algorithm is ignored unless signedAttrs are used; in such a case, only SHA512 is permitted. Signed-off-by: David Howells <dhowells@redhat.com> cc: Jarkko Sakkinen <jarkko@kernel.org> cc: Eric Biggers <ebiggers@kernel.org> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Stephan Mueller <smueller@chronox.de> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- Documentation/admin-guide/module-signing.rst | 16 ++++---- certs/Kconfig | 40 ++++++++++++++++++++ certs/Makefile | 3 ++ scripts/sign-file.c | 39 ++++++++++++++----- 4 files changed, 82 insertions(+), 16 deletions(-) diff --git a/Documentation/admin-guide/module-signing.rst b/Documentation/admin-guide/module-signing.rst index a8667a777490..7f2f127dc76f 100644 --- a/Documentation/admin-guide/module-signing.rst +++ b/Documentation/admin-guide/module-signing.rst @@ -28,10 +28,12 @@ trusted userspace bits. This facility uses X.509 ITU-T standard certificates to encode the public keys involved. The signatures are not themselves encoded in any industrial standard -type. The built-in facility currently only supports the RSA & NIST P-384 ECDSA -public key signing standard (though it is pluggable and permits others to be -used). The possible hash algorithms that can be used are SHA-2 and SHA-3 of -sizes 256, 384, and 512 (the algorithm is selected by data in the signature). +type. The built-in facility currently only supports the RSA, NIST P-384 ECDSA +and NIST FIPS-204 ML-DSA public key signing standards (though it is pluggable +and permits others to be used). For RSA and ECDSA, the possible hash +algorithms that can be used are SHA-2 and SHA-3 of sizes 256, 384, and 512 (the +algorithm is selected by data in the signature); ML-DSA does its own hashing, +but is allowed to be used with a SHA512 hash for signed attributes. ========================== @@ -146,9 +148,9 @@ into vmlinux) using parameters in the:: file (which is also generated if it does not already exist). -One can select between RSA (``MODULE_SIG_KEY_TYPE_RSA``) and ECDSA -(``MODULE_SIG_KEY_TYPE_ECDSA``) to generate either RSA 4k or NIST -P-384 keypair. +One can select between RSA (``MODULE_SIG_KEY_TYPE_RSA``), ECDSA +(``MODULE_SIG_KEY_TYPE_ECDSA``) and ML-DSA (``MODULE_SIG_KEY_TYPE_MLDSA_*``) to +generate an RSA 4k, a NIST P-384 keypair or an ML-DSA 44, 65 or 87 keypair. It is strongly recommended that you provide your own x509.genkey file. diff --git a/certs/Kconfig b/certs/Kconfig index 78307dc25559..8e39a80c7abe 100644 --- a/certs/Kconfig +++ b/certs/Kconfig @@ -39,6 +39,39 @@ config MODULE_SIG_KEY_TYPE_ECDSA Note: Remove all ECDSA signing keys, e.g. certs/signing_key.pem, when falling back to building Linux 5.14 and older kernels. +config MODULE_SIG_KEY_TYPE_MLDSA_44 + bool "ML-DSA-44" + select CRYPTO_MLDSA + depends on OPENSSL_SUPPORTS_ML_DSA + help + Use an ML-DSA-44 key (NIST FIPS 204) for module signing. ML-DSA + support requires OpenSSL-3.5 minimum; preferably OpenSSL-4+. With + the latter, the entire module body will be signed; with the former, + signedAttrs will be used as it lacks support for CMS_NOATTR with + ML-DSA. + +config MODULE_SIG_KEY_TYPE_MLDSA_65 + bool "ML-DSA-65" + select CRYPTO_MLDSA + depends on OPENSSL_SUPPORTS_ML_DSA + help + Use an ML-DSA-65 key (NIST FIPS 204) for module signing. ML-DSA + support requires OpenSSL-3.5 minimum; preferably OpenSSL-4+. With + the latter, the entire module body will be signed; with the former, + signedAttrs will be used as it lacks support for CMS_NOATTR with + ML-DSA. + +config MODULE_SIG_KEY_TYPE_MLDSA_87 + bool "ML-DSA-87" + select CRYPTO_MLDSA + depends on OPENSSL_SUPPORTS_ML_DSA + help + Use an ML-DSA-87 key (NIST FIPS 204) for module signing. ML-DSA + support requires OpenSSL-3.5 minimum; preferably OpenSSL-4+. With + the latter, the entire module body will be signed; with the former, + signedAttrs will be used as it lacks support for CMS_NOATTR with + ML-DSA. + endchoice config SYSTEM_TRUSTED_KEYRING @@ -154,4 +187,11 @@ config SYSTEM_BLACKLIST_AUTH_UPDATE keyring. The PKCS#7 signature of the description is set in the key payload. Blacklist keys cannot be removed. +config OPENSSL_SUPPORTS_ML_DSA + def_bool $(success, openssl list -key-managers | grep -q ML-DSA-87) + help + Support for ML-DSA-44/65/87 was added in openssl-3.5, so as long + as older versions are supported, the key types may only be + set after testing the installed binary for support. + endmenu diff --git a/certs/Makefile b/certs/Makefile index f6fa4d8d75e0..3ee1960f9f4a 100644 --- a/certs/Makefile +++ b/certs/Makefile @@ -43,6 +43,9 @@ targets += x509_certificate_list ifeq ($(CONFIG_MODULE_SIG_KEY),certs/signing_key.pem) keytype-$(CONFIG_MODULE_SIG_KEY_TYPE_ECDSA) := -newkey ec -pkeyopt ec_paramgen_curve:secp384r1 +keytype-$(CONFIG_MODULE_SIG_KEY_TYPE_MLDSA_44) := -newkey ml-dsa-44 +keytype-$(CONFIG_MODULE_SIG_KEY_TYPE_MLDSA_65) := -newkey ml-dsa-65 +keytype-$(CONFIG_MODULE_SIG_KEY_TYPE_MLDSA_87) := -newkey ml-dsa-87 quiet_cmd_gen_key = GENKEY $@ cmd_gen_key = openssl req -new -nodes -utf8 -$(CONFIG_MODULE_SIG_HASH) -days 36500 \ diff --git a/scripts/sign-file.c b/scripts/sign-file.c index 7070245edfc1..78276b15ab23 100644 --- a/scripts/sign-file.c +++ b/scripts/sign-file.c @@ -27,7 +27,7 @@ #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/err.h> -#if OPENSSL_VERSION_MAJOR >= 3 +#if OPENSSL_VERSION_NUMBER >= 0x30000000L # define USE_PKCS11_PROVIDER # include <openssl/provider.h> # include <openssl/store.h> @@ -315,18 +315,39 @@ int main(int argc, char **argv) ERR(!digest_algo, "EVP_get_digestbyname"); #ifndef USE_PKCS7 + + unsigned int flags = + CMS_NOCERTS | + CMS_PARTIAL | + CMS_BINARY | + CMS_DETACHED | + CMS_STREAM | + CMS_NOSMIMECAP | +#ifdef CMS_NO_SIGNING_TIME + CMS_NO_SIGNING_TIME | +#endif + use_keyid; + +#if OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L + if (EVP_PKEY_is_a(private_key, "ML-DSA-44") || + EVP_PKEY_is_a(private_key, "ML-DSA-65") || + EVP_PKEY_is_a(private_key, "ML-DSA-87")) { + /* ML-DSA + CMS_NOATTR is not supported in openssl-3.5 + * and before. + */ + use_signed_attrs = 0; + } +#endif + + flags |= use_signed_attrs; + /* Load the signature message from the digest buffer. */ - cms = CMS_sign(NULL, NULL, NULL, NULL, - CMS_NOCERTS | CMS_PARTIAL | CMS_BINARY | - CMS_DETACHED | CMS_STREAM); + cms = CMS_sign(NULL, NULL, NULL, NULL, flags); ERR(!cms, "CMS_sign"); - ERR(!CMS_add1_signer(cms, x509, private_key, digest_algo, - CMS_NOCERTS | CMS_BINARY | - CMS_NOSMIMECAP | use_keyid | - use_signed_attrs), + ERR(!CMS_add1_signer(cms, x509, private_key, digest_algo, flags), "CMS_add1_signer"); - ERR(CMS_final(cms, bm, NULL, CMS_NOCERTS | CMS_BINARY) != 1, + ERR(CMS_final(cms, bm, NULL, flags) != 1, "CMS_final"); #else
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:11 +0000", "thread_id": "20260202170216.2467036-7-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v16 0/7] x509, pkcs7, crypto: Add ML-DSA signing
Hi Lukas, Ignat, [Note this is based on Eric Bigger's libcrypto-next branch]. These patches add ML-DSA module signing signing: (1) Add a crypto_sig interface for ML-DSA, verification only. (2) Generate a SHA256 hash of the X.509 TBSCertificate and check that in the blacklist. Direct-sign ML-DSA doesn't generate an easily accessible hash. Note that this changes behaviour as we no longer use whatever hash is specified in the certificate for this. (3) Rename the public_key_signature struct's "digest" and "digest_size" members to "m" and "m_size" to reflect that it's not necessarily a digest, but it is an input to the public key algorithm. (4) Modify PKCS#7 support to allow kernel module signatures to carry authenticatedAttributes as OpenSSL refuses to let them be opted out of for ML-DSA (CMS_NOATTR). This adds an extra digest calculation to the process. Modify PKCS#7 to pass the authenticatedAttributes directly to the ML-DSA algorithm rather than passing over a digest as is done with RSA as ML-DSA wants to do its own hashing and will add other stuff into the hash. We could use hashML-DSA or an external mu instead, but they aren't standardised for CMS yet. (5) Add support to the PKCS#7 and X.509 parsers for ML-DSA. (6) Modify sign-file to handle OpenSSL not permitting CMS_NOATTR with ML-DSA and add ML-DSA to the choice of algorithm with which to sign modules. Note that this might need some more 'select' lines in the Kconfig to select the lib stuff as well. (7) Add a config option to allow authenticatedAttributes to be used with ML-DSA for module signing. Ordinarily, authenticatedAttributes are not permitted for this purpose, however direct signing with ML-DSA will not be supported by OpenSSL until v4 is released. The patches can also be found here: https://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs.git/log/?h=keys-pqc David Changes ======= ver #16) - Make the selection of ML-DSA for module signing when configuring contingent on openssl saying it supports ML-DSA (fix from Arnd Bergmann). - Make ML-DSA-related bits of sign-file contingent on openssl >= 3.0.0. ver #15) - Undo a removed blank line to simplify the X.509 patch. - Split the rename of ->digest to ->m into its own patch. - In pkcs7_digest(), always copy the signedAttrs and modify rather than passing the replacement tag byte in a separate shash update call to the rest of the data. That way the ->m buffer is very likely to be optimally aligned for the crypto. - Only allow authenticatedAttributes with ML-DSA for module signing and only if permission is given in the kernel config. ver #14) - public_key: - Rename public_key::digest to public_key::m. - X.509: - Independently calculate the SHA256 hash for the blacklist check as an ML-DSA-signed X.509 cert doesn't generate a digest we can use. - Point public_key::m at the TBS data for ML-DSA. - PKCS#7: - Allocate a big enough digest buffer rather than reallocating in order to store the authattrs/signedattrs instead. - Merge the two patches that add direct signing support. - ML-DSA: - Use bool instead of u8. - Remove references to SHAKE in Kconfig and mention OpenSSL requirements there. - Limit ML-DSA with an intermediate hash (e.g. signedAttrs) to using SHA512 only. - Don't select CRYPTO_LIB_SHA3 for CRYPTO_MLDSA. - RSASSA-PSS: - Allow use with SHA256 and SHA384. - Fix calculation of emBits to be number of bits in the RSA modulus 'n'. - Use strncmp() not memcmp() to avoid reading beyond end of string. - Use correct destructor in rsassa_params_parse(). - Drop this algo for the moment. - Drop the pefile_context::digest_free for now - it's only set to true and is unrelated to public_key::digest_free. ver #13) - Allow a zero-length salt in RSASSA-PSS. - Don't reject ECDSA/ECRDSA with SHA256 and SHA384 otherwise the FIPS selftest panics when used. - Add a FIPS test for RSASSA-PSS (from NIST's SigVerPSS_186-3.rsp). - Add a FIPS test for ML-DSA (from NIST's FIPS204 JSON set). ver #12) - Rebased on Eric's libcrypto-next branch. - Delete references to Dilithium (ML-DSA derived from this). - Made sign-file supply CMS_NOATTR for ML-DSA if openssl >= v4. - Made it possible to do ML-DSA over the data without signedAttrs. - Made RSASSA-PSS info parser use strsep() and match_token(). - Cleaned the RSASSA-PSS param parsing. - Added limitation on what hashes can be used with what algos. - Moved __free()-marked variables to the point of setting. ver #11) - Rebased on Eric's libcrypto-next branch. - Added RSASSA-PSS support patches. ver #10) - Replaced the Leancrypto ML-DSA implementation with Eric's. - Fixed Eric's implementation to have MODULE_* info. - Added a patch to drive Eric's ML-DSA implementation from crypto_sig. - Removed SHAKE256 from the list of available module hash algorithms. - Changed a some more ML_DSA to MLDSA in config symbols. ver #9) - ML-DSA changes: - Separate output into four modules (1 common, 3 strength-specific). - Solves Kconfig issue with needing to select at least one strength. - Separate the strength-specific crypto-lib APIs. - This is now generated by preprocessor-templating. - Remove the multiplexor code. - Multiplex the crypto-lib APIs by C type. - Fix the PKCS#7/X.509 code to have the correct algo names. ver #8) - Moved the ML-DSA code to lib/crypto/mldsa/. - Renamed some bits from ml-dsa to mldsa. - Created a simplified API and placed that in include/crypto/mldsa.h. - Made the testing code use the simplified API. - Fixed a warning about implicitly casting between uint16_t and __le16. ver #7) - Rebased on Eric's tree as that now contains all the necessary SHA-3 infrastructure and drop the SHA-3 patches from here. - Added a minimal patch to provide shake256 support for crypto_sig. - Got rid of the memory allocation wrappers. - Removed the ML-DSA keypair generation code and the signing code, leaving only the signature verification code. - Removed the secret key handling code. - Removed the secret keys from the kunit tests and the signing testing. - Removed some unused bits from the ML-DSA code. - Downgraded the kdoc comments to ordinary comments, but keep the markup for easier comparison to Leancrypto. ver #6) - Added a patch to make the jitterentropy RNG use lib/sha3. - Added back the crypto/sha3_generic changes. - Added ML-DSA implementation (still needs more cleanup). - Added kunit test for ML-DSA. - Modified PKCS#7 to accommodate ML-DSA. - Modified PKCS#7 and X.509 to allow ML-DSA to be specified and used. - Modified sign-file to not use CMS_NOATTR with ML-DSA. - Allowed SHA3 and SHAKE* algorithms for module signing default. - Allowed ML-DSA-{44,65,87} to be selected as the module signing default. ver #5) - Fix gen-hash-testvecs.py to correctly handle algo names that contain a dash. - Fix gen-hash-testvecs.py to not generate HMAC for SHA3-* or SHAKE* as these don't currently have HMAC variants implemented. - Fix algo names to be correct. - Fix kunit module description as it now tests all SHA3 variants. ver #4) - Fix a couple of arm64 build problems. - Doc fixes: - Fix the description of the algorithm to be closer to the NIST spec's terminology. - Don't talk of finialising the context for XOFs. - Don't say "Return: None". - Declare the "Context" to be "Any context" and make no mention of the fact that it might use the FPU. - Change "initialise" to "initialize". - Don't warn that the context is relatively large for stack use. - Use size_t for size parameters/variables. - Make the module_exit unconditional. - Dropped the crypto/ dir-affecting patches for the moment. ver #3) - Renamed conflicting arm64 functions. - Made a separate wrapper API for each algorithm in the family. - Removed sha3_init(), sha3_reinit() and sha3_final(). - Removed sha3_ctx::digest_size. - Renamed sha3_ctx::partial to sha3_ctx::absorb_offset. - Refer to the output of SHAKE* as "output" not "digest". - Moved the Iota transform into the one-round function. - Made sha3_update() warn if called after sha3_squeeze(). - Simplified the module-load test to not do update after squeeze. - Added Return: and Context: kdoc statements and expanded the kdoc headers. - Added an API description document. - Overhauled the kunit tests. - Only have one kunit test. - Only call the general hash tester on one algo. - Add separate simple cursory checks for the other algos. - Add resqueezing tests. - Add some NIST example tests. - Changed crypto/sha3_generic to use this - Added SHAKE128/256 to crypto/sha3_generic and crypto/testmgr - Folded struct sha3_state into struct sha3_ctx. ver #2) - Simplify the endianness handling. - Rename sha3_final() to sha3_squeeze() and don't clear the context at the end as it's permitted to continue calling sha3_final() to extract continuations of the digest (needed by ML-DSA). - Don't reapply the end marker to the hash state in continuation sha3_squeeze() unless sha3_update() gets called again (needed by ML-DSA). - Give sha3_squeeze() the amount of digest to produce as a parameter rather than using ctx->digest_size and don't return the amount digested. - Reimplement sha3_final() as a wrapper around sha3_squeeze() that extracts ctx->digest_size amount of digest and then zeroes out the context. The latter is necessary to avoid upsetting hash-test-template.h. - Provide a sha3_reinit() function to clear the state, but to leave the parameters that indicate the hash properties unaffected, allowing for reuse. - Provide a sha3_set_digestsize() function to change the size of the digest to be extracted by sha3_final(). sha3_squeeze() takes a parameter for this instead. - Don't pass the digest size as a parameter to shake128/256_init() but rather default to 128/256 bits as per the function name. - Provide a sha3_clear() function to zero out the context. David Howells (7): crypto: Add ML-DSA crypto_sig support x509: Separately calculate sha256 for blacklist pkcs7, x509: Rename ->digest to ->m pkcs7: Allow the signing algo to do whatever digestion it wants itself pkcs7, x509: Add ML-DSA support modsign: Enable ML-DSA module signing pkcs7: Allow authenticatedAttributes for ML-DSA Documentation/admin-guide/module-signing.rst | 16 +- certs/Kconfig | 40 ++++ certs/Makefile | 3 + crypto/Kconfig | 9 + crypto/Makefile | 2 + crypto/asymmetric_keys/Kconfig | 11 + crypto/asymmetric_keys/asymmetric_type.c | 4 +- crypto/asymmetric_keys/pkcs7_parser.c | 36 +++- crypto/asymmetric_keys/pkcs7_parser.h | 3 + crypto/asymmetric_keys/pkcs7_verify.c | 78 ++++--- crypto/asymmetric_keys/public_key.c | 13 +- crypto/asymmetric_keys/signature.c | 3 +- crypto/asymmetric_keys/x509_cert_parser.c | 27 ++- crypto/asymmetric_keys/x509_parser.h | 2 + crypto/asymmetric_keys/x509_public_key.c | 42 ++-- crypto/mldsa.c | 201 +++++++++++++++++++ include/crypto/public_key.h | 6 +- include/linux/oid_registry.h | 5 + scripts/sign-file.c | 39 +++- security/integrity/digsig_asymmetric.c | 4 +- 20 files changed, 473 insertions(+), 71 deletions(-) create mode 100644 crypto/mldsa.c
Allow the rejection of authenticatedAttributes in PKCS#7 (signedAttrs in CMS) to be waived in the kernel config for ML-DSA when used for module signing. This reflects the issue that openssl < 4.0 cannot do this and openssl-4 has not yet been released. This does not permit RSA, ECDSA or ECRDSA to be so waived (behaviour unchanged). Signed-off-by: David Howells <dhowells@redhat.com> cc: Lukas Wunner <lukas@wunner.de> cc: Ignat Korchagin <ignat@cloudflare.com> cc: Jarkko Sakkinen <jarkko@kernel.org> cc: Stephan Mueller <smueller@chronox.de> cc: Eric Biggers <ebiggers@kernel.org> cc: Herbert Xu <herbert@gondor.apana.org.au> cc: keyrings@vger.kernel.org cc: linux-crypto@vger.kernel.org --- crypto/asymmetric_keys/Kconfig | 11 +++++++++++ crypto/asymmetric_keys/pkcs7_parser.c | 8 ++++++++ crypto/asymmetric_keys/pkcs7_parser.h | 3 +++ crypto/asymmetric_keys/pkcs7_verify.c | 6 ++++++ 4 files changed, 28 insertions(+) diff --git a/crypto/asymmetric_keys/Kconfig b/crypto/asymmetric_keys/Kconfig index e1345b8f39f1..1dae2232fe9a 100644 --- a/crypto/asymmetric_keys/Kconfig +++ b/crypto/asymmetric_keys/Kconfig @@ -53,6 +53,17 @@ config PKCS7_MESSAGE_PARSER This option provides support for parsing PKCS#7 format messages for signature data and provides the ability to verify the signature. +config PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + bool "Waive rejection of authenticatedAttributes for ML-DSA" + depends on PKCS7_MESSAGE_PARSER + depends on CRYPTO_MLDSA + help + Due to use of CMS_NOATTR with ML-DSA not being supported in + OpenSSL < 4.0 (and thus any released version), enabling this + allows authenticatedAttributes to be used with ML-DSA for + module signing. Use of authenticatedAttributes in this + context is normally rejected. + config PKCS7_TEST_KEY tristate "PKCS#7 testing key type" depends on SYSTEM_DATA_VERIFICATION diff --git a/crypto/asymmetric_keys/pkcs7_parser.c b/crypto/asymmetric_keys/pkcs7_parser.c index 594a8f1d9dfb..db1c90ca6fc1 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.c +++ b/crypto/asymmetric_keys/pkcs7_parser.c @@ -92,9 +92,17 @@ static int pkcs7_check_authattrs(struct pkcs7_message *msg) if (!sinfo) goto inconsistent; +#ifdef CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + msg->authattrs_rej_waivable = true; +#endif + if (sinfo->authattrs) { want = true; msg->have_authattrs = true; +#ifdef CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + if (strncmp(sinfo->sig->pkey_algo, "mldsa", 5) != 0) + msg->authattrs_rej_waivable = false; +#endif } else if (sinfo->sig->algo_takes_data) { sinfo->sig->hash_algo = "none"; } diff --git a/crypto/asymmetric_keys/pkcs7_parser.h b/crypto/asymmetric_keys/pkcs7_parser.h index e17f7ce4fb43..6ef9f335bb17 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.h +++ b/crypto/asymmetric_keys/pkcs7_parser.h @@ -55,6 +55,9 @@ struct pkcs7_message { struct pkcs7_signed_info *signed_infos; u8 version; /* Version of cert (1 -> PKCS#7 or CMS; 3 -> CMS) */ bool have_authattrs; /* T if have authattrs */ +#ifdef CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + bool authattrs_rej_waivable; /* T if authatts rejection can be waived */ +#endif /* Content Data (or NULL) */ enum OID data_type; /* Type of Data */ diff --git a/crypto/asymmetric_keys/pkcs7_verify.c b/crypto/asymmetric_keys/pkcs7_verify.c index 06abb9838f95..519eecfe6778 100644 --- a/crypto/asymmetric_keys/pkcs7_verify.c +++ b/crypto/asymmetric_keys/pkcs7_verify.c @@ -425,6 +425,12 @@ int pkcs7_verify(struct pkcs7_message *pkcs7, return -EKEYREJECTED; } if (pkcs7->have_authattrs) { +#ifdef CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + if (pkcs7->authattrs_rej_waivable) { + pr_warn("Waived invalid module sig (has authattrs)\n"); + break; + } +#endif pr_warn("Invalid module sig (has authattrs)\n"); return -EKEYREJECTED; }
{ "author": "David Howells <dhowells@redhat.com>", "date": "Mon, 2 Feb 2026 17:02:12 +0000", "thread_id": "20260202170216.2467036-7-dhowells@redhat.com.mbox.gz" }
lkml
[PATCH v11 0/3] rust: leds: add led classdev abstractions
This patch series has previously been contained in https://lore.kernel.org/rust-for-linux/20251008181027.662616-1-markus.probst@posteo.de/T/#t which added a rust written led driver for a microcontroller via i2c. As the reading and writing to the i2c client via the register! macro has not been implemented yet [1], the patch series will only contain the additional abstractions required. [1] https://lore.kernel.org/rust-for-linux/DDDS2V0V2NVJ.16ZKXCKUA1HUV@kernel.org/ The following changes were made: * add basic led classdev abstractions to register and unregister leds * add basic led classdev abstractions to register and unregister multicolor leds Changes since v10: * allow in-place initialization of `LedOps` * run rustfmt for code inside `try_pin_init!` Changes since v9: * add missing periods in documentation * duplicate `led::Device` and `led::Adapter` instead of using a complex trait * fix imports not using prelude * adapt to CStr change * documented `led::Color::Multi` and `led::Color::Rgb` Changes since v8: * accept `Option<ARef<Fwnode>>` in `led::InitData::fwnode()` * make functions in `MultiColorSubLed` const * drop the "rust: Add trait to convert a device reference to a bus device reference" patch, as it has been picked into driver-core Changes since v7: * adjusted import style * added classdev parameter to callback functions in `LedOps` * implement `led::Color` * extend `led::InitData` with - initial_brightness - default_trigger - default_color * split generic and normal led classdev abstractions up (see patch 3/4) * add multicolor led class device abstractions (see patch 4/4) * added MAINTAINERS entry Changes since v6: * fixed typos * improved documentation Changes since v5: * rename `IntoBusDevice` trait into `AsBusDevice` * fix documentation about `LedOps::BLOCKING` * removed dependency on i2c bindings * added `AsBusDevice` implementation for `platform::Device` * removed `device::Device` fallback implementation * document that `AsBusDevice` must not be used by drivers and is intended for bus and class device abstractions only. Changes since v4: * add abstraction to convert a device reference to a bus device reference * require the bus device as parent device and provide it in class device callbacks * remove Pin<Vec<_>> abstraction (as not relevant for the led abstractions) * fixed formatting in `led::Device::new` * fixed `LedOps::BLOCKING` did the inverse effect Changes since v3: * fixed kunit tests failing because of example in documentation Changes since v2: * return `Devres` on `led::Device` creation * replace KBox<T> with T in struct definition * increment and decrement reference-count of fwnode * make a device parent mandatory for led classdev creation * rename `led::Handler` to `led::LedOps` * add optional `brightness_get` function to `led::LedOps` * use `#[vtable]` instead of `const BLINK: bool` * use `Opaque::cast_from` instead of casting a pointer * improve documentation * improve support for older rust versions * use `&Device<Bound>` for parent Changes since v1: * fixed typos noticed by Onur Özkan Signed-off-by: Markus Probst <markus.probst@posteo.de> --- Markus Probst (3): rust: leds: add basic led classdev abstractions rust: leds: split generic and normal led classdev abstractions up rust: leds: add multicolor classdev abstractions MAINTAINERS | 8 + rust/bindings/bindings_helper.h | 1 + rust/kernel/led.rs | 300 +++++++++++++++++++++++++++++++ rust/kernel/led/multicolor.rs | 382 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 226 ++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 918 insertions(+) --- base-commit: 18f7fcd5e69a04df57b563360b88be72471d6b62 change-id: 20251114-rust_leds-a959f7c2f7f9
Implement the core abstractions needed for led class devices, including: * `led::LedOps` - the trait for handling leds, including `brightness_set`, `brightness_get` and `blink_set` * `led::InitData` - data set for the led class device * `led::Device` - a safe wrapper around `led_classdev` Signed-off-by: Markus Probst <markus.probst@posteo.de> --- MAINTAINERS | 7 + rust/kernel/led.rs | 453 +++++++++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 461 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 0efa8cc6775b..26765fecb9a9 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -14279,6 +14279,13 @@ F: drivers/leds/ F: include/dt-bindings/leds/ F: include/linux/leds.h +LED SUBSYSTEM [RUST] +M: Markus Probst <markus.probst@posteo.de> +L: linux-leds@vger.kernel.org +L: rust-for-linux@vger.kernel.org +S: Maintained +F: rust/kernel/led.rs + LEGO MINDSTORMS EV3 R: David Lechner <david@lechnology.com> S: Maintained diff --git a/rust/kernel/led.rs b/rust/kernel/led.rs new file mode 100644 index 000000000000..9acb6946f3da --- /dev/null +++ b/rust/kernel/led.rs @@ -0,0 +1,453 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Abstractions for the leds driver model. +//! +//! C header: [`include/linux/leds.h`](srctree/include/linux/leds.h) + +use core::{ + marker::PhantomData, + mem::transmute, + ptr::NonNull, // +}; + +use crate::{ + container_of, + device::{ + self, + property::FwNode, + AsBusDevice, + Bound, // + }, + devres::Devres, + error::{ + from_result, + to_result, + VTABLE_DEFAULT_ERROR, // + }, + macros::vtable, + prelude::*, + str::CStrExt, + types::{ + ARef, + Opaque, // + }, // +}; + +/// The led class device representation. +/// +/// This structure represents the Rust abstraction for a C `struct led_classdev`. +#[pin_data(PinnedDrop)] +pub struct Device<T: LedOps> { + #[pin] + ops: T, + #[pin] + classdev: Opaque<bindings::led_classdev>, +} + +/// The led init data representation. +/// +/// This structure represents the Rust abstraction for a C `struct led_init_data` with additional +/// fields from `struct led_classdev`. +#[derive(Default)] +pub struct InitData<'a> { + fwnode: Option<ARef<FwNode>>, + devicename: Option<&'a CStr>, + devname_mandatory: bool, + initial_brightness: u32, + default_trigger: Option<&'a CStr>, + color: Color, +} + +impl InitData<'static> { + /// Creates a new [`InitData`]. + pub fn new() -> Self { + Self::default() + } +} + +impl<'a> InitData<'a> { + /// Sets the firmware node. + pub fn fwnode(self, fwnode: Option<ARef<FwNode>>) -> Self { + Self { fwnode, ..self } + } + + /// Sets the device name. + pub fn devicename(self, devicename: &'a CStr) -> Self { + Self { + devicename: Some(devicename), + ..self + } + } + + /// Sets if a device name is mandatory. + pub fn devicename_mandatory(self, mandatory: bool) -> Self { + Self { + devname_mandatory: mandatory, + ..self + } + } + + /// Sets the initial brightness value for the led. + /// + /// The default brightness is 0. + /// If [`LedOps::brightness_get`] is implemented, this value will be ignored. + pub fn initial_brightness(self, brightness: u32) -> Self { + Self { + initial_brightness: brightness, + ..self + } + } + + /// Set the default led trigger. + /// + /// This value can be overwritten by the "linux,default-trigger" fwnode property. + pub fn default_trigger(self, trigger: &'a CStr) -> Self { + Self { + default_trigger: Some(trigger), + ..self + } + } + + /// Sets the color of the led. + /// + /// This value can be overwritten by the "color" fwnode property. + pub fn color(self, color: Color) -> Self { + Self { color, ..self } + } +} + +/// Trait defining the operations for a LED driver. +/// +/// # Examples +/// ``` +/// use kernel::{ +/// device, +/// devres::Devres, +/// led, +/// macros::vtable, +/// platform, +/// prelude::*, // +/// }; +/// +/// struct MyLedOps; +/// +/// +/// #[vtable] +/// impl led::LedOps for MyLedOps { +/// type Bus = platform::Device<device::Bound>; +/// const BLOCKING: bool = false; +/// const MAX_BRIGHTNESS: u32 = 255; +/// +/// fn brightness_set( +/// &self, +/// _dev: &platform::Device<device::Bound>, +/// _classdev: &led::Device<Self>, +/// _brightness: u32 +/// ) -> Result<()> { +/// // Set the brightness for the led here +/// Ok(()) +/// } +/// } +/// +/// fn register_my_led( +/// parent: &platform::Device<device::Bound>, +/// ) -> Result<Pin<KBox<Devres<led::Device<MyLedOps>>>>> { +/// KBox::pin_init(led::Device::new( +/// parent, +/// led::InitData::new(), +/// Ok(MyLedOps), +/// ), GFP_KERNEL) +/// } +/// ``` +/// Led drivers must implement this trait in order to register and handle a [`Device`]. +#[vtable] +pub trait LedOps: Send + 'static + Sized { + /// The bus device required by the implementation. + #[allow(private_bounds)] + type Bus: AsBusDevice<Bound>; + /// If set true, [`LedOps::brightness_set`] and [`LedOps::blink_set`] must perform the + /// operation immediately. If set false, they must not sleep. + const BLOCKING: bool; + /// The max brightness level. + const MAX_BRIGHTNESS: u32; + + /// Sets the brightness level. + /// + /// See also [`LedOps::BLOCKING`]. + fn brightness_set( + &self, + dev: &Self::Bus, + classdev: &Device<Self>, + brightness: u32, + ) -> Result<()>; + + /// Gets the current brightness level. + fn brightness_get(&self, _dev: &Self::Bus, _classdev: &Device<Self>) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Activates hardware accelerated blinking. + /// + /// delays are in milliseconds. If both are zero, a sensible default should be chosen. + /// The caller should adjust the timings in that case and if it can't match the values + /// specified exactly. Setting the brightness to 0 will disable the hardware accelerated + /// blinking. + /// + /// See also [`LedOps::BLOCKING`]. + fn blink_set( + &self, + _dev: &Self::Bus, + _classdev: &Device<Self>, + _delay_on: &mut usize, + _delay_off: &mut usize, + ) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } +} + +/// Led colors. +#[derive(Copy, Clone, Debug, Default)] +#[repr(u32)] +#[non_exhaustive] +#[expect( + missing_docs, + reason = "it shouldn't be necessary to document each color" +)] +pub enum Color { + #[default] + White = bindings::LED_COLOR_ID_WHITE, + Red = bindings::LED_COLOR_ID_RED, + Green = bindings::LED_COLOR_ID_GREEN, + Blue = bindings::LED_COLOR_ID_BLUE, + Amber = bindings::LED_COLOR_ID_AMBER, + Violet = bindings::LED_COLOR_ID_VIOLET, + Yellow = bindings::LED_COLOR_ID_YELLOW, + Ir = bindings::LED_COLOR_ID_IR, + Multi = bindings::LED_COLOR_ID_MULTI, + Rgb = bindings::LED_COLOR_ID_RGB, + Purple = bindings::LED_COLOR_ID_PURPLE, + Orange = bindings::LED_COLOR_ID_ORANGE, + Pink = bindings::LED_COLOR_ID_PINK, + Cyan = bindings::LED_COLOR_ID_CYAN, + Lime = bindings::LED_COLOR_ID_LIME, +} + +impl TryFrom<u32> for Color { + type Error = Error; + + fn try_from(value: u32) -> core::result::Result<Self, Self::Error> { + const _: () = { + assert!(bindings::LED_COLOR_ID_MAX == 15); + }; + if value < bindings::LED_COLOR_ID_MAX { + // SAFETY: + // - `Color` is represented as `u32` + // - the const block above guarantees that no additional color has been added + // - `value` is guaranteed to be in the color id range + Ok(unsafe { transmute::<u32, Color>(value) }) + } else { + Err(EINVAL) + } + } +} + +// SAFETY: A `led::Device` can be unregistered from any thread. +unsafe impl<T: LedOps + Send> Send for Device<T> {} + +// SAFETY: `led::Device` can be shared among threads because all methods of `led::Device` +// are thread safe. +unsafe impl<T: LedOps + Sync> Sync for Device<T> {} + +impl<T: LedOps> Device<T> { + /// Registers a new led classdev. + /// + /// The [`Device`] will be unregistered on drop. + pub fn new<'a>( + parent: &'a T::Bus, + init_data: InitData<'a>, + ops: impl PinInit<T, Error> + 'a, + ) -> impl PinInit<Devres<Self>, Error> + 'a { + Devres::new( + parent.as_ref(), + try_pin_init!(Self { + ops <- ops, + classdev <- Opaque::try_ffi_init(|ptr: *mut bindings::led_classdev| { + // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write. + // `led_classdev` gets fully initialized in-place by + // `led_classdev_register_ext` including `mutex` and `list_head`. + unsafe { + ptr.write(bindings::led_classdev { + brightness_set: (!T::BLOCKING) + .then_some(Adapter::<T>::brightness_set_callback), + brightness_set_blocking: T::BLOCKING + .then_some(Adapter::<T>::brightness_set_blocking_callback), + brightness_get: T::HAS_BRIGHTNESS_GET + .then_some(Adapter::<T>::brightness_get_callback), + blink_set: T::HAS_BLINK_SET.then_some(Adapter::<T>::blink_set_callback), + max_brightness: T::MAX_BRIGHTNESS, + brightness: init_data.initial_brightness, + default_trigger: init_data + .default_trigger + .map_or(core::ptr::null(), CStrExt::as_char_ptr), + color: init_data.color as u32, + ..bindings::led_classdev::default() + }) + }; + + let mut init_data_raw = bindings::led_init_data { + fwnode: init_data + .fwnode + .as_ref() + .map_or(core::ptr::null_mut(), |fwnode| fwnode.as_raw()), + default_label: core::ptr::null(), + devicename: init_data + .devicename + .map_or(core::ptr::null(), CStrExt::as_char_ptr), + devname_mandatory: init_data.devname_mandatory, + }; + + // SAFETY: + // - `parent.as_raw()` is guaranteed to be a pointer to a valid `device` + // or a null pointer. + // - `ptr` is guaranteed to be a pointer to an initialized `led_classdev`. + to_result(unsafe { + bindings::led_classdev_register_ext( + parent.as_ref().as_raw(), + ptr, + &raw mut init_data_raw, + ) + })?; + + core::mem::forget(init_data.fwnode); // keep the reference count incremented + + Ok::<_, Error>(()) + }), + }), + ) + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + unsafe fn from_raw<'a>(led_cdev: *mut bindings::led_classdev) -> &'a Self { + // SAFETY: The function's contract guarantees that `led_cdev` points to a `led_classdev` + // field embedded within a valid `led::Device`. `container_of!` can therefore + // safely calculate the address of the containing struct. + unsafe { &*container_of!(Opaque::cast_from(led_cdev), Self, classdev) } + } + + fn parent(&self) -> &device::Device<Bound> { + // SAFETY: + // - `self.classdev.get()` is guaranteed to be a valid pointer to `led_classdev`. + unsafe { device::Device::from_raw((*(*self.classdev.get()).dev).parent) } + } +} + +struct Adapter<T: LedOps> { + _p: PhantomData<T>, +} + +impl<T: LedOps> Adapter<T> { + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + /// This function is called on setting the brightness of a led. + unsafe extern "C" fn brightness_set_callback( + led_cdev: *mut bindings::led_classdev, + brightness: u32, + ) { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::Device`. + let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + let _ = classdev.ops.brightness_set(parent, classdev, brightness); + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + /// This function is called on setting the brightness of a led immediately. + unsafe extern "C" fn brightness_set_blocking_callback( + led_cdev: *mut bindings::led_classdev, + brightness: u32, + ) -> i32 { + from_result(|| { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::Device`. + let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + classdev.ops.brightness_set(parent, classdev, brightness)?; + Ok(0) + }) + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + /// This function is called on getting the brightness of a led. + unsafe extern "C" fn brightness_get_callback(led_cdev: *mut bindings::led_classdev) -> u32 { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::Device`. + let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + classdev.ops.brightness_get(parent, classdev) + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + /// `delay_on` and `delay_off` must be valid pointers to `usize` and have + /// exclusive access for the period of this function. + /// This function is called on enabling hardware accelerated blinking. + unsafe extern "C" fn blink_set_callback( + led_cdev: *mut bindings::led_classdev, + delay_on: *mut usize, + delay_off: *mut usize, + ) -> i32 { + from_result(|| { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::Device`. + let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + classdev.ops.blink_set( + parent, + classdev, + // SAFETY: The function's contract guarantees that `delay_on` points to a `usize` + // and is exclusive for the period of this function. + unsafe { &mut *delay_on }, + // SAFETY: The function's contract guarantees that `delay_off` points to a `usize` + // and is exclusive for the period of this function. + unsafe { &mut *delay_off }, + )?; + Ok(0) + }) + } +} + +#[pinned_drop] +impl<T: LedOps> PinnedDrop for Device<T> { + fn drop(self: Pin<&mut Self>) { + let raw = self.classdev.get(); + // SAFETY: The existence of `self` guarantees that `self.classdev.get()` is a pointer to a + // valid `struct led_classdev`. + let dev: &device::Device = unsafe { device::Device::from_raw((*raw).dev) }; + + let _fwnode = dev + .fwnode() + // SAFETY: the reference count of `fwnode` has previously been + // incremented in `led::Device::new`. + .map(|fwnode| unsafe { ARef::from_raw(NonNull::from(fwnode)) }); + + // SAFETY: The existence of `self` guarantees that `self.classdev` has previously been + // successfully registered with `led_classdev_register_ext`. + unsafe { bindings::led_classdev_unregister(self.classdev.get()) }; + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index f812cf120042..231818e0614b 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -108,6 +108,7 @@ pub mod jump_label; #[cfg(CONFIG_KUNIT)] pub mod kunit; +pub mod led; pub mod list; pub mod maple_tree; pub mod miscdevice; -- 2.52.0
{ "author": "Markus Probst <markus.probst@posteo.de>", "date": "Mon, 02 Feb 2026 13:52:20 +0000", "thread_id": "3fbc5be7ae889501dc8562376aa38707f0e8bdd4.camel@posteo.de.mbox.gz" }
lkml
[PATCH v11 0/3] rust: leds: add led classdev abstractions
This patch series has previously been contained in https://lore.kernel.org/rust-for-linux/20251008181027.662616-1-markus.probst@posteo.de/T/#t which added a rust written led driver for a microcontroller via i2c. As the reading and writing to the i2c client via the register! macro has not been implemented yet [1], the patch series will only contain the additional abstractions required. [1] https://lore.kernel.org/rust-for-linux/DDDS2V0V2NVJ.16ZKXCKUA1HUV@kernel.org/ The following changes were made: * add basic led classdev abstractions to register and unregister leds * add basic led classdev abstractions to register and unregister multicolor leds Changes since v10: * allow in-place initialization of `LedOps` * run rustfmt for code inside `try_pin_init!` Changes since v9: * add missing periods in documentation * duplicate `led::Device` and `led::Adapter` instead of using a complex trait * fix imports not using prelude * adapt to CStr change * documented `led::Color::Multi` and `led::Color::Rgb` Changes since v8: * accept `Option<ARef<Fwnode>>` in `led::InitData::fwnode()` * make functions in `MultiColorSubLed` const * drop the "rust: Add trait to convert a device reference to a bus device reference" patch, as it has been picked into driver-core Changes since v7: * adjusted import style * added classdev parameter to callback functions in `LedOps` * implement `led::Color` * extend `led::InitData` with - initial_brightness - default_trigger - default_color * split generic and normal led classdev abstractions up (see patch 3/4) * add multicolor led class device abstractions (see patch 4/4) * added MAINTAINERS entry Changes since v6: * fixed typos * improved documentation Changes since v5: * rename `IntoBusDevice` trait into `AsBusDevice` * fix documentation about `LedOps::BLOCKING` * removed dependency on i2c bindings * added `AsBusDevice` implementation for `platform::Device` * removed `device::Device` fallback implementation * document that `AsBusDevice` must not be used by drivers and is intended for bus and class device abstractions only. Changes since v4: * add abstraction to convert a device reference to a bus device reference * require the bus device as parent device and provide it in class device callbacks * remove Pin<Vec<_>> abstraction (as not relevant for the led abstractions) * fixed formatting in `led::Device::new` * fixed `LedOps::BLOCKING` did the inverse effect Changes since v3: * fixed kunit tests failing because of example in documentation Changes since v2: * return `Devres` on `led::Device` creation * replace KBox<T> with T in struct definition * increment and decrement reference-count of fwnode * make a device parent mandatory for led classdev creation * rename `led::Handler` to `led::LedOps` * add optional `brightness_get` function to `led::LedOps` * use `#[vtable]` instead of `const BLINK: bool` * use `Opaque::cast_from` instead of casting a pointer * improve documentation * improve support for older rust versions * use `&Device<Bound>` for parent Changes since v1: * fixed typos noticed by Onur Özkan Signed-off-by: Markus Probst <markus.probst@posteo.de> --- Markus Probst (3): rust: leds: add basic led classdev abstractions rust: leds: split generic and normal led classdev abstractions up rust: leds: add multicolor classdev abstractions MAINTAINERS | 8 + rust/bindings/bindings_helper.h | 1 + rust/kernel/led.rs | 300 +++++++++++++++++++++++++++++++ rust/kernel/led/multicolor.rs | 382 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 226 ++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 918 insertions(+) --- base-commit: 18f7fcd5e69a04df57b563360b88be72471d6b62 change-id: 20251114-rust_leds-a959f7c2f7f9
Move code specific to normal led class devices into a separate file and introduce the `led::Mode` trait to allow for other types of led class devices in `led::LedOps`. Signed-off-by: Markus Probst <markus.probst@posteo.de> --- MAINTAINERS | 1 + rust/kernel/led.rs | 245 ++++++---------------------------------------- rust/kernel/led/normal.rs | 226 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 259 insertions(+), 213 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 26765fecb9a9..5f8b59678785 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -14285,6 +14285,7 @@ L: linux-leds@vger.kernel.org L: rust-for-linux@vger.kernel.org S: Maintained F: rust/kernel/led.rs +F: rust/kernel/led/ LEGO MINDSTORMS EV3 R: David Lechner <david@lechnology.com> diff --git a/rust/kernel/led.rs b/rust/kernel/led.rs index 9acb6946f3da..a32473d61c61 100644 --- a/rust/kernel/led.rs +++ b/rust/kernel/led.rs @@ -33,16 +33,9 @@ }, // }; -/// The led class device representation. -/// -/// This structure represents the Rust abstraction for a C `struct led_classdev`. -#[pin_data(PinnedDrop)] -pub struct Device<T: LedOps> { - #[pin] - ops: T, - #[pin] - classdev: Opaque<bindings::led_classdev>, -} +mod normal; + +pub use normal::{Device, Normal}; /// The led init data representation. /// @@ -135,6 +128,7 @@ pub fn color(self, color: Color) -> Self { /// #[vtable] /// impl led::LedOps for MyLedOps { /// type Bus = platform::Device<device::Bound>; +/// type Mode = led::Normal; /// const BLOCKING: bool = false; /// const MAX_BRIGHTNESS: u32 = 255; /// @@ -165,6 +159,12 @@ pub trait LedOps: Send + 'static + Sized { /// The bus device required by the implementation. #[allow(private_bounds)] type Bus: AsBusDevice<Bound>; + + /// The led mode to use. + /// + /// See [`Mode`]. + type Mode: Mode; + /// If set true, [`LedOps::brightness_set`] and [`LedOps::blink_set`] must perform the /// operation immediately. If set false, they must not sleep. const BLOCKING: bool; @@ -177,12 +177,17 @@ pub trait LedOps: Send + 'static + Sized { fn brightness_set( &self, dev: &Self::Bus, - classdev: &Device<Self>, + classdev: &<Self::Mode as Mode>::Device<Self>, brightness: u32, ) -> Result<()>; /// Gets the current brightness level. - fn brightness_get(&self, _dev: &Self::Bus, _classdev: &Device<Self>) -> u32 { + fn brightness_get( + &self, + dev: &Self::Bus, + classdev: &<Self::Mode as Mode>::Device<Self>, + ) -> u32 { + let _ = (dev, classdev); build_error!(VTABLE_DEFAULT_ERROR) } @@ -196,11 +201,12 @@ fn brightness_get(&self, _dev: &Self::Bus, _classdev: &Device<Self>) -> u32 { /// See also [`LedOps::BLOCKING`]. fn blink_set( &self, - _dev: &Self::Bus, - _classdev: &Device<Self>, - _delay_on: &mut usize, - _delay_off: &mut usize, + dev: &Self::Bus, + classdev: &<Self::Mode as Mode>::Device<Self>, + delay_on: &mut usize, + delay_off: &mut usize, ) -> Result<()> { + let _ = (dev, classdev, delay_on, delay_off); build_error!(VTABLE_DEFAULT_ERROR) } } @@ -251,203 +257,16 @@ fn try_from(value: u32) -> core::result::Result<Self, Self::Error> { } } -// SAFETY: A `led::Device` can be unregistered from any thread. -unsafe impl<T: LedOps + Send> Send for Device<T> {} - -// SAFETY: `led::Device` can be shared among threads because all methods of `led::Device` -// are thread safe. -unsafe impl<T: LedOps + Sync> Sync for Device<T> {} - -impl<T: LedOps> Device<T> { - /// Registers a new led classdev. - /// - /// The [`Device`] will be unregistered on drop. - pub fn new<'a>( - parent: &'a T::Bus, - init_data: InitData<'a>, - ops: impl PinInit<T, Error> + 'a, - ) -> impl PinInit<Devres<Self>, Error> + 'a { - Devres::new( - parent.as_ref(), - try_pin_init!(Self { - ops <- ops, - classdev <- Opaque::try_ffi_init(|ptr: *mut bindings::led_classdev| { - // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write. - // `led_classdev` gets fully initialized in-place by - // `led_classdev_register_ext` including `mutex` and `list_head`. - unsafe { - ptr.write(bindings::led_classdev { - brightness_set: (!T::BLOCKING) - .then_some(Adapter::<T>::brightness_set_callback), - brightness_set_blocking: T::BLOCKING - .then_some(Adapter::<T>::brightness_set_blocking_callback), - brightness_get: T::HAS_BRIGHTNESS_GET - .then_some(Adapter::<T>::brightness_get_callback), - blink_set: T::HAS_BLINK_SET.then_some(Adapter::<T>::blink_set_callback), - max_brightness: T::MAX_BRIGHTNESS, - brightness: init_data.initial_brightness, - default_trigger: init_data - .default_trigger - .map_or(core::ptr::null(), CStrExt::as_char_ptr), - color: init_data.color as u32, - ..bindings::led_classdev::default() - }) - }; - - let mut init_data_raw = bindings::led_init_data { - fwnode: init_data - .fwnode - .as_ref() - .map_or(core::ptr::null_mut(), |fwnode| fwnode.as_raw()), - default_label: core::ptr::null(), - devicename: init_data - .devicename - .map_or(core::ptr::null(), CStrExt::as_char_ptr), - devname_mandatory: init_data.devname_mandatory, - }; - - // SAFETY: - // - `parent.as_raw()` is guaranteed to be a pointer to a valid `device` - // or a null pointer. - // - `ptr` is guaranteed to be a pointer to an initialized `led_classdev`. - to_result(unsafe { - bindings::led_classdev_register_ext( - parent.as_ref().as_raw(), - ptr, - &raw mut init_data_raw, - ) - })?; - - core::mem::forget(init_data.fwnode); // keep the reference count incremented - - Ok::<_, Error>(()) - }), - }), - ) - } - - /// # Safety - /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a - /// `led::Device`. - unsafe fn from_raw<'a>(led_cdev: *mut bindings::led_classdev) -> &'a Self { - // SAFETY: The function's contract guarantees that `led_cdev` points to a `led_classdev` - // field embedded within a valid `led::Device`. `container_of!` can therefore - // safely calculate the address of the containing struct. - unsafe { &*container_of!(Opaque::cast_from(led_cdev), Self, classdev) } - } - - fn parent(&self) -> &device::Device<Bound> { - // SAFETY: - // - `self.classdev.get()` is guaranteed to be a valid pointer to `led_classdev`. - unsafe { device::Device::from_raw((*(*self.classdev.get()).dev).parent) } - } -} - -struct Adapter<T: LedOps> { - _p: PhantomData<T>, -} - -impl<T: LedOps> Adapter<T> { - /// # Safety - /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a - /// `led::Device`. - /// This function is called on setting the brightness of a led. - unsafe extern "C" fn brightness_set_callback( - led_cdev: *mut bindings::led_classdev, - brightness: u32, - ) { - // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a - // `led_classdev` embedded within a `led::Device`. - let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; - // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. - let parent = unsafe { T::Bus::from_device(classdev.parent()) }; - - let _ = classdev.ops.brightness_set(parent, classdev, brightness); - } - - /// # Safety - /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a - /// `led::Device`. - /// This function is called on setting the brightness of a led immediately. - unsafe extern "C" fn brightness_set_blocking_callback( - led_cdev: *mut bindings::led_classdev, - brightness: u32, - ) -> i32 { - from_result(|| { - // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a - // `led_classdev` embedded within a `led::Device`. - let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; - // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. - let parent = unsafe { T::Bus::from_device(classdev.parent()) }; - - classdev.ops.brightness_set(parent, classdev, brightness)?; - Ok(0) - }) - } - - /// # Safety - /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a - /// `led::Device`. - /// This function is called on getting the brightness of a led. - unsafe extern "C" fn brightness_get_callback(led_cdev: *mut bindings::led_classdev) -> u32 { - // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a - // `led_classdev` embedded within a `led::Device`. - let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; - // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. - let parent = unsafe { T::Bus::from_device(classdev.parent()) }; - - classdev.ops.brightness_get(parent, classdev) - } - - /// # Safety - /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a - /// `led::Device`. - /// `delay_on` and `delay_off` must be valid pointers to `usize` and have - /// exclusive access for the period of this function. - /// This function is called on enabling hardware accelerated blinking. - unsafe extern "C" fn blink_set_callback( - led_cdev: *mut bindings::led_classdev, - delay_on: *mut usize, - delay_off: *mut usize, - ) -> i32 { - from_result(|| { - // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a - // `led_classdev` embedded within a `led::Device`. - let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; - // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. - let parent = unsafe { T::Bus::from_device(classdev.parent()) }; - - classdev.ops.blink_set( - parent, - classdev, - // SAFETY: The function's contract guarantees that `delay_on` points to a `usize` - // and is exclusive for the period of this function. - unsafe { &mut *delay_on }, - // SAFETY: The function's contract guarantees that `delay_off` points to a `usize` - // and is exclusive for the period of this function. - unsafe { &mut *delay_off }, - )?; - Ok(0) - }) - } +/// The led mode. +/// +/// Each led mode has its own led class device type with different capabilities. +/// +/// See [`Normal`]. +pub trait Mode: private::Sealed { + /// The class device for the led mode. + type Device<T: LedOps<Mode = Self>>; } -#[pinned_drop] -impl<T: LedOps> PinnedDrop for Device<T> { - fn drop(self: Pin<&mut Self>) { - let raw = self.classdev.get(); - // SAFETY: The existence of `self` guarantees that `self.classdev.get()` is a pointer to a - // valid `struct led_classdev`. - let dev: &device::Device = unsafe { device::Device::from_raw((*raw).dev) }; - - let _fwnode = dev - .fwnode() - // SAFETY: the reference count of `fwnode` has previously been - // incremented in `led::Device::new`. - .map(|fwnode| unsafe { ARef::from_raw(NonNull::from(fwnode)) }); - - // SAFETY: The existence of `self` guarantees that `self.classdev` has previously been - // successfully registered with `led_classdev_register_ext`. - unsafe { bindings::led_classdev_unregister(self.classdev.get()) }; - } +mod private { + pub trait Sealed {} } diff --git a/rust/kernel/led/normal.rs b/rust/kernel/led/normal.rs new file mode 100644 index 000000000000..1a17bb2a6d97 --- /dev/null +++ b/rust/kernel/led/normal.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Led mode for the `struct led_classdev`. +//! +//! C header: [`include/linux/leds.h`](srctree/include/linux/leds.h) + +use super::*; + +/// The led mode for the `struct led_classdev`. Leds with this mode can only have a fixed color. +pub enum Normal {} + +impl Mode for Normal { + type Device<T: LedOps<Mode = Self>> = Device<T>; +} +impl private::Sealed for Normal {} + +/// The led class device representation. +/// +/// This structure represents the Rust abstraction for a led class device. +#[pin_data(PinnedDrop)] +pub struct Device<T: LedOps<Mode = Normal>> { + #[pin] + ops: T, + #[pin] + classdev: Opaque<bindings::led_classdev>, +} + +impl<T: LedOps<Mode = Normal>> Device<T> { + /// Registers a new led classdev. + /// + /// The [`Device`] will be unregistered on drop. + pub fn new<'a>( + parent: &'a T::Bus, + init_data: InitData<'a>, + ops: impl PinInit<T, Error> + 'a, + ) -> impl PinInit<Devres<Self>, Error> + 'a { + Devres::new( + parent.as_ref(), + try_pin_init!(Self { + ops <- ops, + classdev <- Opaque::try_ffi_init(|ptr: *mut bindings::led_classdev| { + // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write. + // `led_classdev` gets fully initialized in-place by + // `led_classdev_register_ext` including `mutex` and `list_head`. + unsafe { + ptr.write(bindings::led_classdev { + brightness_set: (!T::BLOCKING) + .then_some(Adapter::<T>::brightness_set_callback), + brightness_set_blocking: T::BLOCKING + .then_some(Adapter::<T>::brightness_set_blocking_callback), + brightness_get: T::HAS_BRIGHTNESS_GET + .then_some(Adapter::<T>::brightness_get_callback), + blink_set: T::HAS_BLINK_SET.then_some(Adapter::<T>::blink_set_callback), + max_brightness: T::MAX_BRIGHTNESS, + brightness: init_data.initial_brightness, + default_trigger: init_data + .default_trigger + .map_or(core::ptr::null(), CStrExt::as_char_ptr), + color: init_data.color as u32, + ..bindings::led_classdev::default() + }) + }; + + let mut init_data_raw = bindings::led_init_data { + fwnode: init_data + .fwnode + .as_ref() + .map_or(core::ptr::null_mut(), |fwnode| fwnode.as_raw()), + default_label: core::ptr::null(), + devicename: init_data + .devicename + .map_or(core::ptr::null(), CStrExt::as_char_ptr), + devname_mandatory: init_data.devname_mandatory, + }; + + // SAFETY: + // - `parent.as_ref().as_raw()` is guaranteed to be a pointer to a valid + // `device`. + // - `ptr` is guaranteed to be a pointer to an initialized `led_classdev`. + to_result(unsafe { + bindings::led_classdev_register_ext( + parent.as_ref().as_raw(), + ptr, + &raw mut init_data_raw, + ) + })?; + + core::mem::forget(init_data.fwnode); // keep the reference count incremented + + Ok::<_, Error>(()) + }), + }), + ) + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + unsafe fn from_raw<'a>(led_cdev: *mut bindings::led_classdev) -> &'a Self { + // SAFETY: The function's contract guarantees that `led_cdev` points to a `led_classdev` + // field embedded within a valid `led::Device`. `container_of!` can therefore + // safely calculate the address of the containing struct. + unsafe { &*container_of!(Opaque::cast_from(led_cdev), Self, classdev) } + } + + fn parent(&self) -> &device::Device<Bound> { + // SAFETY: `self.classdev.get()` is guaranteed to be a valid pointer to `led_classdev`. + unsafe { device::Device::from_raw((*(*self.classdev.get()).dev).parent) } + } +} + +// SAFETY: A `led::Device` can be unregistered from any thread. +unsafe impl<T: LedOps<Mode = Normal> + Send> Send for Device<T> {} + +// SAFETY: `led::Device` can be shared among threads because all methods of `led::Device` +// are thread safe. +unsafe impl<T: LedOps<Mode = Normal> + Sync> Sync for Device<T> {} + +struct Adapter<T: LedOps<Mode = Normal>> { + _p: PhantomData<T>, +} + +impl<T: LedOps<Mode = Normal>> Adapter<T> { + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + /// This function is called on setting the brightness of a led. + unsafe extern "C" fn brightness_set_callback( + led_cdev: *mut bindings::led_classdev, + brightness: u32, + ) { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::Device`. + let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + let _ = classdev.ops.brightness_set(parent, classdev, brightness); + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + /// This function is called on setting the brightness of a led immediately. + unsafe extern "C" fn brightness_set_blocking_callback( + led_cdev: *mut bindings::led_classdev, + brightness: u32, + ) -> i32 { + from_result(|| { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::Device`. + let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + classdev.ops.brightness_set(parent, classdev, brightness)?; + Ok(0) + }) + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + /// This function is called on getting the brightness of a led. + unsafe extern "C" fn brightness_get_callback(led_cdev: *mut bindings::led_classdev) -> u32 { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::Device`. + let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + classdev.ops.brightness_get(parent, classdev) + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::Device`. + /// `delay_on` and `delay_off` must be valid pointers to `usize` and have + /// exclusive access for the period of this function. + /// This function is called on enabling hardware accelerated blinking. + unsafe extern "C" fn blink_set_callback( + led_cdev: *mut bindings::led_classdev, + delay_on: *mut usize, + delay_off: *mut usize, + ) -> i32 { + from_result(|| { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::Device`. + let classdev = unsafe { Device::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + classdev.ops.blink_set( + parent, + classdev, + // SAFETY: The function's contract guarantees that `delay_on` points to a `usize` + // and is exclusive for the period of this function. + unsafe { &mut *delay_on }, + // SAFETY: The function's contract guarantees that `delay_off` points to a `usize` + // and is exclusive for the period of this function. + unsafe { &mut *delay_off }, + )?; + Ok(0) + }) + } +} + +#[pinned_drop] +impl<T: LedOps<Mode = Normal>> PinnedDrop for Device<T> { + fn drop(self: Pin<&mut Self>) { + let raw = self.classdev.get(); + // SAFETY: The existence of `self` guarantees that `self.classdev.get()` is a pointer to a + // valid `led_classdev`. + let dev: &device::Device = unsafe { device::Device::from_raw((*raw).dev) }; + + let _fwnode = dev + .fwnode() + // SAFETY: the reference count of `fwnode` has previously been + // incremented in `led::Device::new`. + .map(|fwnode| unsafe { ARef::from_raw(NonNull::from(fwnode)) }); + + // SAFETY: The existence of `self` guarantees that `self.classdev` has previously been + // successfully registered with `led_classdev_register_ext`. + unsafe { bindings::led_classdev_unregister(raw) }; + } +} -- 2.52.0
{ "author": "Markus Probst <markus.probst@posteo.de>", "date": "Mon, 02 Feb 2026 13:52:22 +0000", "thread_id": "3fbc5be7ae889501dc8562376aa38707f0e8bdd4.camel@posteo.de.mbox.gz" }
lkml
[PATCH v11 0/3] rust: leds: add led classdev abstractions
This patch series has previously been contained in https://lore.kernel.org/rust-for-linux/20251008181027.662616-1-markus.probst@posteo.de/T/#t which added a rust written led driver for a microcontroller via i2c. As the reading and writing to the i2c client via the register! macro has not been implemented yet [1], the patch series will only contain the additional abstractions required. [1] https://lore.kernel.org/rust-for-linux/DDDS2V0V2NVJ.16ZKXCKUA1HUV@kernel.org/ The following changes were made: * add basic led classdev abstractions to register and unregister leds * add basic led classdev abstractions to register and unregister multicolor leds Changes since v10: * allow in-place initialization of `LedOps` * run rustfmt for code inside `try_pin_init!` Changes since v9: * add missing periods in documentation * duplicate `led::Device` and `led::Adapter` instead of using a complex trait * fix imports not using prelude * adapt to CStr change * documented `led::Color::Multi` and `led::Color::Rgb` Changes since v8: * accept `Option<ARef<Fwnode>>` in `led::InitData::fwnode()` * make functions in `MultiColorSubLed` const * drop the "rust: Add trait to convert a device reference to a bus device reference" patch, as it has been picked into driver-core Changes since v7: * adjusted import style * added classdev parameter to callback functions in `LedOps` * implement `led::Color` * extend `led::InitData` with - initial_brightness - default_trigger - default_color * split generic and normal led classdev abstractions up (see patch 3/4) * add multicolor led class device abstractions (see patch 4/4) * added MAINTAINERS entry Changes since v6: * fixed typos * improved documentation Changes since v5: * rename `IntoBusDevice` trait into `AsBusDevice` * fix documentation about `LedOps::BLOCKING` * removed dependency on i2c bindings * added `AsBusDevice` implementation for `platform::Device` * removed `device::Device` fallback implementation * document that `AsBusDevice` must not be used by drivers and is intended for bus and class device abstractions only. Changes since v4: * add abstraction to convert a device reference to a bus device reference * require the bus device as parent device and provide it in class device callbacks * remove Pin<Vec<_>> abstraction (as not relevant for the led abstractions) * fixed formatting in `led::Device::new` * fixed `LedOps::BLOCKING` did the inverse effect Changes since v3: * fixed kunit tests failing because of example in documentation Changes since v2: * return `Devres` on `led::Device` creation * replace KBox<T> with T in struct definition * increment and decrement reference-count of fwnode * make a device parent mandatory for led classdev creation * rename `led::Handler` to `led::LedOps` * add optional `brightness_get` function to `led::LedOps` * use `#[vtable]` instead of `const BLINK: bool` * use `Opaque::cast_from` instead of casting a pointer * improve documentation * improve support for older rust versions * use `&Device<Bound>` for parent Changes since v1: * fixed typos noticed by Onur Özkan Signed-off-by: Markus Probst <markus.probst@posteo.de> --- Markus Probst (3): rust: leds: add basic led classdev abstractions rust: leds: split generic and normal led classdev abstractions up rust: leds: add multicolor classdev abstractions MAINTAINERS | 8 + rust/bindings/bindings_helper.h | 1 + rust/kernel/led.rs | 300 +++++++++++++++++++++++++++++++ rust/kernel/led/multicolor.rs | 382 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 226 ++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 918 insertions(+) --- base-commit: 18f7fcd5e69a04df57b563360b88be72471d6b62 change-id: 20251114-rust_leds-a959f7c2f7f9
Implement the abstractions needed for multicolor led class devices, including: * `led::MultiColor` - the led mode implementation * `MultiColorSubLed` - a safe wrapper arround `mc_subled` * `led::MultiColorDevice` - a safe wrapper around `led_classdev_mc` Signed-off-by: Markus Probst <markus.probst@posteo.de> --- rust/bindings/bindings_helper.h | 1 + rust/kernel/led.rs | 30 +++- rust/kernel/led/multicolor.rs | 382 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 412 insertions(+), 1 deletion(-) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index a067038b4b42..765a4198b85d 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -62,6 +62,7 @@ #include <linux/ioport.h> #include <linux/jiffies.h> #include <linux/jump_label.h> +#include <linux/led-class-multicolor.h> #include <linux/mdio.h> #include <linux/mm.h> #include <linux/miscdevice.h> diff --git a/rust/kernel/led.rs b/rust/kernel/led.rs index a32473d61c61..464e100ab3db 100644 --- a/rust/kernel/led.rs +++ b/rust/kernel/led.rs @@ -33,8 +33,12 @@ }, // }; +#[cfg(CONFIG_LEDS_CLASS_MULTICOLOR)] +mod multicolor; mod normal; +#[cfg(CONFIG_LEDS_CLASS_MULTICOLOR)] +pub use multicolor::{MultiColor, MultiColorDevice, MultiColorSubLed}; pub use normal::{Device, Normal}; /// The led init data representation. @@ -229,7 +233,24 @@ pub enum Color { Violet = bindings::LED_COLOR_ID_VIOLET, Yellow = bindings::LED_COLOR_ID_YELLOW, Ir = bindings::LED_COLOR_ID_IR, + #[cfg_attr( + CONFIG_LEDS_CLASS_MULTICOLOR, + doc = "Use this color for a [`MultiColor`] led." + )] + #[cfg_attr( + not(CONFIG_LEDS_CLASS_MULTICOLOR), + doc = "Use this color for a `MultiColor` led." + )] + /// If the led supports RGB, use [`Color::Rgb`] instead. Multi = bindings::LED_COLOR_ID_MULTI, + #[cfg_attr( + CONFIG_LEDS_CLASS_MULTICOLOR, + doc = "Use this color for a [`MultiColor`] led with rgb support." + )] + #[cfg_attr( + not(CONFIG_LEDS_CLASS_MULTICOLOR), + doc = "Use this color for a `MultiColor` led with rgb support." + )] Rgb = bindings::LED_COLOR_ID_RGB, Purple = bindings::LED_COLOR_ID_PURPLE, Orange = bindings::LED_COLOR_ID_ORANGE, @@ -261,7 +282,14 @@ fn try_from(value: u32) -> core::result::Result<Self, Self::Error> { /// /// Each led mode has its own led class device type with different capabilities. /// -/// See [`Normal`]. +#[cfg_attr( + CONFIG_LEDS_CLASS_MULTICOLOR, + doc = "See [`Normal`] and [`MultiColor`]." +)] +#[cfg_attr( + not(CONFIG_LEDS_CLASS_MULTICOLOR), + doc = "See [`Normal`] and `MultiColor`." +)] pub trait Mode: private::Sealed { /// The class device for the led mode. type Device<T: LedOps<Mode = Self>>; diff --git a/rust/kernel/led/multicolor.rs b/rust/kernel/led/multicolor.rs new file mode 100644 index 000000000000..7bd143d0646e --- /dev/null +++ b/rust/kernel/led/multicolor.rs @@ -0,0 +1,382 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Led mode for the `struct led_classdev_mc`. +//! +//! C header: [`include/linux/led-class-multicolor.h`](srctree/include/linux/led-class-multicolor.h) + +use crate::alloc::KVec; + +use super::*; + +/// The led mode for the `struct led_classdev_mc`. Leds with this mode can have multiple colors. +pub enum MultiColor {} +impl Mode for MultiColor { + type Device<T: LedOps<Mode = Self>> = MultiColorDevice<T>; +} +impl private::Sealed for MultiColor {} + +/// The multicolor sub led info representation. +/// +/// This structure represents the Rust abstraction for a C `struct mc_subled`. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +#[non_exhaustive] +pub struct MultiColorSubLed { + /// the color of the sub led + pub color: Color, + /// the brightness of the sub led. + /// + /// The value will be automatically calculated. + /// See `MultiColor::pre_brightness_set`. + pub brightness: u32, + /// the intensity of the sub led. + pub intensity: u32, + /// arbitrary data for the driver to store. + pub channel: u32, +} + +// We directly pass a reference to the `subled_info` field in `led_classdev_mc` to the driver via +// `Device::subleds()`. +// We need safeguards to ensure `MultiColorSubLed` and `mc_subled` stay identical. +const _: () = { + use core::mem::offset_of; + + const fn assert_same_type<T>(_: &T, _: &T) {} + + let rust_zeroed = MultiColorSubLed { + color: Color::White, + brightness: 0, + intensity: 0, + channel: 0, + }; + let c_zeroed = bindings::mc_subled { + color_index: 0, + brightness: 0, + intensity: 0, + channel: 0, + }; + + assert!(offset_of!(MultiColorSubLed, color) == offset_of!(bindings::mc_subled, color_index)); + assert_same_type(&0u32, &c_zeroed.color_index); + + assert!( + offset_of!(MultiColorSubLed, brightness) == offset_of!(bindings::mc_subled, brightness) + ); + assert_same_type(&rust_zeroed.brightness, &c_zeroed.brightness); + + assert!(offset_of!(MultiColorSubLed, intensity) == offset_of!(bindings::mc_subled, intensity)); + assert_same_type(&rust_zeroed.intensity, &c_zeroed.intensity); + + assert!(offset_of!(MultiColorSubLed, channel) == offset_of!(bindings::mc_subled, channel)); + assert_same_type(&rust_zeroed.channel, &c_zeroed.channel); + + assert!(size_of::<MultiColorSubLed>() == size_of::<bindings::mc_subled>()); +}; + +impl MultiColorSubLed { + /// Create a new multicolor sub led info. + pub const fn new(color: Color) -> Self { + Self { + color, + brightness: 0, + intensity: 0, + channel: 0, + } + } + + /// Set arbitrary data for the driver. + pub const fn channel(mut self, channel: u32) -> Self { + self.channel = channel; + self + } + + /// Set the initial intensity of the subled. + pub const fn initial_intensity(mut self, intensity: u32) -> Self { + self.intensity = intensity; + self + } +} + +/// The multicolor led class device representation. +/// +/// This structure represents the Rust abstraction for a multicolor led class device. +#[pin_data(PinnedDrop)] +pub struct MultiColorDevice<T: LedOps<Mode = MultiColor>> { + #[pin] + ops: T, + #[pin] + classdev: Opaque<bindings::led_classdev_mc>, +} + +impl<T: LedOps<Mode = MultiColor>> MultiColorDevice<T> { + /// Registers a new led classdev. + /// + /// The [`MultiColorDevice`] will be unregistered on drop. + pub fn new<'a>( + parent: &'a T::Bus, + init_data: InitData<'a>, + ops: impl PinInit<T, Error> + 'a, + subleds: &'a [MultiColorSubLed], + ) -> impl PinInit<Devres<Self>, Error> + 'a { + Devres::new( + parent.as_ref(), + try_pin_init!(Self { + ops <- ops, + classdev <- Opaque::try_ffi_init(|ptr: *mut bindings::led_classdev_mc| { + let mut used = 0; + if subleds.iter().any(|subled| { + let bit = 1 << (subled.color as u32); + if (used & bit) != 0 { + true + } else { + used |= bit; + false + } + }) { + dev_err!(parent.as_ref(), "duplicate color in multicolor led\n"); + return Err(EINVAL); + } + let mut subleds_vec = KVec::new(); + subleds_vec.extend_from_slice(subleds, GFP_KERNEL)?; + let (subled_info, num_colors, capacity) = subleds_vec.into_raw_parts(); + debug_assert_eq!(num_colors, capacity); + + // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write. + // `led_classdev_mc` gets fully initialized in-place by + // `led_classdev_multicolor_register_ext` including `mutex` and `list_head`. + unsafe { + ptr.write(bindings::led_classdev_mc { + led_cdev: bindings::led_classdev { + brightness_set: (!T::BLOCKING) + .then_some(Adapter::<T>::brightness_set_callback), + brightness_set_blocking: T::BLOCKING + .then_some(Adapter::<T>::brightness_set_blocking_callback), + brightness_get: T::HAS_BRIGHTNESS_GET + .then_some(Adapter::<T>::brightness_get_callback), + blink_set: T::HAS_BLINK_SET + .then_some(Adapter::<T>::blink_set_callback), + max_brightness: T::MAX_BRIGHTNESS, + brightness: init_data.initial_brightness, + default_trigger: init_data + .default_trigger + .map_or(core::ptr::null(), CStrExt::as_char_ptr), + color: init_data.color as u32, + ..bindings::led_classdev::default() + }, + num_colors: u32::try_from(num_colors)?, + // CAST: The safeguards in the const block ensure that + // `MultiColorSubLed` has an identical layout to `mc_subled`. + subled_info: subled_info.cast::<bindings::mc_subled>(), + }) + }; + + let mut init_data_raw = bindings::led_init_data { + fwnode: init_data + .fwnode + .as_ref() + .map_or(core::ptr::null_mut(), |fwnode| fwnode.as_raw()), + default_label: core::ptr::null(), + devicename: init_data + .devicename + .map_or(core::ptr::null(), CStrExt::as_char_ptr), + devname_mandatory: init_data.devname_mandatory, + }; + + // SAFETY: + // - `parent.as_ref().as_raw()` is guaranteed to be a pointer to a valid + // `device`. + // - `ptr` is guaranteed to be a pointer to an initialized `led_classdev_mc`. + to_result(unsafe { + bindings::led_classdev_multicolor_register_ext( + parent.as_ref().as_raw(), + ptr, + &raw mut init_data_raw, + ) + }) + .inspect_err(|_err| { + // SAFETY: `subled_info` is guaranteed to be a valid array pointer to + // `mc_subled` with the length and capacity of `num_colors`. + drop(unsafe { KVec::from_raw_parts(subled_info, num_colors, num_colors) }); + })?; + + core::mem::forget(init_data.fwnode); // keep the reference count incremented + + Ok::<_, Error>(()) + }), + }), + ) + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::MultiColorDevice`. + unsafe fn from_raw<'a>(led_cdev: *mut bindings::led_classdev) -> &'a Self { + // SAFETY: The function's contract guarantees that `led_cdev` points to a `led_classdev` + // field embedded within a valid `led::MultiColorDevice`. `container_of!` can therefore + // safely calculate the address of the containing struct. + let led_mc_cdev = unsafe { container_of!(led_cdev, bindings::led_classdev_mc, led_cdev) }; + + // SAFETY: It is guaranteed that `led_mc_cdev` points to a `led_classdev_mc` + // field embedded within a valid `led::MultiColorDevice`. `container_of!` can therefore + // safely calculate the address of the containing struct. + unsafe { &*container_of!(Opaque::cast_from(led_mc_cdev), Self, classdev) } + } + + fn parent(&self) -> &device::Device<Bound> { + // SAFETY: `self.classdev.get()` is guaranteed to be a valid pointer to `led_classdev_mc`. + unsafe { device::Device::from_raw((*(*self.classdev.get()).led_cdev.dev).parent) } + } + + /// Returns the subleds passed to [`Device::new_multicolor`]. + pub fn subleds(&self) -> &[MultiColorSubLed] { + // SAFETY: The existence of `self` guarantees that `self.classdev.get()` is a pointer to a + // valid `led_classdev_mc`. + let raw = unsafe { &*self.classdev.get() }; + // SAFETY: `raw.subled_info` is a valid pointer to `mc_subled[num_colors]`. + // CAST: The safeguards in the const block ensure that `MultiColorSubLed` has an identical + // layout to `mc_subled`. + unsafe { + core::slice::from_raw_parts( + raw.subled_info.cast::<MultiColorSubLed>(), + raw.num_colors as usize, + ) + } + } +} + +// SAFETY: A `led::MultiColorDevice` can be unregistered from any thread. +unsafe impl<T: LedOps<Mode = MultiColor> + Send> Send for MultiColorDevice<T> {} + +// SAFETY: `led::MultiColorDevice` can be shared among threads because all methods of `led::Device` +// are thread safe. +unsafe impl<T: LedOps<Mode = MultiColor> + Sync> Sync for MultiColorDevice<T> {} + +struct Adapter<T: LedOps<Mode = MultiColor>> { + _p: PhantomData<T>, +} + +impl<T: LedOps<Mode = MultiColor>> Adapter<T> { + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::MultiColorDevice`. + /// This function is called on setting the brightness of a led. + unsafe extern "C" fn brightness_set_callback( + led_cdev: *mut bindings::led_classdev, + brightness: u32, + ) { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::MultiColorDevice`. + let classdev = unsafe { MultiColorDevice::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + // SAFETY: `classdev.classdev.get()` is guaranteed to be a pointer to a valid + // `led_classdev_mc`. + unsafe { bindings::led_mc_calc_color_components(classdev.classdev.get(), brightness) }; + + let _ = classdev.ops.brightness_set(parent, classdev, brightness); + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::MultiColorDevice`. + /// This function is called on setting the brightness of a led immediately. + unsafe extern "C" fn brightness_set_blocking_callback( + led_cdev: *mut bindings::led_classdev, + brightness: u32, + ) -> i32 { + from_result(|| { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::MultiColorDevice`. + let classdev = unsafe { MultiColorDevice::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + // SAFETY: `classdev.classdev.get()` is guaranteed to be a pointer to a valid + // `led_classdev_mc`. + unsafe { bindings::led_mc_calc_color_components(classdev.classdev.get(), brightness) }; + + classdev.ops.brightness_set(parent, classdev, brightness)?; + Ok(0) + }) + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::MultiColorDevice`. + /// This function is called on getting the brightness of a led. + unsafe extern "C" fn brightness_get_callback(led_cdev: *mut bindings::led_classdev) -> u32 { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::MultiColorDevice`. + let classdev = unsafe { MultiColorDevice::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + classdev.ops.brightness_get(parent, classdev) + } + + /// # Safety + /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a + /// `led::MultiColorDevice`. + /// `delay_on` and `delay_off` must be valid pointers to `usize` and have + /// exclusive access for the period of this function. + /// This function is called on enabling hardware accelerated blinking. + unsafe extern "C" fn blink_set_callback( + led_cdev: *mut bindings::led_classdev, + delay_on: *mut usize, + delay_off: *mut usize, + ) -> i32 { + from_result(|| { + // SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a + // `led_classdev` embedded within a `led::MultiColorDevice`. + let classdev = unsafe { MultiColorDevice::<T>::from_raw(led_cdev) }; + // SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. + let parent = unsafe { T::Bus::from_device(classdev.parent()) }; + + classdev.ops.blink_set( + parent, + classdev, + // SAFETY: The function's contract guarantees that `delay_on` points to a `usize` + // and is exclusive for the period of this function. + unsafe { &mut *delay_on }, + // SAFETY: The function's contract guarantees that `delay_off` points to a `usize` + // and is exclusive for the period of this function. + unsafe { &mut *delay_off }, + )?; + Ok(0) + }) + } +} + +#[pinned_drop] +impl<T: LedOps<Mode = MultiColor>> PinnedDrop for MultiColorDevice<T> { + fn drop(self: Pin<&mut Self>) { + let raw = self.classdev.get(); + // SAFETY: The existence of `self` guarantees that `self.classdev.get()` is a pointer to a + // valid `led_classdev_mc`. + let dev: &device::Device = unsafe { device::Device::from_raw((*raw).led_cdev.dev) }; + + let _fwnode = dev + .fwnode() + // SAFETY: the reference count of `fwnode` has previously been + // incremented in `led::Device::new`. + .map(|fwnode| unsafe { ARef::from_raw(NonNull::from(fwnode)) }); + + // SAFETY: The existence of `self` guarantees that `self.classdev` has previously been + // successfully registered with `led_classdev_multicolor_register_ext`. + unsafe { bindings::led_classdev_multicolor_unregister(raw) }; + + // SAFETY: `raw` is guaranteed to be a valid pointer to `led_classdev_mc`. + let led_cdev = unsafe { &*raw }; + + // SAFETY: `subled_info` is guaranteed to be a valid array pointer to `mc_subled` with the + // length and capacity of `led_cdev.num_colors`. See `led::MulticolorDevice::new`. + drop(unsafe { + KVec::from_raw_parts( + led_cdev.subled_info, + led_cdev.num_colors as usize, + led_cdev.num_colors as usize, + ) + }); + } +} -- 2.52.0
{ "author": "Markus Probst <markus.probst@posteo.de>", "date": "Mon, 02 Feb 2026 13:52:25 +0000", "thread_id": "3fbc5be7ae889501dc8562376aa38707f0e8bdd4.camel@posteo.de.mbox.gz" }
lkml
[PATCH v11 0/3] rust: leds: add led classdev abstractions
This patch series has previously been contained in https://lore.kernel.org/rust-for-linux/20251008181027.662616-1-markus.probst@posteo.de/T/#t which added a rust written led driver for a microcontroller via i2c. As the reading and writing to the i2c client via the register! macro has not been implemented yet [1], the patch series will only contain the additional abstractions required. [1] https://lore.kernel.org/rust-for-linux/DDDS2V0V2NVJ.16ZKXCKUA1HUV@kernel.org/ The following changes were made: * add basic led classdev abstractions to register and unregister leds * add basic led classdev abstractions to register and unregister multicolor leds Changes since v10: * allow in-place initialization of `LedOps` * run rustfmt for code inside `try_pin_init!` Changes since v9: * add missing periods in documentation * duplicate `led::Device` and `led::Adapter` instead of using a complex trait * fix imports not using prelude * adapt to CStr change * documented `led::Color::Multi` and `led::Color::Rgb` Changes since v8: * accept `Option<ARef<Fwnode>>` in `led::InitData::fwnode()` * make functions in `MultiColorSubLed` const * drop the "rust: Add trait to convert a device reference to a bus device reference" patch, as it has been picked into driver-core Changes since v7: * adjusted import style * added classdev parameter to callback functions in `LedOps` * implement `led::Color` * extend `led::InitData` with - initial_brightness - default_trigger - default_color * split generic and normal led classdev abstractions up (see patch 3/4) * add multicolor led class device abstractions (see patch 4/4) * added MAINTAINERS entry Changes since v6: * fixed typos * improved documentation Changes since v5: * rename `IntoBusDevice` trait into `AsBusDevice` * fix documentation about `LedOps::BLOCKING` * removed dependency on i2c bindings * added `AsBusDevice` implementation for `platform::Device` * removed `device::Device` fallback implementation * document that `AsBusDevice` must not be used by drivers and is intended for bus and class device abstractions only. Changes since v4: * add abstraction to convert a device reference to a bus device reference * require the bus device as parent device and provide it in class device callbacks * remove Pin<Vec<_>> abstraction (as not relevant for the led abstractions) * fixed formatting in `led::Device::new` * fixed `LedOps::BLOCKING` did the inverse effect Changes since v3: * fixed kunit tests failing because of example in documentation Changes since v2: * return `Devres` on `led::Device` creation * replace KBox<T> with T in struct definition * increment and decrement reference-count of fwnode * make a device parent mandatory for led classdev creation * rename `led::Handler` to `led::LedOps` * add optional `brightness_get` function to `led::LedOps` * use `#[vtable]` instead of `const BLINK: bool` * use `Opaque::cast_from` instead of casting a pointer * improve documentation * improve support for older rust versions * use `&Device<Bound>` for parent Changes since v1: * fixed typos noticed by Onur Özkan Signed-off-by: Markus Probst <markus.probst@posteo.de> --- Markus Probst (3): rust: leds: add basic led classdev abstractions rust: leds: split generic and normal led classdev abstractions up rust: leds: add multicolor classdev abstractions MAINTAINERS | 8 + rust/bindings/bindings_helper.h | 1 + rust/kernel/led.rs | 300 +++++++++++++++++++++++++++++++ rust/kernel/led/multicolor.rs | 382 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 226 ++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 918 insertions(+) --- base-commit: 18f7fcd5e69a04df57b563360b88be72471d6b62 change-id: 20251114-rust_leds-a959f7c2f7f9
On Mon Feb 2, 2026 at 1:52 PM GMT, Markus Probst wrote: It appears to me that while this reflects on the C API, on the Rust side this is more commonly known as the builder pattern. I think this should properly be name `led::DeviceBuilder`, as it does more than what `led_init_data` does on the C side (e.g. initial_brightness). Perhaps the device creation can be part of this too, e.g. LedDeviceBuilder::new() .fwnode(...) .devicename(...) .initial_brightness(...) .build(parent, ops) ? `static_assert!()` and move this out from the impl. This should be `fwnode.into_raw()` which directly takes the ownership for `ARef`, rather than `as_raw()` and forget the `ARef` later. Best, Gary
{ "author": "\"Gary Guo\" <gary@garyguo.net>", "date": "Mon, 02 Feb 2026 15:41:56 +0000", "thread_id": "3fbc5be7ae889501dc8562376aa38707f0e8bdd4.camel@posteo.de.mbox.gz" }
lkml
[PATCH v11 0/3] rust: leds: add led classdev abstractions
This patch series has previously been contained in https://lore.kernel.org/rust-for-linux/20251008181027.662616-1-markus.probst@posteo.de/T/#t which added a rust written led driver for a microcontroller via i2c. As the reading and writing to the i2c client via the register! macro has not been implemented yet [1], the patch series will only contain the additional abstractions required. [1] https://lore.kernel.org/rust-for-linux/DDDS2V0V2NVJ.16ZKXCKUA1HUV@kernel.org/ The following changes were made: * add basic led classdev abstractions to register and unregister leds * add basic led classdev abstractions to register and unregister multicolor leds Changes since v10: * allow in-place initialization of `LedOps` * run rustfmt for code inside `try_pin_init!` Changes since v9: * add missing periods in documentation * duplicate `led::Device` and `led::Adapter` instead of using a complex trait * fix imports not using prelude * adapt to CStr change * documented `led::Color::Multi` and `led::Color::Rgb` Changes since v8: * accept `Option<ARef<Fwnode>>` in `led::InitData::fwnode()` * make functions in `MultiColorSubLed` const * drop the "rust: Add trait to convert a device reference to a bus device reference" patch, as it has been picked into driver-core Changes since v7: * adjusted import style * added classdev parameter to callback functions in `LedOps` * implement `led::Color` * extend `led::InitData` with - initial_brightness - default_trigger - default_color * split generic and normal led classdev abstractions up (see patch 3/4) * add multicolor led class device abstractions (see patch 4/4) * added MAINTAINERS entry Changes since v6: * fixed typos * improved documentation Changes since v5: * rename `IntoBusDevice` trait into `AsBusDevice` * fix documentation about `LedOps::BLOCKING` * removed dependency on i2c bindings * added `AsBusDevice` implementation for `platform::Device` * removed `device::Device` fallback implementation * document that `AsBusDevice` must not be used by drivers and is intended for bus and class device abstractions only. Changes since v4: * add abstraction to convert a device reference to a bus device reference * require the bus device as parent device and provide it in class device callbacks * remove Pin<Vec<_>> abstraction (as not relevant for the led abstractions) * fixed formatting in `led::Device::new` * fixed `LedOps::BLOCKING` did the inverse effect Changes since v3: * fixed kunit tests failing because of example in documentation Changes since v2: * return `Devres` on `led::Device` creation * replace KBox<T> with T in struct definition * increment and decrement reference-count of fwnode * make a device parent mandatory for led classdev creation * rename `led::Handler` to `led::LedOps` * add optional `brightness_get` function to `led::LedOps` * use `#[vtable]` instead of `const BLINK: bool` * use `Opaque::cast_from` instead of casting a pointer * improve documentation * improve support for older rust versions * use `&Device<Bound>` for parent Changes since v1: * fixed typos noticed by Onur Özkan Signed-off-by: Markus Probst <markus.probst@posteo.de> --- Markus Probst (3): rust: leds: add basic led classdev abstractions rust: leds: split generic and normal led classdev abstractions up rust: leds: add multicolor classdev abstractions MAINTAINERS | 8 + rust/bindings/bindings_helper.h | 1 + rust/kernel/led.rs | 300 +++++++++++++++++++++++++++++++ rust/kernel/led/multicolor.rs | 382 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 226 ++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 918 insertions(+) --- base-commit: 18f7fcd5e69a04df57b563360b88be72471d6b62 change-id: 20251114-rust_leds-a959f7c2f7f9
On Mon Feb 2, 2026 at 1:52 PM GMT, Markus Probst wrote: This patch deleted a lot of code that's added in the previous one. Could you structure it in a way without doing this? Best, Gary
{ "author": "\"Gary Guo\" <gary@garyguo.net>", "date": "Mon, 02 Feb 2026 15:43:37 +0000", "thread_id": "3fbc5be7ae889501dc8562376aa38707f0e8bdd4.camel@posteo.de.mbox.gz" }
lkml
[PATCH v11 0/3] rust: leds: add led classdev abstractions
This patch series has previously been contained in https://lore.kernel.org/rust-for-linux/20251008181027.662616-1-markus.probst@posteo.de/T/#t which added a rust written led driver for a microcontroller via i2c. As the reading and writing to the i2c client via the register! macro has not been implemented yet [1], the patch series will only contain the additional abstractions required. [1] https://lore.kernel.org/rust-for-linux/DDDS2V0V2NVJ.16ZKXCKUA1HUV@kernel.org/ The following changes were made: * add basic led classdev abstractions to register and unregister leds * add basic led classdev abstractions to register and unregister multicolor leds Changes since v10: * allow in-place initialization of `LedOps` * run rustfmt for code inside `try_pin_init!` Changes since v9: * add missing periods in documentation * duplicate `led::Device` and `led::Adapter` instead of using a complex trait * fix imports not using prelude * adapt to CStr change * documented `led::Color::Multi` and `led::Color::Rgb` Changes since v8: * accept `Option<ARef<Fwnode>>` in `led::InitData::fwnode()` * make functions in `MultiColorSubLed` const * drop the "rust: Add trait to convert a device reference to a bus device reference" patch, as it has been picked into driver-core Changes since v7: * adjusted import style * added classdev parameter to callback functions in `LedOps` * implement `led::Color` * extend `led::InitData` with - initial_brightness - default_trigger - default_color * split generic and normal led classdev abstractions up (see patch 3/4) * add multicolor led class device abstractions (see patch 4/4) * added MAINTAINERS entry Changes since v6: * fixed typos * improved documentation Changes since v5: * rename `IntoBusDevice` trait into `AsBusDevice` * fix documentation about `LedOps::BLOCKING` * removed dependency on i2c bindings * added `AsBusDevice` implementation for `platform::Device` * removed `device::Device` fallback implementation * document that `AsBusDevice` must not be used by drivers and is intended for bus and class device abstractions only. Changes since v4: * add abstraction to convert a device reference to a bus device reference * require the bus device as parent device and provide it in class device callbacks * remove Pin<Vec<_>> abstraction (as not relevant for the led abstractions) * fixed formatting in `led::Device::new` * fixed `LedOps::BLOCKING` did the inverse effect Changes since v3: * fixed kunit tests failing because of example in documentation Changes since v2: * return `Devres` on `led::Device` creation * replace KBox<T> with T in struct definition * increment and decrement reference-count of fwnode * make a device parent mandatory for led classdev creation * rename `led::Handler` to `led::LedOps` * add optional `brightness_get` function to `led::LedOps` * use `#[vtable]` instead of `const BLINK: bool` * use `Opaque::cast_from` instead of casting a pointer * improve documentation * improve support for older rust versions * use `&Device<Bound>` for parent Changes since v1: * fixed typos noticed by Onur Özkan Signed-off-by: Markus Probst <markus.probst@posteo.de> --- Markus Probst (3): rust: leds: add basic led classdev abstractions rust: leds: split generic and normal led classdev abstractions up rust: leds: add multicolor classdev abstractions MAINTAINERS | 8 + rust/bindings/bindings_helper.h | 1 + rust/kernel/led.rs | 300 +++++++++++++++++++++++++++++++ rust/kernel/led/multicolor.rs | 382 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 226 ++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 918 insertions(+) --- base-commit: 18f7fcd5e69a04df57b563360b88be72471d6b62 change-id: 20251114-rust_leds-a959f7c2f7f9
On Mon, 2026-02-02 at 15:41 +0000, Gary Guo wrote: With into_raw(), the reference count of fwnode would not decrement if the registration fails. Thanks - Markus Probst
{ "author": "Markus Probst <markus.probst@posteo.de>", "date": "Mon, 02 Feb 2026 16:53:09 +0000", "thread_id": "3fbc5be7ae889501dc8562376aa38707f0e8bdd4.camel@posteo.de.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Export liveupdate_enabled(), liveupdate_register_file_handler(), and liveupdate_unregister_file_handler(). All of these will be used by vfio-pci in a subsequent commit, which can be built as a module. Signed-off-by: David Matlack <dmatlack@google.com> --- kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 ++ 2 files changed, 3 insertions(+) diff --git a/kernel/liveupdate/luo_core.c b/kernel/liveupdate/luo_core.c index dda7bb57d421..59d7793d9444 100644 --- a/kernel/liveupdate/luo_core.c +++ b/kernel/liveupdate/luo_core.c @@ -255,6 +255,7 @@ bool liveupdate_enabled(void) { return luo_global.enabled; } +EXPORT_SYMBOL_GPL(liveupdate_enabled); /** * DOC: LUO ioctl Interface diff --git a/kernel/liveupdate/luo_file.c b/kernel/liveupdate/luo_file.c index 35d2a8b1a0df..32759e846bc9 100644 --- a/kernel/liveupdate/luo_file.c +++ b/kernel/liveupdate/luo_file.c @@ -872,6 +872,7 @@ int liveupdate_register_file_handler(struct liveupdate_file_handler *fh) luo_session_resume(); return err; } +EXPORT_SYMBOL_GPL(liveupdate_register_file_handler); /** * liveupdate_unregister_file_handler - Unregister a liveupdate file handler @@ -917,3 +918,4 @@ int liveupdate_unregister_file_handler(struct liveupdate_file_handler *fh) liveupdate_test_register(fh); return err; } +EXPORT_SYMBOL_GPL(liveupdate_unregister_file_handler); -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:48 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Inherit bus numbers from the previous kernel during a Live Update when one or more PCI devices are being preserved. This is necessary so that preserved devices can DMA through the IOMMU during a Live Update (changing bus numbers would break IOMMU translation). Signed-off-by: David Matlack <dmatlack@google.com> --- drivers/pci/probe.c | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/drivers/pci/probe.c b/drivers/pci/probe.c index af6356c5a156..ca6e5f79debb 100644 --- a/drivers/pci/probe.c +++ b/drivers/pci/probe.c @@ -1351,6 +1351,20 @@ static bool pci_ea_fixed_busnrs(struct pci_dev *dev, u8 *sec, u8 *sub) return true; } +static bool pci_assign_all_busses(void) +{ + /* + * During a Live Update where devices are preserved by the previous + * kernel, inherit all bus numbers assigned by the previous kernel. Bus + * numbers must remain stable for preserved devices so that they can + * perform DMA during the Live Update uninterrupted. + */ + if (pci_liveupdate_incoming_nr_devices()) + return false; + + return pcibios_assign_all_busses(); +} + /* * pci_scan_bridge_extend() - Scan buses behind a bridge * @bus: Parent bus the bridge is on @@ -1378,6 +1392,7 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, int max, unsigned int available_buses, int pass) { + bool assign_all_busses = pci_assign_all_busses(); struct pci_bus *child; int is_cardbus = (dev->hdr_type == PCI_HEADER_TYPE_CARDBUS); u32 buses, i, j = 0; @@ -1424,7 +1439,7 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, pci_write_config_word(dev, PCI_BRIDGE_CONTROL, bctl & ~PCI_BRIDGE_CTL_MASTER_ABORT); - if ((secondary || subordinate) && !pcibios_assign_all_busses() && + if ((secondary || subordinate) && !assign_all_busses && !is_cardbus && !broken) { unsigned int cmax, buses; @@ -1467,7 +1482,7 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, * do in the second pass. */ if (!pass) { - if (pcibios_assign_all_busses() || broken || is_cardbus) + if (assign_all_busses || broken || is_cardbus) /* * Temporarily disable forwarding of the @@ -1542,7 +1557,7 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, max+i+1)) break; while (parent->parent) { - if ((!pcibios_assign_all_busses()) && + if (!assign_all_busses && (parent->busn_res.end > max) && (parent->busn_res.end <= max+i)) { j = 1; -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:50 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Add an API to enable the PCI subsystem to track all devices that are preserved across a Live Update, including both incoming devices (passed from the previous kernel) and outgoing devices (passed to the next kernel). Use PCI segment number and BDF to keep track of devices across Live Update. This means the kernel must keep both identifiers constant across a Live Update for any preserved device. VFs are not supported for now, since that requires preserving SR-IOV state on the device to ensure the same number of VFs appear after kexec and with the same BDFs. Drivers that preserve devices across Live Update can now register their struct liveupdate_file_handler with the PCI subsystem so that the PCI subsystem can allocate and manage File-Lifecycle-Bound (FLB) global data to track the list of incoming and outgoing preserved devices. pci_liveupdate_register_fh(driver_fh) pci_liveupdate_unregister_fh(driver_fh) Drivers can notify the PCI subsystem whenever a device is preserved and unpreserved with the following APIs: pci_liveupdate_outgoing_preserve(pci_dev) pci_liveupdate_outgoing_unpreserve(pci_dev) After a Live Update, the PCI subsystem fetches its FLB global data from the previous kernel from the Live Update Orchestrator (LUO) during device initialization to determine which devices were preserved. Drivers can check if a device was preserved before userspace retrieves the file for it via pci_dev->liveupdate_incoming. Once a driver has finished restoring an incoming preserved device, it can notify the PCI subsystem with the following call, which clears pci_dev->liveupdate_incoming. pci_liveupdate_incoming_finish(pci_dev) This API will be used in subsequent commits by the vfio-pci driver to preserve VFIO devices across Live Update and by the PCI subsystem. Signed-off-by: David Matlack <dmatlack@google.com> --- drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 ++++++++++++++++++++++++++++++++++++ drivers/pci/probe.c | 2 + include/linux/kho/abi/pci.h | 55 ++++++++++ include/linux/pci.h | 47 ++++++++ 5 files changed, 317 insertions(+) create mode 100644 drivers/pci/liveupdate.c create mode 100644 include/linux/kho/abi/pci.h diff --git a/drivers/pci/Makefile b/drivers/pci/Makefile index 8c259a9a8796..a32f7658b9e5 100644 --- a/drivers/pci/Makefile +++ b/drivers/pci/Makefile @@ -16,6 +16,7 @@ obj-$(CONFIG_PROC_FS) += proc.o obj-$(CONFIG_SYSFS) += pci-sysfs.o slot.o obj-$(CONFIG_ACPI) += pci-acpi.o obj-$(CONFIG_GENERIC_PCI_IOMAP) += iomap.o +obj-$(CONFIG_LIVEUPDATE) += liveupdate.o endif obj-$(CONFIG_OF) += of.o diff --git a/drivers/pci/liveupdate.c b/drivers/pci/liveupdate.c new file mode 100644 index 000000000000..182cfc793b80 --- /dev/null +++ b/drivers/pci/liveupdate.c @@ -0,0 +1,212 @@ +// SPDX-License-Identifier: GPL-2.0 + +/* + * Copyright (c) 2025, Google LLC. + * David Matlack <dmatlack@google.com> + */ + +#include <linux/bsearch.h> +#include <linux/io.h> +#include <linux/kexec_handover.h> +#include <linux/kho/abi/pci.h> +#include <linux/liveupdate.h> +#include <linux/mutex.h> +#include <linux/mm.h> +#include <linux/pci.h> +#include <linux/sort.h> + +static DEFINE_MUTEX(pci_flb_outgoing_lock); + +static int pci_flb_preserve(struct liveupdate_flb_op_args *args) +{ + struct pci_dev *dev = NULL; + int max_nr_devices = 0; + struct pci_ser *ser; + unsigned long size; + + for_each_pci_dev(dev) + max_nr_devices++; + + size = struct_size_t(struct pci_ser, devices, max_nr_devices); + + ser = kho_alloc_preserve(size); + if (IS_ERR(ser)) + return PTR_ERR(ser); + + ser->max_nr_devices = max_nr_devices; + + args->obj = ser; + args->data = virt_to_phys(ser); + return 0; +} + +static void pci_flb_unpreserve(struct liveupdate_flb_op_args *args) +{ + struct pci_ser *ser = args->obj; + + WARN_ON_ONCE(ser->nr_devices); + kho_unpreserve_free(ser); +} + +static int pci_flb_retrieve(struct liveupdate_flb_op_args *args) +{ + args->obj = phys_to_virt(args->data); + return 0; +} + +static void pci_flb_finish(struct liveupdate_flb_op_args *args) +{ + kho_restore_free(args->obj); +} + +static struct liveupdate_flb_ops pci_liveupdate_flb_ops = { + .preserve = pci_flb_preserve, + .unpreserve = pci_flb_unpreserve, + .retrieve = pci_flb_retrieve, + .finish = pci_flb_finish, + .owner = THIS_MODULE, +}; + +static struct liveupdate_flb pci_liveupdate_flb = { + .ops = &pci_liveupdate_flb_ops, + .compatible = PCI_LUO_FLB_COMPATIBLE, +}; + +#define INIT_PCI_DEV_SER(_dev) { \ + .domain = pci_domain_nr((_dev)->bus), \ + .bdf = pci_dev_id(_dev), \ +} + +static int pci_dev_ser_cmp(const void *__a, const void *__b) +{ + const struct pci_dev_ser *a = __a, *b = __b; + + return cmp_int(a->domain << 16 | a->bdf, b->domain << 16 | b->bdf); +} + +static struct pci_dev_ser *pci_ser_find(struct pci_ser *ser, + struct pci_dev *dev) +{ + const struct pci_dev_ser key = INIT_PCI_DEV_SER(dev); + + return bsearch(&key, ser->devices, ser->nr_devices, + sizeof(key), pci_dev_ser_cmp); +} + +static int pci_ser_delete(struct pci_ser *ser, struct pci_dev *dev) +{ + struct pci_dev_ser *dev_ser; + int i; + + dev_ser = pci_ser_find(ser, dev); + if (!dev_ser) + return -ENOENT; + + for (i = dev_ser - ser->devices; i < ser->nr_devices - 1; i++) + ser->devices[i] = ser->devices[i + 1]; + + ser->nr_devices--; + return 0; +} + +int pci_liveupdate_outgoing_preserve(struct pci_dev *dev) +{ + struct pci_dev_ser new = INIT_PCI_DEV_SER(dev); + struct pci_ser *ser; + int i, ret; + + /* Preserving VFs is not supported yet. */ + if (dev->is_virtfn) + return -EINVAL; + + guard(mutex)(&pci_flb_outgoing_lock); + + if (dev->liveupdate_outgoing) + return -EBUSY; + + ret = liveupdate_flb_get_outgoing(&pci_liveupdate_flb, (void **)&ser); + if (ret) + return ret; + + if (ser->nr_devices == ser->max_nr_devices) + return -E2BIG; + + for (i = ser->nr_devices; i > 0; i--) { + struct pci_dev_ser *prev = &ser->devices[i - 1]; + int cmp = pci_dev_ser_cmp(&new, prev); + + if (WARN_ON_ONCE(!cmp)) + return -EBUSY; + + if (cmp > 0) + break; + + ser->devices[i] = *prev; + } + + ser->devices[i] = new; + ser->nr_devices++; + dev->liveupdate_outgoing = true; + return 0; +} +EXPORT_SYMBOL_GPL(pci_liveupdate_outgoing_preserve); + +void pci_liveupdate_outgoing_unpreserve(struct pci_dev *dev) +{ + struct pci_ser *ser; + int ret; + + guard(mutex)(&pci_flb_outgoing_lock); + + ret = liveupdate_flb_get_outgoing(&pci_liveupdate_flb, (void **)&ser); + if (WARN_ON_ONCE(ret)) + return; + + WARN_ON_ONCE(pci_ser_delete(ser, dev)); + dev->liveupdate_outgoing = false; +} +EXPORT_SYMBOL_GPL(pci_liveupdate_outgoing_unpreserve); + +u32 pci_liveupdate_incoming_nr_devices(void) +{ + struct pci_ser *ser; + int ret; + + ret = liveupdate_flb_get_incoming(&pci_liveupdate_flb, (void **)&ser); + if (ret) + return 0; + + return ser->nr_devices; +} +EXPORT_SYMBOL_GPL(pci_liveupdate_incoming_nr_devices); + +void pci_liveupdate_setup_device(struct pci_dev *dev) +{ + struct pci_ser *ser; + int ret; + + ret = liveupdate_flb_get_incoming(&pci_liveupdate_flb, (void **)&ser); + if (ret) + return; + + dev->liveupdate_incoming = !!pci_ser_find(ser, dev); +} +EXPORT_SYMBOL_GPL(pci_liveupdate_setup_device); + +void pci_liveupdate_incoming_finish(struct pci_dev *dev) +{ + dev->liveupdate_incoming = false; +} +EXPORT_SYMBOL_GPL(pci_liveupdate_incoming_finish); + +int pci_liveupdate_register_fh(struct liveupdate_file_handler *fh) +{ + return liveupdate_register_flb(fh, &pci_liveupdate_flb); +} +EXPORT_SYMBOL_GPL(pci_liveupdate_register_fh); + +int pci_liveupdate_unregister_fh(struct liveupdate_file_handler *fh) +{ + return liveupdate_unregister_flb(fh, &pci_liveupdate_flb); +} +EXPORT_SYMBOL_GPL(pci_liveupdate_unregister_fh); diff --git a/drivers/pci/probe.c b/drivers/pci/probe.c index 37329095e5fe..af6356c5a156 100644 --- a/drivers/pci/probe.c +++ b/drivers/pci/probe.c @@ -2060,6 +2060,8 @@ int pci_setup_device(struct pci_dev *dev) if (pci_early_dump) early_dump_pci_device(dev); + pci_liveupdate_setup_device(dev); + /* Need to have dev->class ready */ dev->cfg_size = pci_cfg_space_size(dev); diff --git a/include/linux/kho/abi/pci.h b/include/linux/kho/abi/pci.h new file mode 100644 index 000000000000..6577767f8da6 --- /dev/null +++ b/include/linux/kho/abi/pci.h @@ -0,0 +1,55 @@ +/* SPDX-License-Identifier: GPL-2.0 */ + +/* + * Copyright (c) 2025, Google LLC. + * David Matlack <dmatlack@google.com> + */ + +#ifndef _LINUX_KHO_ABI_PCI_H +#define _LINUX_KHO_ABI_PCI_H + +#include <linux/compiler.h> +#include <linux/types.h> + +/** + * DOC: PCI File-Lifecycle Bound (FLB) Live Update ABI + * + * This header defines the ABI for preserving core PCI state across kexec using + * Live Update File-Lifecycle Bound (FLB) data. + * + * This interface is a contract. Any modification to any of the serialization + * structs defined here constitutes a breaking change. Such changes require + * incrementing the version number in the PCI_LUO_FLB_COMPATIBLE string. + */ + +#define PCI_LUO_FLB_COMPATIBLE "pci-v1" + +/** + * struct pci_dev_ser - Serialized state about a single PCI device. + * + * @domain: The device's PCI domain number (segment). + * @bdf: The device's PCI bus, device, and function number. + */ +struct pci_dev_ser { + u16 domain; + u16 bdf; +} __packed; + +/** + * struct pci_ser - PCI Subsystem Live Update State + * + * This struct tracks state about all devices that are being preserved across + * a Live Update for the next kernel. + * + * @max_nr_devices: The length of the devices[] flexible array. + * @nr_devices: The number of devices that were preserved. + * @devices: Flexible array of pci_dev_ser structs for each device. Guaranteed + * to be sorted ascending by domain and bdf. + */ +struct pci_ser { + u64 max_nr_devices; + u64 nr_devices; + struct pci_dev_ser devices[]; +} __packed; + +#endif /* _LINUX_KHO_ABI_PCI_H */ diff --git a/include/linux/pci.h b/include/linux/pci.h index 7e36936bb37a..9ead6d84aef6 100644 --- a/include/linux/pci.h +++ b/include/linux/pci.h @@ -40,6 +40,7 @@ #include <linux/resource_ext.h> #include <linux/msi_api.h> #include <uapi/linux/pci.h> +#include <linux/liveupdate.h> #include <linux/pci_ids.h> @@ -582,6 +583,10 @@ struct pci_dev { u8 tph_mode; /* TPH mode */ u8 tph_req_type; /* TPH requester type */ #endif +#ifdef CONFIG_LIVEUPDATE + unsigned int liveupdate_incoming:1; /* Preserved by previous kernel */ + unsigned int liveupdate_outgoing:1; /* Preserved for next kernel */ +#endif }; static inline struct pci_dev *pci_physfn(struct pci_dev *dev) @@ -2854,4 +2859,46 @@ void pci_uevent_ers(struct pci_dev *pdev, enum pci_ers_result err_type); WARN_ONCE(condition, "%s %s: " fmt, \ dev_driver_string(&(pdev)->dev), pci_name(pdev), ##arg) +#ifdef CONFIG_LIVEUPDATE +int pci_liveupdate_outgoing_preserve(struct pci_dev *dev); +void pci_liveupdate_outgoing_unpreserve(struct pci_dev *dev); +void pci_liveupdate_setup_device(struct pci_dev *dev); +u32 pci_liveupdate_incoming_nr_devices(void); +void pci_liveupdate_incoming_finish(struct pci_dev *dev); +int pci_liveupdate_register_fh(struct liveupdate_file_handler *fh); +int pci_liveupdate_unregister_fh(struct liveupdate_file_handler *fh); +#else /* !CONFIG_LIVEUPDATE */ +static inline int pci_liveupdate_outgoing_preserve(struct pci_dev *dev) +{ + return -EOPNOTSUPP; +} + +static inline void pci_liveupdate_outgoing_unpreserve(struct pci_dev *dev) +{ +} + +static inline void pci_liveupdate_setup_device(struct pci_dev *dev) +{ +} + +static inline u32 pci_liveupdate_incoming_nr_devices(void) +{ + return 0; +} + +static inline void pci_liveupdate_incoming_finish(struct pci_dev *dev) +{ +} + +static inline int pci_liveupdate_register_fh(struct liveupdate_file_handler *fh) +{ + return -EOPNOTSUPP; +} + +static inline int pci_liveupdate_unregister_fh(struct liveupdate_file_handler *fh) +{ + return -EOPNOTSUPP; +} +#endif /* !CONFIG_LIVEUPDATE */ + #endif /* LINUX_PCI_H */ -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:49 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
From: Vipin Sharma <vipinsh@google.com> Register a live update file handler for vfio-pci device files. Add stub implementations of all required callbacks so that registration does not fail (i.e. to avoid breaking git-bisect). This file handler will be extended in subsequent commits to enable a device bound to vfio-pci to run without interruption while the host is going through a kexec Live Update. Signed-off-by: Vipin Sharma <vipinsh@google.com> Co-developed-by: David Matlack <dmatlack@google.com> Signed-off-by: David Matlack <dmatlack@google.com> --- MAINTAINERS | 1 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 9 +++- drivers/vfio/pci/vfio_pci_liveupdate.c | 69 ++++++++++++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 14 ++++++ include/linux/kho/abi/vfio_pci.h | 28 +++++++++++ 6 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/vfio_pci.h diff --git a/MAINTAINERS b/MAINTAINERS index a671e3d4e8be..7d6cdecedb05 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -27520,6 +27520,7 @@ F: Documentation/ABI/testing/debugfs-vfio F: Documentation/ABI/testing/sysfs-devices-vfio-dev F: Documentation/driver-api/vfio.rst F: drivers/vfio/ +F: include/linux/kho/abi/vfio_pci.h F: include/linux/vfio.h F: include/linux/vfio_pci_core.h F: include/uapi/linux/vfio.h diff --git a/drivers/vfio/pci/Makefile b/drivers/vfio/pci/Makefile index e0a0757dd1d2..23305ebc418b 100644 --- a/drivers/vfio/pci/Makefile +++ b/drivers/vfio/pci/Makefile @@ -7,6 +7,7 @@ obj-$(CONFIG_VFIO_PCI_CORE) += vfio-pci-core.o vfio-pci-y := vfio_pci.o vfio-pci-$(CONFIG_VFIO_PCI_IGD) += vfio_pci_igd.o +vfio-pci-$(CONFIG_LIVEUPDATE) += vfio_pci_liveupdate.o obj-$(CONFIG_VFIO_PCI) += vfio-pci.o obj-$(CONFIG_MLX5_VFIO_PCI) += mlx5/ diff --git a/drivers/vfio/pci/vfio_pci.c b/drivers/vfio/pci/vfio_pci.c index 0c771064c0b8..19e88322af2c 100644 --- a/drivers/vfio/pci/vfio_pci.c +++ b/drivers/vfio/pci/vfio_pci.c @@ -258,6 +258,10 @@ static int __init vfio_pci_init(void) int ret; bool is_disable_vga = true; + ret = vfio_pci_liveupdate_init(); + if (ret) + return ret; + #ifdef CONFIG_VFIO_PCI_VGA is_disable_vga = disable_vga; #endif @@ -266,8 +270,10 @@ static int __init vfio_pci_init(void) /* Register and scan for devices */ ret = pci_register_driver(&vfio_pci_driver); - if (ret) + if (ret) { + vfio_pci_liveupdate_cleanup(); return ret; + } vfio_pci_fill_ids(); @@ -281,6 +287,7 @@ module_init(vfio_pci_init); static void __exit vfio_pci_cleanup(void) { pci_unregister_driver(&vfio_pci_driver); + vfio_pci_liveupdate_cleanup(); } module_exit(vfio_pci_cleanup); diff --git a/drivers/vfio/pci/vfio_pci_liveupdate.c b/drivers/vfio/pci/vfio_pci_liveupdate.c new file mode 100644 index 000000000000..b84e63c0357b --- /dev/null +++ b/drivers/vfio/pci/vfio_pci_liveupdate.c @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0 + +/* + * Copyright (c) 2025, Google LLC. + * Vipin Sharma <vipinsh@google.com> + * David Matlack <dmatlack@google.com> + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include <linux/kho/abi/vfio_pci.h> +#include <linux/liveupdate.h> +#include <linux/errno.h> + +#include "vfio_pci_priv.h" + +static bool vfio_pci_liveupdate_can_preserve(struct liveupdate_file_handler *handler, + struct file *file) +{ + return false; +} + +static int vfio_pci_liveupdate_preserve(struct liveupdate_file_op_args *args) +{ + return -EOPNOTSUPP; +} + +static void vfio_pci_liveupdate_unpreserve(struct liveupdate_file_op_args *args) +{ +} + +static int vfio_pci_liveupdate_retrieve(struct liveupdate_file_op_args *args) +{ + return -EOPNOTSUPP; +} + +static void vfio_pci_liveupdate_finish(struct liveupdate_file_op_args *args) +{ +} + +static const struct liveupdate_file_ops vfio_pci_liveupdate_file_ops = { + .can_preserve = vfio_pci_liveupdate_can_preserve, + .preserve = vfio_pci_liveupdate_preserve, + .unpreserve = vfio_pci_liveupdate_unpreserve, + .retrieve = vfio_pci_liveupdate_retrieve, + .finish = vfio_pci_liveupdate_finish, + .owner = THIS_MODULE, +}; + +static struct liveupdate_file_handler vfio_pci_liveupdate_fh = { + .ops = &vfio_pci_liveupdate_file_ops, + .compatible = VFIO_PCI_LUO_FH_COMPATIBLE, +}; + +int __init vfio_pci_liveupdate_init(void) +{ + if (!liveupdate_enabled()) + return 0; + + return liveupdate_register_file_handler(&vfio_pci_liveupdate_fh); +} + +void vfio_pci_liveupdate_cleanup(void) +{ + if (!liveupdate_enabled()) + return; + + liveupdate_unregister_file_handler(&vfio_pci_liveupdate_fh); +} diff --git a/drivers/vfio/pci/vfio_pci_priv.h b/drivers/vfio/pci/vfio_pci_priv.h index 27ac280f00b9..68966ec64e51 100644 --- a/drivers/vfio/pci/vfio_pci_priv.h +++ b/drivers/vfio/pci/vfio_pci_priv.h @@ -133,4 +133,18 @@ static inline void vfio_pci_dma_buf_move(struct vfio_pci_core_device *vdev, } #endif +#ifdef CONFIG_LIVEUPDATE +int __init vfio_pci_liveupdate_init(void); +void vfio_pci_liveupdate_cleanup(void); +#else +static inline int vfio_pci_liveupdate_init(void) +{ + return 0; +} + +static inline void vfio_pci_liveupdate_cleanup(void) +{ +} +#endif /* CONFIG_LIVEUPDATE */ + #endif diff --git a/include/linux/kho/abi/vfio_pci.h b/include/linux/kho/abi/vfio_pci.h new file mode 100644 index 000000000000..37a845eed972 --- /dev/null +++ b/include/linux/kho/abi/vfio_pci.h @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0 */ + +/* + * Copyright (c) 2025, Google LLC. + * Vipin Sharma <vipinsh@google.com> + * David Matlack <dmatlack@google.com> + */ + +#ifndef _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H +#define _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H + +/** + * DOC: VFIO PCI Live Update ABI + * + * This header defines the ABI for preserving the state of a VFIO PCI device + * files across a kexec reboot using LUO. + * + * Device metadata is serialized into memory which is then handed to the next + * kernel via KHO. + * + * This interface is a contract. Any modification to any of the serialization + * structs defined here constitutes a breaking change. Such changes require + * incrementing the version number in the VFIO_PCI_LUO_FH_COMPATIBLE string. + */ + +#define VFIO_PCI_LUO_FH_COMPATIBLE "vfio-pci-v1" + +#endif /* _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H */ -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:51 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
From: Vipin Sharma <vipinsh@google.com> Implement the live update file handler callbacks to preserve a vfio-pci device across a Live Update. Subsequent commits will enable userspace to then retrieve this file after the Live Update. Live Update support is scoped only to cdev files (i.e. not VFIO_GROUP_GET_DEVICE_FD files). State about each device is serialized into a new ABI struct vfio_pci_core_device_ser. The contents of this struct are preserved across the Live Update to the next kernel using a combination of Kexec-Handover (KHO) to preserve the page(s) holding the struct and the Live Update Orchestrator (LUO) to preserve the physical address of the struct. For now the only contents of struct vfio_pci_core_device_ser the device's PCI segment number and BDF, so that the device can be uniquely identified after the Live Update. Require that userspace disables interrupts on the device prior to freeze() so that the device does not send any interrupts until new interrupt handlers have been set up by the next kernel. Reset the device and restore its state in the freeze() callback. This ensures the device can be received by the next kernel in a consistent state. Eventually this will be dropped and the device can be preserved across in a running state, but that requires further work in VFIO and the core PCI layer. Note that LUO holds a reference to this file when it is preserved. So VFIO is guaranteed that vfio_df_device_last_close() will not be called on this device no matter what userspace does. Signed-off-by: Vipin Sharma <vipinsh@google.com> Co-developed-by: David Matlack <dmatlack@google.com> Signed-off-by: David Matlack <dmatlack@google.com> --- drivers/vfio/pci/vfio_pci.c | 2 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 84 +++++++++++++++++++++++++- drivers/vfio/pci/vfio_pci_priv.h | 2 + drivers/vfio/vfio.h | 13 ---- drivers/vfio/vfio_main.c | 10 +-- include/linux/kho/abi/vfio_pci.h | 15 +++++ include/linux/vfio.h | 28 +++++++++ 7 files changed, 129 insertions(+), 25 deletions(-) diff --git a/drivers/vfio/pci/vfio_pci.c b/drivers/vfio/pci/vfio_pci.c index 19e88322af2c..0260afb9492d 100644 --- a/drivers/vfio/pci/vfio_pci.c +++ b/drivers/vfio/pci/vfio_pci.c @@ -125,7 +125,7 @@ static int vfio_pci_open_device(struct vfio_device *core_vdev) return 0; } -static const struct vfio_device_ops vfio_pci_ops = { +const struct vfio_device_ops vfio_pci_ops = { .name = "vfio-pci", .init = vfio_pci_core_init_dev, .release = vfio_pci_core_release_dev, diff --git a/drivers/vfio/pci/vfio_pci_liveupdate.c b/drivers/vfio/pci/vfio_pci_liveupdate.c index b84e63c0357b..f01de98f1b75 100644 --- a/drivers/vfio/pci/vfio_pci_liveupdate.c +++ b/drivers/vfio/pci/vfio_pci_liveupdate.c @@ -8,25 +8,104 @@ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt +#include <linux/kexec_handover.h> #include <linux/kho/abi/vfio_pci.h> #include <linux/liveupdate.h> #include <linux/errno.h> +#include <linux/vfio.h> #include "vfio_pci_priv.h" static bool vfio_pci_liveupdate_can_preserve(struct liveupdate_file_handler *handler, struct file *file) { - return false; + struct vfio_device_file *df = to_vfio_device_file(file); + + if (!df) + return false; + + /* Live Update support is limited to cdev files. */ + if (df->group) + return false; + + return df->device->ops == &vfio_pci_ops; } static int vfio_pci_liveupdate_preserve(struct liveupdate_file_op_args *args) { - return -EOPNOTSUPP; + struct vfio_device *device = vfio_device_from_file(args->file); + struct vfio_pci_core_device_ser *ser; + struct vfio_pci_core_device *vdev; + struct pci_dev *pdev; + + vdev = container_of(device, struct vfio_pci_core_device, vdev); + pdev = vdev->pdev; + + if (IS_ENABLED(CONFIG_VFIO_PCI_ZDEV_KVM)) + return -EINVAL; + + if (vfio_pci_is_intel_display(pdev)) + return -EINVAL; + + ser = kho_alloc_preserve(sizeof(*ser)); + if (IS_ERR(ser)) + return PTR_ERR(ser); + + ser->bdf = pci_dev_id(pdev); + ser->domain = pci_domain_nr(pdev->bus); + + args->serialized_data = virt_to_phys(ser); + return 0; } static void vfio_pci_liveupdate_unpreserve(struct liveupdate_file_op_args *args) { + kho_unpreserve_free(phys_to_virt(args->serialized_data)); +} + +static int vfio_pci_liveupdate_freeze(struct liveupdate_file_op_args *args) +{ + struct vfio_device *device = vfio_device_from_file(args->file); + struct vfio_pci_core_device *vdev; + struct pci_dev *pdev; + int ret; + + vdev = container_of(device, struct vfio_pci_core_device, vdev); + pdev = vdev->pdev; + + guard(mutex)(&device->dev_set->lock); + + /* + * Userspace must disable interrupts on the device prior to freeze so + * that the device does not send any interrupts until new interrupt + * handlers have been established by the next kernel. + */ + if (vdev->irq_type != VFIO_PCI_NUM_IRQS) { + pci_err(pdev, "Freeze failed! Interrupts are still enabled.\n"); + return -EINVAL; + } + + pci_dev_lock(pdev); + + ret = pci_load_saved_state(pdev, vdev->pci_saved_state); + if (ret) + goto out; + + /* + * Reset the device and restore it back to its original state before + * handing it to the next kernel. + * + * Eventually both of these should be dropped and the device should be + * kept running with its current state across the Live Update. + */ + if (vdev->reset_works) + ret = __pci_reset_function_locked(pdev); + + pci_restore_state(pdev); + +out: + pci_dev_unlock(pdev); + return ret; } static int vfio_pci_liveupdate_retrieve(struct liveupdate_file_op_args *args) @@ -42,6 +121,7 @@ static const struct liveupdate_file_ops vfio_pci_liveupdate_file_ops = { .can_preserve = vfio_pci_liveupdate_can_preserve, .preserve = vfio_pci_liveupdate_preserve, .unpreserve = vfio_pci_liveupdate_unpreserve, + .freeze = vfio_pci_liveupdate_freeze, .retrieve = vfio_pci_liveupdate_retrieve, .finish = vfio_pci_liveupdate_finish, .owner = THIS_MODULE, diff --git a/drivers/vfio/pci/vfio_pci_priv.h b/drivers/vfio/pci/vfio_pci_priv.h index 68966ec64e51..d3da79b7b03c 100644 --- a/drivers/vfio/pci/vfio_pci_priv.h +++ b/drivers/vfio/pci/vfio_pci_priv.h @@ -11,6 +11,8 @@ /* Cap maximum number of ioeventfds per device (arbitrary) */ #define VFIO_PCI_IOEVENTFD_MAX 1000 +extern const struct vfio_device_ops vfio_pci_ops; + struct vfio_pci_ioeventfd { struct list_head next; struct vfio_pci_core_device *vdev; diff --git a/drivers/vfio/vfio.h b/drivers/vfio/vfio.h index 50128da18bca..6b89edbbf174 100644 --- a/drivers/vfio/vfio.h +++ b/drivers/vfio/vfio.h @@ -16,17 +16,6 @@ struct iommufd_ctx; struct iommu_group; struct vfio_container; -struct vfio_device_file { - struct vfio_device *device; - struct vfio_group *group; - - u8 access_granted; - u32 devid; /* only valid when iommufd is valid */ - spinlock_t kvm_ref_lock; /* protect kvm field */ - struct kvm *kvm; - struct iommufd_ctx *iommufd; /* protected by struct vfio_device_set::lock */ -}; - void vfio_device_put_registration(struct vfio_device *device); bool vfio_device_try_get_registration(struct vfio_device *device); int vfio_df_open(struct vfio_device_file *df); @@ -34,8 +23,6 @@ void vfio_df_close(struct vfio_device_file *df); struct vfio_device_file * vfio_allocate_device_file(struct vfio_device *device); -extern const struct file_operations vfio_device_fops; - #ifdef CONFIG_VFIO_NOIOMMU extern bool vfio_noiommu __read_mostly; #else diff --git a/drivers/vfio/vfio_main.c b/drivers/vfio/vfio_main.c index f7df90c423b4..276f615f0c28 100644 --- a/drivers/vfio/vfio_main.c +++ b/drivers/vfio/vfio_main.c @@ -1436,15 +1436,7 @@ const struct file_operations vfio_device_fops = { .show_fdinfo = vfio_device_show_fdinfo, #endif }; - -static struct vfio_device *vfio_device_from_file(struct file *file) -{ - struct vfio_device_file *df = file->private_data; - - if (file->f_op != &vfio_device_fops) - return NULL; - return df->device; -} +EXPORT_SYMBOL_GPL(vfio_device_fops); /** * vfio_file_is_valid - True if the file is valid vfio file diff --git a/include/linux/kho/abi/vfio_pci.h b/include/linux/kho/abi/vfio_pci.h index 37a845eed972..9bf58a2f3820 100644 --- a/include/linux/kho/abi/vfio_pci.h +++ b/include/linux/kho/abi/vfio_pci.h @@ -9,6 +9,9 @@ #ifndef _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H #define _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H +#include <linux/compiler.h> +#include <linux/types.h> + /** * DOC: VFIO PCI Live Update ABI * @@ -25,4 +28,16 @@ #define VFIO_PCI_LUO_FH_COMPATIBLE "vfio-pci-v1" +/** + * struct vfio_pci_core_device_ser - Serialized state of a single VFIO PCI + * device. + * + * @bdf: The device's PCI bus, device, and function number. + * @domain: The device's PCI domain number (segment). + */ +struct vfio_pci_core_device_ser { + u16 bdf; + u16 domain; +} __packed; + #endif /* _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H */ diff --git a/include/linux/vfio.h b/include/linux/vfio.h index e90859956514..9aa1587fea19 100644 --- a/include/linux/vfio.h +++ b/include/linux/vfio.h @@ -81,6 +81,34 @@ struct vfio_device { #endif }; +struct vfio_device_file { + struct vfio_device *device; + struct vfio_group *group; + + u8 access_granted; + u32 devid; /* only valid when iommufd is valid */ + spinlock_t kvm_ref_lock; /* protect kvm field */ + struct kvm *kvm; + struct iommufd_ctx *iommufd; /* protected by struct vfio_device_set::lock */ +}; + +extern const struct file_operations vfio_device_fops; + +static inline struct vfio_device_file *to_vfio_device_file(struct file *file) +{ + if (file->f_op != &vfio_device_fops) + return NULL; + + return file->private_data; +} + +static inline struct vfio_device *vfio_device_from_file(struct file *file) +{ + struct vfio_device_file *df = to_vfio_device_file(file); + + return df ? df->device : NULL; +} + /** * struct vfio_device_ops - VFIO bus driver device callbacks * -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:52 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
From: Vipin Sharma <vipinsh@google.com> Enable userspace to retrieve preserved VFIO device files from VFIO after a Live Update by implementing the retrieve() and finish() file handler callbacks. Use an anonymous inode when creating the file, since the retrieved device file is not opened through any particular cdev inode, and the cdev inode does not matter in practice. For now the retrieved file is functionally equivalent a opening the corresponding VFIO cdev file. Subsequent commits will leverage the preserved state associated with the retrieved file to preserve bits of the device across Live Update. Signed-off-by: Vipin Sharma <vipinsh@google.com> Co-developed-by: David Matlack <dmatlack@google.com> Signed-off-by: David Matlack <dmatlack@google.com> --- drivers/vfio/device_cdev.c | 21 ++++++--- drivers/vfio/pci/vfio_pci_liveupdate.c | 60 +++++++++++++++++++++++++- drivers/vfio/vfio_main.c | 13 ++++++ include/linux/vfio.h | 12 ++++++ 4 files changed, 98 insertions(+), 8 deletions(-) diff --git a/drivers/vfio/device_cdev.c b/drivers/vfio/device_cdev.c index 8ceca24ac136..935f84a35875 100644 --- a/drivers/vfio/device_cdev.c +++ b/drivers/vfio/device_cdev.c @@ -16,14 +16,8 @@ void vfio_init_device_cdev(struct vfio_device *device) device->cdev.owner = THIS_MODULE; } -/* - * device access via the fd opened by this function is blocked until - * .open_device() is called successfully during BIND_IOMMUFD. - */ -int vfio_device_fops_cdev_open(struct inode *inode, struct file *filep) +int __vfio_device_fops_cdev_open(struct vfio_device *device, struct file *filep) { - struct vfio_device *device = container_of(inode->i_cdev, - struct vfio_device, cdev); struct vfio_device_file *df; int ret; @@ -52,6 +46,19 @@ int vfio_device_fops_cdev_open(struct inode *inode, struct file *filep) vfio_device_put_registration(device); return ret; } +EXPORT_SYMBOL_GPL(__vfio_device_fops_cdev_open); + +/* + * device access via the fd opened by this function is blocked until + * .open_device() is called successfully during BIND_IOMMUFD. + */ +int vfio_device_fops_cdev_open(struct inode *inode, struct file *filep) +{ + struct vfio_device *device = container_of(inode->i_cdev, + struct vfio_device, cdev); + + return __vfio_device_fops_cdev_open(device, filep); +} static void vfio_df_get_kvm_safe(struct vfio_device_file *df) { diff --git a/drivers/vfio/pci/vfio_pci_liveupdate.c b/drivers/vfio/pci/vfio_pci_liveupdate.c index f01de98f1b75..7f4117181fd0 100644 --- a/drivers/vfio/pci/vfio_pci_liveupdate.c +++ b/drivers/vfio/pci/vfio_pci_liveupdate.c @@ -8,6 +8,8 @@ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt +#include <linux/anon_inodes.h> +#include <linux/file.h> #include <linux/kexec_handover.h> #include <linux/kho/abi/vfio_pci.h> #include <linux/liveupdate.h> @@ -108,13 +110,68 @@ static int vfio_pci_liveupdate_freeze(struct liveupdate_file_op_args *args) return ret; } +static int match_device(struct device *dev, const void *arg) +{ + struct vfio_device *device = container_of(dev, struct vfio_device, device); + const struct vfio_pci_core_device_ser *ser = arg; + struct pci_dev *pdev; + + pdev = dev_is_pci(device->dev) ? to_pci_dev(device->dev) : NULL; + if (!pdev) + return false; + + return ser->bdf == pci_dev_id(pdev) && ser->domain == pci_domain_nr(pdev->bus); +} + static int vfio_pci_liveupdate_retrieve(struct liveupdate_file_op_args *args) { - return -EOPNOTSUPP; + struct vfio_pci_core_device_ser *ser; + struct vfio_device *device; + struct file *file; + int ret; + + ser = phys_to_virt(args->serialized_data); + + device = vfio_find_device(ser, match_device); + if (!device) + return -ENODEV; + + /* + * Simulate opening the character device using an anonymous inode. The + * returned file has the same properties as a cdev file (e.g. operations + * are blocked until BIND_IOMMUFD is called). + */ + file = anon_inode_getfile_fmode("[vfio-device-liveupdate]", + &vfio_device_fops, NULL, + O_RDWR, FMODE_PREAD | FMODE_PWRITE); + if (IS_ERR(file)) { + ret = PTR_ERR(file); + goto out; + } + + ret = __vfio_device_fops_cdev_open(device, file); + if (ret) { + fput(file); + goto out; + } + + args->file = file; + +out: + /* Drop the reference from vfio_find_device() */ + put_device(&device->device); + + return ret; +} + +static bool vfio_pci_liveupdate_can_finish(struct liveupdate_file_op_args *args) +{ + return args->retrieved; } static void vfio_pci_liveupdate_finish(struct liveupdate_file_op_args *args) { + kho_restore_free(phys_to_virt(args->serialized_data)); } static const struct liveupdate_file_ops vfio_pci_liveupdate_file_ops = { @@ -123,6 +180,7 @@ static const struct liveupdate_file_ops vfio_pci_liveupdate_file_ops = { .unpreserve = vfio_pci_liveupdate_unpreserve, .freeze = vfio_pci_liveupdate_freeze, .retrieve = vfio_pci_liveupdate_retrieve, + .can_finish = vfio_pci_liveupdate_can_finish, .finish = vfio_pci_liveupdate_finish, .owner = THIS_MODULE, }; diff --git a/drivers/vfio/vfio_main.c b/drivers/vfio/vfio_main.c index 276f615f0c28..89c5feef75d5 100644 --- a/drivers/vfio/vfio_main.c +++ b/drivers/vfio/vfio_main.c @@ -13,6 +13,7 @@ #include <linux/cdev.h> #include <linux/compat.h> #include <linux/device.h> +#include <linux/device/class.h> #include <linux/fs.h> #include <linux/idr.h> #include <linux/iommu.h> @@ -1758,6 +1759,18 @@ int vfio_dma_rw(struct vfio_device *device, dma_addr_t iova, void *data, } EXPORT_SYMBOL(vfio_dma_rw); +struct vfio_device *vfio_find_device(const void *data, device_match_t match) +{ + struct device *device; + + device = class_find_device(vfio.device_class, NULL, data, match); + if (!device) + return NULL; + + return container_of(device, struct vfio_device, device); +} +EXPORT_SYMBOL_GPL(vfio_find_device); + /* * Module/class support */ diff --git a/include/linux/vfio.h b/include/linux/vfio.h index 9aa1587fea19..dc592dc00f89 100644 --- a/include/linux/vfio.h +++ b/include/linux/vfio.h @@ -419,4 +419,16 @@ int vfio_virqfd_enable(void *opaque, int (*handler)(void *, void *), void vfio_virqfd_disable(struct virqfd **pvirqfd); void vfio_virqfd_flush_thread(struct virqfd **pvirqfd); +#if IS_ENABLED(CONFIG_VFIO_DEVICE_CDEV) +int __vfio_device_fops_cdev_open(struct vfio_device *device, struct file *filep); +#else +static inline int __vfio_device_fops_cdev_open(struct vfio_device *device, + struct file *filep) +{ + return -EOPNOTSUPP; +} +#endif /* IS_ENABLED(CONFIG_VFIO_DEVICE_CDEV) */ + +struct vfio_device *vfio_find_device(const void *data, device_match_t match); + #endif /* VFIO_H */ -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:53 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Notify the PCI subsystem about devices vfio-pci is preserving across Live Update by registering the vfio-pci liveupdate file handler with the PCI subsystem's FLB handler. Notably this will ensure that devices preserved through vfio-pci will have their PCI bus numbers preserved across Live Update, allowing VFIO to use BDF as a key to identify the device across the Live Update and (in the future) allow the device to continue DMA operations across the Live Update. This also enables VFIO to detect that a device was preserved before userspace first retrieves the file from it, which will be used in subsequent commits. Signed-off-by: David Matlack <dmatlack@google.com> --- drivers/vfio/pci/vfio_pci_liveupdate.c | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/drivers/vfio/pci/vfio_pci_liveupdate.c b/drivers/vfio/pci/vfio_pci_liveupdate.c index 7f4117181fd0..ad915352303f 100644 --- a/drivers/vfio/pci/vfio_pci_liveupdate.c +++ b/drivers/vfio/pci/vfio_pci_liveupdate.c @@ -53,6 +53,8 @@ static int vfio_pci_liveupdate_preserve(struct liveupdate_file_op_args *args) if (IS_ERR(ser)) return PTR_ERR(ser); + pci_liveupdate_outgoing_preserve(pdev); + ser->bdf = pci_dev_id(pdev); ser->domain = pci_domain_nr(pdev->bus); @@ -62,6 +64,9 @@ static int vfio_pci_liveupdate_preserve(struct liveupdate_file_op_args *args) static void vfio_pci_liveupdate_unpreserve(struct liveupdate_file_op_args *args) { + struct vfio_device *device = vfio_device_from_file(args->file); + + pci_liveupdate_outgoing_unpreserve(to_pci_dev(device->dev)); kho_unpreserve_free(phys_to_virt(args->serialized_data)); } @@ -171,6 +176,9 @@ static bool vfio_pci_liveupdate_can_finish(struct liveupdate_file_op_args *args) static void vfio_pci_liveupdate_finish(struct liveupdate_file_op_args *args) { + struct vfio_device *device = vfio_device_from_file(args->file); + + pci_liveupdate_incoming_finish(to_pci_dev(device->dev)); kho_restore_free(phys_to_virt(args->serialized_data)); } @@ -192,10 +200,24 @@ static struct liveupdate_file_handler vfio_pci_liveupdate_fh = { int __init vfio_pci_liveupdate_init(void) { + int ret; + if (!liveupdate_enabled()) return 0; - return liveupdate_register_file_handler(&vfio_pci_liveupdate_fh); + ret = liveupdate_register_file_handler(&vfio_pci_liveupdate_fh); + if (ret) + return ret; + + ret = pci_liveupdate_register_fh(&vfio_pci_liveupdate_fh); + if (ret) + goto error; + + return 0; + +error: + liveupdate_unregister_file_handler(&vfio_pci_liveupdate_fh); + return ret; } void vfio_pci_liveupdate_cleanup(void) @@ -203,5 +225,6 @@ void vfio_pci_liveupdate_cleanup(void) if (!liveupdate_enabled()) return; + WARN_ON_ONCE(pci_liveupdate_unregister_fh(&vfio_pci_liveupdate_fh)); liveupdate_unregister_file_handler(&vfio_pci_liveupdate_fh); } -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:54 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Enforce that files for incoming (preserved by previous kernel) VFIO devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD rather than by opening the corresponding VFIO character device or via VFIO_GROUP_GET_DEVICE_FD. Both of these methods would result in VFIO initializing the device without access to the preserved state of the device passed by the previous kernel. Signed-off-by: David Matlack <dmatlack@google.com> --- drivers/vfio/device_cdev.c | 4 ++++ drivers/vfio/group.c | 9 +++++++++ include/linux/vfio.h | 18 ++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/drivers/vfio/device_cdev.c b/drivers/vfio/device_cdev.c index 935f84a35875..355447e2add3 100644 --- a/drivers/vfio/device_cdev.c +++ b/drivers/vfio/device_cdev.c @@ -57,6 +57,10 @@ int vfio_device_fops_cdev_open(struct inode *inode, struct file *filep) struct vfio_device *device = container_of(inode->i_cdev, struct vfio_device, cdev); + /* Device file must be retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD */ + if (vfio_liveupdate_incoming_is_preserved(device)) + return -EBUSY; + return __vfio_device_fops_cdev_open(device, filep); } diff --git a/drivers/vfio/group.c b/drivers/vfio/group.c index d47ffada6912..63fc4d656215 100644 --- a/drivers/vfio/group.c +++ b/drivers/vfio/group.c @@ -311,6 +311,15 @@ static int vfio_group_ioctl_get_device_fd(struct vfio_group *group, if (IS_ERR(device)) return PTR_ERR(device); + /* + * This device was preserved across a Live Update. Accessing it via + * VFIO_GROUP_GET_DEVICE_FD is not allowed. + */ + if (vfio_liveupdate_incoming_is_preserved(device)) { + vfio_device_put_registration(device); + return -EBUSY; + } + fd = FD_ADD(O_CLOEXEC, vfio_device_open_file(device)); if (fd < 0) vfio_device_put_registration(device); diff --git a/include/linux/vfio.h b/include/linux/vfio.h index dc592dc00f89..0921847b18b5 100644 --- a/include/linux/vfio.h +++ b/include/linux/vfio.h @@ -16,6 +16,7 @@ #include <linux/cdev.h> #include <uapi/linux/vfio.h> #include <linux/iova_bitmap.h> +#include <linux/pci.h> struct kvm; struct iommufd_ctx; @@ -431,4 +432,21 @@ static inline int __vfio_device_fops_cdev_open(struct vfio_device *device, struct vfio_device *vfio_find_device(const void *data, device_match_t match); +#ifdef CONFIG_LIVEUPDATE +static inline bool vfio_liveupdate_incoming_is_preserved(struct vfio_device *device) +{ + struct device *d = device->dev; + + if (dev_is_pci(d)) + return to_pci_dev(d)->liveupdate_incoming; + + return false; +} +#else +static inline bool vfio_liveupdate_incoming_is_preserved(struct vfio_device *device) +{ + return false; +} +#endif + #endif /* VFIO_H */ -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:55 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Stash a pointer to a device's incoming Live Updated state in struct vfio_pci_core_device. This will enable subsequent commits to use the preserved state when initializing the device. To enable VFIO to safely access this pointer during device enablement, require that the device is fully enabled before returning true from can_finish(). This is synchronized by vfio_pci_core.c setting vdev->liveupdate_incoming_state to NULL under dev_set lock once it's done using it. Signed-off-by: David Matlack <dmatlack@google.com> --- drivers/vfio/pci/vfio_pci_core.c | 2 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 17 ++++++++++++++++- include/linux/vfio_pci_core.h | 1 + 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/drivers/vfio/pci/vfio_pci_core.c b/drivers/vfio/pci/vfio_pci_core.c index 3a11e6f450f7..b01b94d81e28 100644 --- a/drivers/vfio/pci/vfio_pci_core.c +++ b/drivers/vfio/pci/vfio_pci_core.c @@ -569,7 +569,7 @@ int vfio_pci_core_enable(struct vfio_pci_core_device *vdev) if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev)) vdev->has_vga = true; - + vdev->liveupdate_incoming_state = NULL; return 0; out_free_zdev: diff --git a/drivers/vfio/pci/vfio_pci_liveupdate.c b/drivers/vfio/pci/vfio_pci_liveupdate.c index ad915352303f..1ad7379c70c4 100644 --- a/drivers/vfio/pci/vfio_pci_liveupdate.c +++ b/drivers/vfio/pci/vfio_pci_liveupdate.c @@ -131,6 +131,7 @@ static int match_device(struct device *dev, const void *arg) static int vfio_pci_liveupdate_retrieve(struct liveupdate_file_op_args *args) { struct vfio_pci_core_device_ser *ser; + struct vfio_pci_core_device *vdev; struct vfio_device *device; struct file *file; int ret; @@ -160,6 +161,9 @@ static int vfio_pci_liveupdate_retrieve(struct liveupdate_file_op_args *args) goto out; } + vdev = container_of(device, struct vfio_pci_core_device, vdev); + vdev->liveupdate_incoming_state = ser; + args->file = file; out: @@ -171,7 +175,18 @@ static int vfio_pci_liveupdate_retrieve(struct liveupdate_file_op_args *args) static bool vfio_pci_liveupdate_can_finish(struct liveupdate_file_op_args *args) { - return args->retrieved; + struct vfio_pci_core_device *vdev; + struct vfio_device *device; + + if (!args->retrieved) + return false; + + device = vfio_device_from_file(args->file); + vdev = container_of(device, struct vfio_pci_core_device, vdev); + + /* Check that vdev->liveupdate_incoming_state is no longer in use. */ + guard(mutex)(&device->dev_set->lock); + return !vdev->liveupdate_incoming_state; } static void vfio_pci_liveupdate_finish(struct liveupdate_file_op_args *args) diff --git a/include/linux/vfio_pci_core.h b/include/linux/vfio_pci_core.h index 1ac86896875c..350c30f84a13 100644 --- a/include/linux/vfio_pci_core.h +++ b/include/linux/vfio_pci_core.h @@ -143,6 +143,7 @@ struct vfio_pci_core_device { struct notifier_block nb; struct rw_semaphore memory_lock; struct list_head dmabufs; + struct vfio_pci_core_device_ser *liveupdate_incoming_state; }; enum vfio_pci_io_width { -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:56 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
From: Vipin Sharma <vipinsh@google.com> Do not reset the device when a Live Update preserved vfio-pci device is retrieved and first enabled. vfio_pci_liveupdate_freeze() guarantees the device is reset prior to Live Update, so there's no reason to reset it again after Live Update. Since VFIO normally uses the initial reset to detect if the device supports function resets, pass that from the previous kernel via struct vfio_pci_core_dev_ser. Signed-off-by: Vipin Sharma <vipinsh@google.com> Signed-off-by: David Matlack <dmatlack@google.com> --- drivers/vfio/pci/vfio_pci_core.c | 22 +++++++++++++++++----- drivers/vfio/pci/vfio_pci_liveupdate.c | 1 + include/linux/kho/abi/vfio_pci.h | 2 ++ include/linux/vfio_pci_core.h | 1 + 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/drivers/vfio/pci/vfio_pci_core.c b/drivers/vfio/pci/vfio_pci_core.c index b01b94d81e28..c9f73f597797 100644 --- a/drivers/vfio/pci/vfio_pci_core.c +++ b/drivers/vfio/pci/vfio_pci_core.c @@ -515,12 +515,24 @@ int vfio_pci_core_enable(struct vfio_pci_core_device *vdev) if (ret) goto out_power; - /* If reset fails because of the device lock, fail this path entirely */ - ret = pci_try_reset_function(pdev); - if (ret == -EAGAIN) - goto out_disable_device; + if (vdev->liveupdate_incoming_state) { + /* + * This device was preserved by the previous kernel across a + * Live Update, so it does not need to be reset. + */ + vdev->reset_works = vdev->liveupdate_incoming_state->reset_works; + } else { + /* + * If reset fails because of the device lock, fail this path + * entirely. + */ + ret = pci_try_reset_function(pdev); + if (ret == -EAGAIN) + goto out_disable_device; + + vdev->reset_works = !ret; + } - vdev->reset_works = !ret; pci_save_state(pdev); vdev->pci_saved_state = pci_store_saved_state(pdev); if (!vdev->pci_saved_state) diff --git a/drivers/vfio/pci/vfio_pci_liveupdate.c b/drivers/vfio/pci/vfio_pci_liveupdate.c index 1ad7379c70c4..c52d6bdb455f 100644 --- a/drivers/vfio/pci/vfio_pci_liveupdate.c +++ b/drivers/vfio/pci/vfio_pci_liveupdate.c @@ -57,6 +57,7 @@ static int vfio_pci_liveupdate_preserve(struct liveupdate_file_op_args *args) ser->bdf = pci_dev_id(pdev); ser->domain = pci_domain_nr(pdev->bus); + ser->reset_works = vdev->reset_works; args->serialized_data = virt_to_phys(ser); return 0; diff --git a/include/linux/kho/abi/vfio_pci.h b/include/linux/kho/abi/vfio_pci.h index 9bf58a2f3820..6c3d3c6dfc09 100644 --- a/include/linux/kho/abi/vfio_pci.h +++ b/include/linux/kho/abi/vfio_pci.h @@ -34,10 +34,12 @@ * * @bdf: The device's PCI bus, device, and function number. * @domain: The device's PCI domain number (segment). + * @reset_works: Non-zero if the device supports function resets. */ struct vfio_pci_core_device_ser { u16 bdf; u16 domain; + u8 reset_works; } __packed; #endif /* _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H */ diff --git a/include/linux/vfio_pci_core.h b/include/linux/vfio_pci_core.h index 350c30f84a13..95835298e29e 100644 --- a/include/linux/vfio_pci_core.h +++ b/include/linux/vfio_pci_core.h @@ -16,6 +16,7 @@ #include <linux/types.h> #include <linux/uuid.h> #include <linux/notifier.h> +#include <linux/kho/abi/vfio_pci.h> #ifndef VFIO_PCI_CORE_H #define VFIO_PCI_CORE_H -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:57 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Add documentation for preserving VFIO device files across a Live Update, as well as some generic file preservation documentation. This documentation will be extended in the future as new types of files are supported and new dependency/ordering requirements are added. Signed-off-by: David Matlack <dmatlack@google.com> --- Documentation/userspace-api/liveupdate.rst | 144 +++++++++++++++++++++ 1 file changed, 144 insertions(+) diff --git a/Documentation/userspace-api/liveupdate.rst b/Documentation/userspace-api/liveupdate.rst index 41c0473e4f16..dbf1e4aeddd7 100644 --- a/Documentation/userspace-api/liveupdate.rst +++ b/Documentation/userspace-api/liveupdate.rst @@ -14,6 +14,150 @@ ioctl uAPI =========== .. kernel-doc:: include/uapi/linux/liveupdate.h +File Preservation +================= + +Files can be preserved across Live Update in sessions. Since only one process +can open /dev/liveupdate, sessions must be created by a centralized process +(e.g. "luod") and then passed via UDS to lower privilege processes (e.g. VMMs) +for them to preserve their own files. + +luod:: + + luo_fd = open("/dev/liveupdate", ...); + + ... + + // Create a new session with the given name. + struct liveupdate_ioctl_create_session arg = { + .size = sizeof(arg), + .name = SESSION_NAME, + }; + ioctl(luo_fd, LIVEUPDATE_IOCTL_CREATE_SESSION, &arg); + + // Send session_fd to the VMM over UDS. + send_session_fd(..., arg.fd); + +VMM:: + + // Receive the newly created session from luod over UDS + session_fd = create_session(SESSION_NAME); + + ... + + // Preserve a file with a unique token value in the session. + struct liveupdate_session_preserve_fd arg = { + .size = sizeof(arg), + .fd = fd, + .token = TOKEN, + } + ioctl(session_fd, LIVEUPDATE_SESSION_PRESERVE_FD, &arg); + +Files can be unpreserved with the LIVEUPDATE_SESSION_UNPRESERVE_FD ioctl. They +are also unpreserved once the last reference to the session is dropped. To +carry preserved files across a Live Update, references must be kept on the +session files through the reboot(LINUX_REBOOT_CMD_KEXEC) syscall. + +While a file is preserved in a session, the kernel holds an extra reference +to it to prevent it from being destroyed. + +Only the following types of files support LIVEUPDATE_SESSION_PRESERVE_FD. More +types of files are expected to be added in the future. + + - memfd + - VFIO character device files (vfio-pci only) + +File Retrieval +============== + +Files that are preserved in a session retrieved after +reboot(LINUX_REBOOT_CMD_KEXEC). + +luod:: + + luo_fd = open("/dev/liveupdate", ...); + + ... + + struct liveupdate_ioctl_retrieve_session arg = { + .size = sizeof(arg), + .name = SESSION_NAME, + }; + ioctl(luo_fd, LIVEUPDATE_IOCTL_RETRIEVE_SESSION, &arg); + + // Send session_fd to VMM over UDS. + send_session_fd(..., arg.fd); + +VMM:: + + // Receive the retrieved session from luod over UDS + session_fd = retrieve_session(SESSION_NAME); + + ... + + // Retrieve the file associated with the token from the session. + struct liveupdate_session_retrieve_fd arg = { + .size = sizeof(arg), + .token = TOKEN, + }; + ioctl(session_fd, LIVEUPDATE_SESSION_RETRIEVE_FD, &arg); + + ... + + ioctl(session_fd, LIVEUPDATE_SESSION_FINISH, ...); + +A session can only be finished once all of the files within it have been +retrieved, and are fully restored from the kernel's perspective. The exact +requirements will vary by file type. + +VFIO Character Device (cdev) Files +================================== + +The kernel supports preserving VFIO character device files across Live Update +within a session:: + + device_fd = open("/dev/vfio/devices/X"); + + ... + + ioctl(session_fd, LIVEUPDATE_SESSION_PRESERVE_FD, { ..., device_fd, ...}); + +Attempting to preserve files acquired via VFIO_GROUP_GET_DEVICE_FD will fail. + +Since the kernel holds an extra reference to files preserved in sessions, there +is no way for the underlying PCI device to be unbound from vfio-pci while it +is being preserved. + +When a VFIO device file is preserved in a session, interrupts must be disabled +on the device prior to reboot(LINUX_REBOOT_CMD_KEXEC), or the kexec will fail. + +Preserved VFIO device files can be retrieved after a Live Update just like any +other preserved file:: + + ioctl(session_fd, LIVEUPDATE_SESSION_RETRIEVE_FD, &arg); + device_fd = arg.fd; + + ... + + ioctl(session_fd, LIVEUPDATE_SESSION_FINISH, ...); + +Prior to LIVEUPDATE_SESSION_FINISH, preserved devices must be retrieved from +the session and bound to an iommufd. Attempting to open the device through +its character device (/dev/vfio/devices/X) or VFIO_GROUP_GET_DEVICE_FD will +fail with -EBUSY. + +The eventual goal of these support is to preserve devices running uninterrupted +across a Live Update. However there are many steps still needed to achieve this +(see Future Work below). So for now, VFIO will reset and restore the device +back into an idle state during reboot(LINUX_REBOOT_CMD_KEXEC). + +Future work: + + - Preservation of iommufd files + - Preservation of IOMMU driver state + - Preservation of PCI state (BAR resources, device state, bridge state, ...) + - Preservation of vfio-pci driver state + See Also ======== -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:58 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
From: Vipin Sharma <vipinsh@google.com> Move luo_test_utils.[ch] into a lib/ directory and pull the rules to build them out into a separate make script. This will enable these utilities to be also built by and used within other selftests (such as VFIO) in subsequent commits. No functional change intended. Signed-off-by: Vipin Sharma <vipinsh@google.com> Co-developed-by: David Matlack <dmatlack@google.com> Signed-off-by: David Matlack <dmatlack@google.com> --- tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 ++++--------- .../include/libliveupdate.h} | 8 ++++---- .../selftests/liveupdate/lib/libliveupdate.mk | 20 +++++++++++++++++++ .../{luo_test_utils.c => lib/liveupdate.c} | 2 +- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- 7 files changed, 32 insertions(+), 17 deletions(-) rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (87%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (99%) diff --git a/tools/testing/selftests/liveupdate/.gitignore b/tools/testing/selftests/liveupdate/.gitignore index 661827083ab6..18a0c7036cf3 100644 --- a/tools/testing/selftests/liveupdate/.gitignore +++ b/tools/testing/selftests/liveupdate/.gitignore @@ -3,6 +3,7 @@ !/**/ !*.c !*.h +!*.mk !*.sh !.gitignore !config diff --git a/tools/testing/selftests/liveupdate/Makefile b/tools/testing/selftests/liveupdate/Makefile index 080754787ede..a060cc21f27f 100644 --- a/tools/testing/selftests/liveupdate/Makefile +++ b/tools/testing/selftests/liveupdate/Makefile @@ -1,7 +1,5 @@ # SPDX-License-Identifier: GPL-2.0-only -LIB_C += luo_test_utils.c - TEST_GEN_PROGS += liveupdate TEST_GEN_PROGS_EXTENDED += luo_kexec_simple @@ -10,25 +8,21 @@ TEST_GEN_PROGS_EXTENDED += luo_multi_session TEST_FILES += do_kexec.sh include ../lib.mk +include lib/libliveupdate.mk CFLAGS += $(KHDR_INCLUDES) CFLAGS += -Wall -O2 -Wno-unused-function CFLAGS += -MD -LIB_O := $(patsubst %.c, $(OUTPUT)/%.o, $(LIB_C)) TEST_O := $(patsubst %, %.o, $(TEST_GEN_PROGS)) TEST_O += $(patsubst %, %.o, $(TEST_GEN_PROGS_EXTENDED)) -TEST_DEP_FILES := $(patsubst %.o, %.d, $(LIB_O)) +TEST_DEP_FILES := $(patsubst %.o, %.d, $(LIBLIVEUPDATE_O)) TEST_DEP_FILES += $(patsubst %.o, %.d, $(TEST_O)) -include $(TEST_DEP_FILES) -$(LIB_O): $(OUTPUT)/%.o: %.c - $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@ - -$(TEST_GEN_PROGS) $(TEST_GEN_PROGS_EXTENDED): $(OUTPUT)/%: %.o $(LIB_O) - $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH) $< $(LIB_O) $(LDLIBS) -o $@ +$(TEST_GEN_PROGS) $(TEST_GEN_PROGS_EXTENDED): $(OUTPUT)/%: %.o $(LIBLIVEUPDATE_O) + $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH) $< $(LIBLIVEUPDATE_O) $(LDLIBS) -o $@ -EXTRA_CLEAN += $(LIB_O) EXTRA_CLEAN += $(TEST_O) EXTRA_CLEAN += $(TEST_DEP_FILES) diff --git a/tools/testing/selftests/liveupdate/luo_test_utils.h b/tools/testing/selftests/liveupdate/lib/include/libliveupdate.h similarity index 87% rename from tools/testing/selftests/liveupdate/luo_test_utils.h rename to tools/testing/selftests/liveupdate/lib/include/libliveupdate.h index 90099bf49577..4390a2737930 100644 --- a/tools/testing/selftests/liveupdate/luo_test_utils.h +++ b/tools/testing/selftests/liveupdate/lib/include/libliveupdate.h @@ -7,13 +7,13 @@ * Utility functions for LUO kselftests. */ -#ifndef LUO_TEST_UTILS_H -#define LUO_TEST_UTILS_H +#ifndef SELFTESTS_LIVEUPDATE_LIB_LIVEUPDATE_H +#define SELFTESTS_LIVEUPDATE_LIB_LIVEUPDATE_H #include <errno.h> #include <string.h> #include <linux/liveupdate.h> -#include "../kselftest.h" +#include "../../../kselftest.h" #define LUO_DEVICE "/dev/liveupdate" @@ -41,4 +41,4 @@ typedef void (*luo_test_stage2_fn)(int luo_fd, int state_session_fd); int luo_test(int argc, char *argv[], const char *state_session_name, luo_test_stage1_fn stage1, luo_test_stage2_fn stage2); -#endif /* LUO_TEST_UTILS_H */ +#endif /* SELFTESTS_LIVEUPDATE_LIB_LIVEUPDATE_H */ diff --git a/tools/testing/selftests/liveupdate/lib/libliveupdate.mk b/tools/testing/selftests/liveupdate/lib/libliveupdate.mk new file mode 100644 index 000000000000..fffd95b085b6 --- /dev/null +++ b/tools/testing/selftests/liveupdate/lib/libliveupdate.mk @@ -0,0 +1,20 @@ +include $(top_srcdir)/scripts/subarch.include +ARCH ?= $(SUBARCH) + +LIBLIVEUPDATE_SRCDIR := $(selfdir)/liveupdate/lib + +LIBLIVEUPDATE_C := liveupdate.c + +LIBLIVEUPDATE_OUTPUT := $(OUTPUT)/libliveupdate + +LIBLIVEUPDATE_O := $(patsubst %.c, $(LIBLIVEUPDATE_OUTPUT)/%.o, $(LIBLIVEUPDATE_C)) + +LIBLIVEUPDATE_O_DIRS := $(shell dirname $(LIBLIVEUPDATE_O) | uniq) +$(shell mkdir -p $(LIBLIVEUPDATE_O_DIRS)) + +CFLAGS += -I$(LIBLIVEUPDATE_SRCDIR)/include + +$(LIBLIVEUPDATE_O): $(LIBLIVEUPDATE_OUTPUT)/%.o : $(LIBLIVEUPDATE_SRCDIR)/%.c + $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@ + +EXTRA_CLEAN += $(LIBLIVEUPDATE_OUTPUT) diff --git a/tools/testing/selftests/liveupdate/luo_test_utils.c b/tools/testing/selftests/liveupdate/lib/liveupdate.c similarity index 99% rename from tools/testing/selftests/liveupdate/luo_test_utils.c rename to tools/testing/selftests/liveupdate/lib/liveupdate.c index 3c8721c505df..60121873f685 100644 --- a/tools/testing/selftests/liveupdate/luo_test_utils.c +++ b/tools/testing/selftests/liveupdate/lib/liveupdate.c @@ -21,7 +21,7 @@ #include <errno.h> #include <stdarg.h> -#include "luo_test_utils.h" +#include <libliveupdate.h> int luo_open_device(void) { diff --git a/tools/testing/selftests/liveupdate/luo_kexec_simple.c b/tools/testing/selftests/liveupdate/luo_kexec_simple.c index d7ac1f3dc4cb..786ac93b9ae3 100644 --- a/tools/testing/selftests/liveupdate/luo_kexec_simple.c +++ b/tools/testing/selftests/liveupdate/luo_kexec_simple.c @@ -8,7 +8,7 @@ * across a single kexec reboot. */ -#include "luo_test_utils.h" +#include <libliveupdate.h> #define TEST_SESSION_NAME "test-session" #define TEST_MEMFD_TOKEN 0x1A diff --git a/tools/testing/selftests/liveupdate/luo_multi_session.c b/tools/testing/selftests/liveupdate/luo_multi_session.c index 0ee2d795beef..aac24a5f5ce3 100644 --- a/tools/testing/selftests/liveupdate/luo_multi_session.c +++ b/tools/testing/selftests/liveupdate/luo_multi_session.c @@ -9,7 +9,7 @@ * files. */ -#include "luo_test_utils.h" +#include <libliveupdate.h> #define SESSION_EMPTY_1 "multi-test-empty-1" #define SESSION_EMPTY_2 "multi-test-empty-2" -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:24:59 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
From: Vipin Sharma <vipinsh@google.com> Add helper functions to preserve and retrieve file descriptors from an LUO session. These will be used be used in subsequent commits to preserve FDs other than memfd. No functional change intended. Signed-off-by: Vipin Sharma <vipinsh@google.com> Co-developed-by: David Matlack <dmatlack@google.com> Signed-off-by: David Matlack <dmatlack@google.com> --- .../liveupdate/lib/include/libliveupdate.h | 3 ++ .../selftests/liveupdate/lib/liveupdate.c | 41 +++++++++++++++---- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/tools/testing/selftests/liveupdate/lib/include/libliveupdate.h b/tools/testing/selftests/liveupdate/lib/include/libliveupdate.h index 4390a2737930..4c93d043d2b3 100644 --- a/tools/testing/selftests/liveupdate/lib/include/libliveupdate.h +++ b/tools/testing/selftests/liveupdate/lib/include/libliveupdate.h @@ -26,6 +26,9 @@ int luo_create_session(int luo_fd, const char *name); int luo_retrieve_session(int luo_fd, const char *name); int luo_session_finish(int session_fd); +int luo_session_preserve_fd(int session_fd, int fd, int token); +int luo_session_retrieve_fd(int session_fd, int token); + int create_and_preserve_memfd(int session_fd, int token, const char *data); int restore_and_verify_memfd(int session_fd, int token, const char *expected_data); diff --git a/tools/testing/selftests/liveupdate/lib/liveupdate.c b/tools/testing/selftests/liveupdate/lib/liveupdate.c index 60121873f685..9bf4f16ca0a4 100644 --- a/tools/testing/selftests/liveupdate/lib/liveupdate.c +++ b/tools/testing/selftests/liveupdate/lib/liveupdate.c @@ -54,9 +54,35 @@ int luo_retrieve_session(int luo_fd, const char *name) return arg.fd; } +int luo_session_preserve_fd(int session_fd, int fd, int token) +{ + struct liveupdate_session_preserve_fd arg = { + .size = sizeof(arg), + .fd = fd, + .token = token, + }; + + if (ioctl(session_fd, LIVEUPDATE_SESSION_PRESERVE_FD, &arg)) + return -errno; + + return 0; +} + +int luo_session_retrieve_fd(int session_fd, int token) +{ + struct liveupdate_session_retrieve_fd arg = { + .size = sizeof(arg), + .token = token, + }; + + if (ioctl(session_fd, LIVEUPDATE_SESSION_RETRIEVE_FD, &arg)) + return -errno; + + return arg.fd; +} + int create_and_preserve_memfd(int session_fd, int token, const char *data) { - struct liveupdate_session_preserve_fd arg = { .size = sizeof(arg) }; long page_size = sysconf(_SC_PAGE_SIZE); void *map = MAP_FAILED; int mfd = -1, ret = -1; @@ -75,9 +101,8 @@ int create_and_preserve_memfd(int session_fd, int token, const char *data) snprintf(map, page_size, "%s", data); munmap(map, page_size); - arg.fd = mfd; - arg.token = token; - if (ioctl(session_fd, LIVEUPDATE_SESSION_PRESERVE_FD, &arg) < 0) + ret = luo_session_preserve_fd(session_fd, mfd, token); + if (ret) goto out; ret = 0; @@ -92,15 +117,13 @@ int create_and_preserve_memfd(int session_fd, int token, const char *data) int restore_and_verify_memfd(int session_fd, int token, const char *expected_data) { - struct liveupdate_session_retrieve_fd arg = { .size = sizeof(arg) }; long page_size = sysconf(_SC_PAGE_SIZE); void *map = MAP_FAILED; int mfd = -1, ret = -1; - arg.token = token; - if (ioctl(session_fd, LIVEUPDATE_SESSION_RETRIEVE_FD, &arg) < 0) - return -errno; - mfd = arg.fd; + mfd = luo_session_retrieve_fd(session_fd, token); + if (mfd < 0) + return mfd; map = mmap(NULL, page_size, PROT_READ, MAP_SHARED, mfd, 0); if (map == MAP_FAILED) -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:00 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Add a selftest to exercise preserving a various VFIO files through /dev/liveupdate. Ensure that VFIO cdev device files can be preserved and everything else (group-based device files, group files, and container files) all fail. Signed-off-by: David Matlack <dmatlack@google.com> --- tools/testing/selftests/vfio/Makefile | 1 + .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c diff --git a/tools/testing/selftests/vfio/Makefile b/tools/testing/selftests/vfio/Makefile index f9c040094d4a..666310872217 100644 --- a/tools/testing/selftests/vfio/Makefile +++ b/tools/testing/selftests/vfio/Makefile @@ -4,6 +4,7 @@ TEST_GEN_PROGS += vfio_iommufd_setup_test TEST_GEN_PROGS += vfio_pci_device_test TEST_GEN_PROGS += vfio_pci_device_init_perf_test TEST_GEN_PROGS += vfio_pci_driver_test +TEST_GEN_PROGS += vfio_pci_liveupdate_uapi_test TEST_FILES += scripts/cleanup.sh TEST_FILES += scripts/lib.sh diff --git a/tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c b/tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c new file mode 100644 index 000000000000..3b4276b2532c --- /dev/null +++ b/tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-2.0-only + +#include <libliveupdate.h> +#include <libvfio.h> +#include <kselftest_harness.h> + +static const char *device_bdf; + +FIXTURE(vfio_pci_liveupdate_uapi_test) { + int luo_fd; + int session_fd; + struct iommu *iommu; + struct vfio_pci_device *device; +}; + +FIXTURE_VARIANT(vfio_pci_liveupdate_uapi_test) { + const char *iommu_mode; +}; + +#define FIXTURE_VARIANT_ADD_IOMMU_MODE(_iommu_mode) \ +FIXTURE_VARIANT_ADD(vfio_pci_liveupdate_uapi_test, _iommu_mode) { \ + .iommu_mode = #_iommu_mode, \ +} + +FIXTURE_VARIANT_ADD_ALL_IOMMU_MODES(); +#undef FIXTURE_VARIANT_ADD_IOMMU_MODE + +FIXTURE_SETUP(vfio_pci_liveupdate_uapi_test) +{ + self->luo_fd = luo_open_device(); + ASSERT_GE(self->luo_fd, 0); + + self->session_fd = luo_create_session(self->luo_fd, "session"); + ASSERT_GE(self->session_fd, 0); + + self->iommu = iommu_init(variant->iommu_mode); + self->device = vfio_pci_device_init(device_bdf, self->iommu); +} + +FIXTURE_TEARDOWN(vfio_pci_liveupdate_uapi_test) +{ + vfio_pci_device_cleanup(self->device); + iommu_cleanup(self->iommu); + close(self->session_fd); + close(self->luo_fd); +} + +TEST_F(vfio_pci_liveupdate_uapi_test, preserve_device) +{ + int ret; + + ret = luo_session_preserve_fd(self->session_fd, self->device->fd, 0); + + /* Preservation should only be supported for VFIO cdev files. */ + ASSERT_EQ(ret, self->iommu->iommufd ? 0 : -ENOENT); +} + +TEST_F(vfio_pci_liveupdate_uapi_test, preserve_group_fails) +{ + int ret; + + if (self->iommu->iommufd) + return; + + ret = luo_session_preserve_fd(self->session_fd, self->device->group_fd, 0); + ASSERT_EQ(ret, -ENOENT); +} + +TEST_F(vfio_pci_liveupdate_uapi_test, preserve_container_fails) +{ + int ret; + + if (self->iommu->iommufd) + return; + + ret = luo_session_preserve_fd(self->session_fd, self->iommu->container_fd, 0); + ASSERT_EQ(ret, -ENOENT); +} + +int main(int argc, char *argv[]) +{ + int fd; + + fd = luo_open_device(); + if (fd < 0) { + printf("open(%s) failed: %s, skipping\n", LUO_DEVICE, strerror(errno)); + return KSFT_SKIP; + } + close(fd); + + device_bdf = vfio_selftests_get_bdf(&argc, argv); + return test_harness_run(argc, argv); +} -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:03 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
From: Vipin Sharma <vipinsh@google.com> Import and build liveupdate selftest library in VFIO selftests. It allows to use liveupdate ioctls in VFIO selftests Signed-off-by: Vipin Sharma <vipinsh@google.com> Signed-off-by: David Matlack <dmatlack@google.com> --- tools/testing/selftests/vfio/Makefile | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tools/testing/selftests/vfio/Makefile b/tools/testing/selftests/vfio/Makefile index 3c796ca99a50..1e50998529fd 100644 --- a/tools/testing/selftests/vfio/Makefile +++ b/tools/testing/selftests/vfio/Makefile @@ -12,6 +12,7 @@ TEST_FILES += scripts/setup.sh include ../lib.mk include lib/libvfio.mk +include ../liveupdate/lib/libliveupdate.mk CFLAGS += -I$(top_srcdir)/tools/include CFLAGS += -MD @@ -19,11 +20,15 @@ CFLAGS += $(EXTRA_CFLAGS) LDFLAGS += -pthread -$(TEST_GEN_PROGS): %: %.o $(LIBVFIO_O) - $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $< $(LIBVFIO_O) $(LDLIBS) -o $@ +LIBS_O := $(LIBVFIO_O) +LIBS_O += $(LIBLIVEUPDATE_O) + +$(TEST_GEN_PROGS): %: %.o $(LIBS_O) + $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH) $< $(LIBS_O) $(LDLIBS) -o $@ TEST_GEN_PROGS_O = $(patsubst %, %.o, $(TEST_GEN_PROGS)) -TEST_DEP_FILES = $(patsubst %.o, %.d, $(TEST_GEN_PROGS_O) $(LIBVFIO_O)) +TEST_DEP_FILES := $(patsubst %.o, %.d, $(TEST_GEN_PROGS_O)) +TEST_DEP_FILES += $(patsubst %.o, %.d, $(LIBS_O)) -include $(TEST_DEP_FILES) EXTRA_CLEAN += $(TEST_GEN_PROGS_O) $(TEST_DEP_FILES) -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:01 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Add Makefile support for TEST_GEN_PROGS_EXTENDED targets. These tests are not run by default. TEST_GEN_PROGS_EXTENDED will be used for Live Update selftests in subsequent commits. These selftests must be run manually because they require the user/runner to perform additional actions, such as kexec, during the test. Signed-off-by: David Matlack <dmatlack@google.com> --- tools/testing/selftests/vfio/Makefile | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tools/testing/selftests/vfio/Makefile b/tools/testing/selftests/vfio/Makefile index 1e50998529fd..f9c040094d4a 100644 --- a/tools/testing/selftests/vfio/Makefile +++ b/tools/testing/selftests/vfio/Makefile @@ -23,12 +23,15 @@ LDFLAGS += -pthread LIBS_O := $(LIBVFIO_O) LIBS_O += $(LIBLIVEUPDATE_O) -$(TEST_GEN_PROGS): %: %.o $(LIBS_O) +$(TEST_GEN_PROGS) $(TEST_GEN_PROGS_EXTENDED): %: %.o $(LIBS_O) $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH) $< $(LIBS_O) $(LDLIBS) -o $@ -TEST_GEN_PROGS_O = $(patsubst %, %.o, $(TEST_GEN_PROGS)) -TEST_DEP_FILES := $(patsubst %.o, %.d, $(TEST_GEN_PROGS_O)) +TESTS_O := $(patsubst %, %.o, $(TEST_GEN_PROGS)) +TESTS_O += $(patsubst %, %.o, $(TEST_GEN_PROGS_EXTENDED)) + +TEST_DEP_FILES := $(patsubst %.o, %.d, $(TESTS_O)) TEST_DEP_FILES += $(patsubst %.o, %.d, $(LIBS_O)) -include $(TEST_DEP_FILES) -EXTRA_CLEAN += $(TEST_GEN_PROGS_O) $(TEST_DEP_FILES) +EXTRA_CLEAN += $(TESTS_O) +EXTRA_CLEAN += $(TEST_DEP_FILES) -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:02 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
From: Vipin Sharma <vipinsh@google.com> Use the given VFIO cdev FD to initialize vfio_pci_device in VFIO selftests. Add the assertion to make sure that passed cdev FD is not used with legacy VFIO APIs. If VFIO cdev FD is provided then do not open the device instead use the FD for any interaction with the device. This API will allow to write selftests where VFIO device FD is preserved using liveupdate and retrieved later using liveupdate ioctl after kexec. Signed-off-by: Vipin Sharma <vipinsh@google.com> Co-developed-by: David Matlack <dmatlack@google.com> Signed-off-by: David Matlack <dmatlack@google.com> --- .../lib/include/libvfio/vfio_pci_device.h | 3 ++ .../selftests/vfio/lib/vfio_pci_device.c | 33 ++++++++++++++----- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h b/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h index 2858885a89bb..896dfde88118 100644 --- a/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h +++ b/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h @@ -38,6 +38,9 @@ struct vfio_pci_device { #define dev_info(_dev, _fmt, ...) printf("%s: " _fmt, (_dev)->bdf, ##__VA_ARGS__) #define dev_err(_dev, _fmt, ...) fprintf(stderr, "%s: " _fmt, (_dev)->bdf, ##__VA_ARGS__) +struct vfio_pci_device *__vfio_pci_device_init(const char *bdf, + struct iommu *iommu, + int device_fd); struct vfio_pci_device *vfio_pci_device_init(const char *bdf, struct iommu *iommu); void vfio_pci_device_cleanup(struct vfio_pci_device *device); diff --git a/tools/testing/selftests/vfio/lib/vfio_pci_device.c b/tools/testing/selftests/vfio/lib/vfio_pci_device.c index fac4c0ecadef..08bb582eaa8f 100644 --- a/tools/testing/selftests/vfio/lib/vfio_pci_device.c +++ b/tools/testing/selftests/vfio/lib/vfio_pci_device.c @@ -318,19 +318,27 @@ static void vfio_device_attach_iommufd_pt(int device_fd, u32 pt_id) ioctl_assert(device_fd, VFIO_DEVICE_ATTACH_IOMMUFD_PT, &args); } -static void vfio_pci_iommufd_setup(struct vfio_pci_device *device, const char *bdf) +static void vfio_pci_iommufd_setup(struct vfio_pci_device *device, + const char *bdf, int device_fd) { - const char *cdev_path = vfio_pci_get_cdev_path(bdf); + const char *cdev_path; - device->fd = open(cdev_path, O_RDWR); - VFIO_ASSERT_GE(device->fd, 0); - free((void *)cdev_path); + if (device_fd >= 0) { + device->fd = device_fd; + } else { + cdev_path = vfio_pci_get_cdev_path(bdf); + device->fd = open(cdev_path, O_RDWR); + VFIO_ASSERT_GE(device->fd, 0); + free((void *)cdev_path); + } vfio_device_bind_iommufd(device->fd, device->iommu->iommufd); vfio_device_attach_iommufd_pt(device->fd, device->iommu->ioas_id); } -struct vfio_pci_device *vfio_pci_device_init(const char *bdf, struct iommu *iommu) +struct vfio_pci_device *__vfio_pci_device_init(const char *bdf, + struct iommu *iommu, + int device_fd) { struct vfio_pci_device *device; @@ -341,10 +349,12 @@ struct vfio_pci_device *vfio_pci_device_init(const char *bdf, struct iommu *iomm device->iommu = iommu; device->bdf = bdf; - if (iommu->mode->container_path) + if (iommu->mode->container_path) { + VFIO_ASSERT_EQ(device_fd, -1); vfio_pci_container_setup(device, bdf); - else - vfio_pci_iommufd_setup(device, bdf); + } else { + vfio_pci_iommufd_setup(device, bdf, device_fd); + } vfio_pci_device_setup(device); vfio_pci_driver_probe(device); @@ -352,6 +362,11 @@ struct vfio_pci_device *vfio_pci_device_init(const char *bdf, struct iommu *iomm return device; } +struct vfio_pci_device *vfio_pci_device_init(const char *bdf, struct iommu *iommu) +{ + return __vfio_pci_device_init(bdf, iommu, /*device_fd=*/-1); +} + void vfio_pci_device_cleanup(struct vfio_pci_device *device) { int i; -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:04 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Expose the list of iommu_modes to enable tests that want to iterate through all possible iommu modes. Signed-off-by: David Matlack <dmatlack@google.com> --- tools/testing/selftests/vfio/lib/include/libvfio/iommu.h | 2 ++ tools/testing/selftests/vfio/lib/iommu.c | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/vfio/lib/include/libvfio/iommu.h b/tools/testing/selftests/vfio/lib/include/libvfio/iommu.h index 5c9b9dc6d993..a03ff2281f11 100644 --- a/tools/testing/selftests/vfio/lib/include/libvfio/iommu.h +++ b/tools/testing/selftests/vfio/lib/include/libvfio/iommu.h @@ -15,6 +15,8 @@ struct iommu_mode { unsigned long iommu_type; }; +extern const struct iommu_mode iommu_modes[]; +extern const int nr_iommu_modes; extern const char *default_iommu_mode; struct dma_region { diff --git a/tools/testing/selftests/vfio/lib/iommu.c b/tools/testing/selftests/vfio/lib/iommu.c index 58b7fb7430d4..add35dbc83f8 100644 --- a/tools/testing/selftests/vfio/lib/iommu.c +++ b/tools/testing/selftests/vfio/lib/iommu.c @@ -23,7 +23,7 @@ const char *default_iommu_mode = "iommufd"; /* Reminder: Keep in sync with FIXTURE_VARIANT_ADD_ALL_IOMMU_MODES(). */ -static const struct iommu_mode iommu_modes[] = { +const struct iommu_mode iommu_modes[] = { { .name = "vfio_type1_iommu", .container_path = "/dev/vfio/vfio", @@ -49,6 +49,8 @@ static const struct iommu_mode iommu_modes[] = { }, }; +const int nr_iommu_modes = ARRAY_SIZE(iommu_modes); + static const struct iommu_mode *lookup_iommu_mode(const char *iommu_mode) { int i; -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:06 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Expose a few low-level helper routings for setting up vfio_pci_device structs. These routines will be used in a subsequent commit to assert that VFIO_GROUP_GET_DEVICE_FD fails under certain conditions. Signed-off-by: David Matlack <dmatlack@google.com> --- .../lib/include/libvfio/vfio_pci_device.h | 5 +++ .../selftests/vfio/lib/vfio_pci_device.c | 33 +++++++++++++------ 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h b/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h index 896dfde88118..2389c7698335 100644 --- a/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h +++ b/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h @@ -125,4 +125,9 @@ static inline bool vfio_pci_device_match(struct vfio_pci_device *device, const char *vfio_pci_get_cdev_path(const char *bdf); +/* Low-level routines for setting up a struct vfio_pci_device */ +struct vfio_pci_device *vfio_pci_device_alloc(const char *bdf, struct iommu *iommu); +void vfio_pci_group_setup(struct vfio_pci_device *device); +void vfio_pci_iommu_setup(struct vfio_pci_device *device); + #endif /* SELFTESTS_VFIO_LIB_INCLUDE_LIBVFIO_VFIO_PCI_DEVICE_H */ diff --git a/tools/testing/selftests/vfio/lib/vfio_pci_device.c b/tools/testing/selftests/vfio/lib/vfio_pci_device.c index 08bb582eaa8f..76597c84e956 100644 --- a/tools/testing/selftests/vfio/lib/vfio_pci_device.c +++ b/tools/testing/selftests/vfio/lib/vfio_pci_device.c @@ -198,7 +198,7 @@ static unsigned int vfio_pci_get_group_from_dev(const char *bdf) return group; } -static void vfio_pci_group_setup(struct vfio_pci_device *device, const char *bdf) +void vfio_pci_group_setup(struct vfio_pci_device *device) { struct vfio_group_status group_status = { .argsz = sizeof(group_status), @@ -206,7 +206,7 @@ static void vfio_pci_group_setup(struct vfio_pci_device *device, const char *bdf char group_path[32]; int group; - group = vfio_pci_get_group_from_dev(bdf); + group = vfio_pci_get_group_from_dev(device->bdf); snprintf(group_path, sizeof(group_path), "/dev/vfio/%d", group); device->group_fd = open(group_path, O_RDWR); @@ -218,14 +218,12 @@ static void vfio_pci_group_setup(struct vfio_pci_device *device, const char *bdf ioctl_assert(device->group_fd, VFIO_GROUP_SET_CONTAINER, &device->iommu->container_fd); } -static void vfio_pci_container_setup(struct vfio_pci_device *device, const char *bdf) +void vfio_pci_iommu_setup(struct vfio_pci_device *device) { struct iommu *iommu = device->iommu; unsigned long iommu_type = iommu->mode->iommu_type; int ret; - vfio_pci_group_setup(device, bdf); - ret = ioctl(iommu->container_fd, VFIO_CHECK_EXTENSION, iommu_type); VFIO_ASSERT_GT(ret, 0, "VFIO IOMMU type %lu not supported\n", iommu_type); @@ -235,8 +233,14 @@ static void vfio_pci_container_setup(struct vfio_pci_device *device, const char * because the IOMMU type is already set. */ (void)ioctl(iommu->container_fd, VFIO_SET_IOMMU, (void *)iommu_type); +} - device->fd = ioctl(device->group_fd, VFIO_GROUP_GET_DEVICE_FD, bdf); +static void vfio_pci_container_setup(struct vfio_pci_device *device) +{ + vfio_pci_group_setup(device); + vfio_pci_iommu_setup(device); + + device->fd = ioctl(device->group_fd, VFIO_GROUP_GET_DEVICE_FD, device->bdf); VFIO_ASSERT_GE(device->fd, 0); } @@ -336,9 +340,7 @@ static void vfio_pci_iommufd_setup(struct vfio_pci_device *device, vfio_device_attach_iommufd_pt(device->fd, device->iommu->ioas_id); } -struct vfio_pci_device *__vfio_pci_device_init(const char *bdf, - struct iommu *iommu, - int device_fd) +struct vfio_pci_device *vfio_pci_device_alloc(const char *bdf, struct iommu *iommu) { struct vfio_pci_device *device; @@ -349,9 +351,20 @@ struct vfio_pci_device *__vfio_pci_device_init(const char *bdf, device->iommu = iommu; device->bdf = bdf; + return device; +} + +struct vfio_pci_device *__vfio_pci_device_init(const char *bdf, + struct iommu *iommu, + int device_fd) +{ + struct vfio_pci_device *device; + + device = vfio_pci_device_alloc(bdf, iommu); + if (iommu->mode->container_path) { VFIO_ASSERT_EQ(device_fd, -1); - vfio_pci_container_setup(device, bdf); + vfio_pci_container_setup(device); } else { vfio_pci_iommufd_setup(device, bdf, device_fd); } -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:07 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Verify that opening a VFIO device through its cdev file and via VFIO_GROUP_GET_DEVICE_FD both fail with -EBUSY if the device was preserved across a Live Update. When a device file is preserve across a Live Update, the file must be retrieved from /dev/liveupdate, not from VFIO directly. Signed-off-by: David Matlack <dmatlack@google.com> --- .../vfio/vfio_pci_liveupdate_kexec_test.c | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c b/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c index 15b3e3af91d1..65c48196e44e 100644 --- a/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c +++ b/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c @@ -36,6 +36,42 @@ static void before_kexec(int luo_fd) daemonize_and_wait(); } +static void check_open_vfio_device_fails(void) +{ + const char *cdev_path = vfio_pci_get_cdev_path(device_bdf); + struct vfio_pci_device *device; + struct iommu *iommu; + int ret, i; + + printf("Checking open(%s) fails\n", cdev_path); + ret = open(cdev_path, O_RDWR); + VFIO_ASSERT_EQ(ret, -1); + VFIO_ASSERT_EQ(errno, EBUSY); + free((void *)cdev_path); + + for (i = 0; i < nr_iommu_modes; i++) { + if (!iommu_modes[i].container_path) + continue; + + iommu = iommu_init(iommu_modes[i].name); + + device = vfio_pci_device_alloc(device_bdf, iommu); + vfio_pci_group_setup(device); + vfio_pci_iommu_setup(device); + + printf("Checking ioctl(group_fd, VFIO_GROUP_GET_DEVICE_FD, \"%s\") fails (%s)\n", + device_bdf, iommu_modes[i].name); + + ret = ioctl(device->group_fd, VFIO_GROUP_GET_DEVICE_FD, device->bdf); + VFIO_ASSERT_EQ(ret, -1); + VFIO_ASSERT_EQ(errno, EBUSY); + + close(device->group_fd); + free(device); + iommu_cleanup(iommu); + } +} + static void after_kexec(int luo_fd, int state_session_fd) { struct vfio_pci_device *device; @@ -44,6 +80,8 @@ static void after_kexec(int luo_fd, int state_session_fd) int device_fd; int stage; + check_open_vfio_device_fails(); + restore_and_read_stage(state_session_fd, STATE_TOKEN, &stage); VFIO_ASSERT_EQ(stage, 2); -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:08 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Add a long-running DMA memcpy operation to vfio_pci_liveupdate_kexec_test so that the device attempts to perform DMAs continuously during the Live Update. At this point iommufd preservation is not supported and bus mastering is not kept enabled on the device during across the kexec, so most of these DMAs will be dropped. However this test ensures that the current device preservation support does not lead to system instability or crashes if the device is active. And once iommufd and bus mastering are preserved, this test can be relaxed to check that the DMA operations completed successfully. Signed-off-by: David Matlack <dmatlack@google.com> --- .../vfio/vfio_pci_liveupdate_kexec_test.c | 129 ++++++++++++++++++ 1 file changed, 129 insertions(+) diff --git a/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c b/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c index 65c48196e44e..36bddfbb88ed 100644 --- a/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c +++ b/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c @@ -1,8 +1,16 @@ // SPDX-License-Identifier: GPL-2.0-only +#include <linux/sizes.h> +#include <sys/mman.h> + #include <libliveupdate.h> #include <libvfio.h> +#define MEMCPY_SIZE SZ_1G +#define DRIVER_SIZE SZ_1M +#define MEMFD_SIZE (MEMCPY_SIZE + DRIVER_SIZE) + +static struct dma_region memcpy_region; static const char *device_bdf; static char state_session[LIVEUPDATE_SESSION_NAME_LENGTH]; @@ -11,8 +19,89 @@ static char device_session[LIVEUPDATE_SESSION_NAME_LENGTH]; enum { STATE_TOKEN, DEVICE_TOKEN, + MEMFD_TOKEN, }; +static void dma_memcpy_one(struct vfio_pci_device *device) +{ + void *src = memcpy_region.vaddr, *dst; + u64 size; + + size = min_t(u64, memcpy_region.size / 2, device->driver.max_memcpy_size); + dst = src + size; + + memset(src, 1, size); + memset(dst, 0, size); + + printf("Kicking off 1 DMA memcpy operations of size 0x%lx...\n", size); + vfio_pci_driver_memcpy(device, + to_iova(device, src), + to_iova(device, dst), + size); + + VFIO_ASSERT_EQ(memcmp(src, dst, size), 0); +} + +static void dma_memcpy_start(struct vfio_pci_device *device) +{ + void *src = memcpy_region.vaddr, *dst; + u64 count, size; + + size = min_t(u64, memcpy_region.size / 2, device->driver.max_memcpy_size); + dst = src + size; + + /* + * Rough Math: If we assume the device will perform memcpy at a rate of + * 30GB/s then 7200GB of transfers will run for about 4 minutes. + */ + count = (u64)7200 * SZ_1G / size; + count = min_t(u64, count, device->driver.max_memcpy_count); + + memset(src, 1, size / 2); + memset(dst, 0, size / 2); + + printf("Kicking off %lu DMA memcpy operations of size 0x%lx...\n", count, size); + vfio_pci_driver_memcpy_start(device, + to_iova(device, src), + to_iova(device, dst), + size, count); +} + +static void dma_memfd_map(struct vfio_pci_device *device, int fd) +{ + void *vaddr; + + vaddr = mmap(NULL, MEMFD_SIZE, PROT_WRITE, MAP_SHARED, fd, 0); + VFIO_ASSERT_NE(vaddr, MAP_FAILED); + + memcpy_region.iova = SZ_4G; + memcpy_region.size = MEMCPY_SIZE; + memcpy_region.vaddr = vaddr; + iommu_map(device->iommu, &memcpy_region); + + device->driver.region.iova = memcpy_region.iova + memcpy_region.size; + device->driver.region.size = DRIVER_SIZE; + device->driver.region.vaddr = vaddr + memcpy_region.size; + iommu_map(device->iommu, &device->driver.region); +} + +static void dma_memfd_setup(struct vfio_pci_device *device, int session_fd) +{ + int fd, ret; + + fd = memfd_create("dma-buffer", 0); + VFIO_ASSERT_GE(fd, 0); + + ret = fallocate(fd, 0, 0, MEMFD_SIZE); + VFIO_ASSERT_EQ(ret, 0); + + printf("Preserving memfd of size 0x%x in session\n", MEMFD_SIZE); + ret = luo_session_preserve_fd(session_fd, fd, MEMFD_TOKEN); + VFIO_ASSERT_EQ(ret, 0); + + dma_memfd_map(device, fd); +} + static void before_kexec(int luo_fd) { struct vfio_pci_device *device; @@ -32,6 +121,27 @@ static void before_kexec(int luo_fd) ret = luo_session_preserve_fd(session_fd, device->fd, DEVICE_TOKEN); VFIO_ASSERT_EQ(ret, 0); + dma_memfd_setup(device, session_fd); + + /* + * If the device has a selftests driver, kick off a long-running DMA + * operation to exercise the device trying to DMA during a Live Update. + * Since iommufd preservation is not supported yet, these DMAs should be + * dropped. So this is just looking to verify that the system does not + * fall over and crash as a result of a busy device being preserved. + */ + if (device->driver.ops) { + vfio_pci_driver_init(device); + dma_memcpy_start(device); + + /* + * Disable interrupts on the device or freeze() will fail. + * Unfortunately there isn't a way to easily have a test for + * that here since the check happens during shutdown. + */ + vfio_pci_msix_disable(device); + } + close(luo_fd); daemonize_and_wait(); } @@ -78,6 +188,7 @@ static void after_kexec(int luo_fd, int state_session_fd) struct iommu *iommu; int session_fd; int device_fd; + int memfd; int stage; check_open_vfio_device_fails(); @@ -88,6 +199,10 @@ static void after_kexec(int luo_fd, int state_session_fd) session_fd = luo_retrieve_session(luo_fd, device_session); VFIO_ASSERT_GE(session_fd, 0); + printf("Retrieving memfd from LUO\n"); + memfd = luo_session_retrieve_fd(session_fd, MEMFD_TOKEN); + VFIO_ASSERT_GE(memfd, 0); + printf("Finishing the session before retrieving the device (should fail)\n"); VFIO_ASSERT_NE(luo_session_finish(session_fd), 0); @@ -109,9 +224,23 @@ static void after_kexec(int luo_fd, int state_session_fd) */ device = __vfio_pci_device_init(device_bdf, iommu, device_fd); + dma_memfd_map(device, memfd); + printf("Finishing the session\n"); VFIO_ASSERT_EQ(luo_session_finish(session_fd), 0); + /* + * Once iommufd preservation is supported and the device is kept fully + * running across the Live Update, this should wait for the long- + * running DMA memcpy operation kicked off in before_kexec() to + * complete. But for now we expect the device to be reset so just + * trigger a single memcpy to make sure it's still functional. + */ + if (device->driver.ops) { + vfio_pci_driver_init(device); + dma_memcpy_one(device); + } + vfio_pci_device_cleanup(device); iommu_cleanup(iommu); } -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:09 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
From: Vipin Sharma <vipinsh@google.com> Add a selftest to exercise preserving a vfio-pci device across a Live Update. For now the test is extremely simple and just verifies that the device file can be preserved and retrieved. In the future this test will be extended to verify more parts about device preservation as they are implemented. This test is added to TEST_GEN_PROGS_EXTENDED since it must be run manually along with a kexec. To run this test manually: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... # NOTE: Exact method will be distro-dependent $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 The second call to setup.sh is necessary because preserved devices are not bound to a driver after Live Update. Such devices must be manually bound by userspace after Live Update via driver_override. This test is considered passing if all commands exit with 0. Signed-off-by: Vipin Sharma <vipinsh@google.com> Co-developed-by: David Matlack <dmatlack@google.com> Signed-off-by: David Matlack <dmatlack@google.com> --- tools/testing/selftests/vfio/Makefile | 4 + .../vfio/vfio_pci_liveupdate_kexec_test.c | 89 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c diff --git a/tools/testing/selftests/vfio/Makefile b/tools/testing/selftests/vfio/Makefile index 666310872217..55d685f6e540 100644 --- a/tools/testing/selftests/vfio/Makefile +++ b/tools/testing/selftests/vfio/Makefile @@ -6,6 +6,10 @@ TEST_GEN_PROGS += vfio_pci_device_init_perf_test TEST_GEN_PROGS += vfio_pci_driver_test TEST_GEN_PROGS += vfio_pci_liveupdate_uapi_test +# This test must be run manually since it requires the user/automation to +# perform a kexec during the test. +TEST_GEN_PROGS_EXTENDED += vfio_pci_liveupdate_kexec_test + TEST_FILES += scripts/cleanup.sh TEST_FILES += scripts/lib.sh TEST_FILES += scripts/run.sh diff --git a/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c b/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c new file mode 100644 index 000000000000..15b3e3af91d1 --- /dev/null +++ b/tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: GPL-2.0-only + +#include <libliveupdate.h> +#include <libvfio.h> + +static const char *device_bdf; + +static char state_session[LIVEUPDATE_SESSION_NAME_LENGTH]; +static char device_session[LIVEUPDATE_SESSION_NAME_LENGTH]; + +enum { + STATE_TOKEN, + DEVICE_TOKEN, +}; + +static void before_kexec(int luo_fd) +{ + struct vfio_pci_device *device; + struct iommu *iommu; + int session_fd; + int ret; + + iommu = iommu_init("iommufd"); + device = vfio_pci_device_init(device_bdf, iommu); + + create_state_file(luo_fd, state_session, STATE_TOKEN, /*next_stage=*/2); + + session_fd = luo_create_session(luo_fd, device_session); + VFIO_ASSERT_GE(session_fd, 0); + + printf("Preserving device in session\n"); + ret = luo_session_preserve_fd(session_fd, device->fd, DEVICE_TOKEN); + VFIO_ASSERT_EQ(ret, 0); + + close(luo_fd); + daemonize_and_wait(); +} + +static void after_kexec(int luo_fd, int state_session_fd) +{ + struct vfio_pci_device *device; + struct iommu *iommu; + int session_fd; + int device_fd; + int stage; + + restore_and_read_stage(state_session_fd, STATE_TOKEN, &stage); + VFIO_ASSERT_EQ(stage, 2); + + session_fd = luo_retrieve_session(luo_fd, device_session); + VFIO_ASSERT_GE(session_fd, 0); + + printf("Finishing the session before retrieving the device (should fail)\n"); + VFIO_ASSERT_NE(luo_session_finish(session_fd), 0); + + printf("Retrieving the device FD from LUO\n"); + device_fd = luo_session_retrieve_fd(session_fd, DEVICE_TOKEN); + VFIO_ASSERT_GE(device_fd, 0); + + printf("Finishing the session before binding to iommufd (should fail)\n"); + VFIO_ASSERT_NE(luo_session_finish(session_fd), 0); + + printf("Binding the device to an iommufd and setting it up\n"); + iommu = iommu_init("iommufd"); + + /* + * This will invoke various ioctls on device_fd such as + * VFIO_DEVICE_GET_INFO. So this is a decent sanity test + * that LUO actually handed us back a valid VFIO device + * file and not something else. + */ + device = __vfio_pci_device_init(device_bdf, iommu, device_fd); + + printf("Finishing the session\n"); + VFIO_ASSERT_EQ(luo_session_finish(session_fd), 0); + + vfio_pci_device_cleanup(device); + iommu_cleanup(iommu); +} + +int main(int argc, char *argv[]) +{ + device_bdf = vfio_selftests_get_bdf(&argc, argv); + + sprintf(device_session, "device-%s", device_bdf); + sprintf(state_session, "state-%s", device_bdf); + + return luo_test(argc, argv, state_session, before_kexec, after_kexec); +} -- 2.53.0.rc1.225.gd81095ad13-goog
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 21:25:05 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Hi David, On Thu, 29 Jan 2026 21:24:57 +0000 David Matlack <dmatlack@google.com> wrote: Just wondering what happened to skipping the bus master clearing. I understand this version does not preserve the device itself yet; I’m just curious whether there were specific difficulties that led to dropping the earlier patch which skipped clearing bus master.
{ "author": "Jacob Pan <jacob.pan@linux.microsoft.com>", "date": "Thu, 29 Jan 2026 14:21:58 -0800", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
On 2026-01-29 02:21 PM, Jacob Pan wrote: Hi Jacob, There's several places where bus master gets cleared that we need to eventually eliminate to fully preserve the device. 1. vfio_pci_liveupdate_freeze() clears it during shutdown when it restores vdev->pci_saved_state. 2. pci_device_shutdown() clears it during shutdown. 3. vfio_pci_core_enable() clears it when the preserved device file is bound to an iommufd after the Live Update (in vfio_pci_core_enable()). I think it would be safe to skip (3) in this series, since that's very similar to how this series skips resets during vfio_pci_core_enable() for preserved devices. But I don't think it would be safe to skip (1) or (2) until the attached iommufd is fully preserved. If you are just asking about (3) then I agree it could be skipped and I can include that in the next version.
{ "author": "David Matlack <dmatlack@google.com>", "date": "Thu, 29 Jan 2026 22:33:13 +0000", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
Hi David, On Thu, 29 Jan 2026 22:33:13 +0000 David Matlack <dmatlack@google.com> wrote: I was just asking about (3) and trying to understand the asymmetric handling compared to reset. I don’t have a strong preference since this is temporary—thanks for the explanation. I’ve been testing my noiommu cdev patches on top of yours, and so far they behave the same as with a real IOMMU. As you noted, however, final device preservation still depends on iommufd.
{ "author": "Jacob Pan <jacob.pan@linux.microsoft.com>", "date": "Thu, 29 Jan 2026 16:31:50 -0800", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
在 2026/1/29 13:24, David Matlack 写道: Can the above 2 functions support the virtual devices? For example, bonding, veth, iSWAP and RXE. These virtual devices do not have BDF. As such, I am not sure if your patches take these virtual devices in to account. Thanks a lot. Zhu Yanjun -- Best Regards, Yanjun.Zhu
{ "author": "Zhu Yanjun <yanjun.zhu@linux.dev>", "date": "Sat, 31 Jan 2026 22:38:18 -0800", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 00/22] vfio/pci: Base Live Update support for VFIO device files
This series can be found on GitHub: https://github.com/dmatlack/linux/tree/liveupdate/vfio/cdev/v2 This series adds the base support to preserve a VFIO device file across a Live Update. "Base support" means that this allows userspace to safely preserve a VFIO device file with LIVEUPDATE_SESSION_PRESERVE_FD and retrieve it with LIVEUPDATE_SESSION_RETRIEVE_FD, but the device itself is not preserved in a fully running state across Live Update. This series aims to provide a foundation on which to build the rest of the device preservation infrastructure, including: - Preservation of iommufd files [1] - Preservation of IOMMU driver state - Preservation of PCI state (BAR resources, device state, bridge state, ...) - Preservation of vfio-pci driver state Testing ------- The patches at the end of this series provide comprehensive selftests for the new code added by this series. The selftests have been validated in both a VM environment using a virtio-net PCIe device, and in a baremetal environment on an Intel EMR server with an Intel DSA PCIe device. Here is an example of how to run the new selftests: vfio_pci_liveupdate_uapi_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh vfio_pci_liveupdate_kexec_test: $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 1 0000:00:04.0 $ kexec ... $ tools/testing/selftests/vfio/scripts/setup.sh 0000:00:04.0 $ tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test --stage 2 0000:00:04.0 $ tools/testing/selftests/vfio/scripts/cleanup.sh It is also possible to run vfio_pci_liveupdate_kexec_test multiple times to preserve multiple devices simultaneously across a Live Update. This series has been tested with up to 8 devices concurrently preserved. Changelog --------- v2: - Rebase on top of linux-next (tag: next-20260115) - Add missing EXPORT_SYMBOL_GPLs in LUO (Zhu) - Add Missing EXPORT_SYMBOL_GPLs for vfio_device_fops (Zhu) - Fix circular dependency between vfio-pci-core and vfio-pci (Zhu) - Handle pci=assign-busses (Lukas) - Drop driver_override patch (Jason) - Use kho_alloc_preserve(), kho_unpreserve_free(), kho_restore_free() (Pasha) - Don't access PCI FLB after device initialization (Jason) - Fix folio leak in vfio_pci_liveupdate_retrieve() (Alex) - Add Documentation (Pasha) v1: https://lore.kernel.org/kvm/20251126193608.2678510-1-dmatlack@google.com/ rfc: https://lore.kernel.org/kvm/20251018000713.677779-1-vipinsh@google.com/ Cc: Saeed Mahameed <saeedm@nvidia.com> Cc: Adithya Jayachandran <ajayachandra@nvidia.com> Cc: Jason Gunthorpe <jgg@nvidia.com> Cc: Parav Pandit <parav@nvidia.com> Cc: Leon Romanovsky <leonro@nvidia.com> Cc: William Tu <witu@nvidia.com> Cc: Jacob Pan <jacob.pan@linux.microsoft.com> Cc: Lukas Wunner <lukas@wunner.de> Cc: Pasha Tatashin <pasha.tatashin@soleen.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Pratyush Yadav <pratyush@kernel.org> Cc: Samiullah Khawaja <skhawaja@google.com> Cc: Chris Li <chrisl@kernel.org> Cc: Josh Hilke <jrhilke@google.com> Cc: David Rientjes <rientjes@google.com> [1] https://lore.kernel.org/linux-iommu/20251202230303.1017519-1-skhawaja@google.com/ David Matlack (13): liveupdate: Export symbols needed by modules PCI: Add API to track PCI devices preserved across Live Update PCI: Inherit bus numbers from previous kernel during Live Update vfio/pci: Notify PCI subsystem about devices preserved across Live Update vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD vfio/pci: Store incoming Live Update state in struct vfio_pci_core_device docs: liveupdate: Document VFIO device file preservation vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED vfio: selftests: Add vfio_pci_liveupdate_uapi_test vfio: selftests: Expose iommu_modes to tests vfio: selftests: Expose low-level helper routines for setting up struct vfio_pci_device vfio: selftests: Verify that opening VFIO device fails during Live Update vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test Vipin Sharma (9): vfio/pci: Register a file handler with Live Update Orchestrator vfio/pci: Preserve vfio-pci device files across Live Update vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Skip reset of preserved device after Live Update selftests/liveupdate: Move luo_test_utils.* into a reusable library selftests/liveupdate: Add helpers to preserve/retrieve FDs vfio: selftests: Build liveupdate library in VFIO selftests vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD vfio: selftests: Add vfio_pci_liveupdate_kexec_test Documentation/userspace-api/liveupdate.rst | 144 ++++++++++ MAINTAINERS | 1 + drivers/pci/Makefile | 1 + drivers/pci/liveupdate.c | 212 +++++++++++++++ drivers/pci/probe.c | 23 +- drivers/vfio/device_cdev.c | 25 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +- drivers/vfio/pci/vfio_pci_core.c | 24 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 246 +++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 16 ++ drivers/vfio/vfio.h | 13 - drivers/vfio/vfio_main.c | 23 +- include/linux/kho/abi/pci.h | 55 ++++ include/linux/kho/abi/vfio_pci.h | 45 +++ include/linux/pci.h | 47 ++++ include/linux/vfio.h | 58 ++++ include/linux/vfio_pci_core.h | 2 + kernel/liveupdate/luo_core.c | 1 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/liveupdate/.gitignore | 1 + tools/testing/selftests/liveupdate/Makefile | 14 +- .../include/libliveupdate.h} | 11 +- .../selftests/liveupdate/lib/libliveupdate.mk | 20 ++ .../{luo_test_utils.c => lib/liveupdate.c} | 43 ++- .../selftests/liveupdate/luo_kexec_simple.c | 2 +- .../selftests/liveupdate/luo_multi_session.c | 2 +- tools/testing/selftests/vfio/Makefile | 23 +- .../vfio/lib/include/libvfio/iommu.h | 2 + .../lib/include/libvfio/vfio_pci_device.h | 8 + tools/testing/selftests/vfio/lib/iommu.c | 4 +- .../selftests/vfio/lib/vfio_pci_device.c | 60 ++-- .../vfio/vfio_pci_liveupdate_kexec_test.c | 256 ++++++++++++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 93 +++++++ 35 files changed, 1410 insertions(+), 88 deletions(-) create mode 100644 drivers/pci/liveupdate.c create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/pci.h create mode 100644 include/linux/kho/abi/vfio_pci.h rename tools/testing/selftests/liveupdate/{luo_test_utils.h => lib/include/libliveupdate.h} (80%) create mode 100644 tools/testing/selftests/liveupdate/lib/libliveupdate.mk rename tools/testing/selftests/liveupdate/{luo_test_utils.c => lib/liveupdate.c} (89%) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c base-commit: 9b7977f9e39b7768c70c2aa497f04e7569fd3e00 -- 2.53.0.rc1.225.gd81095ad13-goog
On Sat, Jan 31, 2026 at 10:38 PM Zhu Yanjun <yanjun.zhu@linux.dev> wrote: No this patch series only supports PCI devices, since those are the only devices so far we've needed to support. I am not familiar with any of the devices that you mentioned. If they are virtual then does that mean it's all just software? In that case I would be curious to know what problem is solved by preserving them in the kernel, vs. tearing them down and rebuilding them across a Live Udpate.
{ "author": "David Matlack <dmatlack@google.com>", "date": "Mon, 2 Feb 2026 10:14:56 -0800", "thread_id": "20260129212510.967611-1-dmatlack@google.com.mbox.gz" }
lkml
[PATCH v2 net] net: phy: change devlink flag to AUTOREMOVE_SUPPLIER for non-SFP PHYs
For the shared MDIO bus use case, multiple MACs will share the same MDIO bus. Therefore, these MACs all depend on this MDIO bus. If this shared MDIO bus is removed, all the PHY devices attached to this MDIO bus will also be removed. Consequently, the MAC driver should not access the PHY device, otherwise, it will lead to some potential crashes. Because the corresponding phydev and the mii_bus have been freed, some pointers have become invalid. For example. Abhishek reported a crash issue that occurred if the MDIO bus driver was removed first, followed by the MAC driver. The crash log is as below. Call trace: __list_del_entry_valid_or_report+0xa8/0xe0 __device_link_del+0x40/0xf0 device_link_put_kref+0xb4/0xc8 device_link_del+0x38/0x58 phy_detach+0x2c/0x170 phy_disconnect+0x4c/0x70 phylink_disconnect_phy+0x6c/0xc0 [phylink] stmmac_release+0x60/0x358 [stmmac] Another example is the i.MX95-15x15 platform which has two ENETC ports. When all the external PHYs are managed the EMDIO (the MDIO controller), if the enetc driver is removed after the EMDIO driver. Users will see the below crash log and the console is hanged. Call trace: _phy_state_machine+0x230/0x36c (P) phy_stop+0x74/0x190 phylink_stop+0x28/0xb8 enetc_close+0x28/0x8c __dev_close_many+0xb4/0x1d8 netif_close_many+0x8c/0x13c enetc4_pf_remove+0x2c/0x84 pci_device_remove+0x44/0xe8 To address this issue, Sarosh Hasan tried to change the devlink flag to DL_FLAG_AUTOREMOVE_SUPPLIER [1], so that the MAC driver will be removed along with the PHY driver. However, the solution does not take into account the hot-swappable PHY devices (SFP PHYs), so when the PHY device is unplugged, the MAC driver will automatically be removed, which is not the expected behavior. This issue should not exist for SFP PHYs, so based on the Sarosh's patch, the flag is changed to DL_FLAG_AUTOREMOVE_SUPPLIER for non-SFP PHYs. Reported-by: Abhishek Chauhan (ABC) <quic_abchauha@quicinc.com> Closes: https://lore.kernel.org/all/d696a426-40bb-4c1a-b42d-990fb690de5e@quicinc.com/ Link: https://lore.kernel.org/imx/20250703090041.23137-1-quic_sarohasa@quicinc.com/ # [1] Fixes: bc66fa87d4fd ("net: phy: Add link between phy dev and mac dev") Suggested-by: Maxime Chevallier <maxime.chevallier@bootlin.com> Signed-off-by: Wei Fang <wei.fang@nxp.com> --- v2: 1. Change the subject and update the commit message 2. Based on Maxime's suggestion, only set DL_FLAG_AUTOREMOVE_SUPPLIER flag for non-SFP PHYs. v1 link: https://lore.kernel.org/imx/20260126104409.1070403-1-wei.fang@nxp.com/ --- drivers/net/phy/phy_device.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/net/phy/phy_device.c b/drivers/net/phy/phy_device.c index 81984d4ebb7c..0494ab58ceaf 100644 --- a/drivers/net/phy/phy_device.c +++ b/drivers/net/phy/phy_device.c @@ -1771,9 +1771,17 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev, * another mac interface, so we should create a device link between * phy dev and mac dev. */ - if (dev && phydev->mdio.bus->parent && dev->dev.parent != phydev->mdio.bus->parent) - phydev->devlink = device_link_add(dev->dev.parent, &phydev->mdio.dev, - DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS); + if (dev && bus->parent && dev->dev.parent != bus->parent) { + if (phy_on_sfp(phydev)) + phydev->devlink = device_link_add(dev->dev.parent, + &phydev->mdio.dev, + DL_FLAG_PM_RUNTIME | + DL_FLAG_STATELESS); + else + device_link_add(dev->dev.parent, &phydev->mdio.dev, + DL_FLAG_PM_RUNTIME | + DL_FLAG_AUTOREMOVE_SUPPLIER); + } return err; -- 2.34.1
Hi Wei, On 02/02/2026 06:45, Wei Fang wrote: I gave that patch a test, with the following cases : - On Macchiatobin (we have PHYs that share an mdiobus). When unbinding a PHY, the MAC dissapears as well : #before : # ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 2048 link/ether 00:51:82:42:42:00 brd ff:ff:ff:ff:ff:ff 3: eth1: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc mq state DOWN group default qlen 2048 link/ether 00:51:82:42:42:01 brd ff:ff:ff:ff:ff:ff 4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 2048 link/ether 00:51:82:42:42:02 brd ff:ff:ff:ff:ff:ff 5: eth3: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc mq state DOWN group default qlen 2048 link/ether 00:51:82:42:42:03 brd ff:ff:ff:ff:ff:ff echo f212a600.mdio-mii:08 > /sys/devices/platform/cp0-bus/cp0-bus:bus@f2000000/f212a600.mdio/mdio_bus/f212a600.mdio-mii/f212a600.mdio-mii:08/driver/unbind The MAC interface correctly disappears, but for some reason a lot of other interfaces dissapeared as well (only eth0 is left, where I used to have 4 different interfaces) # after : # ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 2048 link/ether 00:51:82:42:42:00 brd ff:ff:ff:ff:ff:ff - I also tested the SFP PHY setup on a Cyclone V platform, and it worked as expected (i.e. MAC didn't disappear under my feet when removing a Copper SFP, but the devlink was still created when the module was present) : # ls /sys/class/devlink/ mdio_bus:i2c:sfp:16--platform:ff702000.ethernet I don't have time to investigate why my interfaces are dissapearing on mcbin, but OTHO unbinding the devices manually isn't something I do very often... It may or may not be related to this patch. I'll let Russell and Andrew comment more on that as I may still miss other cases, but as far as I can tell, this looks OK. Tested-by: Maxime Chevallier <maxime.chevallier@bootlin.com> Reviewed-by: Maxime Chevallier <maxime.chevallier@bootlin.com> Maxime
{ "author": "Maxime Chevallier <maxime.chevallier@bootlin.com>", "date": "Mon, 2 Feb 2026 12:10:41 +0100", "thread_id": "aYDmPUN5Z-eRWW2K@shell.armlinux.org.uk.mbox.gz" }
lkml
[PATCH v2 net] net: phy: change devlink flag to AUTOREMOVE_SUPPLIER for non-SFP PHYs
For the shared MDIO bus use case, multiple MACs will share the same MDIO bus. Therefore, these MACs all depend on this MDIO bus. If this shared MDIO bus is removed, all the PHY devices attached to this MDIO bus will also be removed. Consequently, the MAC driver should not access the PHY device, otherwise, it will lead to some potential crashes. Because the corresponding phydev and the mii_bus have been freed, some pointers have become invalid. For example. Abhishek reported a crash issue that occurred if the MDIO bus driver was removed first, followed by the MAC driver. The crash log is as below. Call trace: __list_del_entry_valid_or_report+0xa8/0xe0 __device_link_del+0x40/0xf0 device_link_put_kref+0xb4/0xc8 device_link_del+0x38/0x58 phy_detach+0x2c/0x170 phy_disconnect+0x4c/0x70 phylink_disconnect_phy+0x6c/0xc0 [phylink] stmmac_release+0x60/0x358 [stmmac] Another example is the i.MX95-15x15 platform which has two ENETC ports. When all the external PHYs are managed the EMDIO (the MDIO controller), if the enetc driver is removed after the EMDIO driver. Users will see the below crash log and the console is hanged. Call trace: _phy_state_machine+0x230/0x36c (P) phy_stop+0x74/0x190 phylink_stop+0x28/0xb8 enetc_close+0x28/0x8c __dev_close_many+0xb4/0x1d8 netif_close_many+0x8c/0x13c enetc4_pf_remove+0x2c/0x84 pci_device_remove+0x44/0xe8 To address this issue, Sarosh Hasan tried to change the devlink flag to DL_FLAG_AUTOREMOVE_SUPPLIER [1], so that the MAC driver will be removed along with the PHY driver. However, the solution does not take into account the hot-swappable PHY devices (SFP PHYs), so when the PHY device is unplugged, the MAC driver will automatically be removed, which is not the expected behavior. This issue should not exist for SFP PHYs, so based on the Sarosh's patch, the flag is changed to DL_FLAG_AUTOREMOVE_SUPPLIER for non-SFP PHYs. Reported-by: Abhishek Chauhan (ABC) <quic_abchauha@quicinc.com> Closes: https://lore.kernel.org/all/d696a426-40bb-4c1a-b42d-990fb690de5e@quicinc.com/ Link: https://lore.kernel.org/imx/20250703090041.23137-1-quic_sarohasa@quicinc.com/ # [1] Fixes: bc66fa87d4fd ("net: phy: Add link between phy dev and mac dev") Suggested-by: Maxime Chevallier <maxime.chevallier@bootlin.com> Signed-off-by: Wei Fang <wei.fang@nxp.com> --- v2: 1. Change the subject and update the commit message 2. Based on Maxime's suggestion, only set DL_FLAG_AUTOREMOVE_SUPPLIER flag for non-SFP PHYs. v1 link: https://lore.kernel.org/imx/20260126104409.1070403-1-wei.fang@nxp.com/ --- drivers/net/phy/phy_device.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/net/phy/phy_device.c b/drivers/net/phy/phy_device.c index 81984d4ebb7c..0494ab58ceaf 100644 --- a/drivers/net/phy/phy_device.c +++ b/drivers/net/phy/phy_device.c @@ -1771,9 +1771,17 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev, * another mac interface, so we should create a device link between * phy dev and mac dev. */ - if (dev && phydev->mdio.bus->parent && dev->dev.parent != phydev->mdio.bus->parent) - phydev->devlink = device_link_add(dev->dev.parent, &phydev->mdio.dev, - DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS); + if (dev && bus->parent && dev->dev.parent != bus->parent) { + if (phy_on_sfp(phydev)) + phydev->devlink = device_link_add(dev->dev.parent, + &phydev->mdio.dev, + DL_FLAG_PM_RUNTIME | + DL_FLAG_STATELESS); + else + device_link_add(dev->dev.parent, &phydev->mdio.dev, + DL_FLAG_PM_RUNTIME | + DL_FLAG_AUTOREMOVE_SUPPLIER); + } return err; -- 2.34.1
On Mon, Feb 02, 2026 at 12:10:41PM +0100, Maxime Chevallier wrote: Correct, this is why these band-aids are harmful. One "device" can correspond with *multiple* network interfaces, and the loss of one PHY can have a *very* detrimental effect. Consider the case where root-NFS is being used, and removing a PHY on another interface takes out the interface that root-NFS is using. Your machine is now dead in the water. In my opinion, we should be concentrating more on the issue behind the oops. Given that this problem is because of the bus being removed, one thing that would help would be for the MDIO bus to be properly refcounted, and when the bus is unbound, to replace the bus ops with versions that return -ENXIO or similar under the MII bus lock. This would be easier of the MDIO bus ops were a separate struct to struct mii_bus. Similar with the PHY itself - if the PHY is in-use, it should be refcounted to stop the struct phy_device from going away, and should we have the situation where the PHY driver is unbound, phydev->drv should be set to a set of dummy ops (under the phydev mutex and probably rtnl.) It seems to me that throwing devlinks at this problem is giving us more problems than it's solving. A graceful way to handle a MAC losing its PHY is for phylib to indicate that the PHY has gone down, rather than removing the network interface (and potentially a whole host of other network interfaces in the case of one struct device being associated with many interfaces.) -- RMK's Patch system: https://www.armlinux.org.uk/developer/patches/ FTTP is here! 80Mbps down 10Mbps up. Decent connectivity at last!
{ "author": "\"Russell King (Oracle)\" <linux@armlinux.org.uk>", "date": "Mon, 2 Feb 2026 14:25:09 +0000", "thread_id": "aYDmPUN5Z-eRWW2K@shell.armlinux.org.uk.mbox.gz" }
lkml
[PATCH v2 net] net: phy: change devlink flag to AUTOREMOVE_SUPPLIER for non-SFP PHYs
For the shared MDIO bus use case, multiple MACs will share the same MDIO bus. Therefore, these MACs all depend on this MDIO bus. If this shared MDIO bus is removed, all the PHY devices attached to this MDIO bus will also be removed. Consequently, the MAC driver should not access the PHY device, otherwise, it will lead to some potential crashes. Because the corresponding phydev and the mii_bus have been freed, some pointers have become invalid. For example. Abhishek reported a crash issue that occurred if the MDIO bus driver was removed first, followed by the MAC driver. The crash log is as below. Call trace: __list_del_entry_valid_or_report+0xa8/0xe0 __device_link_del+0x40/0xf0 device_link_put_kref+0xb4/0xc8 device_link_del+0x38/0x58 phy_detach+0x2c/0x170 phy_disconnect+0x4c/0x70 phylink_disconnect_phy+0x6c/0xc0 [phylink] stmmac_release+0x60/0x358 [stmmac] Another example is the i.MX95-15x15 platform which has two ENETC ports. When all the external PHYs are managed the EMDIO (the MDIO controller), if the enetc driver is removed after the EMDIO driver. Users will see the below crash log and the console is hanged. Call trace: _phy_state_machine+0x230/0x36c (P) phy_stop+0x74/0x190 phylink_stop+0x28/0xb8 enetc_close+0x28/0x8c __dev_close_many+0xb4/0x1d8 netif_close_many+0x8c/0x13c enetc4_pf_remove+0x2c/0x84 pci_device_remove+0x44/0xe8 To address this issue, Sarosh Hasan tried to change the devlink flag to DL_FLAG_AUTOREMOVE_SUPPLIER [1], so that the MAC driver will be removed along with the PHY driver. However, the solution does not take into account the hot-swappable PHY devices (SFP PHYs), so when the PHY device is unplugged, the MAC driver will automatically be removed, which is not the expected behavior. This issue should not exist for SFP PHYs, so based on the Sarosh's patch, the flag is changed to DL_FLAG_AUTOREMOVE_SUPPLIER for non-SFP PHYs. Reported-by: Abhishek Chauhan (ABC) <quic_abchauha@quicinc.com> Closes: https://lore.kernel.org/all/d696a426-40bb-4c1a-b42d-990fb690de5e@quicinc.com/ Link: https://lore.kernel.org/imx/20250703090041.23137-1-quic_sarohasa@quicinc.com/ # [1] Fixes: bc66fa87d4fd ("net: phy: Add link between phy dev and mac dev") Suggested-by: Maxime Chevallier <maxime.chevallier@bootlin.com> Signed-off-by: Wei Fang <wei.fang@nxp.com> --- v2: 1. Change the subject and update the commit message 2. Based on Maxime's suggestion, only set DL_FLAG_AUTOREMOVE_SUPPLIER flag for non-SFP PHYs. v1 link: https://lore.kernel.org/imx/20260126104409.1070403-1-wei.fang@nxp.com/ --- drivers/net/phy/phy_device.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/net/phy/phy_device.c b/drivers/net/phy/phy_device.c index 81984d4ebb7c..0494ab58ceaf 100644 --- a/drivers/net/phy/phy_device.c +++ b/drivers/net/phy/phy_device.c @@ -1771,9 +1771,17 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev, * another mac interface, so we should create a device link between * phy dev and mac dev. */ - if (dev && phydev->mdio.bus->parent && dev->dev.parent != phydev->mdio.bus->parent) - phydev->devlink = device_link_add(dev->dev.parent, &phydev->mdio.dev, - DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS); + if (dev && bus->parent && dev->dev.parent != bus->parent) { + if (phy_on_sfp(phydev)) + phydev->devlink = device_link_add(dev->dev.parent, + &phydev->mdio.dev, + DL_FLAG_PM_RUNTIME | + DL_FLAG_STATELESS); + else + device_link_add(dev->dev.parent, &phydev->mdio.dev, + DL_FLAG_PM_RUNTIME | + DL_FLAG_AUTOREMOVE_SUPPLIER); + } return err; -- 2.34.1
On 02/02/2026 15:25, Russell King (Oracle) wrote: That's what I've been seeing. I unbound one PHY, it took out 3 netdevs and I don't have log regarding "why". I guess there's devlink debug knobs for that, but not enabled by default it seems. However, we seem to have the issue even without this patch. On MCBin, if I unbind eth1 for example, all 3 interfaces that are on CP1 are gone : cd /sys/class/net/eth1/device/driver echo f4000000.ethernet > unbind only eth0 is now left. This is on net-next/main :( For Wei's case where unbinding netdev 1 brings the mdio bus down, used by PHY on netdev 2, we'd be also dead in the water as well no matter what as well no ? Agreed, that's quite the can of worms though I suspect :( Maxime
{ "author": "Maxime Chevallier <maxime.chevallier@bootlin.com>", "date": "Mon, 2 Feb 2026 18:38:48 +0100", "thread_id": "aYDmPUN5Z-eRWW2K@shell.armlinux.org.uk.mbox.gz" }
lkml
[PATCH v2 net] net: phy: change devlink flag to AUTOREMOVE_SUPPLIER for non-SFP PHYs
For the shared MDIO bus use case, multiple MACs will share the same MDIO bus. Therefore, these MACs all depend on this MDIO bus. If this shared MDIO bus is removed, all the PHY devices attached to this MDIO bus will also be removed. Consequently, the MAC driver should not access the PHY device, otherwise, it will lead to some potential crashes. Because the corresponding phydev and the mii_bus have been freed, some pointers have become invalid. For example. Abhishek reported a crash issue that occurred if the MDIO bus driver was removed first, followed by the MAC driver. The crash log is as below. Call trace: __list_del_entry_valid_or_report+0xa8/0xe0 __device_link_del+0x40/0xf0 device_link_put_kref+0xb4/0xc8 device_link_del+0x38/0x58 phy_detach+0x2c/0x170 phy_disconnect+0x4c/0x70 phylink_disconnect_phy+0x6c/0xc0 [phylink] stmmac_release+0x60/0x358 [stmmac] Another example is the i.MX95-15x15 platform which has two ENETC ports. When all the external PHYs are managed the EMDIO (the MDIO controller), if the enetc driver is removed after the EMDIO driver. Users will see the below crash log and the console is hanged. Call trace: _phy_state_machine+0x230/0x36c (P) phy_stop+0x74/0x190 phylink_stop+0x28/0xb8 enetc_close+0x28/0x8c __dev_close_many+0xb4/0x1d8 netif_close_many+0x8c/0x13c enetc4_pf_remove+0x2c/0x84 pci_device_remove+0x44/0xe8 To address this issue, Sarosh Hasan tried to change the devlink flag to DL_FLAG_AUTOREMOVE_SUPPLIER [1], so that the MAC driver will be removed along with the PHY driver. However, the solution does not take into account the hot-swappable PHY devices (SFP PHYs), so when the PHY device is unplugged, the MAC driver will automatically be removed, which is not the expected behavior. This issue should not exist for SFP PHYs, so based on the Sarosh's patch, the flag is changed to DL_FLAG_AUTOREMOVE_SUPPLIER for non-SFP PHYs. Reported-by: Abhishek Chauhan (ABC) <quic_abchauha@quicinc.com> Closes: https://lore.kernel.org/all/d696a426-40bb-4c1a-b42d-990fb690de5e@quicinc.com/ Link: https://lore.kernel.org/imx/20250703090041.23137-1-quic_sarohasa@quicinc.com/ # [1] Fixes: bc66fa87d4fd ("net: phy: Add link between phy dev and mac dev") Suggested-by: Maxime Chevallier <maxime.chevallier@bootlin.com> Signed-off-by: Wei Fang <wei.fang@nxp.com> --- v2: 1. Change the subject and update the commit message 2. Based on Maxime's suggestion, only set DL_FLAG_AUTOREMOVE_SUPPLIER flag for non-SFP PHYs. v1 link: https://lore.kernel.org/imx/20260126104409.1070403-1-wei.fang@nxp.com/ --- drivers/net/phy/phy_device.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/net/phy/phy_device.c b/drivers/net/phy/phy_device.c index 81984d4ebb7c..0494ab58ceaf 100644 --- a/drivers/net/phy/phy_device.c +++ b/drivers/net/phy/phy_device.c @@ -1771,9 +1771,17 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev, * another mac interface, so we should create a device link between * phy dev and mac dev. */ - if (dev && phydev->mdio.bus->parent && dev->dev.parent != phydev->mdio.bus->parent) - phydev->devlink = device_link_add(dev->dev.parent, &phydev->mdio.dev, - DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS); + if (dev && bus->parent && dev->dev.parent != bus->parent) { + if (phy_on_sfp(phydev)) + phydev->devlink = device_link_add(dev->dev.parent, + &phydev->mdio.dev, + DL_FLAG_PM_RUNTIME | + DL_FLAG_STATELESS); + else + device_link_add(dev->dev.parent, &phydev->mdio.dev, + DL_FLAG_PM_RUNTIME | + DL_FLAG_AUTOREMOVE_SUPPLIER); + } return err; -- 2.34.1
On Mon, Feb 02, 2026 at 06:38:48PM +0100, Maxime Chevallier wrote: See what I said above. "One "device" can correspond with *multiple* network interfaces". On Armada 8040, one network "device" has multiple ports - they all share the same packet infrastructure. Each port is a separate interface in the kernel. Consequently, the "struct device" is common across all ports on one of the CP110 dies (there are two dies.) If one triggers an unbind of that struct device, then you lose *all* ports on that CP110 die whether or not the others _could_ remain functional. Consider a DSA switch, which has external PHYs connected. Should unbinding one port's PHYs take out the entire switch - and in the case of multiple switches, cause the entire switch tree to be taken out? This is why devlinks is a bad idea. It's too heavy handed for cases beyond the simple "one network device per struct device" model that doesn't exist everywhere. For simple cases, yes, maybe, but not where it means that taking out one minor part of the system destroys the entire system because it chose to unbind a multi-interface device. -- RMK's Patch system: https://www.armlinux.org.uk/developer/patches/ FTTP is here! 80Mbps down 10Mbps up. Decent connectivity at last!
{ "author": "\"Russell King (Oracle)\" <linux@armlinux.org.uk>", "date": "Mon, 2 Feb 2026 18:00:29 +0000", "thread_id": "aYDmPUN5Z-eRWW2K@shell.armlinux.org.uk.mbox.gz" }
lkml
[PATCH 0/2] Add HPET NMI Watchdog support
The current NMI watchdog relies on performance counters and consistently occupies one on each CPU. When running virtual machines, we want to pass performance counters to virtual machines so they can make use of them. In addition the host system wants to use performance counters to check the system to identify when anything looks abnormal, such as split locks. That makes PMCs a precious resource. So any PMC we can free up is a PMC we can use for something useful. That made me look at the NMI watchdog. The PMC based NMI watchdog implementation does not actually need any performance counting. It just needs a per-CPU NMI timer source. X86 systems can make anything that emits an interrupt descriptor (IOAPIC, MSI(-X), etc) become an NMI source. So any time goes. Including the HPET. And while they can't really operate per-CPU, in almost all cases you only really want the NMI on *all* CPUs, rather than per-CPU. So I took a stab at building an HPET based NMI watchdog. In my (QEMU based) testing, it's fully functional and can successfully detect when CPUs get stuck. It even survives suspend/resume cycles. For now, its enablement is a config time option because the hardlockup framework does not support dynamic switching of multiple detectors. That's ok for our use case. But maybe something for the interested reader to tackle eventually :). You can enable the HPET watchdog by default by setting CONFIG_HARDLOCKUP_DETECTOR_HPET_DEFAULT=y or passing "hpet=watchdog" to the kernel command line. When active, it will emit a kernel log message to indicate it works: [ 0.179176] hpet: HPET watchdog initialized on timer 0, GSI 2 The HPET can only be in either watchdog or generic mode. I am a bit worried about IO-APIC pin allocation logic, so I opted to reuse the generic timer pin. And that means I'm effectively breaking the normal interrupt delivery path. so the easy way out was to say when watchdog is active, PIT and HPET are not available as timer sources. Which is ok on modern systems. There are way too many (unreliable) timer sources on x86 already. Trimming a few surely won't hurt. I'm open to inputs on how to make the HPET multi-purpose though, in case anyone feels strongly about it. Alex Alexander Graf (2): x86/ioapic: Add NMI delivery configuration helper hpet: Add HPET-based NMI watchdog support .../admin-guide/kernel-parameters.txt | 5 +- arch/x86/Kconfig | 19 ++ arch/x86/include/asm/io_apic.h | 2 + arch/x86/kernel/apic/io_apic.c | 32 ++++ arch/x86/kernel/hpet.c | 172 ++++++++++++++++++ arch/x86/kernel/i8253.c | 9 + drivers/char/hpet.c | 3 + include/linux/hpet.h | 14 ++ 8 files changed, 255 insertions(+), 1 deletion(-) -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
To implement an HPET based NMI watchdog, the HPET code will need to reconfigure an IOAPIC pin to NMI mode. Add a function that allows driver code to configure an IOAPIC pin for NMI delivery mode. (Disclaimer: Some of this code was written with the help of Kiro, an AI coding assistant) Signed-off-by: Alexander Graf <graf@amazon.com> --- arch/x86/include/asm/io_apic.h | 2 ++ arch/x86/kernel/apic/io_apic.c | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/arch/x86/include/asm/io_apic.h b/arch/x86/include/asm/io_apic.h index 0d806513c4b3..58cfb338bf39 100644 --- a/arch/x86/include/asm/io_apic.h +++ b/arch/x86/include/asm/io_apic.h @@ -158,6 +158,8 @@ extern void mp_save_irq(struct mpc_intsrc *m); extern void disable_ioapic_support(void); +extern int ioapic_set_nmi(u32 gsi, bool broadcast); + extern void __init io_apic_init_mappings(void); extern unsigned int native_io_apic_read(unsigned int apic, unsigned int reg); extern void native_restore_boot_irq_mode(void); diff --git a/arch/x86/kernel/apic/io_apic.c b/arch/x86/kernel/apic/io_apic.c index 28f934f05a85..006f328929cd 100644 --- a/arch/x86/kernel/apic/io_apic.c +++ b/arch/x86/kernel/apic/io_apic.c @@ -2951,6 +2951,38 @@ int mp_irqdomain_ioapic_idx(struct irq_domain *domain) return (int)(long)domain->host_data; } +/** + * ioapic_set_nmi - Configure an IOAPIC pin for NMI delivery + * @gsi: Global System Interrupt number + * @broadcast: true to broadcast to all CPUs, false to send to CPU 0 only + * + * Configures the specified GSI for NMI delivery mode. + * + * Returns 0 on success, negative error code on failure. + */ +int ioapic_set_nmi(u32 gsi, bool broadcast) +{ + struct IO_APIC_route_entry entry = { }; + int ioapic_idx, pin; + + ioapic_idx = mp_find_ioapic(gsi); + if (ioapic_idx < 0) + return -ENODEV; + + pin = mp_find_ioapic_pin(ioapic_idx, gsi); + if (pin < 0) + return -ENODEV; + + entry.delivery_mode = APIC_DELIVERY_MODE_NMI; + entry.destid_0_7 = broadcast ? 0xFF : 0; + entry.dest_mode_logical = 0; + entry.masked = 0; + + ioapic_write_entry(ioapic_idx, pin, entry); + + return 0; +} + const struct irq_domain_ops mp_ioapic_irqdomain_ops = { .alloc = mp_irqdomain_alloc, .free = mp_irqdomain_free, -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
{ "author": "Alexander Graf <graf@amazon.com>", "date": "Mon, 2 Feb 2026 17:43:15 +0000", "thread_id": "20260202174803.66640-2-graf@amazon.com.mbox.gz" }
lkml
[PATCH 0/2] Add HPET NMI Watchdog support
The current NMI watchdog relies on performance counters and consistently occupies one on each CPU. When running virtual machines, we want to pass performance counters to virtual machines so they can make use of them. In addition the host system wants to use performance counters to check the system to identify when anything looks abnormal, such as split locks. That makes PMCs a precious resource. So any PMC we can free up is a PMC we can use for something useful. That made me look at the NMI watchdog. The PMC based NMI watchdog implementation does not actually need any performance counting. It just needs a per-CPU NMI timer source. X86 systems can make anything that emits an interrupt descriptor (IOAPIC, MSI(-X), etc) become an NMI source. So any time goes. Including the HPET. And while they can't really operate per-CPU, in almost all cases you only really want the NMI on *all* CPUs, rather than per-CPU. So I took a stab at building an HPET based NMI watchdog. In my (QEMU based) testing, it's fully functional and can successfully detect when CPUs get stuck. It even survives suspend/resume cycles. For now, its enablement is a config time option because the hardlockup framework does not support dynamic switching of multiple detectors. That's ok for our use case. But maybe something for the interested reader to tackle eventually :). You can enable the HPET watchdog by default by setting CONFIG_HARDLOCKUP_DETECTOR_HPET_DEFAULT=y or passing "hpet=watchdog" to the kernel command line. When active, it will emit a kernel log message to indicate it works: [ 0.179176] hpet: HPET watchdog initialized on timer 0, GSI 2 The HPET can only be in either watchdog or generic mode. I am a bit worried about IO-APIC pin allocation logic, so I opted to reuse the generic timer pin. And that means I'm effectively breaking the normal interrupt delivery path. so the easy way out was to say when watchdog is active, PIT and HPET are not available as timer sources. Which is ok on modern systems. There are way too many (unreliable) timer sources on x86 already. Trimming a few surely won't hurt. I'm open to inputs on how to make the HPET multi-purpose though, in case anyone feels strongly about it. Alex Alexander Graf (2): x86/ioapic: Add NMI delivery configuration helper hpet: Add HPET-based NMI watchdog support .../admin-guide/kernel-parameters.txt | 5 +- arch/x86/Kconfig | 19 ++ arch/x86/include/asm/io_apic.h | 2 + arch/x86/kernel/apic/io_apic.c | 32 ++++ arch/x86/kernel/hpet.c | 172 ++++++++++++++++++ arch/x86/kernel/i8253.c | 9 + drivers/char/hpet.c | 3 + include/linux/hpet.h | 14 ++ 8 files changed, 255 insertions(+), 1 deletion(-) -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
To implement an HPET based NMI watchdog, the HPET code will need to reconfigure an IOAPIC pin to NMI mode. Add a function that allows driver code to configure an IOAPIC pin for NMI delivery mode. The caller can choose whether to invoke NMIs on the BSP or broadcast on all CPUs in the system. (Disclaimer: Some of this code was written with the help of Kiro, an AI coding assistant) Signed-off-by: Alexander Graf <graf@amazon.com> --- arch/x86/include/asm/io_apic.h | 2 ++ arch/x86/kernel/apic/io_apic.c | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/arch/x86/include/asm/io_apic.h b/arch/x86/include/asm/io_apic.h index 0d806513c4b3..58cfb338bf39 100644 --- a/arch/x86/include/asm/io_apic.h +++ b/arch/x86/include/asm/io_apic.h @@ -158,6 +158,8 @@ extern void mp_save_irq(struct mpc_intsrc *m); extern void disable_ioapic_support(void); +extern int ioapic_set_nmi(u32 gsi, bool broadcast); + extern void __init io_apic_init_mappings(void); extern unsigned int native_io_apic_read(unsigned int apic, unsigned int reg); extern void native_restore_boot_irq_mode(void); diff --git a/arch/x86/kernel/apic/io_apic.c b/arch/x86/kernel/apic/io_apic.c index 28f934f05a85..5b303e5d2f3f 100644 --- a/arch/x86/kernel/apic/io_apic.c +++ b/arch/x86/kernel/apic/io_apic.c @@ -2951,6 +2951,38 @@ int mp_irqdomain_ioapic_idx(struct irq_domain *domain) return (int)(long)domain->host_data; } +/** + * ioapic_set_nmi - Configure an IOAPIC pin for NMI delivery + * @gsi: Global System Interrupt number + * @broadcast: true to broadcast to all CPUs, false to send to CPU 0 only + * + * Configures the specified GSI for NMI delivery mode. + * + * Returns 0 on success, negative error code on failure. + */ +int ioapic_set_nmi(u32 gsi, bool broadcast) +{ + struct IO_APIC_route_entry entry = { }; + int ioapic_idx, pin; + + ioapic_idx = mp_find_ioapic(gsi); + if (ioapic_idx < 0) + return -ENODEV; + + pin = mp_find_ioapic_pin(ioapic_idx, gsi); + if (pin < 0) + return -ENODEV; + + entry.delivery_mode = APIC_DELIVERY_MODE_NMI; + entry.destid_0_7 = broadcast ? 0xFF : boot_cpu_physical_apicid; + entry.dest_mode_logical = 0; + entry.masked = 0; + + ioapic_write_entry(ioapic_idx, pin, entry); + + return 0; +} + const struct irq_domain_ops mp_ioapic_irqdomain_ops = { .alloc = mp_irqdomain_alloc, .free = mp_irqdomain_free, -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
{ "author": "Alexander Graf <graf@amazon.com>", "date": "Mon, 2 Feb 2026 17:48:02 +0000", "thread_id": "20260202174803.66640-2-graf@amazon.com.mbox.gz" }
lkml
[PATCH 0/2] Add HPET NMI Watchdog support
The current NMI watchdog relies on performance counters and consistently occupies one on each CPU. When running virtual machines, we want to pass performance counters to virtual machines so they can make use of them. In addition the host system wants to use performance counters to check the system to identify when anything looks abnormal, such as split locks. That makes PMCs a precious resource. So any PMC we can free up is a PMC we can use for something useful. That made me look at the NMI watchdog. The PMC based NMI watchdog implementation does not actually need any performance counting. It just needs a per-CPU NMI timer source. X86 systems can make anything that emits an interrupt descriptor (IOAPIC, MSI(-X), etc) become an NMI source. So any time goes. Including the HPET. And while they can't really operate per-CPU, in almost all cases you only really want the NMI on *all* CPUs, rather than per-CPU. So I took a stab at building an HPET based NMI watchdog. In my (QEMU based) testing, it's fully functional and can successfully detect when CPUs get stuck. It even survives suspend/resume cycles. For now, its enablement is a config time option because the hardlockup framework does not support dynamic switching of multiple detectors. That's ok for our use case. But maybe something for the interested reader to tackle eventually :). You can enable the HPET watchdog by default by setting CONFIG_HARDLOCKUP_DETECTOR_HPET_DEFAULT=y or passing "hpet=watchdog" to the kernel command line. When active, it will emit a kernel log message to indicate it works: [ 0.179176] hpet: HPET watchdog initialized on timer 0, GSI 2 The HPET can only be in either watchdog or generic mode. I am a bit worried about IO-APIC pin allocation logic, so I opted to reuse the generic timer pin. And that means I'm effectively breaking the normal interrupt delivery path. so the easy way out was to say when watchdog is active, PIT and HPET are not available as timer sources. Which is ok on modern systems. There are way too many (unreliable) timer sources on x86 already. Trimming a few surely won't hurt. I'm open to inputs on how to make the HPET multi-purpose though, in case anyone feels strongly about it. Alex Alexander Graf (2): x86/ioapic: Add NMI delivery configuration helper hpet: Add HPET-based NMI watchdog support .../admin-guide/kernel-parameters.txt | 5 +- arch/x86/Kconfig | 19 ++ arch/x86/include/asm/io_apic.h | 2 + arch/x86/kernel/apic/io_apic.c | 32 ++++ arch/x86/kernel/hpet.c | 172 ++++++++++++++++++ arch/x86/kernel/i8253.c | 9 + drivers/char/hpet.c | 3 + include/linux/hpet.h | 14 ++ 8 files changed, 255 insertions(+), 1 deletion(-) -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
The traditional NMI watchdog timer uses performance counters to trigger periodic NMIs. But performance counters are a scarce resource that are best used for actual performance counting. However, the HPET is another timer source on most modern x86 systems that can inject NMI interrupts. Add support for using HPET timer as NMI watchdog source instead of performance counters. This frees up a PMC for profiling use. Unlike with the PMU based watchdog where we trigger a per-CPU NMI, APIC based interrupt descriptors can only target either a specific CPU or perform a broadcast on all CPUs. To not run into races and allow for CPU hotplug, the NMI watchdog switches between CPU 0 and broadcast modes based on whether all CPUs are up or not. The HPET watchdog always uses IO-APIC line 2. This line is architecturally defined as the PIT source on PCs and hence always available as long as we disable the PIT (which we do). We could in theory try to find a vacant GSI line, but in practice that would create a big dependency chain on ACPI which I would rather avoid for now. The implementation uses the standard HARDLOCKUP_DETECTOR_ARCH infrastructure, following the same pattern as powerpc's arch-specific hardlockup detector. With this watchdog present, I can successfully capture system lockups, verified by adding "local_irq_disable(); while(1) {}" into mount_root_generic(). (Disclaimer: Some of this code was written with the help of Kiro, an AI coding assistant) Signed-off-by: Alexander Graf <graf@amazon.com> --- .../admin-guide/kernel-parameters.txt | 5 +- arch/x86/Kconfig | 19 ++ arch/x86/kernel/hpet.c | 208 ++++++++++++++++++ arch/x86/kernel/i8253.c | 9 + drivers/char/hpet.c | 3 + include/linux/hpet.h | 14 ++ 6 files changed, 257 insertions(+), 1 deletion(-) diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 1058f2a6d6a8..c6a98812a896 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -2045,11 +2045,14 @@ Kernel parameters hpet= [X86-32,HPET] option to control HPET usage Format: { enable (default) | disable | force | - verbose } + verbose | watchdog } disable: disable HPET and use PIT instead force: allow force enabled of undocumented chips (ICH4, VIA, nVidia) verbose: show contents of HPET registers during setup + watchdog: use HPET timer as NMI watchdog source instead + of performance counters. Use nmi_watchdog=1 to enable + or nmi_watchdog=panic to panic on hard lockup detection. hpet_mmap= [X86, HPET_MMAP] Allow userspace to mmap HPET registers. Default set by CONFIG_HPET_MMAP_DEFAULT. diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig index 80527299f859..e8873218a803 100644 --- a/arch/x86/Kconfig +++ b/arch/x86/Kconfig @@ -948,6 +948,25 @@ config HPET_EMULATE_RTC def_bool y depends on HPET_TIMER && (RTC_DRV_CMOS=m || RTC_DRV_CMOS=y) +config HARDLOCKUP_DETECTOR_HPET + bool "Use HPET for NMI watchdog" + depends on HPET_TIMER + select HAVE_HARDLOCKUP_DETECTOR_ARCH + select HARDLOCKUP_DETECTOR_COUNTS_HRTIMER + help + Use HPET timer as NMI source instead of performance counters. + This frees up a performance counter for profiling. + Enable with hpet=watchdog kernel parameter. + +config HARDLOCKUP_DETECTOR_HPET_DEFAULT + bool "Enable HPET watchdog by default" + depends on HARDLOCKUP_DETECTOR_HPET + help + Say Y here to enable HPET-based NMI watchdog by default without + requiring the hpet=watchdog kernel parameter. + + If unsure, say N. + # Mark as expert because too many people got it wrong. # The code disables itself when not needed. config DMI diff --git a/arch/x86/kernel/hpet.c b/arch/x86/kernel/hpet.c index d6387dde3ff9..c9114997c383 100644 --- a/arch/x86/kernel/hpet.c +++ b/arch/x86/kernel/hpet.c @@ -6,9 +6,12 @@ #include <linux/hpet.h> #include <linux/cpu.h> #include <linux/irq.h> +#include <linux/nmi.h> +#include <linux/syscore_ops.h> #include <asm/cpuid/api.h> #include <asm/irq_remapping.h> +#include <asm/io_apic.h> #include <asm/hpet.h> #include <asm/time.h> #include <asm/mwait.h> @@ -100,6 +103,8 @@ static inline void hpet_clear_mapping(void) /* * HPET command line enable / disable */ +static bool hpet_watchdog_mode = IS_ENABLED(CONFIG_HARDLOCKUP_DETECTOR_HPET_DEFAULT); + static int __init hpet_setup(char *str) { while (str) { @@ -113,6 +118,8 @@ static int __init hpet_setup(char *str) hpet_force_user = true; if (!strncmp("verbose", str, 7)) hpet_verbose = true; + if (!strncmp("watchdog", str, 8)) + hpet_watchdog_mode = true; str = next; } return 1; @@ -985,6 +992,200 @@ static bool __init hpet_is_pc10_damaged(void) return true; } +#ifdef CONFIG_HARDLOCKUP_DETECTOR_HPET +/* + * HPET watchdog uses timer 0 routed to GSI 2 (legacy PIT IRQ line). + * When using HPET as watchdog, we repurpose this line for NMI delivery. + */ +#define HPET_WD_TIMER 0 +#define HPET_WD_GSI 2 + +bool hpet_watchdog_initialized; +static bool hpet_watchdog_ioapic_configured; +static DEFINE_PER_CPU(u32, hpet_watchdog_next_tick); + +static int hpet_nmi_handler(unsigned int cmd, struct pt_regs *regs) +{ + u32 now, next, delta; + + if (panic_in_progress()) + return NMI_HANDLED; + + /* Check if this NMI is from our HPET timer by comparing counter value */ + now = hpet_readl(HPET_COUNTER); + next = __this_cpu_read(hpet_watchdog_next_tick); + delta = hpet_freq * watchdog_thresh; + + /* + * If we have a next tick set and counter hasn't reached it yet, + * this NMI is not from our timer. Allow some tolerance for timing. + */ + if (next && (s32)(now - next) < -(s32)(delta / 4)) + return NMI_DONE; + + /* Update next expected tick */ + __this_cpu_write(hpet_watchdog_next_tick, now + delta); + + watchdog_hardlockup_check(smp_processor_id(), regs); + + return NMI_HANDLED; +} + +/* + * On suspend, clear the configured flag so that the first CPU to come + * online after resume will reconfigure the HPET timer and IO-APIC. + * + * We don't need to explicitly disable the watchdog here because: + * 1. The HPET registers are reset by the hibernation/suspend process anyway + * 2. The IO-APIC state is saved/restored by ioapic_syscore_ops, but we + * need to reconfigure it for NMI delivery after resume + * 3. Secondary CPUs are offlined before suspend, so we can't broadcast + * NMIs until they're back online - the enable callback handles this + */ +static int hpet_watchdog_suspend(void *data) +{ + hpet_watchdog_ioapic_configured = false; + return 0; +} + +static const struct syscore_ops hpet_watchdog_syscore_ops = { + .suspend = hpet_watchdog_suspend, +}; + +static struct syscore hpet_watchdog_syscore = { + .ops = &hpet_watchdog_syscore_ops, +}; + +static int __init hpet_watchdog_init(u32 channels) +{ + u32 cfg, i, route_cap; + + if (channels <= HPET_WD_TIMER) + return 0; + + /* Verify GSI 2 is available in the route capability bitmap */ + route_cap = hpet_readl(HPET_Tn_CFG(HPET_WD_TIMER) + 4); + if (!(route_cap & (1 << HPET_WD_GSI))) { + pr_info("HPET timer 0 cannot route to GSI %d\n", HPET_WD_GSI); + return 0; + } + + /* Deactivate all timers */ + for (i = 0; i < channels; i++) { + cfg = hpet_readl(HPET_Tn_CFG(i)); + cfg &= ~(HPET_TN_ENABLE | HPET_TN_LEVEL | HPET_TN_FSB); + hpet_writel(cfg, HPET_Tn_CFG(i)); + } + + /* Configure HPET timer for periodic mode */ + cfg = hpet_readl(HPET_Tn_CFG(HPET_WD_TIMER)); + cfg &= ~(HPET_TN_ENABLE | HPET_TN_FSB); + cfg |= HPET_TN_PERIODIC | HPET_TN_32BIT | HPET_TN_SETVAL | HPET_TN_LEVEL; + hpet_writel(cfg, HPET_Tn_CFG(HPET_WD_TIMER)); + + /* Route HPET timer to the GSI */ + cfg = hpet_readl(HPET_Tn_CFG(HPET_WD_TIMER)); + cfg &= ~(Tn_INT_ROUTE_CNF_MASK | HPET_CFG_ENABLE); + cfg |= (HPET_WD_GSI << Tn_INT_ROUTE_CNF_SHIFT) & Tn_INT_ROUTE_CNF_MASK; + hpet_writel(cfg, HPET_Tn_CFG(HPET_WD_TIMER)); + + if (register_nmi_handler(NMI_LOCAL, hpet_nmi_handler, 0, "hpet_watchdog")) { + pr_err("Failed to register NMI_LOCAL handler\n"); + return 0; + } + if (register_nmi_handler(NMI_UNKNOWN, hpet_nmi_handler, 0, "hpet_watchdog")) { + unregister_nmi_handler(NMI_LOCAL, "hpet_watchdog"); + pr_err("Failed to register NMI_UNKNOWN handler\n"); + return 0; + } + + hpet_start_counter(); + + hpet_watchdog_initialized = true; + + register_syscore(&hpet_watchdog_syscore); + + pr_info("HPET watchdog initialized on timer %d, GSI %d", HPET_WD_TIMER, HPET_WD_GSI); + + return 0; +} + +void watchdog_hardlockup_stop(void) +{ + u32 cfg; + + if (!hpet_watchdog_initialized) + return; + + cfg = hpet_readl(HPET_Tn_CFG(HPET_WD_TIMER)); + cfg &= ~HPET_TN_ENABLE; + hpet_writel(cfg, HPET_Tn_CFG(HPET_WD_TIMER)); +} + +void watchdog_hardlockup_start(void) +{ + u32 cfg, delta; + + if (!hpet_watchdog_initialized) + return; + + if (!hpet_watchdog_ioapic_configured) { + if (ioapic_set_nmi(HPET_WD_GSI, false)) { + pr_err("Unable to configure IO-APIC for NMI\n"); + return; + } + hpet_watchdog_ioapic_configured = true; + } + + delta = hpet_freq * watchdog_thresh; + + cfg = hpet_readl(HPET_Tn_CFG(HPET_WD_TIMER)); + cfg &= ~(HPET_TN_ENABLE | HPET_TN_FSB | HPET_TN_LEVEL); + cfg |= HPET_TN_PERIODIC | HPET_TN_32BIT | HPET_TN_SETVAL; + hpet_writel(cfg, HPET_Tn_CFG(HPET_WD_TIMER)); + + /* Write twice for AMD 81xx with buggy HPET */ + hpet_writel(delta, HPET_Tn_CMP(HPET_WD_TIMER)); + hpet_writel(delta, HPET_Tn_CMP(HPET_WD_TIMER)); + + cfg |= HPET_TN_ENABLE; + hpet_writel(cfg, HPET_Tn_CFG(HPET_WD_TIMER)); +} + +void watchdog_hardlockup_enable(unsigned int cpu) +{ + if (!hpet_watchdog_ioapic_configured) { + /* + * First CPU online after resume - reconfigure HPET timer. + * This also sets hpet_watchdog_ioapic_configured = true. + */ + watchdog_hardlockup_start(); + } + + if (num_online_cpus() == num_present_cpus()) { + ioapic_set_nmi(HPET_WD_GSI, true); + pr_info("switched to broadcast mode (all %d CPUs online)\n", + num_online_cpus()); + } +} + +void watchdog_hardlockup_disable(unsigned int cpu) +{ + if (num_online_cpus() < num_present_cpus()) { + ioapic_set_nmi(HPET_WD_GSI, false); + pr_info("switched to CPU 0 only (%d CPUs online)\n", + num_online_cpus() - 1); + } +} + +int __init watchdog_hardlockup_probe(void) +{ + return hpet_watchdog_mode ? 0 : -ENODEV; +} +#else +static inline int hpet_watchdog_init(u32 channels) { return 0; } +#endif /* CONFIG_HARDLOCKUP_DETECTOR_HPET */ + /** * hpet_enable - Try to setup the HPET timer. Returns 1 on success. */ @@ -1031,6 +1232,10 @@ int __init hpet_enable(void) /* This is the HPET channel number which is zero based */ channels = ((id & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT) + 1; + /* If watchdog mode, hand off to watchdog driver */ + if (hpet_watchdog_mode) + return hpet_watchdog_init(channels); + /* * The legacy routing mode needs at least two channels, tick timer * and the rtc emulation channel. @@ -1122,6 +1327,9 @@ static __init int hpet_late_init(void) { int ret; + if (hpet_is_watchdog()) + return -ENODEV; + if (!hpet_address) { if (!force_hpet_address) return -ENODEV; diff --git a/arch/x86/kernel/i8253.c b/arch/x86/kernel/i8253.c index cb9852ad6098..36dd948371a4 100644 --- a/arch/x86/kernel/i8253.c +++ b/arch/x86/kernel/i8253.c @@ -7,6 +7,7 @@ #include <linux/init.h> #include <linux/timex.h> #include <linux/i8253.h> +#include <linux/hpet.h> #include <asm/hypervisor.h> #include <asm/apic.h> @@ -31,6 +32,14 @@ struct clock_event_device *global_clock_event; */ static bool __init use_pit(void) { + if (hpet_is_watchdog()) { + /* + * The PIT overlaps the HPET IRQ line which we configure to + * NMI in watchdog mode, rendering the PIT non functional. + */ + return false; + } + if (!IS_ENABLED(CONFIG_X86_TSC) || !boot_cpu_has(X86_FEATURE_TSC)) return true; diff --git a/drivers/char/hpet.c b/drivers/char/hpet.c index 4f5ccd3a1f56..9d9e4d22ab7f 100644 --- a/drivers/char/hpet.c +++ b/drivers/char/hpet.c @@ -977,6 +977,9 @@ static int hpet_acpi_add(struct acpi_device *device) acpi_status result; struct hpet_data data; + if (hpet_is_watchdog()) + return -ENODEV; + memset(&data, 0, sizeof(data)); result = diff --git a/include/linux/hpet.h b/include/linux/hpet.h index 21e69eaf7a36..408b440163cc 100644 --- a/include/linux/hpet.h +++ b/include/linux/hpet.h @@ -108,4 +108,18 @@ static inline void hpet_reserve_timer(struct hpet_data *hd, int timer) int hpet_alloc(struct hpet_data *); +#ifdef CONFIG_HARDLOCKUP_DETECTOR_HPET +extern bool hpet_watchdog_initialized; + +static inline bool hpet_is_watchdog(void) +{ + return hpet_watchdog_initialized; +} +#else +static inline bool hpet_is_watchdog(void) +{ + return false; +} +#endif + #endif /* !__HPET__ */ -- 2.47.1 Amazon Web Services Development Center Germany GmbH Tamara-Danz-Str. 13 10243 Berlin Geschaeftsfuehrung: Christof Hellmis, Andreas Stieger Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B Sitz: Berlin Ust-ID: DE 365 538 597
{ "author": "Alexander Graf <graf@amazon.com>", "date": "Mon, 2 Feb 2026 17:48:03 +0000", "thread_id": "20260202174803.66640-2-graf@amazon.com.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
The index value is already a copy of the maple state so there is no need to set it again. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 9ab42821ee2dc..1e780427c04a0 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -2766,7 +2766,7 @@ static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, b_node.b_end++; /* Stop spanning searches by searching for just index. */ - mast->orig_l->index = mast->orig_l->last = mas->index; + mast->orig_l->last = mas->index; mast->bn = &b_node; /* Combine l_mas and r_mas and split them up evenly again. */ -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:09 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Use RCU_INIT_POINTER to initialize an rcu pointer to an initial value since there are no readers within the tree being created during duplication. There is no risk of readers seeing the initialized or uninitialized value until after the synchronization call in mas_dup_buld(). Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 5aa4c95000188..0e0158ee7ba55 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -6260,8 +6260,15 @@ static inline void mas_dup_alloc(struct ma_state *mas, struct ma_state *new_mas, for (i = 0; i < count; i++) { val = (unsigned long)mt_slot_locked(mas->tree, slots, i); val &= MAPLE_NODE_MASK; - new_slots[i] = ma_mnode_ptr((unsigned long)mas_pop_node(mas) | - val); + /* + * Warning, see rcu_assign_pointer() documentation. Since this + * is a duplication of a tree, there are no readers walking the + * tree until after the rcu_assign_pointer() call in + * mas_dup_build(). + */ + RCU_INIT_POINTER(new_slots[i], + ma_mnode_ptr((unsigned long)mas_pop_node(mas) | + val)); } } -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:06 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Height is not used locally in the function, so call the height argument closer to where it is passed in the next level. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index afa39bbd687c0..91d3fb7ac39c5 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -2750,10 +2750,10 @@ static void mas_spanning_rebalance(struct ma_state *mas, static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, - struct maple_subtree_state *mast, unsigned char height, - struct ma_wr_state *wr_mas) + struct maple_subtree_state *mast, struct ma_wr_state *wr_mas) { struct maple_big_node b_node; + unsigned char height; MA_STATE(l_mas, mas->tree, mas->index, mas->index); MA_STATE(r_mas, mas->tree, mas->index, mas->last); MA_STATE(m_mas, mas->tree, mas->index, mas->index); @@ -2788,6 +2788,7 @@ static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, unlikely(mast->bn->b_end <= mt_min_slots[mast->bn->type])) mast_spanning_rebalance(mast); + height = mas_mt_height(mas) + 1; mas_spanning_rebalance_loop(mas, mast, height); } /* @@ -3448,7 +3449,6 @@ static void mas_wr_spanning_store(struct ma_wr_state *wr_mas) { struct maple_subtree_state mast; struct ma_state *mas; - unsigned char height; /* Left and Right side of spanning store */ MA_STATE(l_mas, NULL, 0, 0); @@ -3476,7 +3476,6 @@ static void mas_wr_spanning_store(struct ma_wr_state *wr_mas) * Node rebalancing may occur due to this store, so there may be three new * entries per level plus a new root. */ - height = mas_mt_height(mas); /* * Set up right side. Need to get to the next offset after the spanning @@ -3509,7 +3508,7 @@ static void mas_wr_spanning_store(struct ma_wr_state *wr_mas) l_mas = *mas; mast.orig_l = &l_mas; mast.orig_r = &r_mas; - mas_wr_spanning_rebalance(mas, &mast, height + 1, wr_mas); + mas_wr_spanning_rebalance(mas, &mast, wr_mas); } /* -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:13 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Move the loop over the tree levels to its own function. No intended functional changes. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 108 +++++++++++++++++++++++++---------------------- 1 file changed, 58 insertions(+), 50 deletions(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 0e0158ee7ba55..70ad474e6ed14 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -2595,49 +2595,16 @@ static inline void *mtree_range_walk(struct ma_state *mas) return NULL; } -/* - * mas_spanning_rebalance() - Rebalance across two nodes which may not be peers. - * @mas: The starting maple state - * @mast: The maple_subtree_state, keeps track of 4 maple states. - * @count: The estimated count of iterations needed. - * - * Follow the tree upwards from @l_mas and @r_mas for @count, or until the root - * is hit. First @b_node is split into two entries which are inserted into the - * next iteration of the loop. @b_node is returned populated with the final - * iteration. @mas is used to obtain allocations. orig_l_mas keeps track of the - * nodes that will remain active by using orig_l_mas->index and orig_l_mas->last - * to account of what has been copied into the new sub-tree. The update of - * orig_l_mas->last is used in mas_consume to find the slots that will need to - * be either freed or destroyed. orig_l_mas->depth keeps track of the height of - * the new sub-tree in case the sub-tree becomes the full tree. - */ -static void mas_spanning_rebalance(struct ma_state *mas, +static void mas_spanning_rebalance_loop(struct ma_state *mas, struct maple_subtree_state *mast, unsigned char count) { + unsigned char split, mid_split; unsigned char slot = 0; unsigned char new_height = 0; /* used if node is a new root */ struct maple_enode *left = NULL, *middle = NULL, *right = NULL; struct maple_enode *old_enode; - MA_STATE(l_mas, mas->tree, mas->index, mas->index); - MA_STATE(r_mas, mas->tree, mas->index, mas->last); - MA_STATE(m_mas, mas->tree, mas->index, mas->index); - - /* - * The tree needs to be rebalanced and leaves need to be kept at the same level. - * Rebalancing is done by use of the ``struct maple_topiary``. - */ - mast->l = &l_mas; - mast->m = &m_mas; - mast->r = &r_mas; - l_mas.status = r_mas.status = m_mas.status = ma_none; - - /* Check if this is not root and has sufficient data. */ - if (((mast->orig_l->min != 0) || (mast->orig_r->max != ULONG_MAX)) && - unlikely(mast->bn->b_end <= mt_min_slots[mast->bn->type])) - mast_spanning_rebalance(mast); - /* * Each level of the tree is examined and balanced, pushing data to the left or * right, or rebalancing against left or right nodes is employed to avoid @@ -2672,10 +2639,10 @@ static void mas_spanning_rebalance(struct ma_state *mas, mast_ascend(mast); mast_combine_cp_left(mast); - l_mas.offset = mast->bn->b_end; - mab_set_b_end(mast->bn, &l_mas, left); - mab_set_b_end(mast->bn, &m_mas, middle); - mab_set_b_end(mast->bn, &r_mas, right); + mast->l->offset = mast->bn->b_end; + mab_set_b_end(mast->bn, mast->l, left); + mab_set_b_end(mast->bn, mast->m, middle); + mab_set_b_end(mast->bn, mast->r, right); /* Copy anything necessary out of the right node. */ mast_combine_cp_right(mast); @@ -2708,17 +2675,17 @@ static void mas_spanning_rebalance(struct ma_state *mas, count++; } - l_mas.node = mt_mk_node(ma_mnode_ptr(mas_pop_node(mas)), + mast->l->node = mt_mk_node(ma_mnode_ptr(mas_pop_node(mas)), mte_node_type(mast->orig_l->node)); - mab_mas_cp(mast->bn, 0, mt_slots[mast->bn->type] - 1, &l_mas, true); + mab_mas_cp(mast->bn, 0, mt_slots[mast->bn->type] - 1, mast->l, true); new_height++; - mas_set_parent(mas, left, l_mas.node, slot); + mas_set_parent(mas, left, mast->l->node, slot); if (middle) - mas_set_parent(mas, middle, l_mas.node, ++slot); + mas_set_parent(mas, middle, mast->l->node, ++slot); if (right) - mas_set_parent(mas, right, l_mas.node, ++slot); + mas_set_parent(mas, right, mast->l->node, ++slot); if (mas_is_root_limits(mast->l)) { new_root: @@ -2726,20 +2693,61 @@ static void mas_spanning_rebalance(struct ma_state *mas, while (!mte_is_root(mast->orig_l->node)) mast_ascend(mast); } else { - mas_mn(&l_mas)->parent = mas_mn(mast->orig_l)->parent; + mas_mn(mast->l)->parent = mas_mn(mast->orig_l)->parent; } old_enode = mast->orig_l->node; - mas->depth = l_mas.depth; - mas->node = l_mas.node; - mas->min = l_mas.min; - mas->max = l_mas.max; - mas->offset = l_mas.offset; + mas->depth = mast->l->depth; + mas->node = mast->l->node; + mas->min = mast->l->min; + mas->max = mast->l->max; + mas->offset = mast->l->offset; mas_wmb_replace(mas, old_enode, new_height); mtree_range_walk(mas); return; } +/* + * mas_spanning_rebalance() - Rebalance across two nodes which may not be peers. + * @mas: The starting maple state + * @mast: The maple_subtree_state, keeps track of 4 maple states. + * @count: The estimated count of iterations needed. + * + * Follow the tree upwards from @l_mas and @r_mas for @count, or until the root + * is hit. First @b_node is split into two entries which are inserted into the + * next iteration of the loop. @b_node is returned populated with the final + * iteration. @mas is used to obtain allocations. orig_l_mas keeps track of the + * nodes that will remain active by using orig_l_mas->index and orig_l_mas->last + * to account of what has been copied into the new sub-tree. The update of + * orig_l_mas->last is used in mas_consume to find the slots that will need to + * be either freed or destroyed. orig_l_mas->depth keeps track of the height of + * the new sub-tree in case the sub-tree becomes the full tree. + */ +static void mas_spanning_rebalance(struct ma_state *mas, + struct maple_subtree_state *mast, unsigned char count) +{ + + MA_STATE(l_mas, mas->tree, mas->index, mas->index); + MA_STATE(r_mas, mas->tree, mas->index, mas->last); + MA_STATE(m_mas, mas->tree, mas->index, mas->index); + + /* + * The tree needs to be rebalanced and leaves need to be kept at the same level. + * Rebalancing is done by use of the ``struct maple_topiary``. + */ + mast->l = &l_mas; + mast->m = &m_mas; + mast->r = &r_mas; + l_mas.status = r_mas.status = m_mas.status = ma_none; + + /* Check if this is not root and has sufficient data. */ + if (((mast->orig_l->min != 0) || (mast->orig_r->max != ULONG_MAX)) && + unlikely(mast->bn->b_end <= mt_min_slots[mast->bn->type])) + mast_spanning_rebalance(mast); + + mas_spanning_rebalance_loop(mas, mast, count); +} + /* * mas_rebalance() - Rebalance a given node. * @mas: The maple state -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:07 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Copy the contents of mas_spanning_rebalance() into mas_wr_spanning_rebalance(), in preparation of removing initial big node use. No functional changes intended. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 1e780427c04a0..fb14ce4a49c3c 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -2754,6 +2754,9 @@ static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, struct ma_wr_state *l_wr_mas) { struct maple_big_node b_node; + MA_STATE(l_mas, mas->tree, mas->index, mas->index); + MA_STATE(r_mas, mas->tree, mas->index, mas->last); + MA_STATE(m_mas, mas->tree, mas->index, mas->index); memset(&b_node, 0, sizeof(struct maple_big_node)); /* Copy l_mas and store the value in b_node. */ @@ -2770,7 +2773,22 @@ static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, mast->bn = &b_node; /* Combine l_mas and r_mas and split them up evenly again. */ - return mas_spanning_rebalance(mas, mast, height); + + /* + * The tree needs to be rebalanced and leaves need to be kept at the same level. + * Rebalancing is done by use of the ``struct maple_topiary``. + */ + mast->l = &l_mas; + mast->m = &m_mas; + mast->r = &r_mas; + l_mas.status = r_mas.status = m_mas.status = ma_none; + + /* Check if this is not root and has sufficient data. */ + if (((mast->orig_l->min != 0) || (mast->orig_r->max != ULONG_MAX)) && + unlikely(mast->bn->b_end <= mt_min_slots[mast->bn->type])) + mast_spanning_rebalance(mast); + + mas_spanning_rebalance_loop(mas, mast, height); } /* * mas_rebalance() - Rebalance a given node. -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:10 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Isolate big node to use in its own function. No functional changes intended. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 44 ++++++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 70ad474e6ed14..9ab42821ee2dc 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -2748,6 +2748,30 @@ static void mas_spanning_rebalance(struct ma_state *mas, mas_spanning_rebalance_loop(mas, mast, count); } + +static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, + struct maple_subtree_state *mast, unsigned char height, + struct ma_wr_state *l_wr_mas) +{ + struct maple_big_node b_node; + + memset(&b_node, 0, sizeof(struct maple_big_node)); + /* Copy l_mas and store the value in b_node. */ + mas_store_b_node(l_wr_mas, &b_node, mast->orig_l->end); + /* Copy r_mas into b_node if there is anything to copy. */ + if (mast->orig_r->max > mast->orig_r->last) + mas_mab_cp(mast->orig_r, mast->orig_r->offset, + mast->orig_r->end, &b_node, b_node.b_end + 1); + else + b_node.b_end++; + + /* Stop spanning searches by searching for just index. */ + mast->orig_l->index = mast->orig_l->last = mas->index; + + mast->bn = &b_node; + /* Combine l_mas and r_mas and split them up evenly again. */ + return mas_spanning_rebalance(mas, mast, height); +} /* * mas_rebalance() - Rebalance a given node. * @mas: The maple state @@ -3400,10 +3424,9 @@ static inline void mas_new_root(struct ma_state *mas, void *entry) * span. * @wr_mas: The maple write state */ -static noinline void mas_wr_spanning_store(struct ma_wr_state *wr_mas) +static void mas_wr_spanning_store(struct ma_wr_state *wr_mas) { struct maple_subtree_state mast; - struct maple_big_node b_node; struct ma_state *mas; unsigned char height; @@ -3467,24 +3490,9 @@ static noinline void mas_wr_spanning_store(struct ma_wr_state *wr_mas) return mas_new_root(mas, wr_mas->entry); } - memset(&b_node, 0, sizeof(struct maple_big_node)); - /* Copy l_mas and store the value in b_node. */ - mas_store_b_node(&l_wr_mas, &b_node, l_mas.end); - /* Copy r_mas into b_node if there is anything to copy. */ - if (r_mas.max > r_mas.last) - mas_mab_cp(&r_mas, r_mas.offset, r_mas.end, - &b_node, b_node.b_end + 1); - else - b_node.b_end++; - - /* Stop spanning searches by searching for just index. */ - l_mas.index = l_mas.last = mas->index; - - mast.bn = &b_node; mast.orig_l = &l_mas; mast.orig_r = &r_mas; - /* Combine l_mas and r_mas and split them up evenly again. */ - return mas_spanning_rebalance(mas, &mast, height + 1); + mas_wr_spanning_rebalance(mas, &mast, height + 1, &l_wr_mas); } /* -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:08 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Moving the maple_subtree_state is necessary for future cleanups and is only set up in mas_wr_spanning_rebalance() but never used. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 91d3fb7ac39c5..c5bb341da5e9d 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -2750,46 +2750,52 @@ static void mas_spanning_rebalance(struct ma_state *mas, static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, - struct maple_subtree_state *mast, struct ma_wr_state *wr_mas) + struct ma_wr_state *wr_mas, struct ma_wr_state *r_wr_mas) { + struct maple_subtree_state mast; struct maple_big_node b_node; unsigned char height; MA_STATE(l_mas, mas->tree, mas->index, mas->index); MA_STATE(r_mas, mas->tree, mas->index, mas->last); MA_STATE(m_mas, mas->tree, mas->index, mas->index); + MA_STATE(mast_l_mas, NULL, 0, 0); + + mast_l_mas = *mas; + mast.orig_l = &mast_l_mas; + mast.orig_r = r_wr_mas->mas; memset(&b_node, 0, sizeof(struct maple_big_node)); /* Copy l_mas and store the value in b_node. */ - mas_store_b_node(wr_mas, &b_node, mast->orig_l->end); + mas_store_b_node(wr_mas, &b_node, mast.orig_l->end); /* Copy r_mas into b_node if there is anything to copy. */ - if (mast->orig_r->max > mast->orig_r->last) - mas_mab_cp(mast->orig_r, mast->orig_r->offset, - mast->orig_r->end, &b_node, b_node.b_end + 1); + if (mast.orig_r->max > mast.orig_r->last) + mas_mab_cp(mast.orig_r, mast.orig_r->offset, + mast.orig_r->end, &b_node, b_node.b_end + 1); else b_node.b_end++; /* Stop spanning searches by searching for just index. */ - mast->orig_l->last = mas->index; + mast.orig_l->last = mas->index; - mast->bn = &b_node; + mast.bn = &b_node; /* Combine l_mas and r_mas and split them up evenly again. */ /* * The tree needs to be rebalanced and leaves need to be kept at the same level. * Rebalancing is done by use of the ``struct maple_topiary``. */ - mast->l = &l_mas; - mast->m = &m_mas; - mast->r = &r_mas; + mast.l = &l_mas; + mast.m = &m_mas; + mast.r = &r_mas; l_mas.status = r_mas.status = m_mas.status = ma_none; /* Check if this is not root and has sufficient data. */ - if (((mast->orig_l->min != 0) || (mast->orig_r->max != ULONG_MAX)) && - unlikely(mast->bn->b_end <= mt_min_slots[mast->bn->type])) - mast_spanning_rebalance(mast); + if (((mast.orig_l->min != 0) || (mast.orig_r->max != ULONG_MAX)) && + unlikely(mast.bn->b_end <= mt_min_slots[mast.bn->type])) + mast_spanning_rebalance(&mast); height = mas_mt_height(mas) + 1; - mas_spanning_rebalance_loop(mas, mast, height); + mas_spanning_rebalance_loop(mas, &mast, height); } /* * mas_rebalance() - Rebalance a given node. @@ -3447,11 +3453,9 @@ static inline void mas_new_root(struct ma_state *mas, void *entry) */ static void mas_wr_spanning_store(struct ma_wr_state *wr_mas) { - struct maple_subtree_state mast; struct ma_state *mas; /* Left and Right side of spanning store */ - MA_STATE(l_mas, NULL, 0, 0); MA_STATE(r_mas, NULL, 0, 0); MA_WR_STATE(r_wr_mas, &r_mas, wr_mas->entry); @@ -3505,10 +3509,7 @@ static void mas_wr_spanning_store(struct ma_wr_state *wr_mas) return mas_new_root(mas, wr_mas->entry); } - l_mas = *mas; - mast.orig_l = &l_mas; - mast.orig_r = &r_mas; - mas_wr_spanning_rebalance(mas, &mast, wr_mas); + mas_wr_spanning_rebalance(mas, wr_mas, &r_wr_mas); } /* -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:14 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
The end_piv will be needed in the next patch set and has not been set correctly in this code path. Correct the oversight before using it. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index c5bb341da5e9d..caac936bd8d40 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -3494,6 +3494,7 @@ static void mas_wr_spanning_store(struct ma_wr_state *wr_mas) r_mas.index = r_mas.last; mas_wr_walk_index(&r_wr_mas); r_mas.last = r_mas.index = mas->last; + r_wr_mas.end_piv = r_wr_mas.r_max; /* Set up left side. */ mas_wr_walk_index(wr_mas); -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:15 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Just copy the code and replace count with height. This is done to avoid affecting other code paths into mas_spanning_rebalance_loop() for the next change. No functional change intended. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 108 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 107 insertions(+), 1 deletion(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 554fdffd6c5b9..a9b7e398c7dbd 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -2862,6 +2862,13 @@ static void mas_spanning_rebalance(struct ma_state *mas, static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, struct ma_wr_state *l_wr_mas, struct ma_wr_state *r_wr_mas) { + + unsigned char split, mid_split; + unsigned char slot = 0; + unsigned char new_height = 0; /* used if node is a new root */ + struct maple_enode *left = NULL, *middle = NULL, *right = NULL; + struct maple_enode *old_enode; + struct maple_subtree_state mast; struct maple_big_node b_node; struct maple_copy cp; @@ -2917,7 +2924,106 @@ static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, mast_spanning_rebalance(&mast); height = mas_mt_height(mas) + 1; - mas_spanning_rebalance_loop(mas, &mast, height); + + /* + * Each level of the tree is examined and balanced, pushing data to the left or + * right, or rebalancing against left or right nodes is employed to avoid + * rippling up the tree to limit the amount of churn. Once a new sub-section of + * the tree is created, there may be a mix of new and old nodes. The old nodes + * will have the incorrect parent pointers and currently be in two trees: the + * original tree and the partially new tree. To remedy the parent pointers in + * the old tree, the new data is swapped into the active tree and a walk down + * the tree is performed and the parent pointers are updated. + * See mas_topiary_replace() for more information. + */ + while (height--) { + mast.bn->b_end--; + mast.bn->type = mte_node_type(mast.orig_l->node); + split = mas_mab_to_node(mas, mast.bn, &left, &right, &middle, + &mid_split); + mast_set_split_parents(&mast, left, middle, right, split, + mid_split); + mast_cp_to_nodes(&mast, left, middle, right, split, mid_split); + new_height++; + + /* + * Copy data from next level in the tree to mast.bn from next + * iteration + */ + memset(mast.bn, 0, sizeof(struct maple_big_node)); + mast.bn->type = mte_node_type(left); + + /* Root already stored in l->node. */ + if (mas_is_root_limits(mast.l)) + goto new_root; + + mast_ascend(&mast); + mast_combine_cp_left(&mast); + mast.l->offset = mast.bn->b_end; + mab_set_b_end(mast.bn, mast.l, left); + mab_set_b_end(mast.bn, mast.m, middle); + mab_set_b_end(mast.bn, mast.r, right); + + /* Copy anything necessary out of the right node. */ + mast_combine_cp_right(&mast); + mast.orig_l->last = mast.orig_l->max; + + if (mast_sufficient(&mast)) { + if (mast_overflow(&mast)) + continue; + + if (mast.orig_l->node == mast.orig_r->node) { + /* + * The data in b_node should be stored in one + * node and in the tree + */ + slot = mast.l->offset; + break; + } + + continue; + } + + /* May be a new root stored in mast.bn */ + if (mas_is_root_limits(mast.orig_l)) + break; + + mast_spanning_rebalance(&mast); + + /* rebalancing from other nodes may require another loop. */ + if (!height) + height++; + } + + mast.l->node = mt_mk_node(ma_mnode_ptr(mas_pop_node(mas)), + mte_node_type(mast.orig_l->node)); + + mab_mas_cp(mast.bn, 0, mt_slots[mast.bn->type] - 1, mast.l, true); + new_height++; + mas_set_parent(mas, left, mast.l->node, slot); + if (middle) + mas_set_parent(mas, middle, mast.l->node, ++slot); + + if (right) + mas_set_parent(mas, right, mast.l->node, ++slot); + + if (mas_is_root_limits(mast.l)) { +new_root: + mas_mn(mast.l)->parent = ma_parent_ptr(mas_tree_parent(mas)); + while (!mte_is_root(mast.orig_l->node)) + mast_ascend(&mast); + } else { + mas_mn(mast.l)->parent = mas_mn(mast.orig_l)->parent; + } + + old_enode = mast.orig_l->node; + mas->depth = mast.l->depth; + mas->node = mast.l->node; + mas->min = mast.l->min; + mas->max = mast.l->max; + mas->offset = mast.l->offset; + mas_wmb_replace(mas, old_enode, new_height); + mtree_range_walk(mas); } /* * mas_rebalance() - Rebalance a given node. -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:18 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Introduce an internal-memory only node type called maple_copy to facilitate internal copy operations. Use it in mas_spanning_rebalance() for just the leaf nodes. Initially, the maple_copy node is used to configure the source nodes and copy the data into the big_node. The maple_copy contains a list of source entries with start and end offsets. One of the maple_copy entries can be itself with an offset of 0 to 2, representing the data where the store partially overwrites entries, or fully overwrites the entry. The side effect is that the source nodes no longer have to worry about partially copying the existing offset if it is not fully overwritten. This is in preparation of removal of the maple big_node, but for the time being the data is copied to the big node to limit the change size. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- include/linux/maple_tree.h | 26 +++++++ lib/maple_tree.c | 140 ++++++++++++++++++++++++++++++++++--- 2 files changed, 157 insertions(+), 9 deletions(-) diff --git a/include/linux/maple_tree.h b/include/linux/maple_tree.h index 7b8aad47121e7..9bc7fa89bc2ee 100644 --- a/include/linux/maple_tree.h +++ b/include/linux/maple_tree.h @@ -139,6 +139,7 @@ enum maple_type { maple_leaf_64, maple_range_64, maple_arange_64, + maple_copy, }; enum store_type { @@ -154,6 +155,30 @@ enum store_type { wr_slot_store, }; +struct maple_copy { + struct { + struct maple_node *node; + unsigned long max; + unsigned char start; + unsigned char end; + enum maple_type mt; + } src[4]; + /* Simulated node */ + void __rcu *slot[3]; + unsigned long min; + union { + unsigned long pivot[3]; + struct { + void *_pad[2]; + unsigned long max; + }; + }; + unsigned char end; + + /*Avoid passing these around */ + unsigned char s_count; +}; + /** * DOC: Maple tree flags * @@ -299,6 +324,7 @@ struct maple_node { }; struct maple_range_64 mr64; struct maple_arange_64 ma64; + struct maple_copy cp; }; }; diff --git a/lib/maple_tree.c b/lib/maple_tree.c index caac936bd8d40..554fdffd6c5b9 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -605,6 +605,8 @@ static inline unsigned long *ma_pivots(struct maple_node *node, case maple_range_64: case maple_leaf_64: return node->mr64.pivot; + case maple_copy: + return node->cp.pivot; case maple_dense: return NULL; } @@ -624,6 +626,7 @@ static inline unsigned long *ma_gaps(struct maple_node *node, switch (type) { case maple_arange_64: return node->ma64.gap; + case maple_copy: case maple_range_64: case maple_leaf_64: case maple_dense: @@ -690,6 +693,7 @@ static inline void mte_set_pivot(struct maple_enode *mn, unsigned char piv, case maple_arange_64: node->ma64.pivot[piv] = val; break; + case maple_copy: case maple_dense: break; } @@ -711,6 +715,8 @@ static inline void __rcu **ma_slots(struct maple_node *mn, enum maple_type mt) case maple_range_64: case maple_leaf_64: return mn->mr64.slot; + case maple_copy: + return mn->cp.slot; case maple_dense: return mn->slot; } @@ -2595,6 +2601,110 @@ static inline void *mtree_range_walk(struct ma_state *mas) return NULL; } +/* + * cp_leaf_init() - Initialize a maple_copy node for the leaf level of a + * spanning store + * @cp: The maple copy node + * @mas: The maple state + * @l_wr_mas: The left write state of the spanning store + * @r_wr_mas: The right write state of the spanning store + */ +static inline void cp_leaf_init(struct maple_copy *cp, + struct ma_state *mas, struct ma_wr_state *l_wr_mas, + struct ma_wr_state *r_wr_mas) +{ + unsigned char end = 0; + + /* + * WARNING: The use of RCU_INIT_POINTER() makes it extremely important + * to not expose the maple_copy node to any readers. Exposure may + * result in buggy code when a compiler reorders the instructions. + */ + + /* Create entries to insert including split entries to left and right */ + if (l_wr_mas->r_min < mas->index) { + end++; + RCU_INIT_POINTER(cp->slot[0], l_wr_mas->content); + cp->pivot[0] = mas->index - 1; + } + RCU_INIT_POINTER(cp->slot[end], l_wr_mas->entry); + cp->pivot[end] = mas->last; + + if (r_wr_mas->end_piv > mas->last) { + end++; + RCU_INIT_POINTER(cp->slot[end], + r_wr_mas->slots[r_wr_mas->offset_end]); + cp->pivot[end] = r_wr_mas->end_piv; + } + + cp->min = l_wr_mas->r_min; + cp->max = cp->pivot[end]; + cp->end = end; +} + +static inline void append_wr_mas_cp(struct maple_copy *cp, + struct ma_wr_state *wr_mas, unsigned char start, unsigned char end) +{ + unsigned char count; + + count = cp->s_count; + cp->src[count].node = wr_mas->node; + cp->src[count].mt = wr_mas->type; + if (wr_mas->mas->end <= end) + cp->src[count].max = wr_mas->mas->max; + else + cp->src[count].max = wr_mas->pivots[end]; + + cp->src[count].start = start; + cp->src[count].end = end; + cp->s_count++; +} + +static inline void init_cp_src(struct maple_copy *cp) +{ + cp->src[cp->s_count].node = ma_mnode_ptr(cp); + cp->src[cp->s_count].mt = maple_copy; + cp->src[cp->s_count].max = cp->max; + cp->src[cp->s_count].start = 0; + cp->src[cp->s_count].end = cp->end; + cp->s_count++; +} + +static inline +void cp_data_write(struct maple_copy *cp, struct maple_big_node *b_node) +{ + struct maple_node *src; + unsigned char s; + unsigned char src_end, s_offset; + unsigned long *b_pivots, *cp_pivots; + void __rcu **b_slots, **cp_slots; + enum maple_type s_mt; + + b_node->b_end = 0; + + s = 0; + b_pivots = b_node->pivot; + b_slots = (void __rcu **)b_node->slot; + do { + unsigned char size; + + src = cp->src[s].node; + s_mt = cp->src[s].mt; + s_offset = cp->src[s].start; + src_end = cp->src[s].end; + size = src_end - s_offset + 1; + cp_pivots = ma_pivots(src, s_mt) + s_offset; + cp_slots = ma_slots(src, s_mt) + s_offset; + memcpy(b_slots, cp_slots, size * sizeof(void __rcu *)); + if (size > 1) + memcpy(b_pivots, cp_pivots, (size - 1) * sizeof(unsigned long)); + b_pivots[size - 1] = cp->src[s].max; + b_pivots += size; + b_slots += size; + b_node->b_end += size; + } while (++s < cp->s_count); +} + static void mas_spanning_rebalance_loop(struct ma_state *mas, struct maple_subtree_state *mast, unsigned char count) { @@ -2750,10 +2860,11 @@ static void mas_spanning_rebalance(struct ma_state *mas, static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, - struct ma_wr_state *wr_mas, struct ma_wr_state *r_wr_mas) + struct ma_wr_state *l_wr_mas, struct ma_wr_state *r_wr_mas) { struct maple_subtree_state mast; struct maple_big_node b_node; + struct maple_copy cp; unsigned char height; MA_STATE(l_mas, mas->tree, mas->index, mas->index); MA_STATE(r_mas, mas->tree, mas->index, mas->last); @@ -2765,15 +2876,26 @@ static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, mast.orig_l = &mast_l_mas; mast.orig_r = r_wr_mas->mas; memset(&b_node, 0, sizeof(struct maple_big_node)); - /* Copy l_mas and store the value in b_node. */ - mas_store_b_node(wr_mas, &b_node, mast.orig_l->end); - /* Copy r_mas into b_node if there is anything to copy. */ - if (mast.orig_r->max > mast.orig_r->last) - mas_mab_cp(mast.orig_r, mast.orig_r->offset, - mast.orig_r->end, &b_node, b_node.b_end + 1); - else - b_node.b_end++; + cp.s_count = 0; + cp_leaf_init(&cp, mas, l_wr_mas, r_wr_mas); + /* Copy left 0 - offset */ + if (l_wr_mas->mas->offset) { + unsigned char off = l_wr_mas->mas->offset - 1; + + append_wr_mas_cp(&cp, l_wr_mas, 0, off); + cp.src[cp.s_count - 1].max = cp.min - 1; + } + + init_cp_src(&cp); + + /* Copy right from offset_end + 1 to end */ + if (r_wr_mas->mas->end != r_wr_mas->offset_end) + append_wr_mas_cp(&cp, r_wr_mas, r_wr_mas->offset_end + 1, + r_wr_mas->mas->end); + + b_node.type = l_wr_mas->type; + cp_data_write(&cp, &b_node); /* Stop spanning searches by searching for just index. */ mast.orig_l->last = mas->index; -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:16 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Now that the spanning rebalance is small, fully inline it in mas_wr_spanning_store(). No functional change. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 38 +++++++++++++++----------------------- 1 file changed, 15 insertions(+), 23 deletions(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index e0929bf0cfa1a..a10f71620e732 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -3407,28 +3407,6 @@ static bool spanning_ascend(struct maple_copy *cp, struct ma_state *mas, return true; } -static noinline void mas_wr_spanning_rebalance(struct ma_state *mas, - struct ma_wr_state *l_wr_mas, struct ma_wr_state *r_wr_mas) -{ - - struct maple_enode *old_enode; - struct maple_copy cp; - struct ma_state sib; - - cp_leaf_init(&cp, mas, l_wr_mas, r_wr_mas); - do { - spanning_data(&cp, l_wr_mas, r_wr_mas, &sib); - multi_src_setup(&cp, l_wr_mas, r_wr_mas, &sib); - dst_setup(&cp, mas, l_wr_mas->type); - cp_data_write(&cp, mas); - } while (spanning_ascend(&cp, mas, l_wr_mas, r_wr_mas, &sib)); - - old_enode = mas->node; - mas->node = mt_slot_locked(mas->tree, cp.slot, 0); - mas_wmb_replace(mas, old_enode, cp.height); - mtree_range_walk(mas); -} - /* * mas_rebalance() - Rebalance a given node. * @mas: The maple state @@ -4085,7 +4063,10 @@ static inline void mas_new_root(struct ma_state *mas, void *entry) */ static void mas_wr_spanning_store(struct ma_wr_state *wr_mas) { + struct maple_enode *old_enode; + struct maple_copy cp; struct ma_state *mas; + struct ma_state sib; /* Left and Right side of spanning store */ MA_STATE(r_mas, NULL, 0, 0); @@ -4142,7 +4123,18 @@ static void mas_wr_spanning_store(struct ma_wr_state *wr_mas) return mas_new_root(mas, wr_mas->entry); } - mas_wr_spanning_rebalance(mas, wr_mas, &r_wr_mas); + cp_leaf_init(&cp, mas, wr_mas, &r_wr_mas); + do { + spanning_data(&cp, wr_mas, &r_wr_mas, &sib); + multi_src_setup(&cp, wr_mas, &r_wr_mas, &sib); + dst_setup(&cp, mas, wr_mas->type); + cp_data_write(&cp, mas); + } while (spanning_ascend(&cp, mas, wr_mas, &r_wr_mas, &sib)); + + old_enode = mas->node; + mas->node = mt_slot_locked(mas->tree, cp.slot, 0); + mas_wmb_replace(mas, old_enode, cp.height); + mtree_range_walk(mas); } /* -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:23 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }
lkml
[PATCH v3 00/30] maple_tree: Replace big node with maple copy
The big node struct was created for simplicity of splitting, rebalancing, and spanning store operations by using a copy buffer to create the data necessary prior to breaking it up into 256B nodes. Certain operations were rather tricky due to the restriction of keeping NULL entries together and never at the end of a node (except the right-most node). The big node struct is incompatible with future features that are currently in development. Specifically different node types and different data type sizes for pivots. The big node struct was also a stack variable, which caused issues with certain configurations of kernel build. This series removes big node by introducing another node type which will never be written to the tree: maple_copy. The maple copy node operates more like a scatter/gather operation with a number of sources and destinations of allocated nodes. The sources are copied to the destinations, in turn, until the sources are exhausted. The destination is changed if it is filled or the split location is reached prior to the source data end. New data is inserted by using the maple copy node itself as a source with up to 3 slots and pivots. The data in the maple copy node is the data being written to the tree along with any fragment of the range(s) being overwritten. As with all nodes, the maple copy node is of size 256B. Using a node type allows for the copy operation to treat the new data stored in the maple copy node the same as any other source node. Analysis of the runtime shows no regression or benefit of removing the larger stack structure. The motivation is the ground work to use new node types and to help those with odd configurations that have had issues. The change was tested by myself using mm_tests on amd64 and by Suren on android (arm64). Limited testing on s390 qemu was also performed using stress-ng on the virtual memory, which should cover many corner cases. v1: https://lore.kernel.org/all/20260115193647.1695937-1-Liam.Howlett@oracle.com/ v2: https://lore.kernel.org/all/20260121164526.2093265-1-Liam.Howlett@oracle.com/ Changes since v2: - Whitespace fix in rebalance_data() - Added ma_init_slot() for cleaner casting during RCU_INIT_POINTER(). Thanks test robot & SK [1] - Fixed off-by-one in rebalance_data() which caused node overuse, reported by linux-next. Thanks Mark [2] - Added new patch to reproducer to test cases in userspace testing for the rebalance_data() off-by-one [1]. https://lore.kernel.org/all/20260122055516.69335-1-sj@kernel.org/ [2]. https://lore.kernel.org/all/bd1c3356-11a1-4d0b-bf58-47eb21bfd24d@sirena.org.uk/ Liam R. Howlett (30): maple_tree: Fix mas_dup_alloc() sparse warning maple_tree: Move mas_spanning_rebalance loop to function maple_tree: Extract use of big node from mas_wr_spanning_store() maple_tree: Remove unnecessary assignment of orig_l index maple_tree: inline mas_spanning_rebalance() into mas_wr_spanning_rebalance() maple_tree: Make ma_wr_states reliable for reuse in spanning store maple_tree: Remove l_wr_mas from mas_wr_spanning_rebalance maple_tree: Don't pass through height in mas_wr_spanning_store maple_tree: Move maple_subtree_state from mas_wr_spanning_store to mas_wr_spanning_rebalance maple_tree: Correct right ma_wr_state end pivot in mas_wr_spanning_store() maple_tree: Introduce maple_copy node and use it in mas_spanning_rebalance() maple_tree: Testing update for spanning store maple_tree: Inline mas_spanning_rebalance_loop() into mas_wr_spanning_rebalance() maple_tree: Change initial big node setup in mas_wr_spanning_rebalance() maple_tree: Introduce ma_leaf_max_gap() maple_tree: Add gap support, slot and pivot sizes for maple copy maple_tree: Start using maple copy node for destination maple_tree: inline mas_wr_spanning_rebalance() maple_tree: Remove unnecessary return statements maple_tree: Separate wr_split_store and wr_rebalance store type code path maple_tree: Add cp_is_new_root() helper maple_tree: Use maple copy node for mas_wr_rebalance() operation maple_tree: Add test for rebalance calculation off-by-one maple_tree: Add copy_tree_location() helper maple_tree: Add cp_converged() helper maple_tree: Use maple copy node for mas_wr_split() maple_tree: Remove maple big node and subtree structs maple_tree: Pass maple copy node to mas_wmb_replace() maple_tree: Don't pass end to mas_wr_append() maple_tree: Clean up mas_wr_node_store() include/linux/maple_tree.h | 42 + lib/maple_tree.c | 2134 +++++++++++++----------------- lib/test_maple_tree.c | 55 +- tools/testing/radix-tree/maple.c | 308 ++++- 4 files changed, 1340 insertions(+), 1199 deletions(-) -- 2.47.3
Add a helper to do what is needed when the maple copy node contains a new root node. This is useful for future commits and is self-documenting code. Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com> --- lib/maple_tree.c | 70 ++++++++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 5280fa6d2d6ec..42038e42a4c7e 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -3337,6 +3337,43 @@ static void mas_spanning_rebalance(struct ma_state *mas, mas_spanning_rebalance_loop(mas, mast, count); } +static inline bool cp_is_new_root(struct maple_copy *cp, struct ma_state *mas) +{ + if (cp->min || cp->max != ULONG_MAX) + return false; + + if (cp->d_count != 1) { + enum maple_type mt = maple_arange_64; + + if (!mt_is_alloc(mas->tree)) + mt = maple_range_64; + + cp->data = cp->d_count; + cp->s_count = 0; + dst_setup(cp, mas, mt); + init_cp_src(cp); + node_copy(mas, cp->src[0].node, 0, cp->data, cp->max, maple_copy, + cp->dst[0].node, 0, mt); + node_finalise(cp->dst[0].node, mt, cp->end + 1); + /* + * Warning, see cp_leaf_init() comment and rcu_assign_pointer() + * documentation. Since this is a new root, there are no + * read-side operations that can view it until it is insert into + * the tree after an rcu_assign_pointer() call. + */ + RCU_INIT_POINTER(cp->slot[0], mt_mk_node(cp->dst[0].node, mt)); + cp->height++; + } + WARN_ON_ONCE(cp->dst[0].node != mte_to_node( + mt_slot_locked(mas->tree, cp->slot, 0))); + cp->dst[0].node->parent = ma_parent_ptr(mas_tree_parent(mas)); + mas->min = 0; + mas->max = ULONG_MAX; + mas->depth = 0; + mas->node = mas_root_locked(mas); + return true; +} + /* * spanning_ascend() - See if a spanning store operation has to keep walking up * the tree @@ -3359,39 +3396,8 @@ static bool spanning_ascend(struct maple_copy *cp, struct ma_state *mas, } cp_dst_to_slots(cp, l_wr_mas->mas->min, r_wr_mas->mas->max, mas); - if (!cp->min && cp->max == ULONG_MAX) { - /* New root */ - if (cp->d_count != 1) { - enum maple_type mt = maple_arange_64; - - if (!mt_is_alloc(mas->tree)) - mt = maple_range_64; - - cp->data = cp->d_count; - cp->s_count = 0; - dst_setup(cp, mas, mt); - init_cp_src(cp); - node_copy(mas, cp->src[0].node, 0, cp->data, cp->max, maple_copy, - cp->dst[0].node, 0, mt); - node_finalise(cp->dst[0].node, mt, cp->end + 1); - /* - * Warning, see cp_leaf_init() comment and rcu_assign_pointer() - * documentation. Since this is a new root, there are no - * read-side operations that can view it until it is insert into - * the tree after an rcu_assign_pointer() call. - */ - ma_init_slot(&cp->slot[0], cp->dst[0].node, mt); - cp->height++; - } - WARN_ON_ONCE(cp->dst[0].node != mte_to_node( - mt_slot_locked(mas->tree, cp->slot, 0))); - cp->dst[0].node->parent = ma_parent_ptr(mas_tree_parent(mas)); - mas->min = 0; - mas->max = ULONG_MAX; - mas->depth = 0; - mas->node = mas_root_locked(mas); + if (cp_is_new_root(cp, mas)) return false; - } /* Converged and has a single destination */ if ((cp->d_count == 1) && -- 2.47.3
{ "author": "\"Liam R. Howlett\" <Liam.Howlett@oracle.com>", "date": "Fri, 30 Jan 2026 15:59:26 -0500", "thread_id": "20260202103154.ad1aa05611c79d21b070a861@linux-foundation.org.mbox.gz" }