VFIO PCI Live Update (noiommu mode)
Subsystems (9)
v6 cover VFIO PCI Live Update (noiommu mode)
This series adds a fully working Live Update support for vfio-pci devices in noiommu mode, using the Live Update Orchestrator (LUO) and Kexec HandOver (KHO).
This series can also be found on GitHub:
https://github.com/shvipin/linux/tree/vfio/liveupdate/v6
Unlike v5, which reset the device in freeze() and required userspace to re-initialize it after kexec, v6 keeps a preserved device running across the kexec: it is not reset, bus mastering and memory decode stay enabled, it stays in D0, and in-flight DMA continues into preserved memory (e.g. a LUO-preserved shmem memfd). In the new kernel, userspace retrieves the device FD from its LUO session and takes over the running device without resetting it on the first VFIO_DEVICE_BIND_IOMMUFD.
Preserving IOMMU-backed devices is refused with -EOPNOTSUPP until LUO can preserve IOMMU state; group/container FDs and unbound cdev FDs are refused with -ENOENT.
This series is built on top of PCI Live Update series version v10:
https://lore.kernel.org/linux-pci/[email protected]/
Design
======
- Preserve: only a bound noiommu vfio-pci cdev FD can be preserved (no VFs, Intel display devices, or zdev). The device is registered with PCI Live Update and its pre-open struct pci_saved_state is serialized into a versioned KHO buffer ("vfio-pci-v1").
- Freeze/unfreeze: freeze() requires interrupts to be disabled, the device to be in D0, and SR-IOV to be disabled (VFs are not preserved). It snapshots vconfig and pci_config_map, and masks physical INTx while leaving bus mastering enabled. If the kexec is aborted, unfreeze() restores INTx and the existing FD keeps working.
- Early protection in the new kernel: an incoming device is kept out of runtime D3, sibling dev_set resets are blocked, and opening it via its cdev or VFIO_GROUP_GET_DEVICE_FD fails with -EBUSY until the session is finished. If the new kernel is not in noiommu mode, bus mastering is cleared at registration.
- Retrieve and take-over: LIVEUPDATE_SESSION_RETRIEVE_FD validates the serialized state against the hardware and returns an unbound cdev FD. The first VFIO_DEVICE_BIND_IOMMUFD takes over the device without clearing bus mastering, resetting, or re-saving its state, restores the preserved vconfig, and keeps the original saved state so that normal reset/restore applies when the FD is closed.
- Unclaimed devices: if the session is finished or closed without taking over the device (not retrieved, retrieved but not bound, unbound, or driverless), the kernel logs one pci_warn(), resets the device, and restores its pre-Live-Update state.
- DMA memory ordering: a running device keeps DMAing until it is taken over or reset, so its DMA memory must stay pinned until then. LUO finishes files in LIFO order, so userspace must preserve the DMA memory (e.g. a memfd) in the same session and before the device. This is documented in Documentation/driver-api/vfio_pci_liveupdate.rst.
Testing
=======
- QEMU with an emulated igb device in noiommu mode, across real kexec reboots: vfio_pci_liveupdate_uapi_test and vfio_pci_liveupdate_kexec_test (opens fail with -EBUSY, memfd stays at the same physical addresses, pre-kexec DMA completes after take-over, and new DMA works without re-init).
- Physical Intel hosts with DSA (8086:0b25), across real kexec
reboots: vfio_pci_liveupdate_kexec_test with DMA started just before the kexec (opens fail with -EBUSY, memfd stays at the same physical addresses, pre-kexec DMA completes correctly after take-over, and new DMA works without re-init).
$ ./setup.sh 0000:6a:01.0 $ ./vfio_pci_liveupdate_kexec_test -s 1 0000:6a:01.0 $ kexec --reuse-cmdline -l -s /boot/vmlinuz $ kexec -e $ ./setup.sh 0000:6a:01.0 $ ./vfio_pci_liveupdate_kexec_test -s 2 0000:6a:01.0
AI disclosure
=============
New and reworked patches were developed with LLM assistance. Assisted-by is not needed now in linux kernel but I thought I should at least disclose this in cover letter.
v6:
- Keep noiommu devices running across kexec and take them over without reset, instead of resetting them in freeze().
- Restrict preservation to bound noiommu cdev FDs.
- Add PCI helpers to serialize and restore struct pci_saved_state.
- Add unfreeze() and close races between freeze() and ioctl/config access. Refuse freeze() while SR-IOV is enabled, and refuse enabling SR-IOV on a frozen device.
- Protect incoming devices in the new kernel until they finish Live Update; reset unclaimed devices in finish() with a single pci_warn(). retrieve() and finish() look the device up under the device lock, so they never act on a device that vfio-pci is still probing.
- Fix vfio_pci_liveupdate_init() error handling to avoid a double unregister at module exit (reported by Sashiko on v5).
- Drop "vfio/pci: Export vfio_pci_dma_buf_move for vfio-pci module", "vfio: selftests: Expose iommu_modes to tests", and exports that were only needed by the v5 reset path.
- Update the VFIO PCI and PCI Live Update documentation.
- Selftests: add an iommufd noiommu mode, IOVA == PA mapping helpers, 2MB THP memfd helpers, an attach() driver op (igb, DSA), and a kexec test with DMA running across the Live Update.
v5: https://lore.kernel.org/kvm/[email protected]/
v4: https://lore.kernel.org/kvm/[email protected]/
v3: https://lore.kernel.org/kvm/[email protected]/
v2: https://lore.kernel.org/kvm/[email protected]/
v1: https://lore.kernel.org/kvm/[email protected]/
rfc: https://lore.kernel.org/kvm/[email protected]/
David Matlack (4):
vfio: Enforce preserved devices are retrieved via
LIVEUPDATE_SESSION_RETRIEVE_FD
docs: liveupdate: Add documentation for VFIO PCI
vfio: selftests: Add vfio_pci_liveupdate_uapi_test
vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED
Vipin Sharma (23):
vfio/pci: Factor out the reset logic in VFIO PCI device close path
vfio: Export various helpers from VFIO
liveupdate: Export symbols needed by modules
vfio/pci: Register a file handler with Live Update Orchestrator
PCI: liveupdate: Add helpers to preserve struct pci_saved_state
vfio: Add helpers to identify device files that can be preserved vfio/pci: Preserve vfio-pci device files across Live Update
vfio: Introduce vfio_find_device() helper
vfio: Refactor vfio_device_fops_cdev_open()
vfio: Add API to open cdev device for Live Update restore vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Protect incoming preserved devices until they finish Live
Update
vfio/pci: Take over preserved devices without resetting them
vfio: selftests: Build liveupdate library in VFIO selftests
vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD
vfio: selftests: Add iommufd noiommu mode
vfio: selftests: Add helpers to map DMA memory at IOVA == PA in
noiommu mode
vfio: selftests: Add helpers for Live Update DMA memory and sysfs
state
vfio: selftests: Add an attach() driver op
vfio: selftests: Test preserving noiommu devices in
vfio_pci_liveupdate_uapi_test
vfio: selftests: Add vfio_pci_liveupdate_kexec_test
vfio: selftests: Verify that opening VFIO device fails during Live
Update
vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test
Documentation/PCI/liveupdate.rst | 3 + Documentation/core-api/liveupdate.rst | 1 + .../driver-api/vfio_pci_liveupdate.rst | 25 + MAINTAINERS | 2 + drivers/pci/liveupdate.c | 223 ++++++ drivers/pci/pci.c | 5 - drivers/pci/pci.h | 6 + drivers/vfio/device_cdev.c | 87 +- drivers/vfio/group.c | 9 + drivers/vfio/pci/Kconfig | 11 + drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 14 +- drivers/vfio/pci/vfio_pci_config.c | 19 +- drivers/vfio/pci/vfio_pci_core.c | 348 ++++++-- drivers/vfio/pci/vfio_pci_intrs.c | 4 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 745 ++++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 177 +++++ drivers/vfio/vfio.h | 28 +- drivers/vfio/vfio_main.c | 85 +- include/linux/kho/abi/pci.h | 47 ++ include/linux/kho/abi/vfio_pci.h | 76 ++ include/linux/pci_liveupdate.h | 7 + include/linux/vfio.h | 19 + include/linux/vfio_pci_core.h | 11 + kernel/liveupdate/luo_file.c | 2 + tools/testing/selftests/vfio/Makefile | 23 +- .../selftests/vfio/lib/drivers/dsa/dsa.c | 35 +- .../selftests/vfio/lib/drivers/igb/igb.c | 39 +- .../selftests/vfio/lib/include/libvfio.h | 3 + .../vfio/lib/include/libvfio/iommu.h | 43 + .../vfio/lib/include/libvfio/sysfs.h | 1 + .../lib/include/libvfio/vfio_pci_device.h | 10 + .../lib/include/libvfio/vfio_pci_driver.h | 17 + tools/testing/selftests/vfio/lib/iommu.c | 70 +- tools/testing/selftests/vfio/lib/libvfio.c | 54 ++ tools/testing/selftests/vfio/lib/sysfs.c | 22 +- .../selftests/vfio/lib/vfio_pci_device.c | 56 +- .../selftests/vfio/lib/vfio_pci_driver.c | 22 +- .../vfio/vfio_pci_liveupdate_kexec_test.c | 388 +++++++++ .../vfio/vfio_pci_liveupdate_uapi_test.c | 227 ++++++ 40 files changed, 2826 insertions(+), 139 deletions(-) create mode 100644 Documentation/driver-api/vfio_pci_liveupdate.rst create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/vfio_pci.h 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: 312200e9211ede3f9a03cc17d094805e06e4674e
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 1/27 vfio/pci: Factor out the reset logic in VFIO PCI device close path
vfio_pci_core_disable() is a very long function doing multiple things like exiting runtime power management, setting device to D0 power, clearing bus master, clearing irqs, freeing eventfds, releasing device regions, unmapping PCI bars, and performing device/bus resets.
The upcoming VFIO Liveupdate feature will also need to utilize same reset logic.
Extract device reset code to a new helper function, vfio_pci_core_try_reset(), and update vfio_pci_core_disable() to use this new function.
No functional change intended.
--- drivers/vfio/pci/vfio_pci_core.c | 100 ++++++++++++++++--------------- 1 file changed, 53 insertions(+), 47 deletions(-)
drivers/vfio/pci/vfio_pci_core.c +53 -47
@@ -680,9 +680,60 @@ int vfio_pci_core_enable(struct vfio_pci_core_device *vdev) }EXPORT_SYMBOL_GPL (vfio_pci_core_enable); -void vfio_pci_core_disable (struct vfio_pci_core_device *vdev) +static void vfio_pci_core_try_reset (struct vfio_pci_core_device *vdev) { +struct pci_dev *pdev = vdev->pdev;struct pci_dev *bridge; + + vdev->needs_reset = true; + +/* +* If we have saved state, restore it. If we can reset the device, +* even better. Resetting with current state seems better than +* nothing, but saving and restoring current state without reset +* is just busy work. +*/ +if (pci_load_and_free_saved_state (pdev, &vdev->pci_saved_state)) { +pci_info (pdev,"%s: Couldn't reload saved state\n" , __func__); + +if (!vdev->reset_works) +return ; + +pci_save_state (pdev); + } + +/* +* Disable INTx and MSI, presumably to avoid spurious interrupts +* during reset. Stolen from pci_reset_function() +*/ +pci_write_config_word (pdev,PCI_COMMAND ,PCI_COMMAND_INTX_DISABLE ); + +/* +* Try to get the locks ourselves to prevent a deadlock. The +* success of this is dependent on being able to lock the device, +* which is not always possible. +* We can not use the "try" reset interface here, which will +* overwrite the previously restored configuration information. +*/ +if (vdev->reset_works) { + bridge =pci_upstream_bridge (pdev); +if (bridge && !pci_dev_trylock (bridge)) + goto out_restore_state; +if (pci_dev_trylock (pdev)) { +if (!__pci_reset_function_locked (pdev)) + vdev->needs_reset = false; +pci_dev_unlock (pdev); + } +if (bridge) +pci_dev_unlock (bridge); + } + +out_restore_state: +pci_restore_state (pdev); +} + +void vfio_pci_core_disable (struct vfio_pci_core_device *vdev) +{struct pci_dev *pdev = vdev->pdev;struct vfio_pci_dummy_resource *dummy_res, *tmp;struct vfio_pci_ioeventfd *ioeventfd, *ioeventfd_tmp;
@@ -757,54 +808,9 @@ void vfio_pci_core_disable(struct vfio_pci_core_device *vdev)kfree (dummy_res); } - vdev->needs_reset = true; -vfio_pci_zdev_close_device (vdev); -/* -* If we have saved state, restore it. If we can reset the device, -* even better. Resetting with current state seems better than -* nothing, but saving and restoring current state without reset -* is just busy work. -*/ -if (pci_load_and_free_saved_state (pdev, &vdev->pci_saved_state)) { -pci_info (pdev,"%s: Couldn't reload saved state\n" , __func__); - -if (!vdev->reset_works) - goto out; - -pci_save_state (pdev); - } - -/* -* Disable INTx and MSI, presumably to avoid spurious interrupts -* during reset. Stolen from pci_reset_function() -*/ -pci_write_config_word (pdev,PCI_COMMAND ,PCI_COMMAND_INTX_DISABLE ); - -/* -* Try to get the locks ourselves to prevent a deadlock. The -* success of this is dependent on being able to lock the device, -* which is not always possible. -* We can not use the "try" reset interface here, which will -* overwrite the previously restored configuration information. -*/ -if (vdev->reset_works) { - bridge =pci_upstream_bridge (pdev); -if (bridge && !pci_dev_trylock (bridge)) - goto out_restore_state; -if (pci_dev_trylock (pdev)) { -if (!__pci_reset_function_locked (pdev)) - vdev->needs_reset = false; -pci_dev_unlock (pdev); - } -if (bridge) -pci_dev_unlock (bridge); - } - -out_restore_state: -pci_restore_state (pdev); -out: +vfio_pci_core_try_reset (vdev);pci_disable_device (pdev);vfio_pci_dev_set_try_reset (vdev->vdev.dev_set);
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 2/27 vfio: Export various helpers from VFIO
In reply to Vipin SharmaThe upcoming VFIO live update feature needs to access various helper functions for its logic which are not exported by default.
Export vfio_device_from_file() for other modules to use it, and make vfio_pci_ops non-static so it can be accessed within the vfio-pci module. Remove static from their declarations and add them in include/linux/vfio.h and drivers/vfio/pci/vfio_pci_priv.h header files.
No functional change intended.
--- drivers/vfio/pci/vfio_pci.c | 2 +- drivers/vfio/pci/vfio_pci_priv.h | 2 ++ drivers/vfio/vfio_main.c | 3 ++- include/linux/vfio.h | 1 + 4 files changed, 6 insertions(+), 2 deletions(-)
drivers/vfio/pci/vfio_pci.c +1 -1
@@ -146,7 +146,7 @@ static int vfio_pci_init_dev(struct vfio_device *core_vdev)return vfio_pci_core_init_dev (core_vdev); } -static const struct vfio_device_ops vfio_pci_ops = { +const struct vfio_device_ops vfio_pci_ops = { .name ="vfio-pci" , .init = vfio_pci_init_dev, .release = vfio_pci_core_release_dev,
drivers/vfio/pci/vfio_pci_priv.h +2 -0
@@ -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;
drivers/vfio/vfio_main.c +2 -1
@@ -1497,7 +1497,7 @@ const struct file_operations vfio_device_fops = {#endif }; -static struct vfio_device *vfio_device_from_file (struct file *file) +struct vfio_device *vfio_device_from_file (struct file *file) {struct vfio_device_file *df = file->private_data;
@@ -1505,6 +1505,7 @@ static struct vfio_device *vfio_device_from_file(struct file *file)return NULL ;return df->device; } +EXPORT_SYMBOL_GPL (vfio_device_from_file);/** * vfio_file_is_valid - True if the file is valid vfio file
include/linux/vfio.h +1 -0
@@ -379,6 +379,7 @@ static inline bool vfio_file_has_dev(struct file *file, struct vfio_device *devibool vfio_file_is_valid (struct file *file);bool vfio_file_enforced_coherent (struct file *file);void vfio_file_set_kvm (struct file *file,struct kvm *kvm); +struct vfio_device *vfio_device_from_file (struct file *file);#define VFIO_PIN_PAGES_MAX_ENTRIES (PAGE_SIZE/sizeof(unsigned long))
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 3/27 liveupdate: Export symbols needed by modules
In reply to Vipin SharmaExport 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.
--- kernel/liveupdate/luo_file.c | 2 ++ 1 file changed, 2 insertions(+)
kernel/liveupdate/luo_file.c +2 -0
@@ -916,6 +916,7 @@ int liveupdate_register_file_handler(struct liveupdate_file_handler *fh)up_write (&luo_register_rwlock);return err; } +EXPORT_SYMBOL_GPL (liveupdate_register_file_handler);/** * liveupdate_unregister_file_handler - Unregister a liveupdate file handler
@@ -933,6 +934,7 @@ void liveupdate_unregister_file_handler(struct liveupdate_file_handler *fh)luo_flb_unregister_all (fh);list_del (&ACCESS_PRIVATE (fh, list)); } +EXPORT_SYMBOL_GPL (liveupdate_unregister_file_handler);/** * liveupdate_get_token_outgoing - Get the token for a preserved file.
Signature · 1 line
2.56.0.317.g454f8302e1-goog
Re: [PATCH v6 03/27] liveupdate: Export symbols needed by modules
Quoted 35 lines · Vipin Sharma
Export
liveupdate_register_file_handler()andliveupdate_unregister_file_handler(). All of these will be used by vfio-pci in a subsequent commit, which can be built as a module.Reviewed-by Samiullah Khawaja <[email protected]>Reviewed-by Pranjal Shrivastava <[email protected]>Signed-off-by David Matlack <[email protected]>Signed-off-by Vipin Sharma <[email protected]>---
kernel/liveupdate/luo_file.c| 2 ++1 file changed, 2 insertions(+)kernel/liveupdate/luo_file.c +2
-0@@ -916,6 +916,7 @@ int liveupdate_register_file_handler(struct liveupdate_file_handler *fh)up_write (&luo_register_rwlock);return err; } +EXPORT_SYMBOL_GPL (liveupdate_register_file_handler);/** * liveupdate_unregister_file_handler - Unregister a liveupdate file handler @@ -933,6 +934,7 @@ void liveupdate_unregister_file_handler(struct liveupdate_file_handler *fh)luo_flb_unregister_all (fh);list_del (&ACCESS_PRIVATE (fh, list)); } +EXPORT_SYMBOL_GPL (liveupdate_unregister_file_handler);/** * liveupdate_get_token_outgoing - Get the token for a preserved file. Signature · 1 line
2.56.0.317.g454f8302e1-goog
Can you please send this separately, it can probably go in without rest of the vfio changes? This is required by iommufd and guest_memfd also I think.
Thanks,
Sami
PATCH v6 4/27 vfio/pci: Register a file handler with Live Update Orchestrator
In reply to Vipin SharmaRegister a live update file handler for vfio-pci device files. Add stub implementations of all required callbacks so that registration does not fail. Register it with both live update framework and PCI subsystem.
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.
Put this support behind a new Kconfig VFIO_PCI_LIVEUPDATE. Initial support is added for no-iommu model vfio-pci devices.
--- MAINTAINERS | 1 + drivers/vfio/pci/Kconfig | 11 ++++ drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +++- drivers/vfio/pci/vfio_pci_liveupdate.c | 75 ++++++++++++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 14 +++++ include/linux/kho/abi/vfio_pci.h | 28 ++++++++++ 7 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 drivers/vfio/pci/vfio_pci_liveupdate.c create mode 100644 include/linux/kho/abi/vfio_pci.h
MAINTAINERS +1 -0
@@ -28662,6 +28662,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
drivers/vfio/pci/Kconfig +11 -0
@@ -42,6 +42,17 @@ config VFIO_PCI_IGD and LPC bridge config space. To enable Intel IGD assignment through vfio-pci, say Y. + +config VFIO_PCI_LIVEUPDATE + bool "VFIO PCI support for Live Update in no-iommu mode" + depends on PCI_LIVEUPDATE && VFIO_NOIOMMU + help + Support for preserving devices bound to vfio-pci in no-iommu mode + across a Live Update. It enables a device to continue working (DMA) + while host kernel is going through a kexec live update. + + If you don't know what to do here, say N. + endif config VFIO_PCI_ZDEV_KVM
drivers/vfio/pci/Makefile +1 -0
@@ -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_VFIO_PCI_LIVEUPDATE) += vfio_pci_liveupdate.o obj-$(CONFIG_VFIO_PCI) += vfio-pci.o obj-$(CONFIG_MLX5_VFIO_PCI) += mlx5/
drivers/vfio/pci/vfio_pci.c +10 -1
@@ -278,10 +278,14 @@ static int __init vfio_pci_init(void) {int ret; + ret =vfio_pci_liveupdate_init (); +if (ret) +return ret; +/* Register and scan for devices */ ret =pci_register_driver (&vfio_pci_driver);if (ret) -return ret; + goto err_liveupdate_cleanup;vfio_pci_fill_ids ();
@@ -289,12 +293,17 @@ static int __init vfio_pci_init(void)pr_warn ("device denylist disabled.\n" );return 0 ; + +err_liveupdate_cleanup: +vfio_pci_liveupdate_cleanup (); +return ret; }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);
drivers/vfio/pci/vfio_pci_liveupdate.c new file +75 -0
75 lines not on this page · raw message
drivers/vfio/pci/vfio_pci_priv.h +14 -0
@@ -148,4 +148,18 @@ static inline void vfio_pci_dma_buf_move(struct vfio_pci_core_device *vdev, }#endif +#ifdef CONFIG_VFIO_PCI_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_VFIO_PCI_LIVEUPDATE */ +#endif
include/linux/kho/abi/vfio_pci.h new file +28 -0
@@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0 */ + +/* +* Copyright (c) 2026, Google LLC. +* Vipin Sharma <[email protected]> +* David Matlack <[email protected]> +*/ + +#ifndef _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H +#define _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H + +/** +* DOC: VFIO PCI Live Update ABI +* +* VFIO uses the ABI defined below for preserving 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 */
Signature · 1 line
2.56.0.317.g454f8302e1-goog
Re: [PATCH v6 04/27] vfio/pci: Register a file handler with Live Update Orchestrator
Quoted 43 lines · Vipin Sharma
Register a live update file handler for vfio-pci device files. Add stub implementations of all required callbacks so that registration does not fail. Register it with both live update framework and PCI subsystem.
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.
Put this support behind a new
KconfigVFIO_PCI_LIVEUPDATE. Initial support is added for no-iommu model vfio-pci devices.Co-developed-by David Matlack <[email protected]>Signed-off-by David Matlack <[email protected]>Signed-off-by Vipin Sharma <[email protected]>---
MAINTAINERS | 1 + drivers/vfio/pci/Kconfig | 11 ++++ drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +++- drivers/vfio/pci/vfio_pci_liveupdate.c | 75 ++++++++++++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 14 +++++ include/linux/kho/abi/vfio_pci.h | 28 ++++++++++ 7 files changed, 140 insertions(+), 1 deletion(-)create mode 100644
drivers/vfio/pci/vfio_pci_liveupdate.ccreate mode 100644include/linux/kho/abi/vfio_pci.hMAINTAINERS +0
-0@@ -28662,6 +28662,7 @@ F: Documentation/ABI/testing/debugfs-vfioF:
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.hdrivers/vfio/pci/Kconfig +0
-0
drivers/vfio/pci/Kconfig config VFIO_PCI_IGD · line 48
Quoted 7 lines
drivers/vfio/pci/Kconfig +4
-0@@ -42,6 +42,17 @@ config VFIO_PCI_IGD and LPC bridge config space. To enable Intel IGD assignment through vfio-pci, say Y. + +config VFIO_PCI_LIVEUPDATE + bool "VFIO PCI support for Live Update in no-iommu mode" + depends on PCI_LIVEUPDATE && VFIO_NOIOMMU
Can we handle this dependency in code instead of doing through configs? Are there any build dependencies on noiommu?
Quoted 9 lines
drivers/vfio/pci/Kconfig +7
-0+ help + Support for preserving devices bound to vfio-pci in no-iommu mode + across a Live Update. It enables a device to continue working (DMA) + while host kernel is going through a kexec live update. + + If you don't know what to do here, say N. +endif
Thanks,
Sami
Re: [PATCH v6 04/27] vfio/pci: Register a file handler with Live Update Orchestrator
Quoted 46 lines · Samiullah Khawaja
Quoted 45 lines · Vipin Sharma
Register a live update file handler for vfio-pci device files. Add stub implementations of all required callbacks so that registration does not fail. Register it with both live update framework and PCI subsystem.
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.
Put this support behind a new
KconfigVFIO_PCI_LIVEUPDATE. Initial support is added for no-iommu model vfio-pci devices.Co-developed-by David Matlack <[email protected]>Signed-off-by David Matlack <[email protected]>Signed-off-by Vipin Sharma <[email protected]>---
MAINTAINERS | 1 + drivers/vfio/pci/Kconfig | 11 ++++ drivers/vfio/pci/Makefile | 1 + drivers/vfio/pci/vfio_pci.c | 11 +++- drivers/vfio/pci/vfio_pci_liveupdate.c | 75 ++++++++++++++++++++++++++ drivers/vfio/pci/vfio_pci_priv.h | 14 +++++ include/linux/kho/abi/vfio_pci.h | 28 ++++++++++ 7 files changed, 140 insertions(+), 1 deletion(-)create mode 100644
drivers/vfio/pci/vfio_pci_liveupdate.ccreate mode 100644include/linux/kho/abi/vfio_pci.hMAINTAINERS +0
-0@@ -28662,6 +28662,7 @@ F: Documentation/ABI/testing/debugfs-vfioF:
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.hdrivers/vfio/pci/Kconfig +0
-0@@ -42,6 +42,17 @@ config VFIO_PCI_IGD and LPC bridge config space.
Quoted 8 lines
drivers/vfio/pci/Kconfig config VFIO_PCI_IGD · line 48
Quoted 5 lines
drivers/vfio/pci/Kconfig +4
-0To enable Intel IGD assignment through vfio-pci, say Y. + +config VFIO_PCI_LIVEUPDATE + bool "VFIO PCI support for Live Update in no-iommu mode" + depends on PCI_LIVEUPDATE && VFIO_NOIOMMUCan we handle this dependency in code instead of doing through configs? Are there any build dependencies on noiommu?
I can remove it but then by itself VFIO series will enable LIVEUPDATE irrespective of VFIO_NOIOMMU and it will just fail when someone tries to enable it. So, kconfig looks cleaner to me.
Can your series modify this kconfig and add (VFIO_NOIOMMU || IOMMU_LIVEUPDATE)? Will that work for you?
PATCH v6 5/27 PCI: liveupdate: Add helpers to preserve struct pci_saved_state
In reply to Vipin SharmaDrivers that keep a device running across Live Update need to hand the state they captured with pci_store_saved_state() to the next kernel, since the next kernel never sees the device in that state. VFIO, for example, captures it at first open and uses it to restore the device when the last user closes it.
struct pci_saved_state is private to the PCI core and its in-memory layout is not a stable ABI. Add helpers to serialize it into a caller-provided buffer and rebuild it in the next kernel with a stable struct pci_saved_state_ser ABI. Using caller-provided buffers allows drivers to embed the serialized saved state directly in their own KHO-preserved data with a single allocation and lifetime.
Validate the serialized buffer and verify that the saved standard configuration header matches the live device before rebuilding the
state: the vendor and device IDs must match, only Type 0 (Normal) headers are accepted, and BAR0-5 and the expansion ROM BAR address must equal the current hardware values. This ensures that restoring the saved state cannot write stale BAR addresses if resources were reassigned in the new kernel. Only the address bits of the ROM BAR are compared, since its enable and validation status bits may legitimately differ.
--- Documentation/PCI/liveupdate.rst | 3 + drivers/pci/liveupdate.c | 223 +++++++++++++++++++++++++++++++ drivers/pci/pci.c | 5 - drivers/pci/pci.h | 6 + include/linux/kho/abi/pci.h | 47 +++++++ include/linux/pci_liveupdate.h | 7 + 6 files changed, 286 insertions(+), 5 deletions(-)
Documentation/PCI/liveupdate.rst +3 -0
@@ -25,6 +25,9 @@ Live Update ABI .. kernel-doc:: include/linux/kho/abi/pci.h :doc: PCI File-Lifecycle Bound (FLB) Live Update ABI +.. kernel-doc:: include/linux/kho/abi/pci.h + :doc: PCI Saved State Live Update ABI + .. kernel-doc:: include/linux/kho/abi/pci.h :internal:
drivers/pci/liveupdate.c +223 -0
226 lines not on this page · raw message
drivers/pci/pci.c +0 -5
@@ -2032,11 +2032,6 @@ void pci_restore_state(struct pci_dev *dev) }EXPORT_SYMBOL (pci_restore_state); -struct pci_saved_state { -u32 config_space[16 ]; -struct pci_cap_saved_data cap[]; -}; -/** * pci_store_saved_state - Allocate and return an opaque struct containing * the device saved state.
drivers/pci/pci.h +6 -0
@@ -244,6 +244,12 @@ struct pci_cap_saved_data {u32 data[]; }; +/* Opaque to drivers, see pci_store_saved_state() */ +struct pci_saved_state { +u32 config_space[16 ]; +struct pci_cap_saved_data cap[]; +}; +struct pci_cap_saved_state {struct hlist_node next;struct pci_cap_saved_data cap;
include/linux/kho/abi/pci.h +47 -0
51 lines not on this page · raw message
include/linux/pci_liveupdate.h +7 -0
@@ -32,6 +32,7 @@ struct pci_liveupdate { };struct pci_dev ; +struct pci_saved_state ;#ifdef CONFIG_PCI_LIVEUPDATE int pci_liveupdate_register_flb (struct liveupdate_file_handler *fh);
@@ -40,6 +41,12 @@ int pci_liveupdate_preserve(struct pci_dev *dev);void pci_liveupdate_unpreserve (struct pci_dev *dev);void pci_liveupdate_finish (struct pci_dev *dev);bool pci_liveupdate_is_incoming (struct pci_dev *dev); +size_t pci_liveupdate_saved_state_ser_size (const struct pci_saved_state *state); +int pci_liveupdate_serialize_saved_state (const struct pci_saved_state *state, +void *buf,size_t size); +struct pci_saved_state *pci_liveupdate_deserialize_saved_state (struct pci_dev *dev, +const void *buf, +size_t size);#else static inline int pci_liveupdate_register_flb (struct liveupdate_file_handler *fh) {
Signature · 1 line
2.56.0.317.g454f8302e1-goog
Re: [PATCH v6 05/27] PCI: liveupdate: Add helpers to preserve struct pci_saved_state
Quoted 23 lines · Vipin Sharma
Drivers that keep a device running across Live Update need to hand the state they captured with
pci_store_saved_state()to the next kernel, since the next kernel never sees the device in that state. VFIO, for example, captures it at first open and uses it to restore the device when the last user closes it.struct
pci_saved_stateis private to the PCI core and its in-memory layout is not a stable ABI. Add helpers to serialize it into a caller-provided buffer and rebuild it in the next kernel with a stable structpci_saved_state_serABI. Using caller-provided buffers allows drivers to embed the serialized saved state directly in their own KHO-preserved data with a single allocation and lifetime.Validate the serialized buffer and verify that the saved standard configuration header matches the live device before rebuilding the
state: the vendor and device IDs must match, only Type 0 (Normal) headers are accepted, and BAR0-5 and the expansion ROM BAR address must equal the current hardware values. This ensures that restoring the saved state cannot write stale BAR addresses if resources were reassigned in the new kernel. Only the address bits of the ROM BAR are compared, since its enable and validation status bits may legitimately differ.
Quoted 1 line
Signed-off-by Vipin Sharma <[email protected]>
A few nits below.
drivers/pci/liveupdate.c void pci_liveupdate_unregister_flb(struct liveupdate_file_handler *fh) · line 1046
Quoted 7 lines
drivers/pci/liveupdate.c +7
-0+static const struct pci_cap_saved_data *pci_saved_cap_next (const struct pci_cap_saved_data *cap) +{ +return (const void *)cap +sizeof (*cap) + cap->size; +} + +/** +* pci_liveupdate_saved_state_ser_size() - Size needed to serialize a saved state
Wrap to fit in 80 columns (75 or so is even nicer because it's a little more relaxed to read and typo fixes are less likely to rewrap).
Quoted 6 lines
+ * @state: Saved state returned by
pci_store_saved_state(), or NULL.
+ *
+ * Return: Number of bytes needed bypci_liveupdate_serialize_saved_state(), or
+ * 0 if @state is NULL.
+ */
+size_tpci_liveupdate_saved_state_ser_size(const struct pci_saved_state *state)
I think pci_liveupdate_saved_state_ser_size() is connected with pci_liveupdate_serialize_saved_state() and pci_liveupdate_deserialize_saved_state().
Would be nice if that were obvious from the names.
They're also pretty long, which makes prototypes and uses very likely to wrap in awkward spots.
include/linux/kho/abi/pci.h struct pci_ser { · line 121
Quoted 8 lines
+ * struct
pci_cap_saved_data_ser- A saved capability in a structpci_saved_state_ser
+ * @cap_nr: Capability ID (PCI_CAP_ID_* or PCI_EXT_CAP_ID_*).
+ * @extended: 1 if @cap_nr is an extended capability ID, 0 otherwise.
+ * @size: Size of @data in bytes, never 0.
+ * @data: The saved registers.
+ */include/linux/kho/abi/pci.h +2
-0+struct pci_cap_saved_data_ser { +u16 cap_nr;
Maybe "cap_id" to avoid confusion with "nr_caps" or indexes into "caps[]" below?
Quoted 9 lines
include/linux/kho/abi/pci.h +9
-0+u16 extended; +u32 size; +u8 data[]; +} __packed; + +/** +* struct pci_saved_state_ser - Serialized struct pci_saved_state +* @size: Size in bytes of this struct, including all entries in @caps. +* @flags: Features a kernel must support to restore the state. None defined.
include/linux/kho/abi/pci.h struct pci_ser { · line 140
Quoted 10 lines
include/linux/kho/abi/pci.h +10
-0+* @nr_caps: Number of entries in @caps. +* @config_space: The saved standard configuration header. +* @caps: @nr_caps struct pci_cap_saved_data_ser entries. +*/ +struct pci_saved_state_ser { +u32 size; +u32 flags; +u32 nr_caps; +u32 config_space[16 ]; +u8 caps[];
I think it would be helpful if the names of "config_space[]" and "caps[]" hinted at the connection between them (both are in config space). "config_space[]" by itself suggests it's complete, which it's not, so maybe there's a place for "hdr" or similar in it.
David Matlack
maintainerRe: [PATCH v6 05/27] PCI: liveupdate: Add helpers to preserve struct pci_saved_state
Quoted 9 lines · Bjorn Helgaas
Quoted 6 lines · Vipin Sharma
struct
pci_saved_stateis private to the PCI core and its in-memory layout is not a stable ABI. Add helpers to serialize it into a caller-provided buffer and rebuild it in the next kernel with a stable structpci_saved_state_serABI. Using caller-provided buffers allows drivers to embed the serialized saved state directly in their own KHO-preserved data with a single allocation and lifetime.Acked-by Bjorn Helgaas <[email protected]>
We discussed this patch off-list this morning. I'll sharing the context here since you were not there Bjorn.
The ABI added by this patch is not actually stable across kernel versions.
struct pci_saved_state_ser is stable, but the contents of each capability entry are not:
Quoted 6 lines
include/linux/kho/abi/pci.h struct pci_ser { · line 125
Quoted 6 lines
include/linux/kho/abi/pci.h +6
-0+struct pci_cap_saved_data_ser { +u16 cap_nr; +u16 extended; +u32 size; +u8 data[]; +} __packed;
@data is a memcpy() of the per-capability save buffer, and the layout of that buffer is not defined by the device or the spec. It is whatever registers that capability's pci_save_*_state() function happens to read, in whatever order it reads them.
None of that is described in include/linux/kho/abi/pci.h, so this patch implicitly turns the private layout of every capability save buffer in drivers/pci/ into Live Update ABI. Someone changing pci_save_pcie_state() or pci_save_aer_state() has no way of knowing they just broke Live Update compatibility.
And these layouts do change. Commit 898585172fa7 ("PCI: save and restore PCIe 2.0 registers") grew the PCIe buffer from 4 to 7 registers, and the AER, LTR, L1SS, PTM, TPH and DPC buffers were all added over time.
This is the problem I was trying to solve with:
https://lore.kernel.org/linux-pci/[email protected]/
That series replaces the per-capability buffers with a single store indexed by config space offset.
Where a saved value goes is then determined by the device's config space, not by the kernel that saved it, so the PCI core can change which registers it saves without changing what the data means. Serializing that for Live Update should be trivial (a size/flags header plus the bitmap and the values). The cross-kernel compatibility question also becomes explicit and per-register ("the previous kernel saved offset X and this kernel doesn't restore it") instead of a size mismatch on an opaque blob.
Bjorn, this is also related to your last comment:
Quoted 3 lines
I think it would be helpful if the names of "config_space[]" and "caps[]" hinted at the connection between them (both are in config space).
With the offset-indexed layout the two are no longer separate. The header and the capability registers are all just DWORDs in the same config space map in struct pci_saved_state.
So I'd suggest that we land the saved state series first and then rebase this patch on top of it.
I can send a v2 of that series this week that addresses Josh's feedback, rebases on top of the PCI Live Update v10 series, and includes the serialization helpers. We can use that as the basis for the next version of this series.
Thanks,
David
Re: [PATCH v6 05/27] PCI: liveupdate: Add helpers to preserve struct pci_saved_state
Quoted 68 lines · David Matlack
Quoted 9 lines · Bjorn Helgaas
Quoted 6 lines · Vipin Sharma
struct
pci_saved_stateis private to the PCI core and its in-memory layout is not a stable ABI. Add helpers to serialize it into a caller-provided buffer and rebuild it in the next kernel with a stable structpci_saved_state_serABI. Using caller-provided buffers allows drivers to embed the serialized saved state directly in their own KHO-preserved data with a single allocation and lifetime.Acked-by Bjorn Helgaas <[email protected]>We discussed this patch off-list this morning. I'll sharing the context here since you were not there Bjorn.
The ABI added by this patch is not actually stable across kernel versions.
struct
pci_saved_state_seris stable, but the contents of each capability entry are not:Quoted 6 lines
include/linux/kho/abi/pci.h struct pci_ser { · line 125
Quoted 6 lines
include/linux/kho/abi/pci.h +6
-0+struct pci_cap_saved_data_ser { +u16 cap_nr; +u16 extended; +u32 size; +u8 data[]; +} __packed;@data is a
memcpy()of the per-capability save buffer, and the layout of that buffer is not defined by the device or the spec. It is whatever registers that capability's pci_save_*_state() function happens to read, in whatever order it reads them.None of that is described in
include/linux/kho/abi/pci.h, so this patch implicitly turns the private layout of every capability save buffer indrivers/pci/into Live Update ABI. Someone changingpci_save_pcie_state()orpci_save_aer_state()has no way of knowing they just broke Live Update compatibility.And these layouts do change. Commit
898585172fa7("PCI: save and restore PCIe 2.0 registers") grew the PCIe buffer from 4 to 7 registers, and the AER, LTR, L1SS, PTM, TPH and DPC buffers were all added over time.This is the problem I was trying to solve with:
https://lore.kernel.org/linux-pci/[email protected]/
That series replaces the per-capability buffers with a single store indexed by config space offset.
Where a saved value goes is then determined by the device's config space, not by the kernel that saved it, so the PCI core can change which registers it saves without changing what the data means. Serializing that for Live Update should be trivial (a size/flags header plus the bitmap and the values). The cross-kernel compatibility question also becomes explicit and per-register ("the previous kernel saved offset X and this kernel doesn't restore it") instead of a size mismatch on an opaque blob.
Bjorn, this is also related to your last comment:
Quoted 3 lines
I think it would be helpful if the names of "config_space[]" and "caps[]" hinted at the connection between them (both are in config space).
With the offset-indexed layout the two are no longer separate. The header and the capability registers are all just DWORDs in the same config space map in struct
pci_saved_state.
Quoted 8 lines
So I'd suggest that we land the saved state series first and then rebase this patch on top of it.
I can send a v2 of that series this week that addresses Josh's feedback, rebases on top of the PCI Live Update v10 series, and includes the serialization helpers. We can use that as the basis for the next version of this series.
Agree with David here. I think David's series will make things more explicit in saving PCI state and easier to find changes. I will review your series provide my feedback but don't stop your v2 on it.
Thanks,
Vipin
PATCH v6 6/27 vfio: Add helpers to identify device files that can be preserved
In reply to Vipin SharmaAdd two helpers needed by vfio-pci Live Update support:
1. vfio_file_is_bound_cdev(): checks whether a specific file is a VFIO cdev device file that has been bound to an iommufd. Only the bound cdev file keeps the device open; the device-level cdev_opened flag cannot distinguish between the bound cdev file and a second, unbound cdev file opened for the same device.
2. vfio_device_is_noiommu(): move the existing helper out of line and export it so vfio-pci can enforce that only devices in no-IOMMU mode are preserved across Live Update.
No functional change intended for existing callers.
--- drivers/vfio/device_cdev.c | 20 ++++++++++++++++++++ drivers/vfio/vfio.h | 10 ---------- drivers/vfio/vfio_main.c | 18 ++++++++++++++++++ include/linux/vfio.h | 10 ++++++++++ 4 files changed, 48 insertions(+), 10 deletions(-)
drivers/vfio/device_cdev.c +20 -0
@@ -200,6 +200,26 @@ void vfio_df_unbind_iommufd(struct vfio_device_file *df)vfio_device_unblock_group (device); } +/** +* vfio_file_is_bound_cdev - True if the file is a VFIO cdev file bound to an +* iommufd +* @file: File to check +* +* Return: True if @file is a VFIO cdev device file on which +* VFIO_DEVICE_BIND_IOMMUFD has succeeded, false otherwise. +*/ +bool vfio_file_is_bound_cdev (struct file *file) +{ +struct vfio_device_file *df = file->private_data; + +if (file->f_op != &vfio_device_fops) +return false; + +/* Paired with smp_store_release() in vfio_df_ioctl_bind_iommufd() */ +return !df->group &&smp_load_acquire (&df->access_granted); +} +EXPORT_SYMBOL_GPL (vfio_file_is_bound_cdev); +int vfio_df_ioctl_attach_pt (struct vfio_device_file *df,struct vfio_device_attach_iommufd_pt __user *arg) {
drivers/vfio/vfio.h +0 -10
@@ -185,16 +185,6 @@ static inline void vfio_group_cleanup(void)#endif /* CONFIG_VFIO_GROUP */ -static inline bool vfio_device_is_noiommu (struct vfio_device *vdev) -{ -#if IS_ENABLED (CONFIG_VFIO_GROUP ) -if (vdev->group && vdev->group->type ==VFIO_NO_IOMMU ) -return true; -#endif - -return IS_ENABLED (CONFIG_IOMMUFD_NOIOMMU ) && vdev->noiommu; -} -#if IS_ENABLED (CONFIG_VFIO_CONTAINER )/** * struct vfio_iommu_driver_ops - VFIO IOMMU driver callbacks
drivers/vfio/vfio_main.c +18 -0
@@ -1507,6 +1507,24 @@ struct vfio_device *vfio_device_from_file(struct file *file) }EXPORT_SYMBOL_GPL (vfio_device_from_file); +/** +* vfio_device_is_noiommu - True if the VFIO device is registered in no-IOMMU +* mode +* @vdev: The VFIO device to check +* +* Return: True if @vdev is registered in no-IOMMU mode, false otherwise. +*/ +bool vfio_device_is_noiommu (struct vfio_device *vdev) +{ +#if IS_ENABLED (CONFIG_VFIO_GROUP ) +if (vdev->group && vdev->group->type ==VFIO_NO_IOMMU ) +return true; +#endif + +return IS_ENABLED (CONFIG_IOMMUFD_NOIOMMU ) && vdev->noiommu; +} +EXPORT_SYMBOL_GPL (vfio_device_is_noiommu); +/** * vfio_file_is_valid - True if the file is valid vfio file * @file: VFIO group file or VFIO device file
include/linux/vfio.h +10 -0
@@ -380,6 +380,7 @@ bool vfio_file_is_valid(struct file *file);bool vfio_file_enforced_coherent (struct file *file);void vfio_file_set_kvm (struct file *file,struct kvm *kvm);struct vfio_device *vfio_device_from_file (struct file *file); +bool vfio_device_is_noiommu (struct vfio_device *vdev);#define VFIO_PIN_PAGES_MAX_ENTRIES (PAGE_SIZE/sizeof(unsigned long))
@@ -431,4 +432,13 @@ 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 ) +bool vfio_file_is_bound_cdev (struct file *file); +#else +static inline bool vfio_file_is_bound_cdev (struct file *file) +{ +return false; +} +#endif /* IS_ENABLED(CONFIG_VFIO_DEVICE_CDEV) */ +#endif /* VFIO_H */
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 7/27 vfio/pci: Preserve vfio-pci device files across Live Update
In reply to Vipin SharmaImplement the Live Update file handler callbacks to preserve a vfio-pci device in noiommu mode across a Live Update while keeping it running across kexec. Subsequent commits will enable userspace to retrieve and take over this file after the Live Update.
State about each device is serialized into struct vfio_pci_core_device_ser using Kexec-Handover (KHO) to preserve the pages holding the struct and the Live Update Orchestrator (LUO) to preserve the physical address of the struct.
Key design notes and constraints:
* Noiommu-only policy and bound cdev requirement: can_preserve() verifies that the preserved file is a bound vfio-pci cdev file descriptor via vfio_file_is_bound_cdev(), and preserve() requires the device to be in noiommu mode via vfio_device_is_noiommu() (returning -EOPNOTSUPP otherwise). CONFIG_VFIO_PCI_LIVEUPDATE now depends on CONFIG_VFIO_DEVICE_CDEV and CONFIG_VFIO_NOIOMMU.
* Serialized state: During preserve(), serialize the PCI domain, BDF, config space size, reset_works flag, and the initial pci_saved_state captured when the device was first opened. During freeze(), snapshot the virtualized PCI config space (vconfig) and capability map (pci_config_map).
* Keep-running freeze and unfreeze: Do not reset the device, clear PCI_COMMAND_MASTER, zap BAR mappings, or revoke dma-bufs during freeze(). Validate that VFIO interrupts are disabled, that the device is in PCI_D0 (and not in VFIO runtime PM low-power mode), and that SR-IOV is not enabled, as VFs are not preserved and the next kernel disables SR-IOV on the running device. Then mask physical INTx (recording the prior state) and mark the device frozen. If the Live Update is aborted after freeze(), unfreeze() restores the physical INTx state and clears liveupdate_frozen so the existing FD remains usable.
* TOCTOU synchronization: vfio_pci_dev_is_frozen() is checked locklessly on entry to the ioctl, read/write and mmap paths, and re-checked under a lock that freeze() holds before any operation that could change the device or vconfig: under vdev->igate in vfio_pci_ioctl_set_irqs() and around every config-space write in vfio_pci_config_rw_single(), under vdev->memory_lock in vfio_pci_runtime_pm_entry(), vfio_pci_ioctl_reset() and the SR-IOV enable path of vfio_pci_core_sriov_configure(), and under dev_set->lock in vfio_pci_dev_set_hot_reset(). A racing operation thus either completes before freeze() takes its snapshot or fails, while existing BAR mmaps, ioeventfds and dma-bufs keep working. Serializing config writes on igate covers the PCI_COMMAND, INTx disable emulation, power state and FLR paths at one point (the INTx disable emulation now uses the igate-held __vfio_pci_intx_mask() and __vfio_pci_intx_unmask() helpers), and also serializes the irq_type and virq_disabled accesses of config writes with VFIO_DEVICE_SET_IRQS.
--- drivers/vfio/pci/Kconfig | 2 +- drivers/vfio/pci/vfio_pci_config.c | 19 +- drivers/vfio/pci/vfio_pci_core.c | 49 +++- drivers/vfio/pci/vfio_pci_intrs.c | 4 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 303 ++++++++++++++++++++++++- drivers/vfio/pci/vfio_pci_priv.h | 13 ++ include/linux/kho/abi/vfio_pci.h | 52 ++++- include/linux/vfio_pci_core.h | 4 + 8 files changed, 434 insertions(+), 12 deletions(-)
drivers/vfio/pci/Kconfig +1 -1
@@ -45,7 +45,7 @@ config VFIO_PCI_IGD config VFIO_PCI_LIVEUPDATE bool "VFIO PCI support for Live Update in no-iommu mode" - depends on PCI_LIVEUPDATE && VFIO_NOIOMMU + depends on PCI_LIVEUPDATE && VFIO_NOIOMMU && VFIO_DEVICE_CDEV help Support for preserving devices bound to vfio-pci in no-iommu mode across a Live Update. It enables a device to continue working (DMA)
drivers/vfio/pci/vfio_pci_config.c +16 -3
@@ -644,10 +644,10 @@ static int vfio_basic_config_write(struct vfio_pci_core_device *vdev, int pos,if (virt_intx_disable && !vdev->virq_disabled) { vdev->virq_disabled = true; -vfio_pci_intx_mask (vdev); +__vfio_pci_intx_mask (vdev); }else if (!virt_intx_disable && vdev->virq_disabled) { vdev->virq_disabled = false; -vfio_pci_intx_unmask (vdev); +__vfio_pci_intx_unmask (vdev); } }
@@ -1957,7 +1957,20 @@ ssize_t vfio_pci_config_rw_single(struct vfio_pci_core_device *vdev,if (copy_from_user (&val, buf, count))return -EFAULT ; - ret = perm->writefn (vdev, *ppos, count, perm, offset, val); +/* +* Serialize with Live Update freeze(), which holds igate, so a +* write that passed the lockless frozen check in vfio_pci_rw() +* cannot change the device or vconfig after freeze() has +* snapshotted vconfig and masked INTx. The INTx disable +* emulation in vfio_basic_config_write() relies on igate too. +*/ +mutex_lock (&vdev->igate); +if (vfio_pci_dev_is_frozen (vdev)) + ret = -EIO ; +else + ret = perm->writefn (vdev, *ppos, count, perm, offset, + val); +mutex_unlock (&vdev->igate); }else {if (perm->readfn) { ret = perm->readfn(vdev, *ppos, count,
drivers/vfio/pci/vfio_pci_core.c +47 -2
118 lines not on this page · raw message
drivers/vfio/pci/vfio_pci_intrs.c +2 -2
@@ -99,7 +99,7 @@ static void vfio_send_intx_eventfd(void *opaque, void *data) }/* Returns true if the INTx vfio_pci_irq_ctx.masked value is changed. */ -static bool __vfio_pci_intx_mask (struct vfio_pci_core_device *vdev) +bool __vfio_pci_intx_mask (struct vfio_pci_core_device *vdev) {struct pci_dev *pdev = vdev->pdev;struct vfio_pci_irq_ctx *ctx;
@@ -203,7 +203,7 @@ static int vfio_pci_intx_unmask_handler(void *opaque, void *data)return ret; } -static void __vfio_pci_intx_unmask (struct vfio_pci_core_device *vdev) +void __vfio_pci_intx_unmask (struct vfio_pci_core_device *vdev) {struct vfio_pci_irq_ctx *ctx =vfio_irq_ctx_get (vdev,0 );
drivers/vfio/pci/vfio_pci_liveupdate.c +301 -2
335 lines not on this page · raw message
drivers/vfio/pci/vfio_pci_priv.h +13 -0
@@ -25,7 +25,9 @@ struct vfio_pci_ioeventfd {bool test_mem; }; +bool __vfio_pci_intx_mask (struct vfio_pci_core_device *vdev);bool vfio_pci_intx_mask (struct vfio_pci_core_device *vdev); +void __vfio_pci_intx_unmask (struct vfio_pci_core_device *vdev);void vfio_pci_intx_unmask (struct vfio_pci_core_device *vdev); int vfio_pci_eventfd_replace_locked(struct vfio_pci_core_device *vdev,
@@ -151,6 +153,12 @@ static inline void vfio_pci_dma_buf_move(struct vfio_pci_core_device *vdev,#ifdef CONFIG_VFIO_PCI_LIVEUPDATE int __init vfio_pci_liveupdate_init (void );void vfio_pci_liveupdate_cleanup (void ); + +static inline bool vfio_pci_dev_is_frozen (struct vfio_pci_core_device *vdev) +{ +/* Written in VFIO PCI Liveupdate during freeze()/unfreeze() */ +return smp_load_acquire (&vdev->liveupdate_frozen); +}#else static inline int vfio_pci_liveupdate_init (void ) {
@@ -160,6 +168,11 @@ static inline int vfio_pci_liveupdate_init(void)static inline void vfio_pci_liveupdate_cleanup (void ) { } + +static inline bool vfio_pci_dev_is_frozen (struct vfio_pci_core_device *vdev) +{ +return false; +}#endif /* CONFIG_VFIO_PCI_LIVEUPDATE */ #endif
include/linux/kho/abi/vfio_pci.h +50 -2
68 lines not on this page · raw message
include/linux/vfio_pci_core.h +4 -0
@@ -149,6 +149,10 @@ struct vfio_pci_core_device {struct notifier_block nb;struct rw_semaphore memory_lock;struct list_head dmabufs; +#ifdef CONFIG_VFIO_PCI_LIVEUPDATE +bool liveupdate_frozen; +bool liveupdate_intx_disabled; +#endif };enum vfio_pci_io_width {
Signature · 1 line
2.56.0.317.g454f8302e1-goog
David Matlack
maintainerRe: [PATCH v6 07/27] vfio/pci: Preserve vfio-pci device files across Live Update
Quoted 8 lines · Vipin Sharma
* TOCTOU synchronization:
vfio_pci_dev_is_frozen()is checked locklessly on entry to the ioctl, read/write and mmap paths, and re-checked under a lock thatfreeze()holds before any operation that could change the device or vconfig: undervdev->igateinvfio_pci_ioctl_set_irqs()and around every config-space write invfio_pci_config_rw_single(), undervdev->memory_lockinvfio_pci_runtime_pm_entry(),vfio_pci_ioctl_reset()and the SR-IOV enable path ofvfio_pci_core_sriov_configure(), and underdev_set->lockin
Quoted 8 lines
vfio_pci_dev_set_hot_reset(). A racing operation thus either completes beforefreeze()takes its snapshot or fails, while existing BAR mmaps, ioeventfds and dma-bufs keep working. Serializing config writes on igate covers thePCI_COMMAND, INTx disable emulation, power state and FLR paths at one point (the INTx disable emulation now uses the igate-held__vfio_pci_intx_mask()and__vfio_pci_intx_unmask()helpers), and also serializes theirq_typeandvirq_disabledaccesses of config writes withVFIO_DEVICE_SET_IRQS.
I think there's a simpler way to do this. Checking the frozen flag locklessly and then re-checking it under whichever lock covers each path spreads the synchronization across igate, memory_lock and dev_set->lock. That makes it hard to convince yourself every path that can change the device is covered. It also makes every config space write take igate, for all vfio-pci users, even when CONFIG_VFIO_PCI_LIVEUPDATE=n.
Instead, I suggest adding a per-device rw_semaphore to struct vfio_device in the VFIO core, e.g. liveupdate_rwsem, that protects a liveupdate_frozen flag:
- vfio_device_fops_unl_ioctl(), vfio_device_fops_read() and vfio_device_fops_write() take liveupdate_rwsem for read and fail with -EIO if the device is frozen. That covers every device ioctl in one place, including the ones handled by the VFIO core (VFIO_DEVICE_FEATURE, VFIO_DEVICE_GET_REGION_INFO and VFIO_DEVICE_{ATTACH,DETACH}_IOMMUFD_PT). This patch doesn't block the last two at all today.
- freeze() and unfreeze() take liveupdate_rwsem for write, before any other lock, and flip the flag. preserve() doesn't need it since it only serializes state that doesn't change after the device is opened.
Putting this in the VFIO core also means other VFIO drivers can reuse it if they add Live Update support in the future.
The lock order then becomes:
liveupdate_rwsem -> dev_set->lock -> igate -> memory_lock
freeze() can still take igate and memory_lock to check irq_type, pm_runtime_engaged and sriov_active. But the ioctl, read and write paths no longer need to re-check anything under those locks. So you can drop the igate change in vfio_pci_config_rw_single(), the open-coded vfio_pci_zap_and_down_write_memory_lock() in vfio_pci_runtime_pm_entry() and vfio_pci_ioctl_reset(), and the smp_load_acquire()/smp_store_release() pair.
Two paths still need their own handling because they don't go through the device's file:
- vfio_pci_core_sriov_configure() is reached through sysfs. Take liveupdate_rwsem for read around the frozen check and the sriov_active update.
- VFIO_DEVICE_PCI_HOT_RESET issued on one device also resets the other devices in its dev_set. Keep the check in vfio_pci_dev_set_hot_reset() under dev_set->lock. freeze() sets the flag while holding both liveupdate_rwsem and dev_set->lock, so holding either one is enough to read it. Please don't take the other devices' liveupdate_rwsem there, since that would invert the lock order relative to freeze().
I don't think mmap needs to be blocked at all. Creating a new mapping doesn't change the device or any of the state that gets preserved, and existing mappings already keep working while the device is frozen. Leaving mmap alone also avoids taking liveupdate_rwsem under mmap_lock, which could deadlock: the ioctl, read and write paths can fault on user memory (taking mmap_lock) while holding liveupdate_rwsem for read, and freeze() may be waiting for the write lock. Please update the comment in freeze() and the DOC section to match.
Quoted 6 lines
drivers/vfio/pci/vfio_pci_config.c +0
-0@@ -644,10 +644,10 @@ static int vfio_basic_config_write(struct vfio_pci_core_device *vdev, int pos,
drivers/vfio/pci/vfio_pci_config.c static int vfio_basic_config_write(struct vfio_pci_core_device *vdev, int pos, · line 652
Quoted 10 lines
drivers/vfio/pci/vfio_pci_config.c +2
-2if (virt_intx_disable && !vdev->virq_disabled) { vdev->virq_disabled = true; -vfio_pci_intx_mask (vdev); +__vfio_pci_intx_mask (vdev); }else if (!virt_intx_disable && vdev->virq_disabled) { vdev->virq_disabled = false; -vfio_pci_intx_unmask (vdev); +__vfio_pci_intx_unmask (vdev); } }
With the rwsem, config writes no longer need igate, so this change isn't needed. If config writes and VFIO_DEVICE_SET_IRQS really do race on irq_type and virq_disabled today, that's unrelated to Live Update. Please send it as a separate fix.
Lastly, please add the freeze infrastructure and the checks in their own commit ahead of this one, e.g. "vfio: Add infrastructure to freeze devices for Live Update". Then this patch only has to implement freeze() and unfreeze() on top of it, which will make both easier to review.
Re: [PATCH v6 07/27] vfio/pci: Preserve vfio-pci device files across Live Update
Quoted 73 lines · David Matlack
Quoted 8 lines · Vipin Sharma
* TOCTOU synchronization:
vfio_pci_dev_is_frozen()is checked locklessly on entry to the ioctl, read/write and mmap paths, and re-checked under a lock thatfreeze()holds before any operation that could change the device or vconfig: undervdev->igateinvfio_pci_ioctl_set_irqs()and around every config-space write invfio_pci_config_rw_single(), undervdev->memory_lockinvfio_pci_runtime_pm_entry(),vfio_pci_ioctl_reset()and the SR-IOV enable path ofvfio_pci_core_sriov_configure(), and underdev_set->lockinQuoted 8 lines
vfio_pci_dev_set_hot_reset(). A racing operation thus either completes beforefreeze()takes its snapshot or fails, while existing BAR mmaps, ioeventfds and dma-bufs keep working. Serializing config writes on igate covers thePCI_COMMAND, INTx disable emulation, power state and FLR paths at one point (the INTx disable emulation now uses the igate-held__vfio_pci_intx_mask()and__vfio_pci_intx_unmask()helpers), and also serializes theirq_typeandvirq_disabledaccesses of config writes withVFIO_DEVICE_SET_IRQS.I think there's a simpler way to do this. Checking the frozen flag locklessly and then re-checking it under whichever lock covers each path spreads the synchronization across igate,
memory_lockanddev_set->lock. That makes it hard to convince yourself every path that can change the device is covered. It also makes every config space write take igate, for all vfio-pci users, even whenCONFIG_VFIO_PCI_LIVEUPDATE=n.Instead, I suggest adding a per-device
rw_semaphoreto structvfio_devicein the VFIO core, e.g.liveupdate_rwsem, that protects aliveupdate_frozenflag:-
vfio_device_fops_unl_ioctl(),vfio_device_fops_read()andvfio_device_fops_write()takeliveupdate_rwsemfor read and fail with-EIOif the device is frozen. That covers every device ioctl in one place, including the ones handled by the VFIO core (VFIO_DEVICE_FEATURE,VFIO_DEVICE_GET_REGION_INFOand VFIO_DEVICE_{ATTACH,DETACH}_IOMMUFD_PT). This patch doesn't block the last two at all today.-
freeze()andunfreeze()takeliveupdate_rwsemfor write, before any other lock, and flip the flag.preserve()doesn't need it since it only serializes state that doesn't change after the device is opened.Putting this in the VFIO core also means other VFIO drivers can reuse it if they add Live Update support in the future.
The lock order then becomes:
liveupdate_rwsem->dev_set->lock-> igate ->memory_lock
freeze()can still take igate andmemory_lockto checkirq_type,pm_runtime_engagedandsriov_active. But the ioctl, read and write paths no longer need to re-check anything under those locks. So you can drop the igate change invfio_pci_config_rw_single(), the open-codedvfio_pci_zap_and_down_write_memory_lock()invfio_pci_runtime_pm_entry()andvfio_pci_ioctl_reset(), and the smp_load_acquire()/smp_store_release() pair.Two paths still need their own handling because they don't go through the device's file:
-
vfio_pci_core_sriov_configure()is reached through sysfs. Takeliveupdate_rwsemfor read around the frozen check and thesriov_activeupdate.-
VFIO_DEVICE_PCI_HOT_RESETissued on one device also resets the other devices in itsdev_set. Keep the check invfio_pci_dev_set_hot_reset()underdev_set->lock.freeze()sets the flag while holding bothliveupdate_rwsemanddev_set->lock, so holding either one is enough to read it. Please don't take the other devices'liveupdate_rwsemthere, since that would invert the lock order relative tofreeze().
Quoted 9 lines
I don't think mmap needs to be blocked at all. Creating a new mapping doesn't change the device or any of the state that gets preserved, and existing mappings already keep working while the device is frozen. Leaving mmap alone also avoids taking
liveupdate_rwsemundermmap_lock, which could deadlock: the ioctl, read and write paths can fault on user memory (takingmmap_lock) while holdingliveupdate_rwsemfor read, andfreeze()may be waiting for the write lock. Please update the comment infreeze()and the DOC section to match.
Thanks for suggestion, this is indeed simpler.
Quoted 6 lines
Quoted 6 lines
drivers/vfio/pci/vfio_pci_config.c +0
-0@@ -644,10 +644,10 @@ static int vfio_basic_config_write(struct vfio_pci_core_device *vdev, int pos,
Quoted 16 lines
drivers/vfio/pci/vfio_pci_config.c static int vfio_basic_config_write(struct vfio_pci_core_device *vdev, int pos, · line 652
Quoted 10 lines
drivers/vfio/pci/vfio_pci_config.c +2
-2if (virt_intx_disable && !vdev->virq_disabled) { vdev->virq_disabled = true; -vfio_pci_intx_mask (vdev); +__vfio_pci_intx_mask (vdev); }else if (!virt_intx_disable && vdev->virq_disabled) { vdev->virq_disabled = false; -vfio_pci_intx_unmask (vdev); +__vfio_pci_intx_unmask (vdev); } }With the rwsem, config writes no longer need igate, so this change isn't needed. If config writes and
VFIO_DEVICE_SET_IRQSreally do race onirq_typeandvirq_disabledtoday, that's unrelated to Live Update. Please send it as a separate fix.
This will go away.
Quoted 5 lines
Lastly, please add the freeze infrastructure and the checks in their own commit ahead of this one, e.g. "vfio: Add infrastructure to freeze devices for Live Update". Then this patch only has to implement
freeze()andunfreeze()on top of it, which will make both easier to review.
Sounds good. Thanks for the review.
David Matlack
maintainerRe: [PATCH v6 07/27] vfio/pci: Preserve vfio-pci device files across Live Update
In reply to Vipin SharmaQuoted 9 lines · Vipin Sharma
+ * DMA Memory Ordering Contract
+ * ============================
+ *
+ * Because a preserved noiommu device continues performing DMA using physical
+ * addresses across kexec, any memory buffer targeted by device DMA must remain
+ * at the same physical address in both kernels and must not be freed to the
+ * page allocator while the device can still access it:
+ *
+ * * When using a LUO-preserved ``memfd``, userspace **must** preserve the
Quoted 12 lines
+ * ``memfd`` in the **same** LUO session as the VFIO device and **before** + * preserving the VFIO device. LUO finishes files within a session in reverse + * preservation order (LIFO), guaranteeing that if the device is not taken + * over in the new kernel, VFIO's ``finish()`` callback stops bus mastering + * and resets the device before the ``memfd``'s ``finish()`` callback releases + * its folios. Cross-session ordering is the responsibility of userspace. + * + * * After retrieving a preserved ``memfd`` in the new kernel, its folios are + * ordinary unpinned shmem page cache until pinned again; userspace must keep + * the ``memfd`` alive and re-pin/map it before finishing the session, and + * must not rely on a ``memfd`` whose ``LIVEUPDATE_SESSION_RETRIEVE_FD`` call + * failed (failed ``memfd`` retrieval frees its folios immediately).
Most of this section documents LUO and memfd behavior (finish ordering within and across sessions, what happens to memfd folios after retrieval), which belongs in the LUO and memfd documentation rather than here. The VFIO documentation should just state what VFIO requires of userspace and what happens if userspace violates it. Something like:
DMA Memory
==========
A preserved device keeps performing DMA across kexec to the physical addresses it was programmed with before kexec. VFIO does not know which memory the device accesses and does not preserve it. Userspace must ensure that all memory the device can access stays allocated at the same physical address in both kernels until the device is stopped, either by userspace after taking it over or by VFIO when the session is finished. If userspace violates this, the device can corrupt memory that has been freed and reused by either kernel. VFIO cannot detect this.
VFIO doesn't stop the device when the session is finished until PATCH 11, so either add this section there or drop that clause here and add it in PATCH 11.
drivers/vfio/pci/vfio_pci_liveupdate.c line 193
Quoted 4 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +4
-0+ cfg_size = pdev->cfg_size; + +if (cfg_size !=PCI_CFG_SPACE_SIZE && cfg_size !=PCI_CFG_SPACE_EXP_SIZE ) +return -EINVAL ;
pdev->cfg_size isn't limited to these two values. PCI quirks set other sizes, e.g. quirk_citrine() (0xA0) and quirk_nfp6000() (0x600), and vfio-pci handles those devices fine since vconfig is just pdev->cfg_size bytes. This check only seems to exist to bound the variable-length layout of struct vfio_pci_core_device_ser, which goes away with the changes suggested below. Please drop it.
Quoted 9 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +9
-0+ total_size =size_add (sizeof (*ser), +size_add (size_mul (2 , cfg_size), saved_size)); +if (total_size >U32_MAX ) +return -EOVERFLOW ; + + ser =kho_alloc_preserve (total_size); +if (IS_ERR (ser)) +return PTR_ERR (ser); +
drivers/vfio/pci/vfio_pci_liveupdate.c line 224
Quoted 10 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +10
-0+if (saved_size) { +void *dst = ser->data +2 * (size_t )cfg_size; + + err =pci_liveupdate_serialize_saved_state (vdev->pci_saved_state, + dst, saved_size); +if (err) { +kho_unpreserve_free (ser); +return err; + } + }
Please don't embed struct pci_saved_state_ser in VFIO's serialized struct. Variable-length serialized structs should be preserved in their own allocation, and VFIO should just store the physical address (0 if there is no saved state). That way the PCI core owns the size, flags and validation of its own ABI, either struct can grow without changing the layout of the other, and the offset math here and in PATCH 11 goes away. struct pci_ser already references its devices array the same way.
I plan to structure the PCI core helpers for serializing and deserializing struct pci_saved_state to require this. The PCI core will do the allocation and just return a pointer to the serialized saved state. But I just wanted to call it out here.
drivers/vfio/pci/vfio_pci_liveupdate.c line 236
Quoted 1 line
drivers/vfio/pci/vfio_pci_liveupdate.c +1
-0+ ser->flags = vdev->reset_works ?VFIO_PCI_SER_RESET_WORKS :0 ;
reset_works shouldn't be serialized. Alex's series replaces vdev->reset_works with pci_reset_supported() [1], which only looks at pdev->reset_methods. Those are set up at enumeration without resetting the device, so the next kernel can answer the question itself. And the next kernel's answer is the one that matters, since it's the kernel that will reset the device.
Please base on that series (or cherry-pick that patch) and drop VFIO_PCI_SER_RESET_WORKS, along with the incoming reset_works copy and the reset_works argument to vfio_pci_core_liveupdate_reset() in PATCH 11, and the copy in vfio_pci_liveupdate_take_over() in PATCH 14. flags then has no defined bits, but please keep it (and keep rejecting unknown bits) for future features, see below.
drivers/vfio/pci/vfio_pci_liveupdate.c line 269
Quoted 3 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +3
-0+if (!vdev->vconfig || !vdev->pci_config_map || + ser->cfg_size != pdev->cfg_size) +return -EINVAL ;
ser->cfg_size was set from pdev->cfg_size in preserve(), and pdev->cfg_size doesn't change after enumeration, so the cfg_size check can't fail.
drivers/vfio/pci/vfio_pci_liveupdate.c line 298
Quoted 2 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +2
-0+memcpy (ser->data, vdev->vconfig, ser->cfg_size); +memcpy (ser->data + ser->cfg_size, vdev->pci_config_map, ser->cfg_size);
pci_config_map doesn't need to be preserved. PATCH 14 already rebuilds it with vfio_config_init() in the next kernel and only uses the preserved copy to check that the two are identical.
I assume the intent is to detect changes to vfio-pci's config emulation between the two kernels, but the map isn't a good proxy for that. It changes for differences that don't matter (e.g. hiding a capability or learning the length of a new extended capability), which would fail take-over and lose the Live Update on exactly the kernel upgrades Live Update is meant for. And it doesn't change for differences that do matter, like which bits are virtualized or writable within a capability.
Preserving vconfig makes vfio-pci's config emulation part of the contract between kernels either way. I think changes to the config emulation that affect how a preserved vconfig is interpreted need to be tied to a userspace opt-in, recorded as a flag in struct vfio_pci_core_device_ser. A kernel that doesn't understand the flag then rejects the preserved device, and userspace shouldn't opt in while it can still roll back to a kernel without the new emulation.
drivers/vfio/pci/vfio_pci_liveupdate.c line 303
Quoted 4 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +4
-0+pci_read_config_word (pdev,PCI_COMMAND , &cmd); + vdev->liveupdate_intx_disabled = !!(cmd &PCI_COMMAND_INTX_DISABLE ); +if (!vdev->liveupdate_intx_disabled) +pci_intx (pdev,0 );
This doesn't mask INTx on devices with pdev->broken_intx_masking set, either because PCI_COMMAND_INTX_DISABLE isn't writable or because a quirk marks INTx masking as broken. vfio-pci normally masks INTx for those devices at the interrupt controller, but nothing does that across kexec, so the device can still assert INTx in the next kernel before anything is ready to handle it. If the line is shared, that can get the line disabled as spurious and break the other device.
Please reject those devices in preserve() if they have an INTx pin and !pci_intx_mask_supported(pdev), and add that to the Restrictions in the DOC. Check the PCI core flag rather than vdev->pci_2_3, since vfio_pci.nointxmask=1 clears pci_2_3 even when INTx masking works.
include/linux/kho/abi/vfio_pci.h line 74
Quoted 10 lines
include/linux/kho/abi/vfio_pci.h +10
-0+struct vfio_pci_core_device_ser { +u32 domain; +u16 bdf; +u16 cfg_size; +u32 size; +u32 flags; +u32 saved_state_size; +u32 reserved; +u8 data[]; +} __packed;
Once config_map and the saved state are gone, vconfig is the only variable-length part left. Please either make it a fixed-length array sized for the largest config space (PCI_CFG_SPACE_EXP_SIZE), or preserve it in a separate allocation like the saved state. Either way this struct becomes fixed-size and data[] goes away.
cfg_size should stay, to record how much of vconfig is valid. The next kernel computes pdev->cfg_size on its own and could come up with a different value, so it needs to check that ser->cfg_size matches (and fits in the vconfig buffer) before using the preserved vconfig. Doing that once in retrieve() should be enough.
I understand this will waste some memory today, since each KHO allocation must be a multiple of a PAGE_SIZE. But that is a KHO problem that can be fixed later.
include/linux/vfio_pci_core.h struct vfio_pci_core_device { · line 155
Quoted 4 lines
include/linux/vfio_pci_core.h +4
-0+#ifdef CONFIG_VFIO_PCI_LIVEUPDATE +bool liveupdate_frozen; +bool liveupdate_intx_disabled; +#endif
nit: liveupdate_intx_disabled reads like "INTx is disabled for Live Update", but it actually records whether INTx was already disabled before freeze(). Inverting it to something like liveupdate_masked_intx (i.e. freeze() masked INTx, so unfreeze() needs to unmask it) would make freeze() and unfreeze() easier to follow.
Re: [PATCH v6 07/27] vfio/pci: Preserve vfio-pci device files across Live Update
Quoted 42 lines · David Matlack
Quoted 9 lines · Vipin Sharma
+ * DMA Memory Ordering Contract
+ * ============================
+ *
+ * Because a preserved noiommu device continues performing DMA using physical
+ * addresses across kexec, any memory buffer targeted by device DMA must remain
+ * at the same physical address in both kernels and must not be freed to the
+ * page allocator while the device can still access it:
+ *
+ * * When using a LUO-preserved ``memfd``, userspace **must** preserve theQuoted 12 lines
+ * ``memfd`` in the **same** LUO session as the VFIO device and **before** + * preserving the VFIO device. LUO finishes files within a session in reverse + * preservation order (LIFO), guaranteeing that if the device is not taken + * over in the new kernel, VFIO's ``finish()`` callback stops bus mastering + * and resets the device before the ``memfd``'s ``finish()`` callback releases + * its folios. Cross-session ordering is the responsibility of userspace. + * + * * After retrieving a preserved ``memfd`` in the new kernel, its folios are + * ordinary unpinned shmem page cache until pinned again; userspace must keep + * the ``memfd`` alive and re-pin/map it before finishing the session, and + * must not rely on a ``memfd`` whose ``LIVEUPDATE_SESSION_RETRIEVE_FD`` call + * failed (failed ``memfd`` retrieval frees its folios immediately).Most of this section documents LUO and memfd behavior (finish ordering within and across sessions, what happens to memfd folios after retrieval), which belongs in the LUO and memfd documentation rather than here. The VFIO documentation should just state what VFIO requires of userspace and what happens if userspace violates it. Something like:
DMA Memory
==========A preserved device keeps performing DMA across kexec to the physical addresses it was programmed with before kexec. VFIO does not know which memory the device accesses and does not preserve it. Userspace must ensure that all memory the device can access stays allocated at the same physical address in both kernels until the device is stopped, either by userspace after taking it over or by VFIO when the session is finished. If userspace violates this, the device can corrupt memory that has been freed and reused by either kernel. VFIO cannot detect this.
Quoted 4 lines
VFIO doesn't stop the device when the session is finished until PATCH 11, so either add this section there or drop that clause here and add it in PATCH 11.
Sounds good. I will remove memfd from here and mention thing what VFIO expects.
Quoted 40 lines
drivers/vfio/pci/vfio_pci_liveupdate.c line 193
Quoted 4 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +4
-0+ cfg_size = pdev->cfg_size; + +if (cfg_size !=PCI_CFG_SPACE_SIZE && cfg_size !=PCI_CFG_SPACE_EXP_SIZE ) +return -EINVAL ;
pdev->cfg_sizeisn't limited to these two values. PCI quirks set other sizes, e.g.quirk_citrine()(0xA0) andquirk_nfp6000()(0x600), and vfio-pci handles those devices fine since vconfig is justpdev->cfg_sizebytes. This check only seems to exist to bound the variable-length layout of structvfio_pci_core_device_ser, which goes away with the changes suggested below. Please drop it.Quoted 9 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +9
-0+ total_size =size_add (sizeof (*ser), +size_add (size_mul (2 , cfg_size), saved_size)); +if (total_size >U32_MAX ) +return -EOVERFLOW ; + + ser =kho_alloc_preserve (total_size); +if (IS_ERR (ser)) +return PTR_ERR (ser); +drivers/vfio/pci/vfio_pci_liveupdate.c line 224
Quoted 10 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +10
-0+if (saved_size) { +void *dst = ser->data +2 * (size_t )cfg_size; + + err =pci_liveupdate_serialize_saved_state (vdev->pci_saved_state, + dst, saved_size); +if (err) { +kho_unpreserve_free (ser); +return err; + } + }Please don't embed struct
pci_saved_state_serin VFIO's serialized struct. Variable-length serialized structs should be preserved in their own allocation, and VFIO should just store the physical address (0 if there is no saved state). That way the PCI core owns the size, flags and validation of its own ABI, either struct can grow without changing the layout of the other, and the offset math here and in PATCH 11 goes away. structpci_seralready references its devices array the same way.
Quoted 5 lines
I plan to structure the PCI core helpers for serializing and deserializing struct
pci_saved_stateto require this. The PCI core will do the allocation and just return a pointer to the serialized saved state. But I just wanted to call it out here.
Sounds good, v7 will store physical address returned by new PCI helpers. I will base my series on top of your PCI saved state series latest version. Current one is v2 at
https://lore.kernel.org/all/[email protected]/
Quoted 9 lines
drivers/vfio/pci/vfio_pci_liveupdate.c line 236
Quoted 1 line
drivers/vfio/pci/vfio_pci_liveupdate.c +1
-0+ ser->flags = vdev->reset_works ?VFIO_PCI_SER_RESET_WORKS :0 ;
reset_worksshouldn't be serialized. Alex's series replacesvdev->reset_workswithpci_reset_supported()[1], which only looks atpdev->reset_methods. Those are set up at enumeration without resetting the device, so the next kernel can answer the question itself. And the next kernel's answer is the one that matters, since it's the kernel that will reset the device.
Thanks for bringing it up. I will send that specific patch separately as discussed in
https://lore.kernel.org/kvm/[email protected]/
Quoted 7 lines
Please base on that series (or cherry-pick that patch) and drop
VFIO_PCI_SER_RESET_WORKS, along with the incomingreset_workscopy and thereset_worksargument tovfio_pci_core_liveupdate_reset()in PATCH 11, and the copy invfio_pci_liveupdate_take_over()in PATCH 14. flags then has no defined bits, but please keep it (and keep rejecting unknown bits) for future features, see below.
Quoted 7 lines
drivers/vfio/pci/vfio_pci_liveupdate.c line 269
Quoted 3 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +3
-0+if (!vdev->vconfig || !vdev->pci_config_map || + ser->cfg_size != pdev->cfg_size) +return -EINVAL ;
ser->cfg_sizewas set frompdev->cfg_sizeinpreserve(), andpdev->cfg_sizedoesn't change after enumeration, so thecfg_sizecheck can't fail.
Yeah, this is redundant.
Quoted 8 lines
drivers/vfio/pci/vfio_pci_liveupdate.c line 298
Quoted 3 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +2
-0+memcpy (ser->data, vdev->vconfig, ser->cfg_size); +memcpy (ser->data + ser->cfg_size, vdev->pci_config_map, ser->cfg_size);
pci_config_mapdoesn't need to be preserved. PATCH 14 already rebuilds it withvfio_config_init()in the next kernel and only uses the preserved copy to check that the two are identical.
Quoted 7 lines
I assume the intent is to detect changes to vfio-pci's config emulation between the two kernels, but the map isn't a good proxy for that. It changes for differences that don't matter (e.g. hiding a capability or learning the length of a new extended capability), which would fail take-over and lose the Live Update on exactly the kernel upgrades Live Update is meant for. And it doesn't change for differences that do matter, like which bits are virtualized or writable within a capability.
I think it does matter because reads and writes of unitialized capabilities in VFIO PCI config space goes to hardware directly. So, in the new kernel if pci_config_map changes it from PCI_CAP_ID_INVALID to others then those reads/writes can go to vconfig which will contain stale unitialized data from the old kernel's heap.
This also changes behavior under a running user. Writes that reached hardware before Live Update can be silently dropped or redirected to vconfig. See the comment above struct perm_bits unassigned_perms{} in vfio_pci_config.c
I do agree current patch is not protecting against bits virt/write changes inside a capability, which is also important.
Quoted 8 lines
Preserving vconfig makes vfio-pci's config emulation part of the contract between kernels either way. I think changes to the config emulation that affect how a preserved vconfig is interpreted need to be tied to a userspace opt-in, recorded as a flag in struct
vfio_pci_core_device_ser. A kernel that doesn't understand the flag then rejects the preserved device, and userspace shouldn't opt in while it can still roll back to a kernel without the new emulation.
How would a userspace opt-in? New kernel can change a capability visiblity or virt and write permission of the bits inside a capability. Kernel cannot know if userspace used the capability or not. Creating a VFIO device in the new kernel by default results in a opt-in and currently there is no way for userspace to opt-out unless we add a new functionality where userspace can disable/enable features something similar to KVM capabilities.
For now, I think we don't need to worry about it. As this version will be a base and if any serialized data with flags set received in this kernel will lead to erroring out restore.
In the next version, I will not preserve pci_config_map. Hopefully, anyone changing VFIO code doesn't forget to update flags if they change capability or permission bits (I will write comments at appropriate places.)
If we want to be very careful, we can do two things in this series:
1. Create a per bit valid mask for the vconfig and compare this between new and old kernel during restore. In the new kernel, VFIO then takes each bit from the preserved copy only where the mask says it was valid, and keeps its own freshly initialized value elsewhere.
2. Create a hash or store virt and writable bits in config space. Compare it with the new kernel.
Both of the above combined will safeguard against forgotten flag update in the code.
We don't have to do it but it safeguards against mistakes. Let me know what you prefer.
Quoted 14 lines
drivers/vfio/pci/vfio_pci_liveupdate.c line 303
Quoted 5 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +4
-0+pci_read_config_word (pdev,PCI_COMMAND , &cmd); + vdev->liveupdate_intx_disabled = !!(cmd &PCI_COMMAND_INTX_DISABLE ); +if (!vdev->liveupdate_intx_disabled) +pci_intx (pdev,0 );This doesn't mask INTx on devices with
pdev->broken_intx_maskingset, either becausePCI_COMMAND_INTX_DISABLEisn't writable or because a quirk marks INTx masking as broken. vfio-pci normally masks INTx for those devices at the interrupt controller, but nothing does that across kexec, so the device can still assert INTx in the next kernel before anything is ready to handle it. If the line is shared, that can get the line disabled as spurious and break the other device.
Quoted 4 lines
Please reject those devices in
preserve()if they have an INTx pin and !pci_intx_mask_supported(pdev), and add that to the Restrictions in the DOC. Check the PCI core flag rather thanvdev->pci_2_3, since vfio_pci.nointxmask=1 clearspci_2_3even when INTx masking works.
Agree, I will reject those devices in preserve().
Quoted 24 lines
include/linux/kho/abi/vfio_pci.h line 74
Quoted 11 lines
include/linux/kho/abi/vfio_pci.h +10
-0+struct vfio_pci_core_device_ser { +u32 domain; +u16 bdf; +u16 cfg_size; +u32 size; +u32 flags; +u32 saved_state_size; +u32 reserved; +u8 data[]; +} __packed;Once
config_mapand the saved state are gone, vconfig is the only variable-length part left. Please either make it a fixed-length array sized for the largest config space (PCI_CFG_SPACE_EXP_SIZE), or preserve it in a separate allocation like the saved state. Either way this struct becomes fixed-size and data[] goes away.
cfg_sizeshould stay, to record how much of vconfig is valid. The next kernel computespdev->cfg_sizeon its own and could come up with a different value, so it needs to check thatser->cfg_sizematches (and fits in the vconfig buffer) before using the preserved vconfig. Doing that once inretrieve()should be enough.
Quoted 4 lines
I understand this will waste some memory today, since each KHO allocation must be a multiple of a
PAGE_SIZE. But that is a KHO problem that can be fixed later.
I agree. I will change data to fixed size for vconfig. We will not need pci_config_map, and pci saved state array.
I am planning to add two flags required and optional similar to your PCI serialization struct.
Thanks again for the review.
David Matlack
maintainerRe: [PATCH v6 07/27] vfio/pci: Preserve vfio-pci device files across Live Update
Quoted 18 lines · Vipin Sharma
Quoted 11 lines
pci_config_mapdoesn't need to be preserved. PATCH 14 already rebuilds it withvfio_config_init()in the next kernel and only uses the preserved copy to check that the two are identical.I assume the intent is to detect changes to vfio-pci's config emulation between the two kernels, but the map isn't a good proxy for that. It changes for differences that don't matter (e.g. hiding a capability or learning the length of a new extended capability), which would fail take-over and lose the Live Update on exactly the kernel upgrades Live Update is meant for. And it doesn't change for differences that do matter, like which bits are virtualized or writable within a capability.
I think it does matter because reads and writes of unitialized capabilities in VFIO PCI config space goes to hardware directly. So, in the new kernel if
pci_config_mapchanges it fromPCI_CAP_ID_INVALIDto others then those reads/writes can go to vconfig which will contain stale unitialized data from the old kernel's heap.
Quoted 4 lines
This also changes behavior under a running user. Writes that reached hardware before Live Update can be silently dropped or redirected to vconfig. See the comment above struct
perm_bitsunassigned_perms{} invfio_pci_config.c
That's true. Unassigned bytes passed through and vconfig is never initialized for them, so hiding or exposing a capability does matter. For example, 6467d0740a2b ("vfio/pci: Add DVSEC PCI Extended Config Capability to user visible list") changed DVSEC from hidden (all bytes raw) to exposed with a virtualized header. Across that boundary, v6 would have served DVSEC from uninitialized bytes in vconfig.
Quoted 11 lines
How would a userspace opt-in? New kernel can change a capability visiblity or virt and write permission of the bits inside a capability. Kernel cannot know if userspace used the capability or not. Creating a VFIO device in the new kernel by default results in a opt-in and currently there is no way for userspace to opt-out unless we add a new functionality where userspace can disable/enable features something similar to KVM capabilities.
For now, I think we don't need to worry about it. As this version will be a base and if any serialized data with flags set received in this kernel will lead to erroring out restore.
We don't need an opt-in mechanism in this series. Detecting mismatches is enough to make Live Update safe in both directions: if the next kernel would emulate the device in an incompatible way, retrieve should fail.
But an opt-in is needed to make rollback possible once vfio-pci starts changing its emulation. I imagine something like a VFIO_DEVICE_FEATURE that userspace can use to enable new emulation behavior right after opening the device, with the enabled bits recorded in a field appended to struct vfio_pci_core_device_ser behind a required flag. Devices that don't opt in keep the baseline emulation and stay compatible with older kernels. But that can come in a follow-on series.
Quoted 14 lines
In the next version, I will not preserve
pci_config_map. Hopefully, anyone changing VFIO code doesn't forget to update flags if they change capability or permission bits (I will write comments at appropriate places.)If we want to be very careful, we can do two things in this series:
1. Create a per bit valid mask for the vconfig and compare this between new and old kernel during restore. In the new kernel, VFIO then takes each bit from the preserved copy only where the mask says it was valid, and keeps its own freshly initialized value elsewhere.
2. Create a hash or store virt and writable bits in config space. Compare it with the new kernel.
Quoted 5 lines
Both of the above combined will safeguard against forgotten flag update in the code.
We don't have to do it but it safeguards against mistakes. Let me know what you prefer.
I think we should do both in this series, as two per-bit masks over config space, preserved in place of pci_config_map:
- virt[]: the bits whose value vfio-pci keeps in vconfig and returns instead of the device's value. This says which bits of the preserved vconfig are valid.
- write[]: the bits whose writes take effect. For bits in virt they update vconfig, and for other bits they are forwarded to the device (possibly after validation). Writes to other bits are ignored.
The masks should describe what vfio-pci actually does rather than copy perm->virt and perm->write.
vfio-pci can keep changing its implementation in ways that don't break Live Update, e.g. start intercepting writes to a register to sanity check them before forwarding them to the device.
Something like:
struct vfio_pci_core_device_ser {
...
u8 virt[PCI_CFG_SPACE_EXP_SIZE];
u8 write[PCI_CFG_SPACE_EXP_SIZE];
u8 vconfig[PCI_CFG_SPACE_EXP_SIZE];
} __packed;[ Note: I'd probably store virt[], write[], and vconfig[] on their
own folios to avoid multi-order folio allocations, but I am embedding them here for simplicity. ]
The outgoing kernel computes virt[] and write[] through a helper in vfio_pci_config.c and saves vconfig[] during freeze().
The incoming kernel computes its own virt[] and write[] masks and requires both to match exactly with what's in vfio_pci_core_device_ser, otherwise it fails the retrieve. On take-over it uses the preserved value for bits in virt and its own freshly initialized value for the rest, like your option 1.
I'd store the full masks rather than a hash, so that a mismatch can be pinpointed.
Re: [PATCH v6 07/27] vfio/pci: Preserve vfio-pci device files across Live Update
In reply to Vipin SharmaQuoted 67 lines · Vipin Sharma
Implement the Live Update file handler callbacks to preserve a vfio-pci device in noiommu mode across a Live Update while keeping it running across kexec. Subsequent commits will enable userspace to retrieve and take over this file after the Live Update.
State about each device is serialized into struct
vfio_pci_core_device_serusing Kexec-Handover (KHO) to preserve the pages holding the struct and the Live Update Orchestrator (LUO) to preserve the physical address of the struct.Key design notes and constraints:
* Noiommu-only policy and bound cdev requirement:
can_preserve()verifies that the preserved file is a bound vfio-pci cdev file descriptor viavfio_file_is_bound_cdev(), andpreserve()requires the device to be in noiommu mode viavfio_device_is_noiommu()(returning-EOPNOTSUPPotherwise).CONFIG_VFIO_PCI_LIVEUPDATEnow depends onCONFIG_VFIO_DEVICE_CDEVandCONFIG_VFIO_NOIOMMU.* Serialized state: During
preserve(), serialize the PCI domain, BDF, config space size,reset_worksflag, and the initialpci_saved_statecaptured when the device was first opened. Duringfreeze(), snapshot the virtualized PCI config space (vconfig) and capability map (pci_config_map).* Keep-running freeze and unfreeze: Do not reset the device, clear
PCI_COMMAND_MASTER, zap BAR mappings, or revoke dma-bufs duringfreeze(). Validate that VFIO interrupts are disabled, that the device is inPCI_D0(and not in VFIO runtime PM low-power mode), and that SR-IOV is not enabled, as VFs are not preserved and the next kernel disables SR-IOV on the running device. Then mask physical INTx (recording the prior state) and mark the device frozen. If the Live Update is aborted afterfreeze(),unfreeze()restores the physical INTx state and clearsliveupdate_frozenso the existing FD remains usable.* TOCTOU synchronization:
vfio_pci_dev_is_frozen()is checked locklessly on entry to the ioctl, read/write and mmap paths, and re-checked under a lock thatfreeze()holds before any operation that could change the device or vconfig: undervdev->igateinvfio_pci_ioctl_set_irqs()and around every config-space write invfio_pci_config_rw_single(), undervdev->memory_lockinvfio_pci_runtime_pm_entry(),vfio_pci_ioctl_reset()and the SR-IOV enable path ofvfio_pci_core_sriov_configure(), and underdev_set->lockinvfio_pci_dev_set_hot_reset(). A racing operation thus either completes beforefreeze()takes its snapshot or fails, while existing BAR mmaps, ioeventfds and dma-bufs keep working. Serializing config writes on igate covers thePCI_COMMAND, INTx disable emulation, power state and FLR paths at one point (the INTx disable emulation now uses the igate-held__vfio_pci_intx_mask()and__vfio_pci_intx_unmask()helpers), and also serializes theirq_typeandvirq_disabledaccesses of config writes withVFIO_DEVICE_SET_IRQS.Co-developed-by David Matlack <[email protected]>Signed-off-by David Matlack <[email protected]>Signed-off-by Vipin Sharma <[email protected]>---
drivers/vfio/pci/Kconfig | 2 +- drivers/vfio/pci/vfio_pci_config.c | 19 +- drivers/vfio/pci/vfio_pci_core.c | 49 +++- drivers/vfio/pci/vfio_pci_intrs.c | 4 +- drivers/vfio/pci/vfio_pci_liveupdate.c | 303 ++++++++++++++++++++++++- drivers/vfio/pci/vfio_pci_priv.h | 13 ++ include/linux/kho/abi/vfio_pci.h | 52 ++++- include/linux/vfio_pci_core.h | 4 + 8 files changed, 434 insertions(+), 12 deletions(-)
[snip]
Quoted 59 lines
include/linux/kho/abi/vfio_pci.h +36
-2@@ -9,14 +9,19 @@#ifndef _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H#define _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H +#include <linux/bits.h> +#include <linux/compiler.h> +#include <linux/types.h> +/** * DOC: VFIO PCI Live Update ABI * * VFIO uses the ABI defined below for preserving device files across a kexec * reboot using LUO. * -* Device metadata is serialized into memory which is then handed to the next -* kernel via KHO. +* Device metadata, virtualized PCI configuration space, VFIO's capability map, +* and the initial PCI saved state captured when the device was first opened are +* 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 @@ -25,4 +30,47 @@#define VFIO_PCI_LUO_FH_COMPATIBLE "vfio-pci-v1" +/** +* define VFIO_PCI_SER_RESET_WORKS - Device supports function reset. +* +* Set in &vfio_pci_core_device_ser.flags when the preserved device had +* ``vdev->reset_works == true`` prior to kexec. +*/ +#define VFIO_PCI_SER_RESET_WORKS BIT(0) + +#define VFIO_PCI_SER_KNOWN_FLAGS VFIO_PCI_SER_RESET_WORKS + +/** +* struct vfio_pci_core_device_ser - Serialized state of a single VFIO PCI +* device. +* +* @domain: The device's PCI domain number (segment). +* @bdf: The device's PCI bus, device, and function number. +* @cfg_size: Size in bytes of the device's PCI configuration space +* (``PCI_CFG_SPACE_SIZE`` or ``PCI_CFG_SPACE_EXP_SIZE``). +* @size: Total size in bytes of this serialized buffer, equal to +* ``sizeof(struct vfio_pci_core_device_ser) + 2 * @cfg_size + @saved_state_size``. +* @flags: Bitmask of ``VFIO_PCI_SER_*`` flags; unknown bits are rejected. +* @saved_state_size: Size in bytes of the serialized &struct pci_saved_state_ser +* blob stored in @data after ``config_map``, or 0 if none. +* @reserved: Reserved for future use; must be 0. +* @data: Variable-length payload containing, in order: +* 1. ``u8 vconfig[@cfg_size]`` - VFIO virtualized config space snapshot +* captured during ``freeze()``. +* 2. ``u8 config_map[@cfg_size]`` - VFIO capability map snapshot +* captured during ``freeze()``.
include/linux/kho/abi/vfio_pci.h line 71
Quoted 10 lines
include/linux/kho/abi/vfio_pci.h +10
-0+* 3. ``u8 saved_state[@saved_state_size]`` - serialized +* &struct pci_saved_state_ser captured during ``preserve()``. +*/ +struct vfio_pci_core_device_ser { +u32 domain; +u16 bdf; +u16 cfg_size; +u32 size; +u32 flags; +u32 saved_state_size;
We will need space for iommufd_token when we preserve that, we should probably add it now as otherwise the compatibility would be broken when we add it? Is the reserved here for that?
Quoted 23 lines
include/linux/kho/abi/vfio_pci.h +4
-0+u32 reserved; + u8 data[]; +} __packed; +#endif /* _LINUX_LIVEUPDATE_ABI_VFIO_PCI_H */ include/linux/vfio_pci_core.h +4
-0@@ -149,6 +149,10 @@ struct vfio_pci_core_device {struct notifier_block nb;struct rw_semaphore memory_lock;struct list_head dmabufs; +#ifdef CONFIG_VFIO_PCI_LIVEUPDATE +bool liveupdate_frozen; +bool liveupdate_intx_disabled; +#endif };enum vfio_pci_io_width {Signature · 1 line
2.56.0.317.g454f8302e1-goog
Thanks,
Sami
Re: [PATCH v6 07/27] vfio/pci: Preserve vfio-pci device files across Live Update
Quoted 26 lines · Samiullah Khawaja
Quoted 25 lines · Vipin Sharma
include/linux/kho/abi/vfio_pci.h +25
-0+/** +* struct vfio_pci_core_device_ser - Serialized state of a single VFIO PCI +* device. +* +* @domain: The device's PCI domain number (segment). +* @bdf: The device's PCI bus, device, and function number. +* @cfg_size: Size in bytes of the device's PCI configuration space +* (``PCI_CFG_SPACE_SIZE`` or ``PCI_CFG_SPACE_EXP_SIZE``). +* @size: Total size in bytes of this serialized buffer, equal to +* ``sizeof(struct vfio_pci_core_device_ser) + 2 * @cfg_size + @saved_state_size``. +* @flags: Bitmask of ``VFIO_PCI_SER_*`` flags; unknown bits are rejected. +* @saved_state_size: Size in bytes of the serialized &struct pci_saved_state_ser +* blob stored in @data after ``config_map``, or 0 if none. +* @reserved: Reserved for future use; must be 0. +* @data: Variable-length payload containing, in order: +* 1. ``u8 vconfig[@cfg_size]`` - VFIO virtualized config space snapshot +* captured during ``freeze()``. +* 2. ``u8 config_map[@cfg_size]`` - VFIO capability map snapshot +* captured during ``freeze()``. +* 3. ``u8 saved_state[@saved_state_size]`` - serialized +* &struct pci_saved_state_ser captured during ``preserve()``. +*/ +struct vfio_pci_core_device_ser { +u32 domain; +u16 bdf;
Quoted 8 lines
include/linux/kho/abi/vfio_pci.h line 71
Quoted 4 lines
include/linux/kho/abi/vfio_pci.h +4
-0+u16 cfg_size; +u32 size; +u32 flags; +u32 saved_state_size;We will need space for
iommufd_tokenwhen we preserve that, we should probably add it now as otherwise the compatibility would be broken when we add it? Is the reserved here for that?
No, reserved was just to align data[] to 4 bytes boundary.
Based on David's suggestion, I am gonna get rid of variable length data[]. This whole serialization struct will be fixed length.
I think it will be fine to extend this struct by adding a new field at the end of struct in your series along with updated flag when you add iommufd support.
iommufd preserved vfio device cannot be rollbacked to this kernel where there is no support for iommufd preservation, so, flags will be correct to reject the change.
Do you have some other concerns when yiou compatibility would be broken?
Quoted 4 lines
Quoted 4 lines
include/linux/kho/abi/vfio_pci.h +4
-0+u32 reserved; +u8 data[]; +} __packed; +
PATCH v6 8/27 vfio: Introduce vfio_find_device() helper
In reply to Vipin SharmaIntroduce vfio_find_device() to discover a registered vfio_device from vfio_device_class matching user-provided criteria.
To ensure safe lifecycle handling, vfio_find_device() acquires a registration reference (device->refcount) via vfio_device_try_get_registration() rather than relying solely on device.kref taken in class_find_device(). Holding only kref allows vendor modules to unload while external callers hold device pointers, leading to a kernel panic on release. Callers must release the device via vfio_device_put_registration().
Additionally, move refcount_set() prior to vfio_device_add() in __vfio_register_dev() so device->refcount is initialized before the device is published to class lookups, avoiding registration data races.
On vfio_device_add() failure, the error path drops the initial registration reference and waits for completion to drain any reference taken by a concurrent lookup before returning the error to the driver.
--- drivers/vfio/vfio_main.c | 64 +++++++++++++++++++++++++++++++++++++--- include/linux/vfio.h | 2 ++ 2 files changed, 62 insertions(+), 4 deletions(-)
drivers/vfio/vfio_main.c +60 -4
@@ -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>
@@ -383,17 +384,20 @@ static int __vfio_register_dev(struct vfio_device *device, goto err_out; } - ret =vfio_device_add (device); -if (ret) - goto err_out; -/* Refcounting can't start until the driver calls register */ refcount_set (&device->refcount,1 ); + ret =vfio_device_add (device); +if (ret) + goto err_add; +vfio_device_group_register (device);vfio_device_debugfs_init (device);return 0 ; +err_add: +vfio_device_put_registration (device); +wait_for_completion (&device->comp); err_out:vfio_device_remove_group (device);return ret;
@@ -1845,6 +1849,58 @@ int vfio_dma_rw(struct vfio_device *device, dma_addr_t iova, void *data, }EXPORT_SYMBOL (vfio_dma_rw); +struct vfio_device_match_data { +const void *data; +device_match_t match; +}; + +static int vfio_device_match_fn (struct device *dev,const void *data) +{ + struct vfio_device *vdev = container_of(dev, struct vfio_device, device); +const struct vfio_device_match_data *mdata = data; + +if (mdata->match (dev, mdata->data)) { +if (vfio_device_try_get_registration (vdev)) +return 1 ; + } +return 0 ; +} + +/** +* vfio_find_device - Find a registered VFIO device matching search criteria +* @data: Context data passed to the @match function +* @match: Device match callback function +* +* Finds a registered VFIO device in the vfio_device_class matching the search +* criteria specified by @match. +* +* On success, this function acquires a registration reference on the matched +* device via vfio_device_try_get_registration(). This pins the device and +* prevents its vendor driver module from unloading or unbinding while the +* reference is held. +* +* Return: Pointer to the matching vfio_device on success, or NULL if no +* matching device is found. The caller MUST release the acquired registration +* reference using vfio_device_put_registration() when finished with the device. +*/ +struct vfio_device *vfio_find_device (const void *data,device_match_t match) +{ +struct vfio_device_match_data mdata = { .data = data, .match = match }; +struct device *device; + + device =class_find_device (&vfio_device_class,NULL , &mdata, vfio_device_match_fn); +if (!device) +return NULL ; + +/* +* Drop standard kref reference. Caller holds reference from +* vfio_device_try_get_registration(). +*/ +put_device (device); + return container_of(device, struct vfio_device, device); +} +EXPORT_SYMBOL_GPL (vfio_find_device); +/* * Module/class support */
include/linux/vfio.h +2 -0
@@ -441,4 +441,6 @@ static inline bool vfio_file_is_bound_cdev(struct file *file) }#endif /* IS_ENABLED(CONFIG_VFIO_DEVICE_CDEV) */ +struct vfio_device *vfio_find_device (const void *data,device_match_t match); +#endif /* VFIO_H */
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 9/27 vfio: Refactor vfio_device_fops_cdev_open()
In reply to Vipin SharmaRefactor vfio_device_fops_cdev_open() to use a static helper vfio_device_cdev_open(). This helper will be used in subsequent patches to support opening the device file during Live Update restore.
No functional change intended.
--- drivers/vfio/device_cdev.c | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-)
drivers/vfio/device_cdev.c +15 -9
@@ -20,14 +20,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) +static int vfio_device_cdev_open (struct vfio_device *device,struct file *file) { -struct vfio_device *device =container_of (inode->i_cdev, - struct vfio_device, cdev);struct vfio_device_file *df;int ret;
@@ -46,14 +40,14 @@ int vfio_device_fops_cdev_open(struct inode *inode, struct file *filep) goto err_put_registration; } - filep->private_data = df; + file->private_data = df;/* * Use the pseudo fs inode on the device to link all mmaps * to the same address space, allowing us to unmap all vmas * associated to this device using unmap_mapping_range(). */ - filep->f_mapping = device->inode->i_mapping; + file->f_mapping = device->inode->i_mapping;return 0 ;
@@ -62,6 +56,18 @@ int vfio_device_fops_cdev_open(struct inode *inode, struct file *filep)return ret; } +/* +* 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 *file) +{ +struct vfio_device *device =container_of (inode->i_cdev, + struct vfio_device, cdev); + +return vfio_device_cdev_open (device, file); +} +static void vfio_df_get_kvm_safe (struct vfio_device_file *df) {spin_lock (&df->kvm_ref_lock);
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 10/27 vfio: Add API to open cdev device for Live Update restore
In reply to Vipin SharmaDuring Live Update restore, VFIO PCI driver needs to recreate the device file context that was preserved before kexec and return it to the user.
Provide an API for VFIO Live Update to get VFIO device file. 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.
--- drivers/vfio/device_cdev.c | 39 ++++++++++++++++++++++++++++++++++++-- include/linux/vfio.h | 6 ++++++ 2 files changed, 43 insertions(+), 2 deletions(-)
drivers/vfio/device_cdev.c +37 -2
@@ -2,6 +2,7 @@/* * Copyright (c) 2023 Intel Corporation. */ +#include <linux/anon_inodes.h> #include <linux/vfio.h> #include <linux/iommufd.h>
@@ -20,9 +21,10 @@ void vfio_init_device_cdev(struct vfio_device *device) device->cdev.owner =THIS_MODULE ; } -static int vfio_device_cdev_open (struct vfio_device *device,struct file *file) +static int vfio_device_cdev_open (struct vfio_device *device,struct file **filep) {struct vfio_device_file *df; +struct file *file = *filep;int ret;/* Paired with the put in vfio_device_fops_release() */
@@ -40,6 +42,24 @@ static int vfio_device_cdev_open(struct vfio_device *device, struct file *file) goto err_put_registration; } +/* +* 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). +*/ +if (!file) { + 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 err_free_device_file; + } + + *filep = file; + } + file->private_data = df;/*
@@ -51,11 +71,26 @@ static int vfio_device_cdev_open(struct vfio_device *device, struct file *file)return 0 ; +err_free_device_file: +kfree (df); err_put_registration:vfio_device_put_registration (device);return ret; } +struct file *vfio_device_liveupdate_cdev_open (struct vfio_device *device) +{ +struct file *file =NULL ; +int ret; + + ret =vfio_device_cdev_open (device, &file); +if (ret) +return ERR_PTR (ret); + +return file; +} +EXPORT_SYMBOL_GPL (vfio_device_liveupdate_cdev_open); +/* * device access via the fd opened by this function is blocked until * .open_device() is called successfully during BIND_IOMMUFD.
@@ -65,7 +100,7 @@ int vfio_device_fops_cdev_open(struct inode *inode, struct file *file)struct vfio_device *device =container_of (inode->i_cdev, struct vfio_device, cdev); -return vfio_device_cdev_open (device, file); +return vfio_device_cdev_open (device, &file); }static void vfio_df_get_kvm_safe (struct vfio_device_file *df)
include/linux/vfio.h +6 -0
@@ -434,11 +434,17 @@ void vfio_virqfd_flush_thread(struct virqfd **pvirqfd);#if IS_ENABLED (CONFIG_VFIO_DEVICE_CDEV )bool vfio_file_is_bound_cdev (struct file *file); +struct file *vfio_device_liveupdate_cdev_open (struct vfio_device *device);#else static inline bool vfio_file_is_bound_cdev (struct file *file) {return false; } + +static inline struct file *vfio_device_liveupdate_cdev_open (struct vfio_device *device) +{ +return ERR_PTR (-EOPNOTSUPP ); +}#endif /* IS_ENABLED(CONFIG_VFIO_DEVICE_CDEV) */ struct vfio_device *vfio_find_device (const void *data,device_match_t match);
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 11/27 vfio/pci: Retrieve preserved device files after Live Update
In reply to Vipin SharmaEnable userspace to retrieve preserved VFIO device files after a Live Update by implementing the retrieve() and finish() file handler callbacks.
During retrieve():
* Validate the handed-over struct vfio_pci_core_device_ser header, sizes, and flags.
* Locate the registered vfio-pci device matching the serialized domain and BDF (requiring device->ops == &vfio_pci_ops) under the device lock. vfio-pci registers the vfio device before its probe completes, and the probe holds that lock, so a device that is still being probed is not returned.
* Require the device to be in noiommu mode in the new kernel (returning -EOPNOTSUPP otherwise), still marked incoming by the PCI Live Update core, and matching the serialized PCI config space size.
* Deserialize the inherited struct pci_saved_state and copy the handed-over vconfig and pci_config_map into a kernel-owned struct vfio_pci_liveupdate_incoming attached to vdev under dev_set->lock via vfio_pci_liveupdate_attach_incoming(), leaving the KHO serialized buffer read-only.
* Open and return an anonymous VFIO cdev file via vfio_device_liveupdate_cdev_open().
Do not implement can_finish(): closing a retrieved LUO session invokes finish, and refusing can_finish() would leak the session and leave unclaimed devices running. Instead, finish() always completes:
* If the retrieved device was claimed by opening it via VFIO_DEVICE_BIND_IOMMUFD (which consumes vdev->liveupdate_incoming; subsequent patches replace the open-time reset with non-reset take-over, reject opening incoming devices other than via retrieve(), and protect incoming kept-running devices across runtime PM, dev_set resets, and non-noiommu boots), finish() simply completes its PCI Live Update participation.
* If the device was not claimed (never retrieved, retrieve() failed, or retrieved but never bound via VFIO_DEVICE_BIND_IOMMUFD), vfio_pci_core_liveupdate_reset() logs one pci_warn() naming the device, clears PCI_COMMAND_MASTER, resets the function, and restores the inherited pci_saved_state just as closing the device would. If the device has a function reset but is not reset, e.g. because pci_dev_trylock() contends with a concurrent driver unbind, latch vdev->liveupdate_reset_pending so vfio_pci_core_unregister_device() completes the function reset and state restoration via vfio_pci_core_liveupdate_reset_locked() under the device lock held by device_release_driver(). Opening the device after finish() resets it like any open, so it drops the latch.
* If the device was not retrieved, look it up under pci_dev_lock(), which waits for a vfio-pci probe in progress. If it is bound to vfio-pci, finish it as above. If it has no driver, clear bus mastering and reset it. Otherwise leave it to the bound driver.
* Call pci_liveupdate_finish() and kho_restore_free() on every path.
--- drivers/vfio/pci/vfio_pci_core.c | 65 +++++ drivers/vfio/pci/vfio_pci_liveupdate.c | 342 ++++++++++++++++++++++++- drivers/vfio/pci/vfio_pci_priv.h | 75 ++++++ include/linux/vfio_pci_core.h | 6 + 4 files changed, 484 insertions(+), 4 deletions(-)
drivers/vfio/pci/vfio_pci_core.c +65 -0
@@ -671,6 +671,8 @@ int vfio_pci_core_enable(struct vfio_pci_core_device *vdev)vfio_pci_core_map_bars (vdev); +vfio_pci_liveupdate_claim_incoming (vdev); +return 0 ; out_free_zdev:
@@ -739,6 +741,63 @@ static void vfio_pci_core_try_reset(struct vfio_pci_core_device *vdev)pci_restore_state (pdev); } +/* +* Reset a device that was kept running across a Live Update but not taken over, +* from the Live Update finish() of the device. Return true if the device was +* reset, false if it could not be reset, e.g. because its device lock could +* not be taken. +*/ +bool vfio_pci_core_liveupdate_reset (struct vfio_pci_core_device *vdev, +struct pci_saved_state *saved_state, +bool reset_works,const char *reason) +{ +struct pci_dev *pdev = vdev->pdev; + +lockdep_assert_held (&vdev->vdev.dev_set->lock); + +if (reason) +pci_warn (pdev, +"Resetting device not taken over after Live Update (%s)\n" , + reason); + +pci_clear_master (pdev); +if (!saved_state) +pci_save_state (pdev); +kfree (vdev->pci_saved_state); + vdev->pci_saved_state = saved_state; + vdev->reset_works = reset_works; +vfio_pci_core_try_reset (vdev); + +return !vdev->needs_reset; +} +EXPORT_SYMBOL_GPL (vfio_pci_core_liveupdate_reset); + +/* +* Reset a device preserved across a Live Update from its remove() path, where +* the driver core holds the device lock. Save and restore the config space +* around the reset like vfio_pci_core_try_reset(), and block user config +* access while doing so. Like pci_reset_function_locked(), do not take the +* upstream bridge lock: remove() cannot wait for it without inverting the +* bridge -> device lock order, and the Live Update finish() of an unbound +* device holds it while it waits for the device lock held here. +*/ +void vfio_pci_core_liveupdate_reset_locked (struct vfio_pci_core_device *vdev) +{ +struct pci_dev *pdev = vdev->pdev; + +device_lock_assert (&pdev->dev); +lockdep_assert_held (&vdev->vdev.dev_set->lock); + +pci_clear_master (pdev); +pci_cfg_access_lock (pdev); +pci_save_state (pdev); +pci_write_config_word (pdev,PCI_COMMAND ,PCI_COMMAND_INTX_DISABLE ); +if (!__pci_reset_function_locked (pdev)) + vdev->needs_reset = false; +pci_restore_state (pdev); +pci_cfg_access_unlock (pdev); +} +void vfio_pci_core_disable (struct vfio_pci_core_device *vdev) {struct pci_dev *pdev = vdev->pdev;
@@ -2362,6 +2421,12 @@ void vfio_pci_core_unregister_device(struct vfio_pci_core_device *vdev)vfio_unregister_group_dev (&vdev->vdev); +/* +* Must follow vfio_unregister_group_dev(), which waits for the +* references a Live Update finish() of the device may hold. +*/ +vfio_pci_liveupdate_unregister_dev (vdev); +vfio_pci_vf_uninit (vdev);vfio_pci_vga_uninit (vdev);
drivers/vfio/pci/vfio_pci_liveupdate.c +338 -4
384 lines not on this page · raw message
drivers/vfio/pci/vfio_pci_priv.h +75 -0
93 lines not on this page · raw message
include/linux/vfio_pci_core.h +6 -0
@@ -152,6 +152,9 @@ struct vfio_pci_core_device {#ifdef CONFIG_VFIO_PCI_LIVEUPDATE bool liveupdate_frozen;bool liveupdate_intx_disabled; +bool liveupdate_claimed; +bool liveupdate_reset_pending; +struct vfio_pci_liveupdate_incoming *liveupdate_incoming;#endif };
@@ -197,6 +200,9 @@ int vfio_pci_core_match_token_uuid(struct vfio_device *core_vdev,int vfio_pci_core_enable (struct vfio_pci_core_device *vdev);void vfio_pci_core_disable (struct vfio_pci_core_device *vdev);void vfio_pci_core_finish_enable (struct vfio_pci_core_device *vdev); +bool vfio_pci_core_liveupdate_reset (struct vfio_pci_core_device *vdev, +struct pci_saved_state *saved_state, +bool reset_works,const char *reason);pci_ers_result_t vfio_pci_core_aer_err_detected (struct pci_dev *pdev,pci_channel_state_t state); ssize_t vfio_pci_core_do_io_rw(struct vfio_pci_core_device *vdev, bool test_mem,
Signature · 1 line
2.56.0.317.g454f8302e1-goog
David Matlack
maintainerRe: [PATCH v6 11/27] vfio/pci: Retrieve preserved device files after Live Update
Quoted 8 lines · Vipin Sharma
During
retrieve():
* Validate the handed-over structvfio_pci_core_device_serheader, sizes, and flags.
* Locate the registered vfio-pci device matching the serialized domain and BDF (requiringdevice->ops==&vfio_pci_ops) under the device lock. vfio-pci registers the vfio device before its probe completes, and the probe holds that lock, so a device that is still being probed is not returned.
[...]
Quoted 2 lines
* Open and return an anonymous VFIO cdev file via
vfio_device_liveupdate_cdev_open().
Here's an idea for how the device file could be created on retrieve, which I'd like to hear your thoughts on.
The patches from Pasha at [1] lets userspace pass a file-handler-specific argument to LIVEUPDATE_SESSION_RETRIEVE_FD. In the next version of the tmpfs series, I'm planning to use that to have userspace create the file and pass it in the argument, and the kernel then restores the preserved file into it.
I wonder if VFIO should work the same way, e.g.:
struct liveupdate_vfio_retrieve_arg {
__u32 size;
__s32 fd;
};Userspace would open /dev/vfio/devices/noiommu-vfioX itself and pass the fd. retrieve() would check that it's an unbound vfio-pci cdev file for the preserved device (domain/BDF, noiommu, incoming, cfg_size), attach the incoming state to that file, and LUO would track that file as the retrieved file. VFIO_DEVICE_BIND_IOMMUFD would then take over the device as it does now. Since VFIO preservation is new, the argument could simply be required.
I think this could get rid of some of the special handling:
- There'd be no need to fake a cdev open with an anonymous inode, so PATCH 09 and PATCH 10 could probably be dropped.
- retrieve() wouldn't need to look up the device by BDF, or reason about racing with probe under the device lock. If userspace was able to open the cdev, the device is registered and probed.
- The device file would be opened through the normal cdev path, so the usual permission and LSM checks on the device node would apply.
- It would be the same model across file types.
A few things I think would need care if you go this way. The file check and the attach would need to happen under dev_set->lock so they can't race with a concurrent VFIO_DEVICE_BIND_IOMMUFD on the same fd. And the incoming state should probably be tied to that specific vfio_device_file rather than just the vdev, so only the file passed to RETRIEVE_FD can take over the device.
It would also change PATCH 12. Opening the cdev of an incoming device would have to succeed, so the check would move to the first open of the device instead: fail with -EBUSY if the device is incoming and the file being bound doesn't have the incoming state attached. That one check in vfio-pci would also cover VFIO_GROUP_GET_DEVICE_FD, which opens the device right away, so vfio_liveupdate_incoming_is_preserved() and its dev_is_pci() special case could be dropped from the VFIO core.
The next tmpfs version will also add a way for a file handler to say a failed retrieve can be retried, and a helper to claim an existing file before restoring into it (so a file LUO already manages, e.g. one that is preserved in an outgoing session, is rejected). Both seem useful here too, e.g. so that a mistake in the argument (wrong fd, an fd for another device, an already bound fd) doesn't make the device unretrievable. I'll Cc you when I send it, and I'm happy to share the branch before then.
What do you think?
Re: [PATCH v6 11/27] vfio/pci: Retrieve preserved device files after Live Update
Quoted 75 lines · David Matlack
Quoted 8 lines · Vipin Sharma
During
retrieve():
* Validate the handed-over structvfio_pci_core_device_serheader, sizes, and flags.
* Locate the registered vfio-pci device matching the serialized domain and BDF (requiringdevice->ops==&vfio_pci_ops) under the device lock. vfio-pci registers the vfio device before its probe completes, and the probe holds that lock, so a device that is still being probed is not returned.[...]
Quoted 2 lines
* Open and return an anonymous VFIO cdev file via
vfio_device_liveupdate_cdev_open().Here's an idea for how the device file could be created on retrieve, which I'd like to hear your thoughts on.
The patches from Pasha at [1] lets userspace pass a file-handler-specific argument to
LIVEUPDATE_SESSION_RETRIEVE_FD. In the next version of the tmpfs series, I'm planning to use that to have userspace create the file and pass it in the argument, and the kernel then restores the preserved file into it.I wonder if VFIO should work the same way, e.g.:
struct liveupdate_vfio_retrieve_arg { __u32 size; __s32 fd; };Userspace would open
/dev/vfio/devices/noiommu-vfioXitself and pass the fd.retrieve()would check that it's an unbound vfio-pci cdev file for the preserved device (domain/BDF, noiommu, incoming,cfg_size), attach the incoming state to that file, and LUO would track that file as the retrieved file.VFIO_DEVICE_BIND_IOMMUFDwould then take over the device as it does now. Since VFIO preservation is new, the argument could simply be required.I think this could get rid of some of the special handling:
- There'd be no need to fake a cdev open with an anonymous inode, so PATCH 09 and PATCH 10 could probably be dropped.
-
retrieve()wouldn't need to look up the device by BDF, or reason about racing with probe under the device lock. If userspace was able to open the cdev, the device is registered and probed.- The device file would be opened through the normal cdev path, so the usual permission and LSM checks on the device node would apply.
- It would be the same model across file types.
A few things I think would need care if you go this way. The file check and the attach would need to happen under
dev_set->lockso they can't race with a concurrentVFIO_DEVICE_BIND_IOMMUFDon the same fd. And the incoming state should probably be tied to that specificvfio_device_filerather than just the vdev, so only the file passed toRETRIEVE_FDcan take over the device.It would also change PATCH 12. Opening the cdev of an incoming device would have to succeed, so the check would move to the first open of the device instead: fail with
-EBUSYif the device is incoming and the file being bound doesn't have the incoming state attached. That one check in vfio-pci would also coverVFIO_GROUP_GET_DEVICE_FD, which opens the device right away, sovfio_liveupdate_incoming_is_preserved()and itsdev_is_pci()special case could be dropped from the VFIO core.The next tmpfs version will also add a way for a file handler to say a failed retrieve can be retried, and a helper to claim an existing file before restoring into it (so a file LUO already manages, e.g. one that is preserved in an outgoing session, is rejected). Both seem useful here too, e.g. so that a mistake in the argument (wrong fd, an fd for another device, an already bound fd) doesn't make the device unretrievable. I'll Cc you when I send it, and I'm happy to share the branch before then.
Quoted 1 line
What do you think?
Overall, I agree with the strategy. I think VFIO cdev retrieval should happen as the flow you mentioned above. I want to hightlight two things:
1. This will lead to lot of code changes happening in vfio core. This means VFIO PCI live update code change will spill in vfio core. Should I create a config VFIO_LIVEUPDATE for VFIO core code. It will not be visible menuconfig option but selected when VFIO_PCI_LIVEUPDATE is enabled.
2. List of other inflight series that this series will depend on is increasing. It will be 3 (reset function, pci saved state, and restore into fd).
For '2', should I send v7 without changes you are recommending in this patch and future version of this series can transition to the approach you are suggesting after LUO changes are landed. VFIO liveupdate series will go through more iterations, so we will have opportunity to make the change. WDYT?
Quoted 2 lines
David Matlack
maintainerRe: [PATCH v6 11/27] vfio/pci: Retrieve preserved device files after Live Update
Quoted 43 lines · Vipin Sharma
Quoted 28 lines · David Matlack
Quoted 2 lines · Vipin Sharma
* Open and return an anonymous VFIO cdev file via
vfio_device_liveupdate_cdev_open().Here's an idea for how the device file could be created on retrieve, which I'd like to hear your thoughts on.
The patches from Pasha at [1] lets userspace pass a file-handler-specific argument to
LIVEUPDATE_SESSION_RETRIEVE_FD. In the next version of the tmpfs series, I'm planning to use that to have userspace create the file and pass it in the argument, and the kernel then restores the preserved file into it.I wonder if VFIO should work the same way, e.g.:
struct liveupdate_vfio_retrieve_arg { __u32 size; __s32 fd; };Userspace would open
/dev/vfio/devices/noiommu-vfioXitself and pass the fd.retrieve()would check that it's an unbound vfio-pci cdev file for the preserved device (domain/BDF, noiommu, incoming,cfg_size), attach the incoming state to that file, and LUO would track that file as the retrieved file.VFIO_DEVICE_BIND_IOMMUFDwould then take over the device as it does now. Since VFIO preservation is new, the argument could simply be required.Quoted 1 line
What do you think?
Overall, I agree with the strategy. I think VFIO cdev retrieval should happen as the flow you mentioned above. I want to hightlight two things:
1. This will lead to lot of code changes happening in vfio core. This means VFIO PCI live update code change will spill in vfio core. Should I create a config
VFIO_LIVEUPDATEfor VFIO core code. It will not be visible menuconfig option but selected whenVFIO_PCI_LIVEUPDATEis enabled.
2. List of other inflight series that this series will depend on is increasing. It will be 3 (reset function, pci saved state, and restore into fd).
Quoted 5 lines
For '2', should I send v7 without changes you are recommending in this patch and future version of this series can transition to the approach you are suggesting after LUO changes are landed. VFIO liveupdate series will go through more iterations, so we will have opportunity to make the change. WDYT?
Sounds good. I am not 100% convinced yet we should switch to a retrieve-into approach. But let's keep discussing it VFIO and IOMMUFD.
David Matlack
maintainerRe: [PATCH v6 11/27] vfio/pci: Retrieve preserved device files after Live Update
In reply to Vipin SharmaQuoted 8 lines · Vipin Sharma
Enable userspace to retrieve preserved VFIO device files after a Live Update by implementing the
retrieve()andfinish()file handler callbacks.During
retrieve():
* Validate the handed-over structvfio_pci_core_device_serheader, sizes, and flags.
[...]
Please make the commit messages in this series easier to read. They are mostly long bulleted lists of everything the code does, which is hard to follow and largely repeats the diff. A commit message should explain, in prose, what problem the patch solves and why it solves it this way, and only call out details that a reviewer can't easily get from the code. This applies to most of the patches in the series (e.g. PATCH 07 and PATCH 13 too).
Quoted 19 lines
Do not implement
can_finish(): closing a retrieved LUO session invokes finish, and refusingcan_finish()would leak the session and leave unclaimed devices running. Instead,finish()always completes:
* If the retrieved device was claimed by opening it viaVFIO_DEVICE_BIND_IOMMUFD(which consumesvdev->liveupdate_incoming; subsequent patches replace the open-time reset with non-reset take-over, reject opening incoming devices other than viaretrieve(), and protect incoming kept-running devices across runtime PM,dev_setresets, and non-noiommu boots),finish()simply completes its PCI Live Update participation.
* If the device was not claimed (never retrieved,retrieve()failed, or retrieved but never bound viaVFIO_DEVICE_BIND_IOMMUFD),vfio_pci_core_liveupdate_reset()logs onepci_warn()naming the device, clearsPCI_COMMAND_MASTER, resets the function, and restores the inheritedpci_saved_statejust as closing the device would. If the device has a function reset but is not reset, e.g. becausepci_dev_trylock()contends with a concurrent driver unbind, latchvdev->liveupdate_reset_pendingsovfio_pci_core_unregister_device()completes the function reset and state restoration via
Quoted 8 lines
vfio_pci_core_liveupdate_reset_locked()under the device lock held bydevice_release_driver(). Opening the device afterfinish()resets it like any open, so it drops the latch.
* If the device was not retrieved, look it up underpci_dev_lock(), which waits for a vfio-pci probe in progress. If it is bound to vfio-pci, finish it as above. If it has no driver, clear bus mastering and reset it. Otherwise leave it to the bound driver.
* Callpci_liveupdate_finish()andkho_restore_free()on every path.
This is a lot of complexity for one commit, and it's hard to review. I'd like to start with the simplest approach and build from there: implement can_finish() and have it return false until the device is fully retrieved, i.e. retrieved and taken over by VFIO_DEVICE_BIND_IOMMUFD. Then finish() only needs to free the incoming state and call pci_liveupdate_finish().
That gets rid of vfio_pci_core_liveupdate_reset(), vfio_pci_core_liveupdate_reset_locked(), vfio_pci_liveupdate_finish_lookup() and its bridge and device locking, liveupdate_reset_pending, and most of the finish documentation. If you want to handle the other scenarios (devices that are never retrieved or never bound, devices bound to other drivers, unbind racing with finish), please add them in separate commits on top, each with its own justification.
As for closing the session leaking it and leaving unclaimed devices
running: that only happens if userspace closes the session without taking over all of its devices, and leaving the device running with its memory still preserved is safe. Resetting the device in that case is something that can be added later.
It also has a nice side effect: LUO calls can_finish() on every file in a session before finishing any of them, so a memfd in the same session that the device DMAs into can't be finished before the device has been taken over.
drivers/vfio/pci/vfio_pci_liveupdate.c static void vfio_pci_liveupdate_unfreeze(struct liveupdate_file_op_args *args) · line 460
Quoted 13 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +13
-0+static int +vfio_pci_liveupdate_attach_incoming (struct vfio_pci_core_device *vdev, +struct vfio_pci_liveupdate_incoming *in) +{ +guard (mutex)(&vdev->vdev.dev_set->lock); + +if (vdev->liveupdate_incoming || vdev->liveupdate_claimed || + !pci_liveupdate_is_incoming (vdev->pdev)) +return -EBUSY ; + + vdev->liveupdate_incoming = in; +return 0 ; +}
The pci_liveupdate_is_incoming() check here is redundant with the one in vfio_pci_liveupdate_retrieve(). Nothing can clear it in between, since only finish() should do that (see below) and LUO holds the session mutex across both retrieve and finish.
The liveupdate_claimed check is redundant too: LUO only lets a token be retrieved successfully once, PATCH 12 prevents opening an incoming device any other way, and the liveupdate_incoming check already prevents attaching twice.
drivers/vfio/pci/vfio_pci_liveupdate.c static void vfio_pci_liveupdate_unfreeze(struct liveupdate_file_op_args *args) · line 498
Quoted 5 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +5
-0+if (!pci_liveupdate_is_incoming (pdev) || + ser->cfg_size != pdev->cfg_size) { + ret = -EINVAL ; + goto out_put_dev; + }
If the device isn't incoming here, that's a kernel bug. The previous kernel only preserves the file after pci_liveupdate_preserve() succeeds, the PCI core marks the device incoming when it's enumerated, and only VFIO's finish() should clear it. So this should be a WARN_ON_ONCE().
drivers/vfio/pci/vfio_pci_liveupdate.c static void vfio_pci_liveupdate_unfreeze(struct liveupdate_file_op_args *args) · line 592
Quoted 3 lines
drivers/vfio/pci/vfio_pci_liveupdate.c +3
-0+if (pci_liveupdate_is_incoming (pdev)) +pci_liveupdate_finish (pdev); +}
Likewise, the device must still be incoming here, so pci_liveupdate_finish() can be called unconditionally.
Quoted 10 lines
drivers/vfio/pci/vfio_pci_priv.h +10
-0+static inline void +vfio_pci_liveupdate_unregister_dev (struct vfio_pci_core_device *vdev) +{ +struct pci_dev *pdev = vdev->pdev; + + scoped_guard(mutex, &vdev->vdev.dev_set->lock) { +/* +* Complete a reset that finish() could not do, see +* vfio_pci_liveupdate_finish_vdev(). +*/
drivers/vfio/pci/vfio_pci_priv.h static inline bool vfio_pci_dev_is_frozen(struct vfio_pci_core_device *vdev) · line 221
Quoted 10 lines
drivers/vfio/pci/vfio_pci_priv.h +10
-0+if (vdev->liveupdate_reset_pending) { +vfio_pci_core_liveupdate_reset_locked (vdev); + vdev->liveupdate_reset_pending = false; + } +vfio_pci_liveupdate_free_incoming (vdev); + } + +if (pci_liveupdate_is_incoming (pdev)) +pci_liveupdate_finish (pdev); +}
VFIO should only call pci_liveupdate_finish() from its finish() callback (see the kernel-doc of pci_liveupdate_finish()).
If vfio-pci is unbound from an incoming device before finish(), it should just leave the device and its Live Update state alone. That's
fine: if vfio-pci is bound to the device again, the device is still incoming and can still be retrieved. And once the device has been retrieved, LUO holds a reference to the device file until finish(), so vfio_unregister_group_dev() already blocks unbinding it like it does for any other open device file.
If userspace binds a different driver to the device instead, that's userspace's problem. The PCI core documentation already says it is the user's responsibility to ensure that incoming preserved devices are bound to the correct driver.
So I don't think the unbind path needs any Live Update handling at all.
include/linux/vfio_pci_core.h struct vfio_pci_core_device { · line 158
Quoted 7 lines
#ifdef
CONFIG_VFIO_PCI_LIVEUPDATEinclude/linux/vfio_pci_core.h +3
-0bool liveupdate_frozen;bool liveupdate_intx_disabled; +bool liveupdate_claimed; +bool liveupdate_reset_pending; +struct vfio_pci_liveupdate_incoming *liveupdate_incoming;#endif
With the simpler finish(), I don't think liveupdate_claimed or liveupdate_reset_pending are needed.
PATCH 13 later inverts liveupdate_claimed into liveupdate_kept_running and uses it to block dev_set resets while a preserved device is still running. That can use pci_liveupdate_is_incoming() instead. It blocks resets until finish() rather than until take-over, but since finish() now requires take-over, userspace controls that window. If some flag is still needed later, please introduce it once with its final name and meaning instead of adding it here and inverting it in PATCH 13.
PATCH v6 12/27 vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD
In reply to Vipin SharmaFrom: David Matlack <[email protected]>
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.
--- drivers/vfio/device_cdev.c | 8 ++++++++ drivers/vfio/group.c | 9 +++++++++ drivers/vfio/pci/vfio_pci_liveupdate.c | 6 ++++++ drivers/vfio/vfio.h | 18 ++++++++++++++++++ 4 files changed, 41 insertions(+)
drivers/vfio/device_cdev.c +8 -0
@@ -58,6 +58,14 @@ static int vfio_device_cdev_open(struct vfio_device *device, struct file **filep } *filep = file; + }else if (vfio_liveupdate_incoming_is_preserved (device)) { +/* +* Since it is live update preserved device, it must be +* retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD instead of +* opening /dev/vfio/devices/vfioX. +*/ + ret = -EBUSY ; + goto err_free_device_file; } file->private_data = df;
drivers/vfio/group.c +9 -0
@@ -316,6 +316,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);
drivers/vfio/pci/vfio_pci_liveupdate.c +6 -0
@@ -43,6 +43,12 @@* ... * ioctl(session_fd, LIVEUPDATE_SESSION_FINISH, ...); * +* .. note:: +* After kexec, if a device was preserved by the previous kernel, attempting +* to open a new file for the device via its character device +* (``/dev/vfio/devices/X``) or via ``VFIO_GROUP_GET_DEVICE_FD`` will fail +* with ``-EBUSY``. +* * Restrictions * ============ *
drivers/vfio/vfio.h +18 -0
@@ -11,6 +11,7 @@#include <linux/cdev.h> #include <linux/module.h> #include <linux/vfio.h> +#include <linux/pci.h> struct iommufd_ctx ;struct iommu_group ;
@@ -446,4 +447,21 @@ static inline void vfio_device_debugfs_init(struct vfio_device *vdev) { }static inline void vfio_device_debugfs_exit (struct vfio_device *vdev) { }#endif /* CONFIG_VFIO_DEBUGFS */ +#ifdef CONFIG_VFIO_PCI_LIVEUPDATE +static inline bool vfio_liveupdate_incoming_is_preserved (struct vfio_device *device) +{ +struct device *d = device->dev; + +if (dev_is_pci (d)) +return pci_liveupdate_is_incoming (to_pci_dev (d)); + +return false; +} +#else +static inline bool vfio_liveupdate_incoming_is_preserved (struct vfio_device *device) +{ +return false; +} +#endif /* CONFIG_VFIO_PCI_LIVEUPDATE */ +#endif
Signature · 1 line
2.56.0.317.g454f8302e1-goog
David Matlack
maintainerRe: [PATCH v6 12/27] vfio: Enforce preserved devices are retrieved via LIVEUPDATE_SESSION_RETRIEVE_FD
Quoted 22 lines · Vipin Sharma
drivers/vfio/vfio.h +7
-0@@ -11,6 +11,7 @@#include <linux/cdev.h> #include <linux/module.h> #include <linux/vfio.h> +#include <linux/pci.h> struct iommufd_ctx ;struct iommu_group ;@@ -446,4 +447,21 @@ static inline void vfio_device_debugfs_init(struct vfio_device *vdev) { }static inline void vfio_device_debugfs_exit (struct vfio_device *vdev) { }#endif /* CONFIG_VFIO_DEBUGFS */ +#ifdef CONFIG_VFIO_PCI_LIVEUPDATE +static inline bool vfio_liveupdate_incoming_is_preserved (struct vfio_device *device) +{ +struct device *d = device->dev; + +if (dev_is_pci (d))
drivers/vfio/vfio.h static inline void vfio_device_debugfs_init(struct vfio_device *vdev) { } · line 465
Quoted 10 lines
drivers/vfio/vfio.h +10
-0+return pci_liveupdate_is_incoming (to_pci_dev (d)); + + return false; +} +#else +static inline bool vfio_liveupdate_incoming_is_preserved (struct vfio_device *device) +{ +return false; +} +#endif /* CONFIG_VFIO_PCI_LIVEUPDATE */
No need for the ifdef here and 2 definitions here. If CONFIG_PCI_LIVEUPDATE is not enabled then the compiler should be able to optimize vfio_liveupdate_incoming_is_preserved() to false.
PATCH v6 13/27 vfio/pci: Protect incoming preserved devices until they finish Live Update
In reply to Vipin SharmaProtect incoming preserved devices that were kept running across kexec from being disturbed before userspace either claims them or finishes the Live Update session:
* Runtime PM idle D3: In vfio_pci_init_dev(), when pci_liveupdate_is_incoming(pdev) is true, latch vdev->disable_idle_d3 = true and vdev->liveupdate_kept_running = true. Without this, vfio_pci_core_register_device() drops the runtime PM reference and allows the PCI runtime PM core to transition an idle incoming device into D3hot, stopping bus mastering and potentially triggering an internal reset on NoSoftRst- devices.
* Non-noiommu boot fallback: In vfio_pci_core_register_device(), after vfio_register_group_dev() determines whether the device is in noiommu mode, if an incoming kept-running device is not in noiommu mode in this kernel, log a pci_warn(), clear PCI_COMMAND_MASTER immediately to stop untranslated DMA, and record liveupdate_stopped_early so finish() resets it without printing a duplicate warning.
* Bus/slot reset guards: Refuse vfio_pci_dev_set_needs_reset() and vfio_pci_dev_set_hot_reset() (-EBUSY) while any device in the dev_set has liveupdate_kept_running set, preventing another device in the same dev_set from resetting an unclaimed kept-running device. When an unclaimed device finishes Live Update and no device in its dev_set is open, invoke vfio_pci_dev_set_try_reset() after clearing liveupdate_kept_running so devices without function-level reset still receive a bus/slot reset.
* Unbind before finish: In vfio_pci_core_unregister_device(), if a still-unclaimed incoming device is unbound from vfio-pci before the session finishes (or if a concurrent finish() deferred its function reset via liveupdate_reset_pending), clear bus mastering, reset the function and restore config state via vfio_pci_core_liveupdate_reset_locked() under the device lock already held by remove(), and call pci_liveupdate_finish().
--- drivers/vfio/pci/vfio_pci.c | 1 + drivers/vfio/pci/vfio_pci_core.c | 19 +++++++- drivers/vfio/pci/vfio_pci_liveupdate.c | 16 +++++-- drivers/vfio/pci/vfio_pci_priv.h | 62 ++++++++++++++++++++++++-- include/linux/vfio_pci_core.h | 3 +- 5 files changed, 91 insertions(+), 10 deletions(-)
drivers/vfio/pci/vfio_pci.c +1 -0
@@ -139,6 +139,7 @@ static int vfio_pci_init_dev(struct vfio_device *core_vdev)*/ vdev->nointxmask = nointxmask; vdev->disable_idle_d3 = disable_idle_d3; +vfio_pci_liveupdate_init_dev (vdev);#ifdef CONFIG_VFIO_PCI_VGA vdev->disable_vga = disable_vga;#endif
drivers/vfio/pci/vfio_pci_core.c +17 -2
@@ -768,6 +768,15 @@ bool vfio_pci_core_liveupdate_reset(struct vfio_pci_core_device *vdev, vdev->reset_works = reset_works;vfio_pci_core_try_reset (vdev); +/* +* Like vfio_pci_core_disable(), try a bus or slot reset for the devices +* in the set that still need one, e.g. this device if it has no usable +* function reset, or others whose reset was deferred while this device +* was kept running. This device is not open, so none in the set may be. +*/ +if (!vfio_device_set_open_count (vdev->vdev.dev_set)) +vfio_pci_dev_set_try_reset (vdev->vdev.dev_set); +return !vdev->needs_reset; }EXPORT_SYMBOL_GPL (vfio_pci_core_liveupdate_reset);
@@ -2399,6 +2408,8 @@ int vfio_pci_core_register_device(struct vfio_pci_core_device *vdev)if (ret) goto out_power; +vfio_pci_liveupdate_check_noiommu (vdev); +vfio_pci_core_debugfs_init (vdev);return 0 ;
@@ -2642,7 +2653,8 @@ static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,list_for_each_entry (vdev, &dev_set->device_list, vdev.dev_set_list) {bool owned; -if (vfio_pci_dev_is_frozen (vdev)) { +if (vfio_pci_dev_is_frozen (vdev) || +vfio_pci_dev_is_kept_running (vdev)) { ret = -EBUSY ;break ; }
@@ -2744,8 +2756,11 @@ static bool vfio_pci_dev_set_needs_reset(struct vfio_device_set *dev_set)if (vfio_device_set_open_count (dev_set) >1 )return false; -list_for_each_entry (cur, &dev_set->device_list, vdev.dev_set_list) +list_for_each_entry (cur, &dev_set->device_list, vdev.dev_set_list) { +if (vfio_pci_dev_is_kept_running (cur)) +return false; needs_reset |= cur->needs_reset; + }return needs_reset; }
drivers/vfio/pci/vfio_pci_liveupdate.c +13 -3
@@ -457,7 +457,7 @@ vfio_pci_liveupdate_attach_incoming(struct vfio_pci_core_device *vdev, {guard (mutex)(&vdev->vdev.dev_set->lock); -if (vdev->liveupdate_incoming || vdev->liveupdate_claimed || +if (vdev->liveupdate_incoming || !vdev->liveupdate_kept_running || !pci_liveupdate_is_incoming (vdev->pdev))return -EBUSY ;
@@ -558,8 +558,7 @@ static void vfio_pci_liveupdate_finish_vdev(struct vfio_pci_core_device *vdev,bool was_reset; scoped_guard(mutex, &vdev->vdev.dev_set->lock) { -if (!vdev->liveupdate_claimed && -pci_liveupdate_is_incoming (pdev)) { +if (vdev->liveupdate_kept_running) {if (vdev->liveupdate_incoming) { saved_state = vdev->liveupdate_incoming->saved_state; vdev->liveupdate_incoming->saved_state =NULL ;
@@ -572,6 +571,17 @@ static void vfio_pci_liveupdate_finish_vdev(struct vfio_pci_core_device *vdev, saved_state =NULL ; } +/* +* The device is stopped below, so stop shielding it from +* the dev_set resets, including the fallback done by +* vfio_pci_core_liveupdate_reset(). +*/ + vdev->liveupdate_kept_running = false; + +/* A device stopped early was logged when it was stopped. */ +if (vdev->liveupdate_stopped_early) + reason =NULL ; +/* * An unbind of the device waits for the reference held * by finish() with the device lock held, so the reset
drivers/vfio/pci/vfio_pci_priv.h +58 -4
88 lines not on this page · raw message
include/linux/vfio_pci_core.h +2 -1
@@ -152,7 +152,8 @@ struct vfio_pci_core_device {#ifdef CONFIG_VFIO_PCI_LIVEUPDATE bool liveupdate_frozen;bool liveupdate_intx_disabled; -bool liveupdate_claimed; +bool liveupdate_kept_running; +bool liveupdate_stopped_early;bool liveupdate_reset_pending;struct vfio_pci_liveupdate_incoming *liveupdate_incoming;#endif
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 14/27 vfio/pci: Take over preserved devices without resetting them
In reply to Vipin SharmaWhen userspace binds a retrieved VFIO cdev file descriptor via VFIO_DEVICE_BIND_IOMMUFD after kexec, take over the running device in vfio_pci_core_enable() via vfio_pci_liveupdate_take_over() without resetting it or clearing bus mastering:
- Skip pci_clear_master(), pci_try_reset_function(), and pci_save_state().
- Save PCI_COMMAND before pci_enable_device() and restore the memory and I/O decode bits afterwards so pci_enable_device() does not re-enable BAR decode (such as I/O port decode) that was disabled before kexec.
- Also restore PCI_COMMAND_INTX_DISABLE, which freeze() set before kexec, when vfio-pci uses PCI 2.3 INTx masking for the device (vdev->pci_2_3) or masks its broken INTx (vdev->nointx), so INTx stays masked until userspace configures interrupts. Otherwise vfio-pci masks INTx at the interrupt controller (e.g. with vfio_pci.nointxmask=1), so leave DisINTx cleared by pci_enable_device() as a normal open does.
- Build pci_config_map via vfio_config_init(), verify that it matches the preserved config map snapshot, and overlay the preserved vconfig snapshot onto vdev->vconfig.
- Perform all fallible take-over setup before adopting the preserved state. If take-over fails before the device is claimed, leave the running device untouched (keeping bus mastering, decode bits, and liveupdate_incoming intact) so userspace can retry binding the retrieved FD or let the session finish/close reset the unclaimed device.
- Once vfio_pci_liveupdate_take_over() succeeds, adopt the preserved pci_saved_state and reset_works flag, clear liveupdate_kept_running, and free the temporary incoming state; any subsequent error or final device close follows the normal vfio_pci_core_disable() path and resets the device.
--- drivers/vfio/pci/vfio_pci_core.c | 117 +++++++++++++++++++++---- drivers/vfio/pci/vfio_pci_liveupdate.c | 23 ++++- drivers/vfio/pci/vfio_pci_priv.h | 23 ++++- 3 files changed, 141 insertions(+), 22 deletions(-)
drivers/vfio/pci/vfio_pci_core.c +98 -19
@@ -595,8 +595,68 @@ static const struct dev_pm_ops vfio_pci_core_pm_ops = { NULL) }; +/* +* Take over a device that was kept running across a Live Update. The device +* is enabled only after every step that can fail, because unwinding with +* pci_disable_device() would clear bus mastering on the running device. A +* failed take-over thus leaves the device untouched and can be retried. +*/ +static int vfio_pci_liveupdate_take_over (struct vfio_pci_core_device *vdev, +struct vfio_pci_liveupdate_incoming *in) +{ +const u8 *vconfig = in->data; +const u8 *config_map = in->data + in->cfg_size; +struct pci_dev *pdev = vdev->pdev; +u16 orig, cmd, keep; +int ret; + +if (in->cfg_size != pdev->cfg_size || +memcmp (config_map, vdev->pci_config_map, in->cfg_size)) { +pci_warn (pdev, +"Config map mismatch during Live Update take-over\n" ); +return -EINVAL ; + } + +pci_read_config_word (pdev,PCI_COMMAND , &orig); + ret =pci_enable_device (pdev); + +/* +* pci_enable_device() enables memory and I/O decode for all assigned +* BARs and clears PCI_COMMAND_INTX_DISABLE. Restore the decode settings +* the device was running with and keep INTx masked, as freeze() left +* it, until userspace configures interrupts. If vfio-pci does not use +* PCI 2.3 INTx masking for the device, it masks INTx at the interrupt +* controller instead, so leave PCI_COMMAND_INTX_DISABLE as a normal +* open does. If enabling failed, restore everything. +*/ + keep =PCI_COMMAND_IO |PCI_COMMAND_MEMORY ; +if (ret || vdev->pci_2_3 || vdev->nointx) + keep |=PCI_COMMAND_INTX_DISABLE ; +pci_read_config_word (pdev,PCI_COMMAND , &cmd); +if ((cmd ^ orig) & keep) +pci_write_config_word (pdev,PCI_COMMAND , + (cmd & ~keep) | (orig & keep)); +if (ret) +return ret; + +memcpy (vdev->vconfig, vconfig, in->cfg_size); +/* +* Redo the virtual BAR fixup: the snapshot may hold a BAR sizing write +* not fixed up yet, or a fixup half done by a config read racing with +* freeze(), as config reads do not take vdev->igate. +*/ + vdev->bardirty = true; + cmd =le16_to_cpu (*(__le16 *)&vdev->vconfig[PCI_COMMAND ]); + vdev->virq_disabled = !!(cmd &PCI_COMMAND_INTX_DISABLE ); + vdev->reset_works = in->reset_works; + +return 0 ; +} +int vfio_pci_core_enable (struct vfio_pci_core_device *vdev) { +struct vfio_pci_liveupdate_incoming *in = +vfio_pci_liveupdate_incoming (vdev);struct pci_dev *pdev = vdev->pdev;int ret;u16 cmd;
@@ -608,23 +668,30 @@ int vfio_pci_core_enable(struct vfio_pci_core_device *vdev)return ret; } -/* Don't allow our initial saved state to include busmaster */ -pci_clear_master (pdev); +/* +* A device kept running across a Live Update is enabled later, without +* a reset, by vfio_pci_liveupdate_take_over(). +*/ +if (!in) { +/* Don't allow our initial saved state to include busmaster */ +pci_clear_master (pdev); - ret =pci_enable_device (pdev); -if (ret) - goto out_power; + ret =pci_enable_device (pdev); +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 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; -pci_save_state (pdev); - vdev->pci_saved_state =pci_store_saved_state (pdev); -if (!vdev->pci_saved_state) -pci_dbg (pdev,"%s: Couldn't store saved state\n" , __func__); + vdev->reset_works = !ret; +pci_save_state (pdev); + vdev->pci_saved_state =pci_store_saved_state (pdev); +if (!vdev->pci_saved_state) +pci_dbg (pdev,"%s: Couldn't store saved state\n" , + __func__); + }if (likely (!vdev->nointxmask)) {if (vfio_pci_nointx (pdev)) {
@@ -635,10 +702,12 @@ int vfio_pci_core_enable(struct vfio_pci_core_device *vdev) vdev->pci_2_3 =pci_intx_mask_supported (pdev); } -pci_read_config_word (pdev,PCI_COMMAND , &cmd); -if (vdev->pci_2_3 && (cmd &PCI_COMMAND_INTX_DISABLE )) { - cmd &= ~PCI_COMMAND_INTX_DISABLE ; -pci_write_config_word (pdev,PCI_COMMAND , cmd); +if (!in) { +pci_read_config_word (pdev,PCI_COMMAND , &cmd); +if (vdev->pci_2_3 && (cmd &PCI_COMMAND_INTX_DISABLE )) { + cmd &= ~PCI_COMMAND_INTX_DISABLE ; +pci_write_config_word (pdev,PCI_COMMAND , cmd); + } } ret =vfio_pci_zdev_open_device (vdev);
@@ -649,6 +718,12 @@ int vfio_pci_core_enable(struct vfio_pci_core_device *vdev)if (ret) goto out_free_zdev; +if (in) { + ret =vfio_pci_liveupdate_take_over (vdev, in); +if (ret) + goto out_free_config; + } + msix_pos = pdev->msix_cap;if (msix_pos) {u16 flags;
@@ -675,13 +750,17 @@ int vfio_pci_core_enable(struct vfio_pci_core_device *vdev)return 0 ; +out_free_config: +vfio_config_free (vdev); out_free_zdev:vfio_pci_zdev_close_device (vdev); out_free_state:kfree (vdev->pci_saved_state); vdev->pci_saved_state =NULL ; out_disable_device: -pci_disable_device (pdev); +/* A take-over enables the device only once nothing can fail. */ +if (!in) +pci_disable_device (pdev); out_power:if (!vdev->disable_idle_d3)pm_runtime_put (&pdev->dev);
drivers/vfio/pci/vfio_pci_liveupdate.c +22 -1
@@ -120,7 +120,28 @@* * ``LIVEUPDATE_SESSION_RETRIEVE_FD`` validates the handed-over serialized state * and returns a new unbound VFIO cdev file descriptor. The device is claimed on -* the first ``VFIO_DEVICE_BIND_IOMMUFD`` on that file descriptor. +* the first ``VFIO_DEVICE_BIND_IOMMUFD`` on that file descriptor without +* resetting it or clearing ``PCI_COMMAND_MASTER``: +* +* * ``vfio_pci_core_enable()`` skips ``pci_clear_master()``, +* ``pci_try_reset_function()``, and ``pci_save_state()``. It builds +* ``pci_config_map`` normally via ``vfio_config_init()`` and verifies that +* it matches the preserved snapshot before it enables the device. It keeps +* the memory and I/O decode settings and ``PCI_COMMAND_MASTER`` the device +* was running with, and keeps physical INTx masked until userspace +* configures interrupts. On devices for which vfio-pci does not use PCI +* 2.3 INTx masking (e.g. with ``vfio_pci.nointxmask=1``), vfio-pci masks +* INTx at the interrupt controller, so ``PCI_COMMAND_INTX_DISABLE`` is left +* as on a normal open. It then overlays the preserved ``vconfig`` snapshot +* and adopts the preserved ``pci_saved_state`` and ``reset_works`` flag for +* subsequent resets or device close. +* +* * If the take-over in ``vfio_pci_core_enable()`` fails, +* ``VFIO_DEVICE_BIND_IOMMUFD`` fails and leaves the device running +* untouched, and userspace can retry the bind. If the ioctl fails after +* the device was claimed, it closes the device, which resets it like any +* other close. A device that is never claimed is reset when the session +* is finished or closed, as described below. * * ``LIVEUPDATE_SESSION_FINISH`` (or closing a retrieved session file * descriptor) always completes:
drivers/vfio/pci/vfio_pci_priv.h +21 -2
@@ -203,6 +203,12 @@ vfio_pci_liveupdate_check_noiommu(struct vfio_pci_core_device *vdev) } } +static inline struct vfio_pci_liveupdate_incoming * +vfio_pci_liveupdate_incoming (struct vfio_pci_core_device *vdev) +{ +return vdev->liveupdate_incoming; +} +static inline void vfio_pci_liveupdate_free_incoming (struct vfio_pci_core_device *vdev) {
@@ -219,6 +225,8 @@ vfio_pci_liveupdate_free_incoming(struct vfio_pci_core_device *vdev)static inline void vfio_pci_liveupdate_claim_incoming (struct vfio_pci_core_device *vdev) { +struct vfio_pci_liveupdate_incoming *in = vdev->liveupdate_incoming; +/* * A reset that finish() left for unbind is not needed once the device * is opened after finish(): the open resets the device if it can, and
@@ -226,10 +234,15 @@ vfio_pci_liveupdate_claim_incoming(struct vfio_pci_core_device *vdev)*/ vdev->liveupdate_reset_pending = false; -if (!vdev->liveupdate_incoming) +if (!in)return ; -vfio_pci_liveupdate_free_incoming (vdev); + vdev->pci_saved_state = in->saved_state; +if (!vdev->pci_saved_state) +pci_dbg (vdev->pdev,"%s: Couldn't store saved state\n" , + __func__); +kfree (in); + vdev->liveupdate_incoming =NULL ; vdev->liveupdate_kept_running = false; }
@@ -288,6 +301,12 @@ vfio_pci_liveupdate_check_noiommu(struct vfio_pci_core_device *vdev) { } +static inline struct vfio_pci_liveupdate_incoming * +vfio_pci_liveupdate_incoming (struct vfio_pci_core_device *vdev) +{ +return NULL ; +} +static inline void vfio_pci_liveupdate_free_incoming (struct vfio_pci_core_device *vdev) {
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 15/27 docs: liveupdate: Add documentation for VFIO PCI
In reply to Vipin SharmaFrom: David Matlack <[email protected]>
Add documentation for preserving VFIO device files across a Live Update, generated from the kernel-doc comments in the code.
--- Documentation/core-api/liveupdate.rst | 1 + .../driver-api/vfio_pci_liveupdate.rst | 25 +++++++++++++++++++ MAINTAINERS | 1 + 3 files changed, 27 insertions(+) create mode 100644 Documentation/driver-api/vfio_pci_liveupdate.rst
Documentation/core-api/liveupdate.rst +1 -0
@@ -38,6 +38,7 @@ The following types of file descriptors can be preserved :maxdepth: 1 ../mm/memfd_preservation + ../driver-api/vfio_pci_liveupdate Public API ==========
Documentation/driver-api/vfio_pci_liveupdate.rst new file +25 -0
@@ -0,0 +1,25 @@ +.. SPDX-License-Identifier: GPL-2.0-or-later + +==================================== +VFIO PCI Device Preservation via LUO +==================================== + +.. kernel-doc:: drivers/vfio/pci/vfio_pci_liveupdate.c + :doc: VFIO PCI Preservation via LUO + +VFIO PCI Preservation ABI +========================= + +.. kernel-doc:: include/linux/kho/abi/vfio_pci.h + :doc: VFIO PCI Live Update ABI + +.. kernel-doc:: include/linux/kho/abi/vfio_pci.h + :internal: + +See Also +======== + +- :doc:`/core-api/liveupdate` +- :doc:`/core-api/kho/index` +- :doc:`/PCI/liveupdate` +- :doc:`/driver-api/vfio`
MAINTAINERS +1 -0
@@ -28661,6 +28661,7 @@ T: git https://github.com/awilliam/linux-vfio.git F: Documentation/ABI/testing/debugfs-vfio F: Documentation/ABI/testing/sysfs-devices-vfio-dev F: Documentation/driver-api/vfio.rst +F: Documentation/driver-api/vfio_pci_liveupdate.rst F: drivers/vfio/ F: include/linux/kho/abi/vfio_pci.h F: include/linux/vfio.h
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 16/27 vfio: selftests: Build liveupdate library in VFIO selftests
In reply to Vipin SharmaImport and build liveupdate selftest library in VFIO selftests.
It allows using liveupdate ioctls in VFIO selftests
--- tools/testing/selftests/vfio/Makefile | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
tools/testing/selftests/vfio/Makefile +7 -3
@@ -21,6 +21,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
@@ -29,14 +30,17 @@ CFLAGS += $(EXTRA_CFLAGS) LDFLAGS += -pthread -$(TEST_GEN_PROGS): $(OUTPUT)/%: $(OUTPUT)/%.o $(LIBVFIO_O) - $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $< $(LIBVFIO_O) $(LDLIBS) -o $@ +LIBS_O := $(LIBVFIO_O) +LIBS_O += $(LIBLIVEUPDATE_O) + +$(TEST_GEN_PROGS): $(OUTPUT)/%: $(OUTPUT)/%.o $(LIBS_O) + $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $< $(LIBS_O) $(LDLIBS) -o $@ TEST_GEN_PROGS_O = $(patsubst %, %.o, $(TEST_GEN_PROGS)) $(TEST_GEN_PROGS_O): $(OUTPUT)/%.o: %.c $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@ -TEST_DEP_FILES = $(patsubst %.o, %.d, $(TEST_GEN_PROGS_O) $(LIBVFIO_O)) +TEST_DEP_FILES = $(patsubst %.o, %.d, $(TEST_GEN_PROGS_O) $(LIBS_O)) -include $(TEST_DEP_FILES) EXTRA_CLEAN += $(TEST_GEN_PROGS_O) $(TEST_DEP_FILES)
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 17/27 vfio: selftests: Add vfio_pci_liveupdate_uapi_test
In reply to Vipin SharmaFrom: David Matlack <[email protected]>
Add a selftest to exercise preserving various VFIO files through /dev/liveupdate. Only the VFIO cdev files of devices in noiommu mode can be preserved. Ensure that preserving the cdev file of a device that is not in noiommu mode fails, and that everything else (group-based device files, group files, and container files) fails too.
In FIXTURE_SETUP, probe luo_session_preserve_fd() on the bound cdev FD in a temporary session for iommufd variants and skip if LUO returns -ENOENT, so the test skips cleanly when CONFIG_VFIO_PCI_LIVEUPDATE=n or when the target device does not support VFIO PCI Live Update (e.g. an SR-IOV VF).
--- tools/testing/selftests/vfio/Makefile | 1 + .../vfio/vfio_pci_liveupdate_uapi_test.c | 126 ++++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c
tools/testing/selftests/vfio/Makefile +1 -0
@@ -13,6 +13,7 @@ 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_sriov_uapi_test +TEST_GEN_PROGS += vfio_pci_liveupdate_uapi_test TEST_FILES += scripts/cleanup.sh TEST_FILES += scripts/lib.sh
tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c new file +126 -0
126 lines not on this page · raw message
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 18/27 vfio: selftests: Initialize vfio_pci_device using a VFIO cdev FD
In reply to Vipin SharmaUse 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 writing selftests where VFIO device FD is preserved using liveupdate and retrieved later using liveupdate ioctl after kexec.
--- .../lib/include/libvfio/vfio_pci_device.h | 3 +++ .../selftests/vfio/lib/vfio_pci_device.c | 25 ++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-)
tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h +3 -0
@@ -40,6 +40,9 @@ struct vfio_pci_device {struct vfio_pci_device *vfio_pci_device_alloc (const char *bdf,struct iommu *iommu);void vfio_pci_device_free (struct vfio_pci_device *device); +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);
tools/testing/selftests/vfio/lib/vfio_pci_device.c +19 -6
@@ -457,9 +457,13 @@ void vfio_pci_cdev_open(struct vfio_pci_device *device, const char *bdf) }static void vfio_pci_iommufd_setup (struct vfio_pci_device *device, -const char *bdf,const char *vf_token) +const char *bdf,int device_fd, +const char *vf_token) { -vfio_pci_cdev_open (device, bdf); +if (device_fd >=0 ) + device->fd = device_fd; +else +vfio_pci_cdev_open (device, bdf);vfio_device_bind_iommufd (device->fd, device->iommu->iommufd, vf_token);vfio_device_attach_iommufd_pt (device->fd, device->iommu->ioas_id); }
@@ -482,16 +486,20 @@ void vfio_pci_device_free(struct vfio_pci_device *device)free (device); } -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; device =vfio_pci_device_alloc (bdf, iommu); -if (iommu->mode->container_path) +if (iommu->mode->container_path) { +VFIO_ASSERT_EQ (device_fd,-1 );vfio_pci_container_setup (device, bdf,NULL ); -else -vfio_pci_iommufd_setup (device, bdf,NULL ); + }else { +vfio_pci_iommufd_setup (device, bdf, device_fd,NULL ); + }vfio_pci_device_setup (device);vfio_pci_driver_probe (device);
@@ -499,6 +507,11 @@ struct vfio_pci_device *vfio_pci_device_init(const char *bdf, struct iommu *iommreturn 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;
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 19/27 vfio: selftests: Add Makefile support for TEST_GEN_PROGS_EXTENDED
In reply to Vipin SharmaFrom: David Matlack <[email protected]>
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.
--- tools/testing/selftests/vfio/Makefile | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
tools/testing/selftests/vfio/Makefile +7 -5
@@ -34,16 +34,18 @@ LDFLAGS += -pthread LIBS_O := $(LIBVFIO_O) LIBS_O += $(LIBLIVEUPDATE_O) -$(TEST_GEN_PROGS): $(OUTPUT)/%: $(OUTPUT)/%.o $(LIBS_O) +$(TEST_GEN_PROGS) $(TEST_GEN_PROGS_EXTENDED): $(OUTPUT)/%: $(OUTPUT)/%.o $(LIBS_O) $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $< $(LIBS_O) $(LDLIBS) -o $@ -TEST_GEN_PROGS_O = $(patsubst %, %.o, $(TEST_GEN_PROGS)) -$(TEST_GEN_PROGS_O): $(OUTPUT)/%.o: %.c +TESTS_O := $(patsubst %, %.o, $(TEST_GEN_PROGS)) +TESTS_O += $(patsubst %, %.o, $(TEST_GEN_PROGS_EXTENDED)) + +$(TESTS_O): $(OUTPUT)/%.o: %.c $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@ -TEST_DEP_FILES = $(patsubst %.o, %.d, $(TEST_GEN_PROGS_O) $(LIBS_O)) +TEST_DEP_FILES = $(patsubst %.o, %.d, $(TESTS_O) $(LIBS_O)) -include $(TEST_DEP_FILES) -EXTRA_CLEAN += $(TEST_GEN_PROGS_O) $(TEST_DEP_FILES) +EXTRA_CLEAN += $(TESTS_O) $(TEST_DEP_FILES) endif
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 20/27 vfio: selftests: Add iommufd noiommu mode
In reply to Vipin SharmaAdd an opt-in iommufd_noiommu mode (MODE_IOMMUFD_NOIOMMU) for devices bound to vfio-pci in noiommu mode. When a device is in noiommu mode, its VFIO character device is named /dev/vfio/devices/noiommu-vfioX (opening it requires CAP_SYS_RAWIO), and binding and attaching to an iommufd IOAS use a software page table.
Add __vfio_pci_get_cdev_path(bdf, noiommu) to look up either the regular or the noiommu cdev path and return NULL when none is present, and make vfio_pci_cdev_open() select the cdev based on mode->noiommu.
Because a device in noiommu mode DMAs directly to physical addresses, tests that program arbitrary or unmapped IOVAs would corrupt memory. Keep MODE_IOMMUFD_NOIOMMU out of FIXTURE_VARIANT_ADD_ALL_IOMMU_MODES() so that only noiommu-aware tests opt into it.
--- .../vfio/lib/include/libvfio/iommu.h | 17 ++++++++++ .../lib/include/libvfio/vfio_pci_device.h | 7 +++++ tools/testing/selftests/vfio/lib/iommu.c | 9 +++++- .../selftests/vfio/lib/vfio_pci_device.c | 31 +++++++++++++------ 4 files changed, 53 insertions(+), 11 deletions(-)
tools/testing/selftests/vfio/lib/include/libvfio/iommu.h +17 -0
@@ -13,6 +13,12 @@ struct iommu_mode {const char *name;const char *container_path;unsigned long iommu_type; +/* +* For devices bound to vfio-pci in noiommu mode, i.e. not behind an +* IOMMU. Such devices DMA to the addresses programmed into them as +* physical addresses. +*/ +bool noiommu; };extern const char *default_iommu_mode;
@@ -67,6 +73,17 @@ struct iommu_iova_range *iommu_iova_ranges(struct iommu *iommu, u32 *nranges);#define MODE_IOMMUFD_COMPAT_TYPE1V2 "iommufd_compat_type1v2"#define MODE_IOMMUFD "iommufd" +/* +* iommufd with a device bound to vfio-pci in noiommu mode +* (vfio.enable_unsafe_noiommu_mode=1 and CONFIG_IOMMUFD_NOIOMMU), whose cdev +* is /dev/vfio/devices/noiommu-vfioX. Opening it requires CAP_SYS_RAWIO. +* +* Not part of FIXTURE_VARIANT_ADD_ALL_IOMMU_MODES(): tests must opt in, since +* the device DMAs to IOVAs as physical addresses, and tests that DMA to +* arbitrary or unmapped IOVAs would corrupt memory. +*/ +#define MODE_IOMMUFD_NOIOMMU "iommufd_noiommu" +/* * Generator for VFIO selftests fixture variants that replicate across all * possible IOMMU modes. Tests must define FIXTURE_VARIANT_ADD_IOMMU_MODE()
tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h +7 -0
@@ -154,6 +154,13 @@ static inline bool vfio_pci_device_match(struct vfio_pci_device *device, (device_id ==vfio_pci_config_readw (device,PCI_DEVICE_ID )); } +/* +* Return the path of the VFIO cdev of @bdf, or NULL if there is none. The cdev +* of a device bound to vfio-pci in noiommu mode is named noiommu-vfioX rather +* than vfioX, and @noiommu selects which of the two to look for. Free with +* free(). +*/ +const char *__vfio_pci_get_cdev_path (const char *bdf,bool noiommu);const char *vfio_pci_get_cdev_path (const char *bdf);void vfio_pci_group_setup (struct vfio_pci_device *device,const char *bdf);
tools/testing/selftests/vfio/lib/iommu.c +8 -1
@@ -22,7 +22,10 @@const char *default_iommu_mode =MODE_IOMMUFD ; -/* Reminder: Keep in sync with FIXTURE_VARIANT_ADD_ALL_IOMMU_MODES(). */ +/* +* Reminder: Keep in sync with FIXTURE_VARIANT_ADD_ALL_IOMMU_MODES(), which +* deliberately leaves out the noiommu modes. +*/ static const struct iommu_mode iommu_modes[] = { { .name =MODE_VFIO_TYPE1_IOMMU ,
@@ -47,6 +50,10 @@ static const struct iommu_mode iommu_modes[] = { { .name = MODE_IOMMUFD, }, + { + .name = MODE_IOMMUFD_NOIOMMU, + .noiommu = true, + }, };static const struct iommu_mode *lookup_iommu_mode (const char *iommu_mode)
tools/testing/selftests/vfio/lib/vfio_pci_device.c +21 -10
@@ -380,35 +380,42 @@ static void vfio_pci_device_setup(struct vfio_pci_device *device) device->msi_eventfds[i] =-1 ; } -const char *vfio_pci_get_cdev_path (const char *bdf) +const char *__vfio_pci_get_cdev_path (const char *bdf,bool noiommu) { +const char *prefix = noiommu ?"noiommu-vfio" :"vfio" ;char dir_path[PATH_MAX ];struct dirent *entry; -char *cdev_path; +char *cdev_path =NULL ;DIR *dir; - cdev_path =calloc_assert (PATH_MAX ,1 ); -snprintf_assert (dir_path,sizeof (dir_path),"/sys/bus/pci/devices/%s/vfio-dev/" , bdf); dir =opendir (dir_path); -VFIO_ASSERT_NOT_NULL (dir,"Failed to open directory %s\n" , dir_path); +if (!dir) +return NULL ;while ((entry =readdir (dir)) !=NULL ) { -/* Find the file that starts with "vfio" */ -if (strncmp ("vfio" , entry->d_name,4 )) +if (strncmp (prefix, entry->d_name,strlen (prefix)))continue ; + cdev_path =calloc_assert (PATH_MAX ,1 );snprintf_assert (cdev_path,PATH_MAX ,"/dev/vfio/devices/%s" , entry->d_name);break ; } -VFIO_ASSERT_NE (cdev_path[0 ],0 ,"Failed to find vfio cdev file.\n" );VFIO_ASSERT_EQ (closedir (dir),0 );return cdev_path; } +const char *vfio_pci_get_cdev_path (const char *bdf) +{ +const char *cdev_path =__vfio_pci_get_cdev_path (bdf, false); + +VFIO_ASSERT_NOT_NULL (cdev_path,"Failed to find vfio cdev file for %s\n" , bdf); +return cdev_path; +} +int __vfio_device_bind_iommufd (int device_fd,int iommufd,const char *vf_token) {struct vfio_device_bind_iommufd args = {
@@ -449,10 +456,14 @@ static void vfio_device_attach_iommufd_pt(int device_fd, u32 pt_id)void vfio_pci_cdev_open (struct vfio_pci_device *device,const char *bdf) { -const char *cdev_path =vfio_pci_get_cdev_path (bdf); +bool noiommu = device->iommu->mode->noiommu; +const char *cdev_path =__vfio_pci_get_cdev_path (bdf, noiommu); + +VFIO_ASSERT_NOT_NULL (cdev_path,"Failed to find %svfio cdev file for %s\n" , + noiommu ?"noiommu-" :"" , bdf); device->fd =open (cdev_path,O_RDWR ); -VFIO_ASSERT_GE (device->fd,0 ); +VFIO_ASSERT_GE (device->fd,0 ,"open(%s) failed\n" , cdev_path);free ((void *)cdev_path); }
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 21/27 vfio: selftests: Add helpers to map DMA memory at IOVA == PA in noiommu mode
In reply to Vipin SharmaSelftest drivers program the IOVA returned by to_iova() into the device. Because a device in noiommu mode uses those addresses directly as physical addresses, DMA buffers must be mapped at IOVA == PA so that to_iova() returns the buffer's physical address without changing the drivers.
Add __iommu_noiommu_get_pa() to wrap IOMMU_IOAS_NOIOMMU_GET_PA and iommu_map_identity() to map a physically contiguous buffer at IOVA == PA by first pinning it at a scratch IOVA (BIT_ULL(52), above the 52-bit output address space of the noiommu page table), querying its physical address and contiguity, mapping it at IOVA == PA, and then unmapping the scratch range while keeping the pages pinned.
--- .../vfio/lib/include/libvfio/iommu.h | 26 ++++++++ tools/testing/selftests/vfio/lib/iommu.c | 61 +++++++++++++++++++ 2 files changed, 87 insertions(+)
tools/testing/selftests/vfio/lib/include/libvfio/iommu.h +26 -0
@@ -65,6 +65,32 @@ static inline void iommu_unmap_all(struct iommu *iommu)int __iommu_hva2iova (struct iommu *iommu,void *vaddr,iova_t *iova);iova_t iommu_hva2iova (struct iommu *iommu,void *vaddr); +/* +* Look up the physical address @iova maps to in the noiommu IOAS of @iommu +* (IOMMU_IOAS_NOIOMMU_GET_PA, requires CAP_SYS_RAWIO). On success, *@length is +* the number of physically contiguous bytes from *@pa, at most @max_length. +*/ +int __iommu_noiommu_get_pa (struct iommu *iommu,iova_t iova,u64 max_length, +u64 *pa,u64 *length); + +/* +* Map @region->size bytes at @region->vaddr at IOVA == PA, and set +* @region->iova to that PA. Devices in noiommu mode use the addresses that +* drivers program into them, i.e. to_iova(), as physical addresses, which such +* a mapping makes right. +* +* The buffer must be physically contiguous (e.g. a hugepage or a THP), and a +* noiommu device must be attached to @iommu already. The memory stays pinned, +* and so at the same physical address, until iommu_unmap(@region), which must +* not be called before the device stopped accessing it. +*/ +int __iommu_map_identity (struct iommu *iommu,struct dma_region *region); + +static inline void iommu_map_identity (struct iommu *iommu,struct dma_region *region) +{ +VFIO_ASSERT_EQ (__iommu_map_identity (iommu, region),0 ); +} +struct iommu_iova_range *iommu_iova_ranges (struct iommu *iommu,u32 *nranges);#define MODE_VFIO_TYPE1_IOMMU "vfio_type1_iommu"
tools/testing/selftests/vfio/lib/iommu.c +61 -0
73 lines not on this page · raw message
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 22/27 vfio: selftests: Add helpers for Live Update DMA memory and sysfs state
In reply to Vipin SharmaAdd shared libvfio helpers used by the Live Update kexec selftest:
- vfio_thp_memfd_alloc() and vfio_memfd_mmap_aligned() to allocate a shmem memfd, map it at a 2MB-aligned virtual address, and back it with 2MB THP folios via MADV_HUGEPAGE, write-fault population, and MADV_COLLAPSE.
- __sysfs_iommu_group_get(), a variant of sysfs_iommu_group_get() that returns an error instead of asserting when the device has no IOMMU group.
--- .../selftests/vfio/lib/include/libvfio.h | 3 ++ .../vfio/lib/include/libvfio/sysfs.h | 1 + tools/testing/selftests/vfio/lib/libvfio.c | 54 +++++++++++++++++++ tools/testing/selftests/vfio/lib/sysfs.c | 22 ++++++-- 4 files changed, 77 insertions(+), 3 deletions(-)
tools/testing/selftests/vfio/lib/include/libvfio.h +3 -0
@@ -33,4 +33,7 @@ char **vfio_selftests_get_bdfs(int *argc, char *argv[], int *nr_bdfs);*/ void *mmap_reserve (size_t size,size_t align,size_t offset); +int vfio_thp_memfd_alloc (size_t size,void **vaddr_out); +void *vfio_memfd_mmap_aligned (int fd,size_t size,size_t align); +#endif /* SELFTESTS_VFIO_LIB_INCLUDE_LIBVFIO_H */
tools/testing/selftests/vfio/lib/include/libvfio/sysfs.h +1 -0
@@ -6,6 +6,7 @@ int sysfs_sriov_totalvfs_get(const char *bdf);int sysfs_sriov_numvfs_get (const char *bdf);void sysfs_sriov_numvfs_set (const char *bdf,int numvfs);char *sysfs_sriov_vf_bdf_get (const char *pf_bdf,int i); +int __sysfs_iommu_group_get (const char *bdf,int *group);int sysfs_iommu_group_get (const char *bdf);char *sysfs_driver_get (const char *bdf);
tools/testing/selftests/vfio/lib/libvfio.c +54 -0
71 lines not on this page · raw message
tools/testing/selftests/vfio/lib/sysfs.c +19 -3
@@ -115,14 +115,30 @@ char *sysfs_sriov_vf_bdf_get(const char *pf_bdf, int i)return out_vf_bdf; } -int sysfs_iommu_group_get (const char *bdf) +int __sysfs_iommu_group_get (const char *bdf,int *group) { +char rl_path[PATH_MAX ];char path[PATH_MAX ]; -int group; +char *end; +int ret;snprintf_assert (path,PATH_MAX ,"/sys/bus/pci/devices/%s/iommu_group" , bdf); -readlink_base (path,"%d" , &group); + ret =readlink_safe (path, rl_path); +if (ret ==-1 ) +return -errno; + + errno =0 ; + *group =strtol (basename (rl_path), &end,10 ); +VFIO_ASSERT_EQ (errno,0 ); +VFIO_ASSERT_EQ (*end,'\0' ); +return 0 ; +} + +int sysfs_iommu_group_get (const char *bdf) +{ +int group; +VFIO_ASSERT_EQ (__sysfs_iommu_group_get (bdf, &group),0 );return group; }
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 23/27 vfio: selftests: Add an attach() driver op
In reply to Vipin SharmaAdd a new attach() op to vfio_pci_driver_ops and a corresponding vfio_pci_driver_attach() wrapper to adopt a device that was already initialized (and optionally has memcpy operations in flight) in another process prior to a Live Update, without resetting or reprogramming the hardware.
Implement attach() for the igb and dsa selftest drivers: refresh process- local BAR pointers, verify that the device hardware state and descriptor rings are still intact as left before kexec, re-enable MSI-X, and set driver capability limits.
--- .../selftests/vfio/lib/drivers/dsa/dsa.c | 35 +++++++++++++++-- .../selftests/vfio/lib/drivers/igb/igb.c | 39 +++++++++++++++++-- .../lib/include/libvfio/vfio_pci_driver.h | 17 ++++++++ .../selftests/vfio/lib/vfio_pci_driver.c | 22 ++++++++++- 4 files changed, 105 insertions(+), 8 deletions(-)
tools/testing/selftests/vfio/lib/drivers/dsa/dsa.c +31 -4
@@ -215,6 +215,16 @@ static void dsa_register_cache_init(struct vfio_pci_device *device) dsa->max_copies_per_batch =min (dsa->max_copies_per_batch,ARRAY_SIZE (dsa->copy)); } +static void dsa_set_limits (struct vfio_pci_device *device) +{ +struct dsa_state *dsa =to_dsa_state (device); + + device->driver.max_memcpy_count = + dsa->max_batches * dsa->max_copies_per_batch; + device->driver.max_memcpy_size =1UL << dsa->gen_cap.max_xfer_shift; + device->driver.msi =MSIX_VECTOR ; +} +static void dsa_init (struct vfio_pci_device *device) {struct dsa_state *dsa =to_dsa_state (device);
@@ -236,11 +246,27 @@ static void dsa_init(struct vfio_pci_device *device)dsa_command (device,IDXD_CMD_ENABLE_WQ );vfio_pci_msix_enable (device,MSIX_VECTOR ,1 ); +dsa_set_limits (device); +} - device->driver.max_memcpy_count = - dsa->max_batches * dsa->max_copies_per_batch; - device->driver.max_memcpy_size =1UL << dsa->gen_cap.max_xfer_shift; - device->driver.msi =MSIX_VECTOR ; +static void dsa_attach (struct vfio_pci_device *device) +{ +struct dsa_state *dsa =to_dsa_state (device); +union gensts_reg gensts; + +VFIO_ASSERT_GE (device->driver.region.size,sizeof (*dsa)); + +/* The device must still be enabled as dsa_init() left it. */ + gensts.bits =readl (device->bars[0 ].vaddr +IDXD_GENSTATS_OFFSET ); +VFIO_ASSERT_EQ ((u32 )gensts.state,IDXD_DEVICE_STATE_ENABLED , +"Device was disabled or reset\n" ); +dsa_check_sw_err (device); + +/* BAR0 is mapped at a different address now, refresh the pointers into it. */ +dsa_register_cache_init (device); + +vfio_pci_msix_enable (device,MSIX_VECTOR ,1 ); +dsa_set_limits (device); }static void dsa_remove (struct vfio_pci_device *device)
@@ -420,6 +446,7 @@ const struct vfio_pci_driver_ops dsa_ops = { .name = "dsa", .probe = dsa_probe, .init = dsa_init, + .attach = dsa_attach, .remove = dsa_remove, .memcpy_start = dsa_memcpy_start, .memcpy_wait = dsa_memcpy_wait,
tools/testing/selftests/vfio/lib/drivers/igb/igb.c +36 -3
@@ -224,6 +224,13 @@ static void igb_reset(struct igb *igb)igb_write32 (igb,E1000_IMC ,0xFFFFFFFF ); } +static void igb_set_limits (struct vfio_pci_device *device) +{ + device->driver.max_memcpy_size =IGB_MAX_CHUNK_SIZE ; + device->driver.max_memcpy_count =RING_SIZE -1 ; + device->driver.msi =MSIX_VECTOR ; +} +/* * Program the device into a usable state. Split out of igb_init() so it * can be reused after a device reset to re-program the registers that
@@ -372,9 +379,7 @@ static void igb_hw_init(struct vfio_pci_device *device) igb->tx_tail =0 ; igb->rx_tail =0 ; - device->driver.max_memcpy_size =IGB_MAX_CHUNK_SIZE ; - device->driver.max_memcpy_count =RING_SIZE -1 ; - device->driver.msi =MSIX_VECTOR ; +igb_set_limits (device); }static void igb_init (struct vfio_pci_device *device)
@@ -400,6 +405,33 @@ static void igb_init(struct vfio_pci_device *device)igb_hw_init (device); } +static void igb_attach (struct vfio_pci_device *device) +{ +struct igb *igb =to_igb_state (device); +u64 iova_tx, iova_rx; + +VFIO_ASSERT_GE (device->driver.region.size,sizeof (struct igb )); + +/* BAR0 is mapped at a different address in this process. */ + igb->bar0 = device->bars[0 ].vaddr; + +/* +* The device must still use the rings and tails in the driver region, +* i.e. it was not reset and the region is mapped at the same IOVAs. +*/ + iova_tx =to_iova (device, igb->tx_ring); + iova_rx =to_iova (device, igb->rx_ring); +VFIO_ASSERT_EQ (igb_read32 (igb,E1000_TDBAL (0 )), (u32 )iova_tx); +VFIO_ASSERT_EQ (igb_read32 (igb,E1000_TDBAH (0 )), (u32)(iova_tx >>32 )); +VFIO_ASSERT_EQ (igb_read32 (igb,E1000_RDBAL (0 )), (u32 )iova_rx); +VFIO_ASSERT_EQ (igb_read32 (igb,E1000_RDBAH (0 )), (u32)(iova_rx >>32 )); +VFIO_ASSERT_EQ (igb_read32 (igb,E1000_TDT (0 )), igb->tx_tail); +VFIO_ASSERT_EQ (igb_read32 (igb,E1000_RDT (0 )), igb->rx_tail); + +vfio_pci_msix_enable (device,MSIX_VECTOR ,1 ); +igb_set_limits (device); +} +static void igb_remove (struct vfio_pci_device *device) {struct igb *igb =to_igb_state (device);
@@ -578,6 +610,7 @@ const struct vfio_pci_driver_ops igb_ops = { .name = "igb", .probe = igb_probe, .init = igb_init, + .attach = igb_attach, .remove = igb_remove, .memcpy_start = igb_memcpy_start, .memcpy_wait = igb_memcpy_wait,
tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_driver.h +17 -0
@@ -28,6 +28,21 @@ struct vfio_pci_driver_ops {*/ void (*remove)(struct vfio_pci_device *device); +/** +* attach() - Adopt @device as init() and memcpy_start() left it, e.g. +* in another process before a Live Update, without resetting or +* reprogramming it. Memcpy operations started then keep going and can be +* waited for with memcpy_wait(). Optional. +* +* Only sets up what is specific to the calling process (pointers into the +* BARs kept in the driver state, MSI-X) and the driver limits. +* +* Must be called after device->driver.region, and any memory the device +* was told to DMA to, have been mapped at the same IOVAs as when init() +* and memcpy_start() were called. +*/ +void (*attach)(struct vfio_pci_device *device); +/** * memcpy_start() - Kick off @count repeated memcpy operations from * [@src, @src + @size) to [@dst, @dst + @size).
@@ -85,6 +100,8 @@ struct vfio_pci_driver {void vfio_pci_driver_probe (struct vfio_pci_device *device);void vfio_pci_driver_init (struct vfio_pci_device *device); +void vfio_pci_driver_attach (struct vfio_pci_device *device, +bool memcpy_in_progress);void vfio_pci_driver_remove (struct vfio_pci_device *device);int vfio_pci_driver_memcpy (struct vfio_pci_device *device,iova_t src,iova_t dst,u64 size);
tools/testing/selftests/vfio/lib/vfio_pci_driver.c +21 -1
@@ -40,7 +40,8 @@ static void vfio_check_driver_op(struct vfio_pci_driver *driver, void *op, {VFIO_ASSERT_NOT_NULL (driver->ops);VFIO_ASSERT_NOT_NULL (op,"Driver has no %s()\n" , op_name); -VFIO_ASSERT_EQ (driver->initialized, op != driver->ops->init); +VFIO_ASSERT_EQ (driver->initialized, + op != driver->ops->init && op != driver->ops->attach);VFIO_ASSERT_EQ (driver->memcpy_in_progress, op == driver->ops->memcpy_wait); }
@@ -61,6 +62,25 @@ void vfio_pci_driver_init(struct vfio_pci_device *device) driver->initialized = true; } +/* +* Take over @device as vfio_pci_driver_init() left it in another process, e.g. +* before a Live Update. Pass @memcpy_in_progress if memcpy operations were +* started there, to be able to wait for them with vfio_pci_driver_memcpy_wait(). +*/ +void vfio_pci_driver_attach (struct vfio_pci_device *device, +bool memcpy_in_progress) +{ +struct vfio_pci_driver *driver = &device->driver; + +VFIO_ASSERT_NOT_NULL (driver->region.vaddr); +VFIO_CHECK_DRIVER_OP (driver, attach); + + driver->ops->attach (device); + + driver->initialized = true; + driver->memcpy_in_progress = memcpy_in_progress; +} +void vfio_pci_driver_remove (struct vfio_pci_device *device) {struct vfio_pci_driver *driver = &device->driver;
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 24/27 vfio: selftests: Test preserving noiommu devices in vfio_pci_liveupdate_uapi_test
In reply to Vipin SharmaAdd the iommufd_noiommu fixture variant to vfio_pci_liveupdate_uapi_test and detect at startup whether the target device is bound to vfio-pci in noiommu mode so that variants not matching the device cleanly skip, in addition to skipping iommufd variants when probing luo_session_preserve_fd() in FIXTURE_SETUP reports -ENOENT (e.g. on an SR-IOV VF or when CONFIG_VFIO_PCI_LIVEUPDATE=n).
When the device is in noiommu mode, verify that preserving its bound VFIO cdev FD succeeds, and add tests verifying that:
- preserving an unbound second cdev FD fails with -ENOENT without affecting the bound FD (preserve_unbound_fd_fails),
- preserving a cdev FD that was never bound fails with -ENOENT (preserve_never_bound_fails), and
- closing the Live Update session unpreserves the device so that it can be preserved again in a new session (preserve_after_unpreserve).
--- .../vfio/vfio_pci_liveupdate_uapi_test.c | 103 +++++++++++++++++- 1 file changed, 102 insertions(+), 1 deletion(-)
tools/testing/selftests/vfio/vfio_pci_liveupdate_uapi_test.c +102 -1
@@ -1,10 +1,13 @@// SPDX-License-Identifier: GPL-2.0-only +#include <fcntl.h> +#include <linux/pci_regs.h> #include <libliveupdate.h> #include <libvfio.h> #include <kselftest_harness.h> static const char *device_bdf; +static bool device_is_noiommu;FIXTURE (vfio_pci_liveupdate_uapi_test) {int luo_fd;
@@ -45,10 +48,19 @@ FIXTURE_VARIANT_ADD(vfio_pci_liveupdate_uapi_test, _iommu_mode) { \ }FIXTURE_VARIANT_ADD_ALL_IOMMU_MODES (); +FIXTURE_VARIANT_ADD_IOMMU_MODE (iommufd_noiommu);#undef FIXTURE_VARIANT_ADD_IOMMU_MODEFIXTURE_SETUP (vfio_pci_liveupdate_uapi_test) { +bool variant_is_noiommu; + + variant_is_noiommu = !strcmp (variant->iommu_mode,MODE_IOMMUFD_NOIOMMU ); +if (variant_is_noiommu != device_is_noiommu) +SKIP (return,"%s does not apply to a %s device" , + variant->iommu_mode, + device_is_noiommu ?"noiommu" :"non-noiommu" ); + self->luo_fd =luo_open_device ();ASSERT_GT (self->luo_fd,0 );
@@ -77,6 +89,7 @@ FIXTURE_TEARDOWN(vfio_pci_liveupdate_uapi_test) TEST_F(vfio_pci_liveupdate_uapi_test, preserve_device) { +int expected;int ret; ret =luo_session_preserve_fd (self->session_fd, self->device->fd,0 );
@@ -85,7 +98,84 @@ TEST_F(vfio_pci_liveupdate_uapi_test, preserve_device)* Only VFIO cdev files of devices in noiommu mode can be preserved; * device files obtained through a VFIO group never can. */ -ASSERT_EQ (ret, self->iommu->iommufd ? -EOPNOTSUPP : -ENOENT ); +if (device_is_noiommu) + expected =0 ; +else + expected = self->iommu->iommufd ? -EOPNOTSUPP : -ENOENT ; + +ASSERT_EQ (ret, expected); +} + +TEST_F(vfio_pci_liveupdate_uapi_test, preserve_unbound_fd_fails) +{ +const char *cdev_path; +int unbound_fd; +int ret; + +if (!self->iommu->iommufd) +SKIP (return,"Only iommufd modes use VFIO cdev files" ); + + cdev_path =__vfio_pci_get_cdev_path (device_bdf, device_is_noiommu); +ASSERT_NE (cdev_path,NULL ); + + unbound_fd =open (cdev_path,O_RDWR ); +ASSERT_GE (unbound_fd,0 ); +free ((void *)cdev_path); + +/* +* A second cdev FD that has not been bound via VFIO_DEVICE_BIND_IOMMUFD +* must be rejected even while another FD for the same device is bound. +*/ + ret =luo_session_preserve_fd (self->session_fd, unbound_fd,0 ); +ASSERT_EQ (ret, -ENOENT ); +ASSERT_EQ (close (unbound_fd),0 ); + +/* Verify the failed attempt had no side effects on the bound FD. */ + ret =luo_session_preserve_fd (self->session_fd, self->device->fd,0 ); +ASSERT_EQ (ret, device_is_noiommu ?0 : -EOPNOTSUPP ); +} + +TEST_F(vfio_pci_liveupdate_uapi_test, preserve_never_bound_fails) +{ +const char *cdev_path; +int unbound_fd; +int ret; + +if (!self->iommu->iommufd) +SKIP (return,"Only iommufd modes use VFIO cdev files" ); + +vfio_pci_device_cleanup (self->device); + self->device =NULL ; + + cdev_path =__vfio_pci_get_cdev_path (device_bdf, device_is_noiommu); +ASSERT_NE (cdev_path,NULL ); + + unbound_fd =open (cdev_path,O_RDWR ); +ASSERT_GE (unbound_fd,0 ); +free ((void *)cdev_path); + + ret =luo_session_preserve_fd (self->session_fd, unbound_fd,0 ); +ASSERT_EQ (ret, -ENOENT ); +ASSERT_EQ (close (unbound_fd),0 ); +} + +TEST_F(vfio_pci_liveupdate_uapi_test, preserve_after_unpreserve) +{ +u16 vendor_id; + +if (!device_is_noiommu) +SKIP (return,"Only noiommu devices can be preserved" ); + +ASSERT_EQ (luo_session_preserve_fd (self->session_fd, self->device->fd,0 ),0 ); + +ASSERT_EQ (close (self->session_fd),0 ); + self->session_fd =luo_create_session (self->luo_fd,"session2" ); +ASSERT_GT (self->session_fd,0 ); + +ASSERT_EQ (luo_session_preserve_fd (self->session_fd, self->device->fd,0 ),0 ); + + vendor_id =vfio_pci_config_readw (self->device,PCI_VENDOR_ID ); +ASSERT_NE (vendor_id,0xffff ); }TEST_F (vfio_pci_liveupdate_uapi_test, preserve_group_fails)
@@ -112,6 +202,7 @@ TEST_F(vfio_pci_liveupdate_uapi_test, preserve_container_fails)int main (int argc,char *argv[]) { +const char *cdev_path;int fd; fd =luo_open_device ();
@@ -122,5 +213,15 @@ int main(int argc, char *argv[])close (fd); device_bdf =vfio_selftests_get_bdf (&argc, argv); + + cdev_path =__vfio_pci_get_cdev_path (device_bdf, true); +if (cdev_path) { + device_is_noiommu = true; + }else { + cdev_path =vfio_pci_get_cdev_path (device_bdf); + device_is_noiommu = false; + } +free ((void *)cdev_path); +return test_harness_run (argc, argv); }
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 25/27 vfio: selftests: Add vfio_pci_liveupdate_kexec_test
In reply to Vipin SharmaAdd a selftest to exercise preserving a vfio-pci device in noiommu mode across a Live Update. For now the test is simple and verifies that the device file can be preserved, retrieved, and bound to iommufd in the new kernel. Subsequent commits extend this test to verify that the device cannot be opened through VFIO during the Live Update and that DMA continues across it.
This test is added to TEST_GEN_PROGS_EXTENDED since it must be run manually along with a kexec.
The kernel must be booted with vfio.enable_unsafe_noiommu_mode=1 and the target device must be bound to vfio-pci in both kernels. In the new kernel, the preserved device must be bound to vfio-pci without first being bound to or unbound from any other driver. This can be done during boot, e.g. with vfio-pci.ids=<vid>:<did> on the kernel command line, or manually before running stage 2:
$ echo vfio-pci > /sys/bus/pci/devices/0000:00:04.0/driver_override $ echo 0000:00:04.0 > /sys/bus/pci/drivers/vfio-pci/bind
To run this test manually:
$ ./vfio_pci_liveupdate_kexec_test -s 1 0000:00:04.0
$ kexec ... # NOTE: Exact method will be distro-dependent
$ ./vfio_pci_liveupdate_kexec_test -s 2 0000:00:04.0
Do not unbind the device from vfio-pci after kexec (e.g. by running setup.sh on a device that is already bound to vfio-pci), as unbinding it would reset it.
This test is considered passing if all commands exit with 0.
--- tools/testing/selftests/vfio/Makefile | 4 + .../vfio/vfio_pci_liveupdate_kexec_test.c | 102 ++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c
tools/testing/selftests/vfio/Makefile +4 -0
@@ -15,6 +15,10 @@ TEST_GEN_PROGS += vfio_pci_driver_test TEST_GEN_PROGS += vfio_pci_sriov_uapi_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
tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c new file +102 -0
102 lines not on this page · raw message
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 26/27 vfio: selftests: Verify that opening VFIO device fails during Live Update
In reply to Vipin SharmaVerify 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 preserved across a Live Update, the file must be retrieved from /dev/liveupdate, not from VFIO directly.
--- .../vfio/vfio_pci_liveupdate_kexec_test.c | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+)
tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c +38 -0
@@ -1,6 +1,9 @@// SPDX-License-Identifier: GPL-2.0-only #include <fcntl.h> +#include <limits.h> +#include <sys/ioctl.h> +#include <linux/vfio.h> #include <libliveupdate.h> #include <libvfio.h>
@@ -56,6 +59,39 @@ 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, true); +char group_path[PATH_MAX ]; +int group_fd; +int group; +int ret; + +VFIO_ASSERT_NOT_NULL (cdev_path); + + ret =open (cdev_path,O_RDWR ); +VFIO_ASSERT_EQ (ret,-1 ); +VFIO_ASSERT_EQ (errno,EBUSY ); +free ((void *)cdev_path); + +if (__sysfs_iommu_group_get (device_bdf, &group)) +return ; + +snprintf_assert (group_path,sizeof (group_path),"/dev/vfio/noiommu-%d" , + group); + group_fd =open (group_path,O_RDWR ); +if (group_fd <0 ) { +VFIO_ASSERT_EQ (errno,ENOENT ); +return ; + } + + ret =ioctl (group_fd,VFIO_GROUP_GET_DEVICE_FD , device_bdf); +VFIO_ASSERT_EQ (ret,-1 ); +VFIO_ASSERT_EQ (errno,EBUSY ); + +VFIO_ASSERT_EQ (close (group_fd),0 ); +} +static void after_kexec (int luo_fd,int state_session_fd) {struct vfio_pci_device *device;
@@ -64,6 +100,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 );
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH v6 27/27 vfio: selftests: Add continuous DMA to vfio_pci_liveupdate_kexec_test
In reply to Vipin SharmaExtend vfio_pci_liveupdate_kexec_test to exercise continuous DMA across a Live Update when the device is in noiommu mode.
Allocate a shmem memfd backed by three 2MB THP folios (for the driver region, source buffer, and destination buffer), map each folio at IOVA == PA via iommu_map_identity(), and preserve the memfd in the same Live Update session before the device so that LUO's LIFO finish order keeps the memory alive until after the device is finished.
Before kexec, initialize the selftest driver, run a sanity memcpy, kick off a long-running DMA memcpy, and disable MSI-X so freeze() succeeds. After kexec, take over the device via __vfio_pci_device_init(), retrieve and map the preserved memfd verifying that all three 2MB folios stayed at the exact same physical addresses, attach the driver without resetting the device, wait for the pre-kexec memcpy to complete, and run another memcpy without reinitializing the device.
--- .../vfio/vfio_pci_liveupdate_kexec_test.c | 266 +++++++++++++++++- 1 file changed, 257 insertions(+), 9 deletions(-)
tools/testing/selftests/vfio/vfio_pci_liveupdate_kexec_test.c +257 -9
@@ -1,22 +1,120 @@// SPDX-License-Identifier: GPL-2.0-only +#include <errno.h> #include <fcntl.h> #include <limits.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> +#include <sys/ioctl.h> +#include <sys/mman.h> + +#include <linux/sizes.h> #include <linux/vfio.h> +#include <libliveupdate.h> #include <libvfio.h> +#define DRIVER_REGION_SIZE SZ_2M +#define MEMCPY_FOLIO_SIZE SZ_2M +#define NR_MEMFD_FOLIOS 3 +#define MEMFD_SIZE (NR_MEMFD_FOLIOS * SZ_2M) + +#define MEMCPY_TIMEOUT_S (30 * 60) + +static struct dma_region src_region; +static struct dma_region dst_region; +static void *memfd_vaddr; +static u64 folio_pa[NR_MEMFD_FOLIOS ]; +static const char *device_bdf;static char state_session[LIVEUPDATE_SESSION_NAME_LENGTH ]; +static char data_session[LIVEUPDATE_SESSION_NAME_LENGTH ];static char device_session[LIVEUPDATE_SESSION_NAME_LENGTH ];enum {STATE_TOKEN ,DEVICE_TOKEN , +MEMFD_TOKEN , +DATA_TOKEN , }; +static u64 memcpy_size (struct vfio_pci_device *device) +{ +return min_t (u64, src_region.size, device->driver.max_memcpy_size); +} + +static bool is_filled (const char *buf,u64 size,char c) +{ +return buf[0 ] == c && !memcmp (buf, buf +1 , size -1 ); +} + +static void dma_memcpy_one (struct vfio_pci_device *device,char c) +{ +u64 size =memcpy_size (device); +void *src = src_region.vaddr; +void *dst = dst_region.vaddr; + +memset (src, c, size); +memset (dst,0 , size); + +VFIO_ASSERT_EQ (vfio_pci_driver_memcpy (device,to_iova (device, src), +to_iova (device, dst), size),0 ); +VFIO_ASSERT_TRUE (is_filled (dst, size, c)); +} + +static void dma_memcpy_start (struct vfio_pci_device *device) +{ +u64 size =memcpy_size (device); +void *src = src_region.vaddr; +void *dst = dst_region.vaddr; +u64 count; + +/* +* 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,'x' , size); +memset (dst,0 , size); + +ksft_print_msg ("Starting %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_memcpy_wait (struct vfio_pci_device *device) +{ +u64 size =memcpy_size (device); +void *src = src_region.vaddr; +void *dst = dst_region.vaddr; +struct timespec start, end; +long ms; + +VFIO_ASSERT_EQ (clock_gettime (CLOCK_MONOTONIC , &start),0 ); + +/* Fail rather than hang if the device stopped, e.g. as it was reset. */ +alarm (MEMCPY_TIMEOUT_S ); +VFIO_ASSERT_EQ (vfio_pci_driver_memcpy_wait (device),0 ); +alarm (0 ); + +VFIO_ASSERT_EQ (clock_gettime (CLOCK_MONOTONIC , &end),0 ); + ms = (end.tv_sec - start.tv_sec) *1000 + + (end.tv_nsec - start.tv_nsec) /1000000 ; + +VFIO_ASSERT_TRUE (is_filled (src, size,'x' )); +VFIO_ASSERT_TRUE (is_filled (dst, size,'x' )); + +ksft_print_msg ("Pre-kexec DMA memcpy operations completed after %ld ms\n" , + ms); +} +static void check_noiommu (const char *bdf) {const char *cdev_path =__vfio_pci_get_cdev_path (bdf, true);
@@ -35,26 +133,162 @@ static void check_noiommu(const char *bdf)free ((void *)cdev_path); } +static void dma_memfd_regions_map (struct vfio_pci_device *device,int fd, +bool before_kexec) +{ +struct dma_region *regions[NR_MEMFD_FOLIOS ] = { + &device->driver.region, + &src_region, + &dst_region, + }; +int i; + + memfd_vaddr =vfio_memfd_mmap_aligned (fd,MEMFD_SIZE ,SZ_2M ); + +for (i =0 ; i <NR_MEMFD_FOLIOS ; i++) { +struct dma_region *r = regions[i]; + + r->vaddr = memfd_vaddr + (u64 )i *SZ_2M ; + r->size =SZ_2M ; +iommu_map_identity (device->iommu, r); + +if (before_kexec) + folio_pa[i] = r->iova; +else +VFIO_ASSERT_EQ (r->iova, folio_pa[i], +"Folio %d moved across kexec (0x%lx != 0x%lx)\n" , + i, r->iova, folio_pa[i]); + } +} + +static void dma_memfd_recheck_pa (struct vfio_pci_device *device) +{ +struct dma_region *regions[NR_MEMFD_FOLIOS ] = { + &device->driver.region, + &src_region, + &dst_region, + }; +int i; + +for (i =0 ; i <NR_MEMFD_FOLIOS ; i++) { +u64 pa, len; + +VFIO_ASSERT_EQ (__iommu_noiommu_get_pa (device->iommu, + regions[i]->iova,SZ_2M , + &pa, &len),0 ); +VFIO_ASSERT_EQ (pa, folio_pa[i]); +VFIO_ASSERT_EQ (len, (u64 )SZ_2M ); + } +} + +static void dma_memfd_regions_unmap (struct vfio_pci_device *device) +{ +iommu_unmap (device->iommu, &dst_region); +iommu_unmap (device->iommu, &src_region); +iommu_unmap (device->iommu, &device->driver.region); +VFIO_ASSERT_EQ (munmap (memfd_vaddr,MEMFD_SIZE ),0 ); + memfd_vaddr =NULL ; +} + +static void save_data_session (int luo_fd) +{ +char buf[256 ]; +int data_fd; + + data_fd =luo_create_session (luo_fd, data_session); +VFIO_ASSERT_GE (data_fd,0 ); + +snprintf_assert (buf,sizeof (buf),"0x%lx 0x%lx 0x%lx" , + folio_pa[0 ], folio_pa[1 ], folio_pa[2 ]); +VFIO_ASSERT_EQ (create_and_preserve_memfd (data_fd,DATA_TOKEN , buf),0 ); +} + +static void load_data_session (int luo_fd) +{ +char buf[256 ] = {}; +char *end, *cur; +int data_fd; +int mfd; +int i; + + data_fd =luo_retrieve_session (luo_fd, data_session); +VFIO_ASSERT_GE (data_fd,0 ); + + mfd =luo_session_retrieve_fd (data_fd,DATA_TOKEN ); +VFIO_ASSERT_GE (mfd,0 ); +VFIO_ASSERT_GT (pread (mfd, buf,sizeof (buf) -1 ,0 ),0 ); +VFIO_ASSERT_EQ (close (mfd),0 ); + + cur = buf; +for (i =0 ; i <NR_MEMFD_FOLIOS ; i++) { + errno =0 ; + folio_pa[i] =strtoull (cur, &end,0 ); +VFIO_ASSERT_EQ (errno,0 ); +VFIO_ASSERT_NE (end, cur); + cur = end; + } + +VFIO_ASSERT_EQ (luo_session_finish (data_fd),0 ); +VFIO_ASSERT_EQ (close (data_fd),0 ); +} +static void before_kexec (int luo_fd) {struct vfio_pci_device *device;struct iommu *iommu; +void *init_vaddr =NULL ;int session_fd; +int memfd;int ret;check_noiommu (device_bdf); + memfd =vfio_thp_memfd_alloc (MEMFD_SIZE , &init_vaddr); +if (memfd <0 ) +ksft_exit_skip ("Failed to allocate 2MB THP memfd: %s\n" , +strerror (-memfd)); +VFIO_ASSERT_EQ (munmap (init_vaddr,MEMFD_SIZE ),0 ); + iommu =iommu_init (MODE_IOMMUFD_NOIOMMU ); device =vfio_pci_device_init (device_bdf, iommu); +if (!device->driver.ops || !device->driver.ops->attach) +ksft_exit_skip ("No driver that supports attach() found for %s\n" , + device_bdf); + +dma_memfd_regions_map (device, memfd, true); +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 ); +/* +* Preserve the DMA memfd in the same session before the device so that +* LUO's LIFO finish order resets an unclaimed device before freeing +* the memfd folios. +*/ + ret =luo_session_preserve_fd (session_fd, memfd,MEMFD_TOKEN ); +VFIO_ASSERT_EQ (ret,0 ); + +dma_memfd_recheck_pa (device); + ret =luo_session_preserve_fd (session_fd, device->fd,DEVICE_TOKEN );VFIO_ASSERT_EQ (ret,0 ); +vfio_pci_driver_init (device); +dma_memcpy_one (device,'a' ); + +dma_memcpy_start (device); + +/* +* Disable interrupts on the device or freeze() will fail. The memcpy +* operations do not generate any. +*/ +vfio_pci_msix_disable (device); + +save_data_session (luo_fd); +close (luo_fd);daemonize_and_wait (); }
@@ -98,13 +332,16 @@ 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 (); -restore_and_read_stage (state_session_fd,STATE_TOKEN , &stage);VFIO_ASSERT_EQ (stage,2 ); +load_data_session (luo_fd); + +check_open_vfio_device_fails (); + session_fd =luo_retrieve_session (luo_fd, device_session);VFIO_ASSERT_GE (session_fd,0 );
@@ -112,16 +349,25 @@ static void after_kexec(int luo_fd, int state_session_fd)VFIO_ASSERT_GE (device_fd,0 ); iommu =iommu_init (MODE_IOMMUFD_NOIOMMU ); - -/* -* 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); + memfd =luo_session_retrieve_fd (session_fd,MEMFD_TOKEN ); +VFIO_ASSERT_GE (memfd,0 ); + +dma_memfd_regions_map (device, memfd, false); + +vfio_pci_driver_attach (device,/*memcpy_in_progress=*/ true); +dma_memcpy_wait (device); + +/* The device was not reset, so it can be used without reinitializing it. */ +dma_memcpy_one (device,'y' ); +VFIO_ASSERT_EQ (luo_session_finish (session_fd),0 ); +VFIO_ASSERT_EQ (close (session_fd),0 ); + +vfio_pci_driver_remove (device); +dma_memfd_regions_unmap (device); +VFIO_ASSERT_EQ (close (memfd),0 );vfio_pci_device_cleanup (device);iommu_cleanup (iommu);
@@ -133,6 +379,8 @@ int main(int argc, char *argv[])snprintf_assert (device_session,sizeof (device_session),"vfio-lu-device-%s" , device_bdf); +snprintf_assert (data_session,sizeof (data_session), +"vfio-lu-data-%s" , device_bdf);snprintf_assert (state_session,sizeof (state_session),"vfio-lu-state-%s" , device_bdf);
Signature · 1 line
2.56.0.317.g454f8302e1-goog
David Matlack
maintainerQuoted 28 lines · Vipin Sharma
David Matlack (4):
vfio: Enforce preserved devices are retrieved via
LIVEUPDATE_SESSION_RETRIEVE_FD
docs: liveupdate: Add documentation for VFIO PCI
vfio: selftests: Addvfio_pci_liveupdate_uapi_test
vfio: selftests: AddMakefilesupport forTEST_GEN_PROGS_EXTENDEDVipin Sharma (23):
vfio/pci: Factor out the reset logic in VFIO PCI device close path
vfio: Export various helpers from VFIO
liveupdate: Export symbols needed by modules
vfio/pci: Register a file handler with Live Update Orchestrator
PCI: liveupdate: Add helpers to preserve structpci_saved_state
vfio: Add helpers to identify device files that can be preserved vfio/pci: Preserve vfio-pci device files across Live Update
vfio: Introducevfio_find_device()helper
vfio: Refactorvfio_device_fops_cdev_open()
vfio: Add API to open cdev device for Live Update restore vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Protect incoming preserved devices until they finish Live
Update
vfio/pci: Take over preserved devices without resetting them
vfio: selftests: Build liveupdate library in VFIO selftests
vfio: selftests: Initializevfio_pci_deviceusing a VFIO cdev FD
vfio: selftests: Add iommufd noiommu mode
vfio: selftests: Add helpers to map DMA memory at IOVA == PA in
noiommu mode
vfio: selftests: Add helpers for Live Update DMA memory and sysfs
Quoted 8 lines
state
vfio: selftests: Add anattach()driver op
vfio: selftests: Test preserving noiommu devices in
vfio_pci_liveupdate_uapi_test
vfio: selftests: Addvfio_pci_liveupdate_kexec_test
vfio: selftests: Verify that opening VFIO device fails during Live
Update
vfio: selftests: Add continuous DMA tovfio_pci_liveupdate_kexec_test
This series is getting quite long. I would consider splitting out the selftests into its own series and we can iterate on each separately.
Quoted 39 lines · David Matlack
Quoted 28 lines · Vipin Sharma
David Matlack (4):
vfio: Enforce preserved devices are retrieved via
LIVEUPDATE_SESSION_RETRIEVE_FD
docs: liveupdate: Add documentation for VFIO PCI
vfio: selftests: Addvfio_pci_liveupdate_uapi_test
vfio: selftests: AddMakefilesupport forTEST_GEN_PROGS_EXTENDEDVipin Sharma (23):
vfio/pci: Factor out the reset logic in VFIO PCI device close path
vfio: Export various helpers from VFIO
liveupdate: Export symbols needed by modules
vfio/pci: Register a file handler with Live Update Orchestrator
PCI: liveupdate: Add helpers to preserve structpci_saved_state
vfio: Add helpers to identify device files that can be preserved vfio/pci: Preserve vfio-pci device files across Live Update
vfio: Introducevfio_find_device()helper
vfio: Refactorvfio_device_fops_cdev_open()
vfio: Add API to open cdev device for Live Update restore vfio/pci: Retrieve preserved device files after Live Update vfio/pci: Protect incoming preserved devices until they finish Live
Update
vfio/pci: Take over preserved devices without resetting them
vfio: selftests: Build liveupdate library in VFIO selftests
vfio: selftests: Initializevfio_pci_deviceusing a VFIO cdev FD
vfio: selftests: Add iommufd noiommu mode
vfio: selftests: Add helpers to map DMA memory at IOVA == PA in
noiommu mode
vfio: selftests: Add helpers for Live Update DMA memory and sysfsQuoted 8 lines
state
vfio: selftests: Add anattach()driver op
vfio: selftests: Test preserving noiommu devices in
vfio_pci_liveupdate_uapi_test
vfio: selftests: Addvfio_pci_liveupdate_kexec_test
vfio: selftests: Verify that opening VFIO device fails during Live
Update
vfio: selftests: Add continuous DMA tovfio_pci_liveupdate_kexec_test
Quoted 2 lines
This series is getting quite long. I would consider splitting out the selftests into its own series and we can iterate on each separately.
I think it is a good idea. In next version, v7, I will send two series, kernel and selftests patches.