AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/09 14:37 flow patch-triage
1m Args:
null

Results:
{
  "EnableConfigs": null,
  "FocusSymbols": [],
  "KMSANReasoning": "",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series adds live guest migration support for s390 VFIO-AP (Adjunct Processor) devices, modifying documentation and driver code strictly under drivers/s390/crypto/. These code paths are exclusive to the s390 architecture (CONFIG_S390 / CONFIG_VFIO_AP) and cannot be compiled or executed on the target architecture (amd64). Consequently, the changes are structurally unreachable for fuzzing on amd64.",
  "WorthFuzzing": false
}

1/1 2026/10/09 14:37 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 2224a13792a5e8ace3c129e7390e3c29fac6d1d6\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Fri Oct 9 14:36:58 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/arch/s390/vfio-ap.rst b/Documentation/arch/s390/vfio-ap.rst\nindex ac0c07f76ddd7..02d7cbe5e4791 100644\n--- a/Documentation/arch/s390/vfio-ap.rst\n+++ b/Documentation/arch/s390/vfio-ap.rst\n@@ -1012,7 +1012,7 @@ guest_matrix dyn ap_config\n \n the following features are advertised:\n \n----------------+---------------------------------------------------------------+\n++--------------+---------------------------------------------------------------+\n | Flag         | Description                                                   |\n +==============+===============================================================+\n | guest_matrix | guest_matrix attribute exists. It reports the matrix of       |\n@@ -1021,105 +1021,523 @@ the following features are advertised:\n +--------------+---------------------------------------------------------------+\n | dyn          | Indicates hot plug/unplug of AP adapters, domains and control |\n |              | domains for a guest to which the mdev is attached.            |\n-+------------+-----------------------------------------------------------------+\n++--------------+---------------------------------------------------------------+\n | ap_config    | ap_config interface for one-shot modifications to mdev config |\n +--------------+---------------------------------------------------------------+\n+| migratable   | Indicates that live guest migration is supported for guests   |\n+|              | to which crypto devices are passed through                    |\n++--------------+---------------------------------------------------------------+\n \n-Limitations\n-===========\n-Live guest migration is not supported for guests using AP devices without\n-intervention by a system administrator. Before a KVM guest can be migrated,\n-the vfio_ap mediated device must be removed. Unfortunately, it can not be\n-removed manually (i.e., echo 1 \u003e /sys/devices/vfio_ap/matrix/$UUID/remove) while\n-the mdev is in use by a KVM guest. If the guest is being emulated by QEMU,\n-its mdev can be hot unplugged from the guest in one of two ways:\n-\n-1. If the KVM guest was started with libvirt, you can hot unplug the mdev via\n-   the following commands:\n-\n-      virsh detach-device \u003cguestname\u003e \u003cpath-to-device-xml\u003e\n-\n-      For example, to hot unplug mdev 62177883-f1bb-47f0-914d-32a22e3a8804 from\n-      the guest named 'my-guest':\n-\n-         virsh detach-device my-guest ~/config/my-guest-hostdev.xml\n-\n-            The contents of my-guest-hostdev.xml:\n-\n-.. code-block:: xml\n-\n-            \u003chostdev mode='subsystem' type='mdev' managed='no' model='vfio-ap'\u003e\n-              \u003csource\u003e\n-                \u003caddress uuid='62177883-f1bb-47f0-914d-32a22e3a8804'/\u003e\n-              \u003c/source\u003e\n-            \u003c/hostdev\u003e\n-\n-\n-      virsh qemu-monitor-command \u003cguest-name\u003e --hmp \"device-del \u003cdevice-id\u003e\"\n-\n-      For example, to hot unplug the vfio_ap mediated device identified on the\n-      qemu command line with 'id=hostdev0' from the guest named 'my-guest':\n-\n-.. code-block:: sh\n-\n-         virsh qemu-monitor-command my-guest --hmp \"device_del hostdev0\"\n-\n-2. A vfio_ap mediated device can be hot unplugged by attaching the qemu monitor\n-   to the guest and using the following qemu monitor command:\n-\n-      (QEMU) device-del id=\u003cdevice-id\u003e\n-\n-      For example, to hot unplug the vfio_ap mediated device that was specified\n-      on the qemu command line with 'id=hostdev0' when the guest was started:\n-\n-         (QEMU) device-del id=hostdev0\n-\n-After live migration of the KVM guest completes, an AP configuration can be\n-restored to the KVM guest by hot plugging a vfio_ap mediated device on the target\n-system into the guest in one of two ways:\n-\n-1. If the KVM guest was started with libvirt, you can hot plug a matrix mediated\n-   device into the guest via the following virsh commands:\n-\n-   virsh attach-device \u003cguestname\u003e \u003cpath-to-device-xml\u003e\n-\n-      For example, to hot plug mdev 62177883-f1bb-47f0-914d-32a22e3a8804 into\n-      the guest named 'my-guest':\n-\n-         virsh attach-device my-guest ~/config/my-guest-hostdev.xml\n-\n-            The contents of my-guest-hostdev.xml:\n-\n-.. code-block:: xml\n-\n-            \u003chostdev mode='subsystem' type='mdev' managed='no' model='vfio-ap'\u003e\n-              \u003csource\u003e\n-                \u003caddress uuid='62177883-f1bb-47f0-914d-32a22e3a8804'/\u003e\n-              \u003c/source\u003e\n-            \u003c/hostdev\u003e\n-\n-\n-   virsh qemu-monitor-command \u003cguest-name\u003e --hmp \\\n-   \"device_add vfio-ap,sysfsdev=\u003cpath-to-mdev\u003e,id=\u003cdevice-id\u003e\"\n-\n-      For example, to hot plug the vfio_ap mediated device\n-      62177883-f1bb-47f0-914d-32a22e3a8804 into the guest named 'my-guest' with\n-      device-id hostdev0:\n-\n-      virsh qemu-monitor-command my-guest --hmp \\\n-      \"device_add vfio-ap,\\\n-      sysfsdev=/sys/devices/vfio_ap/matrix/62177883-f1bb-47f0-914d-32a22e3a8804,\\\n-      id=hostdev0\"\n-\n-2. A vfio_ap mediated device can be hot plugged by attaching the qemu monitor\n-   to the guest and using the following qemu monitor command:\n-\n-      (qemu) device_add \"vfio-ap,sysfsdev=\u003cpath-to-mdev\u003e,id=\u003cdevice-id\u003e\"\n-\n-      For example, to plug the vfio_ap mediated device\n-      62177883-f1bb-47f0-914d-32a22e3a8804 into the guest with the device-id\n-      hostdev0:\n+Live Guest Migration\n+====================\n+The VFIO AP mediated device is not used to provide userspace with direct\n+access to device memory as is the case with other devices that use the VFIO\n+framework for device pass-through. Instead, it manages AP\n+configuration metadata identifying the adapters, domains, and control\n+domains to which a guest will be granted access. These AP resources are\n+configured by assigning them to a vfio-ap mediated device via its sysfs\n+assignment interfaces. When the guest is started, the vfio_ap device driver\n+sets the guest's AP configuration from the metadata stored with the mediated\n+device. The AP devices are not accessed directly through the vfio_ap driver,\n+so the driver does not migrate the state of the AP devices themselves.\n+Instead, it migrates the AP configuration metadata. The vfio_ap device\n+driver on the destination host will then ensure that the AP configuration\n+metadata migrated from the source host is compatible with the AP\n+configuration available on the destination host and if\n+so, will set the destination guest's AP configuration accordingly.\n \n-         (QEMU) device-add \"vfio-ap,\\\n-         sysfsdev=/sys/devices/vfio_ap/matrix/62177883-f1bb-47f0-914d-32a22e3a8804,\\\n-         id=hostdev0\"\n+To be considered compatible, the AP configuration for the destination host must\n+meet these requirements:\n+\n+* Each AP adapter, domain and control domain number assigned to the source\n+  guest's AP configuration must be in the destination host's AP\n+  configuration. This can be verified as follows:\n+\n+  * On the source host, display the AP configuration of the source guest\n+    with the following two commands:\n+\n+    .. code-block:: bash\n+\n+       cat /sys/devices/vfio_ap/matrix/$UUID/guest_matrix\n+       cat /sys/devices/vfio_ap/matrix/$UUID/control_domains\n+\n+    .. note::\n+       Replace ``$UUID`` with the actual UUID of your mediated device.\n+\n+       The ``guest_matrix`` lists the APQNs of the queue devices assigned\n+       to the mediated device; for example:\n+\n+       .. code-block:: bash\n+\n+          00.0033\n+          00.003a\n+\n+       The ``control_domains`` lists the domain numbers of the control\n+       domains; for example:\n+\n+       .. code-block:: bash\n+\n+          0033\n+          003a\n+\n+  * Display the AP configuration of the destination host with the following\n+    two commands:\n+\n+    .. code-block:: bash\n+\n+       lszcrypt -V\n+       cat /sys/bus/ap/ap_control_domain_mask\n+\n+    .. note::\n+       The ``lszcrypt -V`` command lists the AP cards (adapters) and queue\n+       devices on the host system; for example:\n+\n+       .. code-block:: bash\n+\n+          =========== ===== ============ ==========\n+          CARD.DOMAIN TYPE  MODE         DRIVER\n+          =========== ===== ============ ==========\n+          00          CEX5C CCA-Coproc   cex4card\n+          00.0033     CEX5C CCA-Coproc   vfio_ap\n+          00.003a     CEX5C CCA-Coproc   vfio_ap\n+          =========== ===== ============ ==========\n+\n+       Each bit in the ap_control_domain_mask corresponds to\n+       domain numbers 0-255. If a bit is set to one, then\n+       the control domain is available on the source host. For\n+       example:\n+\n+       .. code-block:: bash\n+\n+          0x0000000000001020000000000000000000000000000000000000000000000000\n+\n+       This mask indicates that AP control domains 51 (0x33) and 58 (0x3a) are\n+       in the AP configuration of the host system.\n+\n+  * Verify the configurations:\n+\n+    * Each APQN in the guest's sysfs ``guest_matrix`` file must match an\n+      APQN returned from the ``lszcrypt -V`` command on the destination host. It\n+      is important to note the driver to which the queue is bound which\n+      is displayed in the ``driver`` column. Queues not bound to the vfio_ap\n+      driver are not available to the destination guest. Even if the APQNs are\n+      available to the driver, that does not guarantee they can be used by the\n+      guest being migrated; for example, migration will fail if any of these APQNs\n+      are assigned to a mediated device other than the one being migrated.\n+\n+    * Each domain number from the source guest's sysfs\n+      ``control_domains`` attribute must correspond to a bit set to one in\n+      the destination host's ``ap_control_domain_mask``.\n+\n+\n+* Each APQN assigned to the source guest and destination guest must\n+  reference a queue device with compatible hardware capabilities:\n+\n+  +--------------+---------------------------------------------------------------+\n+  | Hardware     | Description                                                   |\n+  | Capabilities |                                                               |\n+  +==============+===============================================================+\n+  | [1]          | * AP special command facility (APSC)                          |\n+  | Facilities   | * AP 4096-bit ME PKU commands facility (AP4KM)                |\n+  |              | * AP 4096-bit CRT PKU commands (AP4KC)                        |\n+  +--------------+---------------------------------------------------------------+\n+  | [1] Mode     | * CCA-mode                                                    |\n+  |              | * Accelerator-mode                                            |\n+  |              | * XCP-mode (EP11)                                             |\n+  +--------------+---------------------------------------------------------------+\n+  | [1] AP       |   APXA installed                                              |\n+  | extended     |                                                               |\n+  | addressing   |                                                               |\n+  +--------------+---------------------------------------------------------------+\n+  | [1] Command  |   Command filtering available                                 |\n+  | filtering    |                                                               |\n+  +--------------+---------------------------------------------------------------+\n+  | [2]          | * Full native card function                                   |\n+  | Functional   | * Only stateless functions                                    |\n+  | capabilities |                                                               |\n+  +--------------+---------------------------------------------------------------+\n+  | [3] AP type  | * 10 (0x0a): CEX4                                             |\n+  |              | * 11 (0x0b): CEX5                                             |\n+  |              | * 12 (0x0c)  CEX6                                             |\n+  |              | * 13 (0x0d)  CEX7                                             |\n+  |              | * 14 (0x0e)  CEX8                                             |\n+  +--------------+---------------------------------------------------------------+\n+\n+  +-----------------------------------------------------------------------------+\n+  | Table Keys                                                                  |\n+  +=============================================================================+\n+  |                                                                             |\n+  | [1]        The hardware capability must be the same for both the source     |\n+  |            and destination queue device.                                    |\n+  |                                                                             |\n+  | [2]        The source and destination queues must either both have          |\n+  |            full native card function or both have stateless functions.      |\n+  |            If the functional capabilities don't match, then the source      |\n+  |            queue can have stateless capabilities since full native card     |\n+  |            function can handle stateless functions; otherwise, migration    |\n+  |            will fail.                                                       |\n+  |                                                                             |\n+  | [3]        The AP type on the source and destination guests can             |\n+  |            differ if the queue passed through to the target guest is a      |\n+  |            newer model (backwards compatible)                               |\n+  +-----------------------------------------------------------------------------+\n+\n+  * To verify the hardware capabilities are compatible:\n+\n+    * On both the source and destination hosts, display the hardware capabilities\n+      for each AP adapter in the AP configuration for that host:\n+\n+      .. code-block:: bash\n+\n+         cat /sys/bus/ap/devices/card$APID/ap_functions\n+\n+      .. note::\n+         The ``$APID`` is the two-character adapter number in hexadecimal format;\n+         for example, ``card02`` or ``card1f``. The ``/sys/bus/ap/devices`` directory\n+         also lists the APQNs of the queue devices installed in the respective\n+         host system with the first two characters being the APID; for example:\n+         ``02.0004`` or ``00.0033`` .\n+\n+    * Verify the hardware capabilities for each AP adapter device on the source\n+      and destination host are compatible. The ``ap_functions`` attribute is a\n+      bitmask. The bits in the mask read from left to right starting with bit 0.\n+      Each bit that is set to one indicates the corresponding hardware capability\n+      is installed:\n+\n+      * Bits 0-2 are the facilities bits. Each bit value must match for the AP\n+        devices on the source and destination systems. The values indicate the\n+        following:\n+\n+        * bit-0: APSC is installed\n+        * bit-1: AP4KM is installed\n+        * bit-2: AP4KC is installed\n+\n+      * Bits 3-5 specify the adapter Modes. Only one of these bits will be set to\n+        one and must be the same for both the source and destination adapter\n+        devices:\n+\n+        * bit-3: CCA-mode\n+        * bit-4: Accelerator-mode\n+        * bit-5: XCP-mode (EP11)\n+\n+      * Bit 6 specifies whether APXA is installed and must be the same for both\n+        the source and destination adapter devices.\n+\n+      * Bit 7 specifies whether command filtering is installed\n+        and must be the same for both the source and destination adapter devices.\n+\n+      * Bits 8-15 are the classification bits. There are only two relevant\n+        bits and only one of them will be set to one. For the source and destination\n+        adapter devices to be considered compatible:\n+\n+        * Bit 8 may be set to 1 on both hosts (full native card function)\n+        * Bit 9 may be set to 1 on both hosts (only stateless functions available)\n+        * Bit 9 may be set to 1 on the source host and bit 8 may be set to 1 on\n+          the destination host\n+\n+      * Bits 16-17 are the binding state bits which must be 00\n+\n+  * To verify the AP types are compatible:\n+\n+    * On both the source and destination hosts, display the hardware type\n+      for each AP adapter in the AP configuration for that host to ensure the\n+      source and destination adapter types are the same, or the source type is\n+      less than the destination type::\n+\n+       cat /sys/bus/ap/devices/card$APID/hwtype\n+\n+      .. note::\n+         The ``$APID`` is the two-character adapter number in hexadecimal format;\n+         for example, ``card02`` or ``card1f``.\n+\n+Setting up for live guest migration on the destination host\n+-----------------------------------------------------------\n+To set up a host as the destination for live guest migration, do the\n+following:\n+\n+1. Create a mediated device\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+Create a mediated device with the same name (UUID) as the mediated device\n+used to supply the AP configuration to the source guest. For example, if\n+the mediated device on the source guest is named\n+62177883-f1bb-47f0-914d-32a22e3a8804:\n+\n+.. code-block:: bash\n+\n+   echo 62177883-f1bb-47f0-914d-32a22e3a8804 \u003e \\\n+     /sys/devices/vfio_ap/matrix/mdev_supported_types/vfio_ap-passthrough/create\n+\n+2. Reserve adapters and domains for the vfio_ap device driver's use\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+Reserve the same adapters, and domains passed through to the source guest\n+for the vfio_ap device driver on the destination host by clearing the\n+adapter numbers from the ``/sys/bus/ap/apmask`` and/or the domain numbers\n+from the ``/sys/bus/ap/aqmask`` files.\n+\n+For example, suppose adapters 0, 20 (0x14) and 22 (0x16) as well as\n+domains 51 (0x33) and 58 (0x3a) are passed through to the source guest. To\n+ensure they can be passed through to the destination guest, they must be\n+made available to the vfio_ap device driver on the destination host. To\n+make them available, do one or both of the following on the destination host:\n+\n+.. code-block:: bash\n+\n+   echo -0,-0x14,-22 \u003e /sys/bus/ap/apmask\n+   echo -0,-0x33,-0x3a \u003e /sys/bus/ap/aqmask\n+\n+.. note::\n+\n+    * It is not necessary to reserve both the adapters and domains.\n+      Reserving an adapter implicitly allows the vfio_ap driver to assign\n+      each of the domains available on the system along with the reserved\n+      adapters to a guest's AP configuration and vice versa.\n+\n+    * The Cartesian product of the adapters and domains reserved for the\n+      vfio_ap device driver identifies the APQNs of the AP queue devices to be\n+      bound to the vfio_ap device driver. If an APQN does not reference a\n+      queue device installed in the system at the time of live guest migration,\n+      the migration will fail.\n+\n+    * It is not necessary to configure the destination mediated device with\n+      adapters, domains and control domains because the source guest's AP\n+      configuration will overlay the destination guest's during migration.\n+\n+    * To verify that the queue devices are reserved for the vfio_ap\n+      device driver, issue the ``lszcrypt -V`` command and you should\n+      see ``vfio_ap`` in the ``DRIVER`` column of the output.\n+\n+Live guest migration failures due to AP configuration errors\n+------------------------------------------------------------\n+This section describes the errors that may occur during live guest migration\n+when the AP configuration of the source guest and destination host are not\n+compatible and where to look for problem determination.\n+\n+The destination host is missing the mediated device\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+This error occurs when a mediated device with the same name (UUID) as the\n+mediated device being migrated has not been created on the destination host.\n+\n+**Source host**\n+\n++--------------+----------------------------------------------------------------+\n+| Log          | Message                                                        |\n++==============+================================================================+\n+| Console log: | error: device not found: mediated device '$UUID' not           |\n+|              | found                                                          |\n++--------------+----------------------------------------------------------------+\n+| QEMU log:    | initiating migration                                           |\n+|              | qemu-system-s390x: Sibling indicated error 1                   |\n++--------------+----------------------------------------------------------------+\n+\n+.. note::\n+   $UUID is the UUID of the mediated device being migrated from the source host.\n+\n+\n+One or more queues are not bound to the vfio_ap driver on the destination host\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+The queue devices passed through to the source guest are not installed in the\n+destination host or are not bound to its vfio_ap device driver.\n+\n+**Source host**\n+\n++--------------+----------------------------------------------------------------+\n+| Log          | Message                                                        |\n++==============+================================================================+\n+| Console log: | error: operation failed: migration failed. Message from the    |\n+|              | source host: operation failed: job 'migration out' failed:     |\n+|              | Sibling indicated error 1. Message from the destination host:  |\n+|              | operation failed: job 'migration in' failed: load of migration |\n+|              | failed: No such device: Failed to load vmstate version_id: 1,  |\n+|              | ret: -19                                                       |\n++--------------+----------------------------------------------------------------+\n+\n+**Destination host**\n+\n++--------------+----------------------------------------------------------------+\n+| Kernel log:  | vfio_ap_mdev $UUID: Queue $APID.$APQI not available to         |\n+|              | vfio_ap driver on target host                                  |\n++--------------+----------------------------------------------------------------+\n+| QEMU log:    | shutting down, reason=failed                                   |\n+|              | qemu-system-s390x: terminating on signal $SIGNAL_NUM from      |\n+|              | pid $PID $DAEMON                                               |\n++--------------+----------------------------------------------------------------+\n+\n+\n+One or more control domains are not available on the destination host\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+The control domains passed through to the source guest are not installed on the\n+destination host.\n+\n+**Source host**\n+\n++--------------+----------------------------------------------------------------+\n+| Log          | Message                                                        |\n++==============+================================================================+\n+| Console log: | error: operation failed: migration failed. Message from the    |\n+|              | source host: operation failed: job 'migration out' failed:     |\n+|              | Sibling indicated error 1. Message from the destination host:  |\n+|              | operation failed: job 'migration in' failed: load of migration |\n+|              | failed: No such device: Failed to load vmstate version_id: 1,  |\n+|              | ret: -19                                                       |\n++--------------+----------------------------------------------------------------+\n+\n+**Destination host**\n+\n++--------------+----------------------------------------------------------------+\n+| Kernel log:  | vfio_ap_mdev $UUID: Control domain $DOMAIN_NUM not available   |\n+|              | on the destination host                                        |\n++--------------+----------------------------------------------------------------+\n+| QEMU log:    | shutting down, reason=failed                                   |\n+|              | qemu-system-s390x: terminating on signal $SIGNAL_NUM from      |\n+|              | pid $PID $DAEMON                                               |\n++--------------+----------------------------------------------------------------+\n+\n+\n+.. note::\n+   * $UUID is the UUID of the mediated device being migrated from the source host.\n+   * $APID.$APQI is adapter number and queue index (domain number) comprising the\n+     $APQN (for example, 00.0033) of the queue device that is not available.\n+   * $SIGNAL_NUM is the signal number that caused the QEMU process to terminate.\n+   * $PID is the process ID of the QEMU process on the destination host.\n+   * $DAEMON is the name of the QEMU daemon process.\n+   * This message will be logged for each queue for which this error is detected.\n+\n+Failure to get hardware information for a queue device on destination host\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+The vfio_ap device driver on the destination host will execute an AP instruction\n+to get the hardware information for a queue device to perform queue compatibility\n+checks. The instruction can fail for a number of reasons in which case the\n+migration will be terminated.\n+\n+**Source host**\n+\n++--------------+----------------------------------------------------------------+\n+| Log          | Message                                                        |\n++==============+================================================================+\n+| Console log: | error: operation failed: migration failed. Message from the    |\n+|              | source host: operation failed: job 'migration out' failed:     |\n+|              | Sibling indicated error 1. Message from the destination host:  |\n+|              | operation failed: job 'migration in' failed: load of migration |\n+|              | failed: failed to get hardware information for queue device    |\n+|              | $APQN                                                          |\n++--------------+----------------------------------------------------------------+\n+\n+**Destination host**\n+\n++--------------+----------------------------------------------------------------+\n+| Log          | Message                                                        |\n++==============+================================================================+\n+| Console log: | vfio_ap_mdev $UUID: migration failed: Failed to get hwinfo for |\n+|              | queue $APQN on target host: rc=$RESPONSE-CODE                  |\n++--------------+----------------------------------------------------------------+\n+| QEMU log:    | shutting down, reason=failed                                   |\n+|              | qemu-system-s390x: terminating on signal $SIGNAL-ID from pid   |\n+|              | $PID $DAEMON                                                   |\n++--------------+----------------------------------------------------------------+\n+\n+.. note::\n+   * $UUID is the UUID of the mediated device being migrated from the source host.\n+   * $APQN (for example, 00.0033) of the queue device that is not compatible.\n+   * $RESPONSE_CODE is the response code from the AP instruction.\n+   * $SIGNAL_NUM is the signal number of the signal that caused the QEMU process\n+     to terminate.\n+   * $PID is the process ID of the QEMU process on the destination host.\n+   * $DAEMON is the name of the QEMU daemon process.\n+   * This message will be logged for each queue for which this error is detected.\n+\n+The AP configurations of the source guest and destination host not compatible\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+The functional capabilities or facilities available on one or more of the queues\n+passed through to the source guest are not compatible with the queue device with\n+the same APQN on the destination system (see the Hardware Capabilities table above)\n+\n+**Source host**\n+\n++--------------+----------------------------------------------------------------+\n+| Log          | Message                                                        |\n++==============+================================================================+\n+| Console log: | error: operation failed: migration failed. Message from the    |\n+|              | source host: operation failed: job 'migration out' failed:     |\n+|              | Sibling indicated error 1. Message from the destination host:  |\n+|              | operation failed: job 'migration in' failed: load of migration |\n+|              | failed: No such device: Failed to load vmstate version_id: 1,  |\n+|              | ret: -19                                                       |\n++--------------+----------------------------------------------------------------+\n+| Kernel log:  | N/A                                                            |\n++--------------+----------------------------------------------------------------+\n+| QEMU log:    | *initiating migration*                                         |\n+|              |                                                                |\n+|              | *qemu-system-s390x: Sibling indicated error 1*                 |\n++--------------+----------------------------------------------------------------+\n+\n+**Destination host**\n+\n++--------------+----------------------------------------------------------------+\n+| Log          | Message                                                        |\n++==============+================================================================+\n+| Console log: | N/A                                                            |\n++--------------+----------------------------------------------------------------+\n+| Kernel log:  | *vfio_ap_mdev $UUID: Migration failed: Source and target       |\n+|              | queue ($APQN) not compatible*                                  |\n+|              |                                                                |\n+|              | The message above will be followed by one or more messages     |\n+|              | enumerating the incompatible features; for example:            |\n+|              |                                                                |\n+|              | ``vfio_ap_mdev $UUID: APSC facility installed in source queue  |\n+|              | $APQN``                                                        |\n+|              | ``vfio_ap_mdev $UUID: APSC facility not installed in target    |\n+|              | queue $APQN``                                                  |\n+|              |                                                                |\n+|              | ``AP type of source ($APTYPE1) not compatible with target      |\n+|              | ($APTYPE2)`` ...                                               |\n++--------------+----------------------------------------------------------------+\n+| QEMU log:    | *initiating migration*                                         |\n+|              |                                                                |\n+|              | *qemu-system-s390x: error while loading state section id ...*  |\n+|              |                                                                |\n+|              | *shutting down, reason=failed*                                 |\n+|              |                                                                |\n+|              | *terminating on signal $SIGNAL-ID from pid $PID $DAEMON*       |\n++--------------+----------------------------------------------------------------+\n+\n+.. note::\n+   * $UUID is the UUID of the mediated device being migrated from the source host.\n+   * $APQN (for example, 00.0033) of the queue device that is incompatible.\n+   * $APTYPE1 is the type of the source queue device.\n+   * $APTYPE2 is the type of the target queue device.\n+   * $SIGNAL-ID is the signal number of the signal that caused the QEMU process\n+     to terminate.\n+   * $PROCESS-ID is the process ID of the QEMU process on the source host.\n+   * $PID is the process ID of the QEMU process on the destination host.\n+   * $DAEMON is the name of the QEMU daemon process.\n+   * Each follow-on message logging the incompatibility will be logged for each\n+     error detected for the specified queue device.\n+\n+AP Configuration Management\n+---------------------------\n+The AP configurations of the source guest and destination host must be kept\n+in synchronization or live guest migration will likely fail due to potential\n+incompatibilities introduced by such changes. In particular, changing adapter\n+or domain reservations via the sysfs ``apmask`` or ``aqmask`` attributes on\n+either the source or destination host without coordinating such changes between\n+the two hosts -especially while a migration is taking place - can result in\n+migration failures.\n+\n+Configuration stability is an orchestration-layer or system administrator\n+responsibility, which is consistent with other VFIO device types. The vfio_ap\n+device driver will validate source and destination configurations and provide\n+clear diagnostics when incompatibilities are detected, enabling orchestration\n+tools to implement appropriate policies; for example, blocking migration when\n+such changes are to be made.\n+\n+Master Key administration\n+--------------------------\n+It is imperative that s390 Common Cryptographic Architecture (CCA) master key\n+administration be performed on both the source and destination AP\n+devices to synchronize the key values prior to allowing live guest\n+migration. If the master keys do not match, then crypto applications that\n+rely on secure keys wrapped by a CCA master key will fail when the guest on\n+which they are running is migrated to the destination host. Again, this is\n+an orchestration-layer or system administrator responsibility and migration must\n+be blocked while master key administration is being performed.\ndiff --git a/drivers/s390/crypto/Makefile b/drivers/s390/crypto/Makefile\nindex e83c6603c8587..20f29184825a7 100644\n--- a/drivers/s390/crypto/Makefile\n+++ b/drivers/s390/crypto/Makefile\n@@ -34,5 +34,5 @@ pkey-uv-objs := pkey_uv.o\n obj-$(CONFIG_PKEY_UV) += pkey-uv.o\n \n # adjunct processor matrix\n-vfio_ap-objs := vfio_ap_drv.o vfio_ap_ops.o\n+vfio_ap-objs := vfio_ap_drv.o vfio_ap_ops.o vfio_ap_migration.o\n obj-$(CONFIG_VFIO_AP) += vfio_ap.o\ndiff --git a/drivers/s390/crypto/vfio_ap_drv.c b/drivers/s390/crypto/vfio_ap_drv.c\nindex 8e69ed286bb9c..c63a050a23569 100644\n--- a/drivers/s390/crypto/vfio_ap_drv.c\n+++ b/drivers/s390/crypto/vfio_ap_drv.c\n@@ -26,9 +26,21 @@ MODULE_LICENSE(\"GPL v2\");\n struct ap_matrix_dev *matrix_dev;\n debug_info_t *vfio_ap_dbf_info;\n \n+#define VFIO_AP_BASE_FEATURES\t\"guest_matrix hotplug ap_config\"\n+#define VFIO_AP_SE_EXCLUDED_FEATURES \"migration\"\n+\n static ssize_t features_show(struct device *dev, struct device_attribute *attr, char *buf)\n {\n-\treturn sysfs_emit(buf, \"guest_matrix hotplug ap_config\\n\");\n+\t/*\n+\t * SE guests do not support live guest migration; emit only the base\n+\t * feature set for them.\n+\t */\n+\tif (ap_is_se_guest())\n+\t\treturn sysfs_emit(buf, \"%s\\n\", VFIO_AP_BASE_FEATURES);\n+\n+\t/* Non-SE: base features plus those not available on SE guests */\n+\treturn sysfs_emit(buf, \"%s %s\\n\", VFIO_AP_BASE_FEATURES,\n+\t\t\t  VFIO_AP_SE_EXCLUDED_FEATURES);\n }\n static DEVICE_ATTR_RO(features);\n \ndiff --git a/drivers/s390/crypto/vfio_ap_migration.c b/drivers/s390/crypto/vfio_ap_migration.c\nnew file mode 100644\nindex 0000000000000..7fa58f0868125\n--- /dev/null\n+++ b/drivers/s390/crypto/vfio_ap_migration.c\n@@ -0,0 +1,1494 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Drives vfio_ap mdev migration.\n+ *\n+ * Copyright IBM Corp. 2025\n+ */\n+#include \u003clinux/anon_inodes.h\u003e\n+#include \u003clinux/file.h\u003e\n+#include \"vfio_ap_private.h\"\n+\n+/* Magic number and version for the vfio_ap_config migration blob */\n+#define VFIO_AP_MIG_MAGIC\t\t\t0x76666170U  /* \"vfap\" */\n+#define VFIO_AP_MIG_VERSION\t\t\t1U\n+\n+/*\n+ * Masks the fields of the queue information returned from the PQAP(TAPQ)\n+ * command. In order to migrate a guest, it's AP configuration must be\n+ * compatible with AP configuration assigned to the target guest's mdev.\n+ * This mask is used to verify that the queue information for each source and\n+ * target queue is compatible.\n+ *\n+ * The following bits must match for the source device and the corresponding\n+ * destination device:\n+ * -------------------------------------------------------------------------\n+ * S bit 0: APSC  facility installed\n+ * M bit 1: APQKM facility installed\n+ * C bit 2: AP4KC facility installed\n+ * Mode bits 3-5:\n+ *     D bit 3: CCA-mode facility\n+ *     A bit 4: accelerator-mode facility\n+ *     X bit 5: XCP-mode facility\n+ * N  bit 6: APXA facility installed\n+ * SL bit 7: SLCF facility installed\n+ *\n+ * Either bit 8 or bit 9 will be set. If bit 8 is set for the source device,\n+ * then it must also be set for the corresponding destination device:\n+ * -------------------------------------------------------------------------\n+ * Classification (functional capabilities) bits 8-16\n+ *     bit 8: Native card function\n+ *     bit 9: Only stateless functions\n+ *\n+ * The BS bits must be set to 0 for both the source and corresponding\n+ * destination device:\n+ * -------------------------------------------------------------------------\n+ * BS bits 16-17:\n+ *\n+ * The AP type of the source device must be less than or equal to that of\n+ * the corresponding destination device:\n+ * -------------------------------------------------------------------------\n+ * AP Type bits 32-40:\n+ */\n+#define QINFO_DATA_MASK\t\t0xffffc000ff000000\n+\n+/*\n+ * Masks the bit that indicates whether full native card function is available\n+ * from the 8 bits specifying the functional capabilities of a queue\n+ */\n+#define CLASSIFICATION_NATIVE_FCN_MASK\t\t0x80\n+\n+/* The maximum number of queues that can be installed in an s390 system */\n+#define MAX_AP_QUEUES\t\t\t\t(AP_DEVICES * AP_DOMAINS)\n+\n+/* The maximum size of a vfio_ap_config blob, used to pre-allocate the receive\n+ * buffer on the destination host during the RESUMING phase of migration.\n+ */\n+#define VFIO_AP_CONFIG_MAX_SIZE \\\n+\t(sizeof(struct vfio_ap_config) + \\\n+\t MAX_AP_QUEUES * sizeof(struct vfio_ap_queue_info))\n+\n+/**\n+ * struct vfio_ap_migration_file\n+ *\n+ * This object is used for chunk processing of multiple reads and writes of\n+ * AP configuration information.\n+ *\n+ * @filp:\tfile stream used to read or write AP configuration data\n+ * @ap_config:\tobject used to store AP configuration data between read or write\n+ *\t\tcalls\n+ * @config_sz:\tthe size (in bytes) of @ap_config\n+ */\n+struct vfio_ap_migration_file {\n+\tstruct file\t\t*filp;\n+\tstruct vfio_ap_config\t*ap_config;\n+\tunsigned long\t\tconfig_sz;\n+};\n+\n+/**\n+ * struct vfio_ap_migration_data:\n+ *\n+ * Manages the migration state for the VFIO device that maintains the AP\n+ * configuration of the guest being migrated.\n+ *\n+ * @mig_state:\t\tthe current migration state\n+ * @resuming_mig_file:\tthe object used to restore the state of the vfio-ap\n+ *\t\t\tdevice on the destination host.\n+ * @stop_copy_mig_file:\tthe object used to store the AP configuration of the\n+ *\t\t\tsource guest for transfer to the destination host.\n+ */\n+struct vfio_ap_migration_data {\n+\tenum vfio_device_mig_state\tmig_state;\n+\tstruct vfio_ap_migration_file\tresuming_mig_file;\n+\tstruct vfio_ap_migration_file\tstop_copy_mig_file;\n+};\n+\n+/**\n+ * struct vfio_ap_queue_info - the information for an AP queue\n+ *\n+ * @data: contains the queue information returned in GR2 from the PQAP(TAPQ)\n+ *\t  command\n+ * @apqn: the APQN of the queue\n+ * @reserved: padding to ensure consistent structure size across platforms\n+ */\n+struct vfio_ap_queue_info {\n+\tu64 data;\n+\tu16 apqn;\n+\tu8  reserved[6];\n+};\n+\n+/**\n+ * struct vfio_ap_config:\n+ *\n+ * Stores the state of a guest's AP configuration.\n+ *\n+ * VFIO device migration state transition from STOP to STOP_COPY:\n+ * -------------------------------------------------------------\n+ * When the migration state transitions from STOP to STOP_COPY, the vfio_ap device\n+ * driver will open a file stream in read-only mode and return the fd to userspace.\n+ * This fd is used during the STOP_COPY phase to read the current state of the\n+ * vfio-ap device on the source host. In response, the driver will store the\n+ * source guest's AP configuration data in a vfio_ap_config object and copy it to\n+ * userspace.\n+ *\n+ * VFIO device migration state transition from STOP to RESUMING:\n+ * ------------------------------------------------------------\n+ * When the VFIO migration state transitions from STOP to RESUMING,\n+ * the vfio_ap device driver will open a file stream in write-only mode and\n+ * return the fd to userspace. This fd is used during the RESUMING phase to\n+ * write the source guest's vfio_ap_config data that was read in during the\n+ * STOP_COPY phase to the vfio_ap device driver on the destination host. In\n+ * response, the device driver will copy the data sent from userspace to a\n+ * vfio_ap_config instance which is then used to update the destination guest's\n+ * AP configuration.\n+ *\n+ * Since the source and destination hosts may be running different versions of\n+ * the linux kernel, the vfio_ap_config object provides two fields (@magic and\n+ * @version) which must be set by the source device driver and verified by the\n+ * destination device driver to ensure the migration ABI of the source and\n+ * destination hosts are compatible.\n+ *\n+ * Note: Since a guest's AP configuration could be comprised of a large number of\n+ *\t AP queue devices, a vfio_ap_config object should be allocated using\n+ *\t kvzalloc.\n+ *\n+ * @magic:\tidentifies this as a valid vfio_ap_config migration blob;\n+ *\t\tmust equal VFIO_AP_MIG_MAGIC\n+ * @version:\tlayout version; must equal VFIO_AP_MIG_VERSION\n+ * @num_queues:\tthe number of queues passed through to the guest\n+ * @reserved:\tpadding to ensure proper alignment of @adm\n+ * @adm:\tbitmap specifying the control domains in the AP configuration\n+ * @qinfo:\tan array of vfio_ap_queue_info objects, each specifying the\n+ *\t\tqueue information for a queue passed through to the guest\n+ */\n+struct vfio_ap_config {\n+\tu32\t\t\t\tmagic;\n+\tu32\t\t\t\tversion;\n+\tu32\t\t\t\tnum_queues;\n+\tu8\t\t\t\treserved[4];\n+\tu64\t\t\t\tadm[DIV_ROUND_UP(AP_DOMAINS, 64)];\n+\tstruct vfio_ap_queue_info\tqinfo[] __counted_by(num_queues);\n+};\n+\n+static void\n+vfio_ap_release_stop_copy_file(struct vfio_ap_migration_data *mig_data)\n+{\n+\tkvfree(mig_data-\u003estop_copy_mig_file.ap_config);\n+\tmig_data-\u003estop_copy_mig_file.ap_config = NULL;\n+\tmig_data-\u003estop_copy_mig_file.config_sz = 0;\n+\tmig_data-\u003estop_copy_mig_file.filp = NULL;\n+}\n+\n+static void vfio_ap_release_resuming_file(struct vfio_ap_migration_data *mig_data)\n+{\n+\tkvfree(mig_data-\u003eresuming_mig_file.ap_config);\n+\tmig_data-\u003eresuming_mig_file.ap_config = NULL;\n+\tmig_data-\u003eresuming_mig_file.config_sz = 0;\n+\tmig_data-\u003eresuming_mig_file.filp = NULL;\n+}\n+\n+static void vfio_ap_release_mig_files(struct ap_matrix_mdev *matrix_mdev);\n+\n+static int vfio_ap_release_mig_file(struct inode *file_inode, struct file *filp)\n+{\n+\tstruct ap_matrix_mdev *matrix_mdev = filp-\u003eprivate_data;\n+\n+\t/*\n+\t * The VFIO device lifetime is tied to migration FD lifetime (see\n+\t * vfio_ap_open_file_stream() function) to guarantee that the\n+\t * matrix_mdev remains valid for every read/write operation. Let's drop\n+\t * it here since the migration FD is being released.\n+\t */\n+\tvfio_device_put_registration(\u0026matrix_mdev-\u003evdev);\n+\treturn 0;\n+}\n+\n+/**\n+ * validate_stop_copy_read_parms: Validate the input parameters to the\n+ *                                vfio_ap_stop_copy_read function\n+ *\n+ * @filp: Pointer to the file stream used to read the vfio-ap device state\n+ * @len:  The length of the data to be read\n+ *\n+ * Verify the following:\n+ * - @filp private data is an ap_matrix_mdev instance\n+ * - @filp is the instance opened when state transitioned from STOP to STOP_COPY\n+ * - @filp-\u003ef_pos + @len does not cause integer overflow\n+ *\n+ * Returns: 0 if the parameters pass validation; otherwise returns an error\n+ */\n+static int validate_stop_copy_read_parms(struct file *filp, size_t len)\n+{\n+\tstruct vfio_ap_migration_data *mig_data;\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\tloff_t total_len;\n+\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tif (check_add_overflow((loff_t)len, filp-\u003ef_pos, \u0026total_len))\n+\t\treturn -EIO;\n+\n+\t/*\n+\t * matrix_mdev is guaranteed live here: vfio_ap_open_file_stream() took\n+\t * a vfio_device registration reference that is held until\n+\t * vfio_ap_release_mig_file() runs, so the embedding matrix_mdev cannot\n+\t * be freed while this file descriptor is open.\n+\t */\n+\tmatrix_mdev = filp-\u003eprivate_data;\n+\n+\tif (!matrix_mdev-\u003emig_data)\n+\t\treturn -ENODEV;\n+\n+\tmig_data = matrix_mdev-\u003emig_data;\n+\n+\tif (mig_data-\u003estop_copy_mig_file.filp != filp)\n+\t\treturn -EINVAL;\n+\n+\treturn 0;\n+}\n+\n+static size_t vfio_ap_config_size(struct ap_matrix_mdev *matrix_mdev,\n+\t\t\t\t  int *num_queues)\n+{\n+\tsize_t qinfo_size;\n+\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\t*num_queues = vfio_ap_mdev_get_num_queues(\u0026matrix_mdev-\u003eshadow_apcb);\n+\tqinfo_size = *num_queues * sizeof(struct vfio_ap_queue_info);\n+\n+\treturn qinfo_size + sizeof(struct vfio_ap_config);\n+}\n+\n+static int get_hardware_info_for_queue(const char *mdev_name,\n+\t\t\t\t       struct ap_tapq_hwinfo *hwinfo,\n+\t\t\t\t       unsigned long apqn)\n+{\n+\tstruct ap_queue_status status;\n+\n+\tstatus = ap_tapq(apqn, hwinfo);\n+\n+\tswitch (status.response_code) {\n+\tcase AP_RESPONSE_NORMAL:\n+\tcase AP_RESPONSE_RESET_IN_PROGRESS:\n+\tcase AP_RESPONSE_DECONFIGURED:\n+\tcase AP_RESPONSE_CHECKSTOPPED:\n+\tcase AP_RESPONSE_BUSY:\n+\t\t/* For all these RCs the tapq info should be available */\n+\t\treturn 0;\n+\tcase AP_RESPONSE_Q_NOT_AVAIL:\n+\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Failed to get hwinfo for queue %02lx.%04lx: TAPQ rc=%d\\n\",\n+\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn),\n+\t\t\t\t   status.response_code);\n+\t\treturn -ENODEV;\n+\tdefault:\n+\t\t/*\n+\t\t * Without a pending async error, the tapq info should be\n+\t\t * available\n+\t\t */\n+\t\tif (status.async)\n+\t\t\treturn 0;\n+\n+\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Failed to get hwinfo for queue %02lx.%04lx: TAPQ rc=%d\\n\",\n+\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn),\n+\t\t\t\t   status.response_code);\n+\t\treturn -EIO;\n+\t}\n+}\n+\n+/**\n+ * vfio_ap_store_queue_info:\n+ *\n+ * Stores the hardware information returned from the PQAP(TAPQ) command for each\n+ * queue device identified in the 'qinfo' field of the a vfio_ap_config\n+ * object. The APQNs in the 'qinfo' field must already have been snapshotted\n+ * prior to calling this function.\n+ *\n+ * @mdev_name:\tThe name (UUID) of the mediated device to use in log messages\n+ * @ap_config:\tA reference to the vfio_ap_config instance in which to store\n+ *\t\tthe queue information. It is expected that each APQN identifying\n+ *\t\ta queue device for which hardware information is to be retrieved\n+ *\t\tshall be snapshotted prior to calling this function.\n+ *\n+ * Returns:\tZero (0) if the hardware information is retrieved for each queue\n+ *\t\tdevice in the AP configuration; otherwise, returns an error.\n+ */\n+static int vfio_ap_store_queue_info(const char *mdev_name,\n+\t\t\t\t    struct vfio_ap_config *ap_config)\n+{\n+\tstruct ap_tapq_hwinfo source_hwinfo;\n+\tunsigned long num_queues;\n+\tint ret;\n+\n+\tfor (num_queues = 0; num_queues \u003c ap_config-\u003enum_queues; num_queues++) {\n+\t\tret = get_hardware_info_for_queue(mdev_name, \u0026source_hwinfo,\n+\t\t\t\t\t\t  ap_config-\u003eqinfo[num_queues].apqn);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\n+\t\tap_config-\u003eqinfo[num_queues].data = source_hwinfo.value;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+static int vfio_ap_get_config(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tstruct vfio_ap_config *ap_configuration;\n+\tunsigned long *apm, *aqm, apid, apqi;\n+\tunsigned int num_queues;\n+\tconst char *mdev_name;\n+\tsize_t ap_config_size;\n+\tint ret, qindex;\n+\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tap_config_size = vfio_ap_config_size(matrix_mdev, \u0026num_queues);\n+\n+\tap_configuration = kvzalloc(ap_config_size, GFP_KERNEL_ACCOUNT);\n+\tif (!ap_configuration)\n+\t\treturn -ENOMEM;\n+\n+\tap_configuration-\u003emagic   = VFIO_AP_MIG_MAGIC;\n+\tap_configuration-\u003eversion = VFIO_AP_MIG_VERSION;\n+\n+\t/*\n+\t * num_queues must be set before writing qinfo[] elements; the\n+\t * __counted_by(num_queues) annotation on qinfo[] causes the compiler to\n+\t * insert bounds checks that evaluate against ap_configuration-\u003enum_queues.\n+\t * Writing through qinfo[i] with num_queues still 0 would trap.\n+\t */\n+\tap_configuration-\u003enum_queues = num_queues;\n+\n+\tapm = matrix_mdev-\u003eshadow_apcb.apm;\n+\taqm = matrix_mdev-\u003eshadow_apcb.aqm;\n+\tqindex = 0;\n+\tfor_each_set_bit_inv(apid, apm, AP_DEVICES) {\n+\t\tfor_each_set_bit_inv(apqi, aqm, AP_DOMAINS) {\n+\t\t\tap_configuration-\u003eqinfo[qindex].apqn =\n+\t\t\t\tAP_MKQID(apid, apqi);\n+\t\t\tqindex += 1;\n+\t\t}\n+\t}\n+\tmemcpy(ap_configuration-\u003eadm, matrix_mdev-\u003eshadow_apcb.adm,\n+\t       sizeof(ap_configuration-\u003eadm));\n+\tmdev_name = dev_name(matrix_mdev-\u003evdev.dev);\n+\n+\tret = vfio_ap_store_queue_info(mdev_name, ap_configuration);\n+\tif (ret) {\n+\t\tkvfree(ap_configuration);\n+\t\treturn ret;\n+\t}\n+\n+\tmatrix_mdev-\u003emig_data-\u003estop_copy_mig_file.ap_config = ap_configuration;\n+\tmatrix_mdev-\u003emig_data-\u003estop_copy_mig_file.config_sz = ap_config_size;\n+\n+\treturn 0;\n+}\n+\n+static ssize_t vfio_ap_stop_copy_read(struct file *filp, char __user *buf,\n+\t\t\t\t      size_t len, loff_t *pos)\n+{\n+\tstruct vfio_ap_migration_file *mig_file;\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\tloff_t read_pos;\n+\tssize_t ret;\n+\n+\t/*\n+\t * This file was opened with stream_open(), so pos should be NULL for\n+\t * sequential read() calls; a non-NULL pointer will be passed only\n+\t * for positional pread() calls in which case we return an error\n+\t * indicating broken pipe/illegal seek on a non-seekable file\n+\t */\n+\tif (pos)\n+\t\treturn -ESPIPE;\n+\n+\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tpos = \u0026filp-\u003ef_pos;\n+\n+\tret = validate_stop_copy_read_parms(filp, len);\n+\tif (ret) {\n+\t\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\t\treturn ret;\n+\t}\n+\n+\tmatrix_mdev = filp-\u003eprivate_data;\n+\tmig_file = \u0026matrix_mdev-\u003emig_data-\u003estop_copy_mig_file;\n+\n+\t/*\n+\t * Lazy initialization: the migration config is generated on the first\n+\t * read() call. vfio_ap_open_file_stream() initializes ap_config to NULL\n+\t * and config_sz to 0. On first read, we generate the config by\n+\t * snapshotting the guest's APQNs from shadow_apcb and retrieving hardware\n+\t * info via TAPQ for each queue. The result is cached in mig_file-\u003eap_config\n+\t * for subsequent read() calls. The config is freed when the migration FD\n+\t * is released (vfio_ap_release_mig_file -\u003e vfio_ap_release_stop_copy_file).\n+\t */\n+\tif (!mig_file-\u003eap_config) {\n+\t\tret = vfio_ap_get_config(matrix_mdev);\n+\t\tif (ret) {\n+\t\t\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\t\t\treturn ret;\n+\t\t}\n+\t}\n+\n+\t/*\n+\t * Compute the offset and clamped length fully under the lock so that\n+\t * concurrent read()s on this stream file each see a consistent view of\n+\t * the current position.  *pos is advanced here while we still hold the\n+\t * lock; copy_to_user() then uses the snapshot read_pos.  This prevents\n+\t * two threads from calculating the same offset and both copying the\n+\t * same region (or one reading past the end of the buffer).\n+\t */\n+\tif (*pos \u003e= mig_file-\u003econfig_sz) {\n+\t\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\t\treturn 0;\n+\t}\n+\n+\tlen = min_t(size_t, mig_file-\u003econfig_sz - *pos, len);\n+\tif (len == 0) {\n+\t\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\t\treturn 0;\n+\t}\n+\n+\tread_pos = *pos;\n+\t*pos += len;\n+\n+\t/*\n+\t * Keep mdevs_lock held across copy_to_user() to prevent a concurrent\n+\t * vfio_ap_reset_migration_state() from freeing ap_config while we are\n+\t * reading it.  copy_to_user() may fault on a non-resident user page,\n+\t * but that is legal for a sleeping mutex.  The data transferred is at\n+\t * most a few KB for any realistic AP configuration, so holding the lock\n+\t * here is acceptable.\n+\t */\n+\tif (copy_to_user(buf, (char *)mig_file-\u003eap_config + read_pos, len)) {\n+\t\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\t\treturn -EFAULT;\n+\t}\n+\n+\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\treturn len;\n+}\n+\n+static const struct file_operations vfio_ap_stop_copy_fops = {\n+\t.owner = THIS_MODULE,\n+\t.read = vfio_ap_stop_copy_read,\n+\t.compat_ioctl = compat_ptr_ioctl,\n+\t.release = vfio_ap_release_mig_file,\n+};\n+\n+static struct file *vfio_ap_open_file_stream(struct ap_matrix_mdev *matrix_mdev,\n+\t\t\t\t\t     const struct file_operations *fops,\n+\t\t\t\t\t     int flags)\n+{\n+\tstruct file *filp;\n+\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\t/*\n+\t * Pin the vfio_device registration so that matrix_mdev cannot be freed\n+\t * while the migration FD is still open. The matching put is in\n+\t * vfio_ap_release_mig_file().\n+\t */\n+\tif (!vfio_device_try_get_registration(\u0026matrix_mdev-\u003evdev))\n+\t\treturn ERR_PTR(-ENODEV);\n+\n+\tfilp = anon_inode_getfile(\"vfio_ap_mig_file\", fops, matrix_mdev, flags);\n+\tif (IS_ERR(filp)) {\n+\t\tvfio_device_put_registration(\u0026matrix_mdev-\u003evdev);\n+\t\treturn filp;\n+\t}\n+\n+\tstream_open(filp-\u003ef_inode, filp);\n+\n+\treturn filp;\n+}\n+\n+static int validate_resuming_write_parms(struct file *filp, size_t len)\n+{\n+\tstruct vfio_ap_migration_data *mig_data;\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\tloff_t total_len;\n+\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tif (!len || filp-\u003ef_pos \u003c 0)\n+\t\treturn -EINVAL;\n+\n+\tif (check_add_overflow((loff_t)len, filp-\u003ef_pos, \u0026total_len))\n+\t\treturn -ERANGE;\n+\n+\tmatrix_mdev = filp-\u003eprivate_data;\n+\tif (!matrix_mdev || !matrix_mdev-\u003emig_data)\n+\t\treturn -ENODEV;\n+\n+\tmig_data = matrix_mdev-\u003emig_data;\n+\n+\tif (filp != mig_data-\u003eresuming_mig_file.filp)\n+\t\treturn -ENXIO;\n+\n+\t/* Reject writes that would overflow the pre-allocated buffer */\n+\tif (filp-\u003ef_pos + len \u003e VFIO_AP_CONFIG_MAX_SIZE)\n+\t\treturn -EIO;\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * qdev_is_bound_to_vfio_ap:\n+ *\n+ * Query to determine whether a queue with the specified APQN is available on\n+ * the host system and bound to the vfio_ap device driver.\n+ *\n+ * @apqn: The APQN of the queue device being queried\n+ *\n+ * Returns: True if there is a queue device with the specified @apqn installed\n+ *\t    in the system and is bound to the vfio_ap device driver; otherwise,\n+ *\t    returns false.\n+ */\n+static bool qdev_is_bound_to_vfio_ap(unsigned int apqn)\n+{\n+\tstruct ap_queue *queue;\n+\tbool is_bound = true;\n+\n+\tqueue = ap_get_qdev(apqn);\n+\tif (!queue)\n+\t\treturn false;\n+\n+\tif (queue-\u003eap_dev.device.driver != \u0026matrix_dev-\u003evfio_ap_drv-\u003edriver)\n+\t\tis_bound = false;\n+\n+\tput_device(\u0026queue-\u003eap_dev.device);\n+\n+\treturn is_bound;\n+}\n+\n+/**\n+ * queues_available:\n+ *\n+ * Query whether each queue from the source guest's AP configuration is\n+ * available and bound to the vfio_ap device driver; if not, log an error\n+ * message.\n+ *\n+ * @mdev_name:\t   The mdev name to use in error messages\n+ * @source_config: The object specifying the source guest's AP configuration\n+ *\n+ * Returns: true if each queue identified in @source_config is available and\n+ *\t    bound to the vfio_ap device driver; otherwise, returns false.\n+ */\n+static bool queues_available(const char *mdev_name,\n+\t\t\t     struct vfio_ap_config *source_config)\n+{\n+\tunsigned long apqn;\n+\tbool ret = true;\n+\n+\tfor (int i = 0; i \u003c source_config-\u003enum_queues; i++) {\n+\t\tapqn = source_config-\u003eqinfo[i].apqn;\n+\n+\t\t/*\n+\t\t * Find the queue device bound to the vfio_ap device driver. If it is\n+\t\t * not found, log an error and continue so users see all problems\n+\t\t * at once, not one-at-a-time through retries of the migration.\n+\t\t */\n+\t\tif (!qdev_is_bound_to_vfio_ap(apqn)) {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Queue %02lx.%04lx not available to vfio_ap driver on target host\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t\tret = false;\n+\t\t}\n+\t}\n+\n+\treturn ret;\n+}\n+\n+/**\n+ * control_domains_available\n+ *\n+ * Query whether each control domain specified in the source guest's AP\n+ * configuration is installed in the host system.\n+ *\n+ * @mdev_name:\t\tThe name of the mdev to use when logging messages\n+ * @source_config:\tThe object specifying the source guest's AP config\n+ *\n+ * Returns:\tTrue if each control domain is installed; otherwise, logs an\n+ *\t\terror message for each unavailable control domain and returns\n+ *\t\tfalse.\n+ */\n+static bool control_domains_available(const char *mdev_name,\n+\t\t\t\t      struct vfio_ap_config *source_config)\n+{\n+\tunsigned long domain_num;\n+\tbool available = true;\n+\n+\tfor_each_set_bit_inv(domain_num, (unsigned long *)source_config-\u003eadm,\n+\t\t\t     AP_DOMAINS) {\n+\t\tif (ap_test_config_ctrl_domain(domain_num))\n+\t\t\tcontinue;\n+\n+\t\tpr_err_ratelimited(\"vfio_ap_mdev: %s: Control domain %04lx not available on the destination host\\n\",\n+\t\t\t\t   mdev_name, domain_num);\n+\t\tavailable = false;\n+\t}\n+\n+\treturn available;\n+}\n+\n+static void report_facilities_compatibility(const char *mdev_name,\n+\t\t\t\t\t    unsigned long apqn,\n+\t\t\t\t\t    struct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t\t\t    struct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\tif (src_hwinfo-\u003eapsc != target_hwinfo-\u003eapsc) {\n+\t\tif (src_hwinfo-\u003eapsc) {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: APSC facility installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: APSC facility not installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t} else {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: APSC facility not installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: APSC facility installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t}\n+\t}\n+\n+\tif (src_hwinfo-\u003emex4k != target_hwinfo-\u003emex4k) {\n+\t\tif (src_hwinfo-\u003emex4k) {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: mex4k facility installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: mex4k facility not installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t} else {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: mex4k facility not installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: mex4k facility installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t}\n+\t}\n+\n+\tif (src_hwinfo-\u003ecrt4k != target_hwinfo-\u003ecrt4k) {\n+\t\tif (src_hwinfo-\u003ecrt4k) {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: crt4k facility installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: crt4k facility not installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t} else {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: crt4k facility not installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: crt4k facility installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t}\n+\t}\n+}\n+\n+static void report_mode_compatibility(const char *mdev_name,\n+\t\t\t\t      unsigned long apqn,\n+\t\t\t\t      struct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t\t      struct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\tif (src_hwinfo-\u003ecca != target_hwinfo-\u003ecca) {\n+\t\tif (src_hwinfo-\u003ecca) {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Coprocessor-mode facility installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Coprocessor-mode facility not installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t} else {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Coprocessor-mode facility not installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Coprocessor-mode facility installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t}\n+\t}\n+\n+\tif (src_hwinfo-\u003eaccel != target_hwinfo-\u003eaccel) {\n+\t\tif (src_hwinfo-\u003eaccel) {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Accelerator-mode facility installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Accelerator-mode facility not installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t} else {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Accelerator-mode facility not installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Accelerator-mode facility installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t}\n+\t}\n+\n+\tif (src_hwinfo-\u003eep11 != target_hwinfo-\u003eep11) {\n+\t\tif (src_hwinfo-\u003eep11) {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: XCP-mode facility installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: XCP-mode facility not installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t} else {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: XCP-mode facility not installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: XCP-mode facility installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t}\n+\t}\n+}\n+\n+static void report_apxa_compatibility(const char *mdev_name,\n+\t\t\t\t      unsigned long apqn,\n+\t\t\t\t      struct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t\t      struct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\tif (src_hwinfo-\u003eapxa != target_hwinfo-\u003eapxa) {\n+\t\tif (src_hwinfo-\u003eapxa) {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: AP-extended-addressing (APXA) facility installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: AP-extended-addressing (APXA) facility not installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t} else {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: AP-extended-addressing (APXA) facility not installed in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: AP-extended-addressing (APXA) facility installed in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t}\n+\t}\n+}\n+\n+static void report_slcf_compatibility(const char *mdev_name,\n+\t\t\t\t      unsigned long apqn,\n+\t\t\t\t      struct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t\t      struct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\tif (src_hwinfo-\u003eslcf != target_hwinfo-\u003eslcf) {\n+\t\tif (src_hwinfo-\u003eslcf) {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Stateless-command-filtering (SLCF) available in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Stateless-command-filtering (SLCF) not available in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t} else {\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Stateless-command-filtering (SLCF) not available in source queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Stateless-command-filtering (SLCF) available in target queue %02lx.%04lx\\n\",\n+\t\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t\t}\n+\t}\n+}\n+\n+static void report_bs_compatibility(const char *mdev_name,\n+\t\t\t\t    unsigned long apqn,\n+\t\t\t\t    struct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t\t    struct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\t/*\n+\t * The BS field on both the source and destination must be 0, so if one\n+\t * of them is not, then report an error.\n+\t */\n+\tif (src_hwinfo-\u003ebs || target_hwinfo-\u003ebs) {\n+\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Bind/associate state for source (%01x) and target (%01x) queue %02lx.%04lx must be 0\\n\",\n+\t\t\t\t   mdev_name, src_hwinfo-\u003ebs, target_hwinfo-\u003ebs,\n+\t\t\t\t   AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t}\n+}\n+\n+static void report_aptype_compatibility(const char *mdev_name,\n+\t\t\t\t\tunsigned long apqn,\n+\t\t\t\t\tstruct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t\t\tstruct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\tif (src_hwinfo-\u003eat \u003e target_hwinfo-\u003eat) {\n+\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: AP type of source (%02x) not compatible with target (%02x)\\n\",\n+\t\t\t\t   mdev_name, src_hwinfo-\u003eat, target_hwinfo-\u003eat);\n+\t}\n+}\n+\n+static bool classes_compatible(struct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t       struct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\tunsigned long src_native, target_native;\n+\n+\tsrc_native = src_hwinfo-\u003eclass \u0026 CLASSIFICATION_NATIVE_FCN_MASK;\n+\ttarget_native = target_hwinfo-\u003eclass \u0026 CLASSIFICATION_NATIVE_FCN_MASK;\n+\n+\t/*\n+\t * If the source queue has full native card function and the\n+\t * target queue has only stateless functions available, then\n+\t * there may be instructions that will not execute on the\n+\t * target queue. This shall be reported as an error.\n+\t *\n+\t * If the source queue has only stateless card functions and the\n+\t * target queue has full native card function available, then\n+\t * we are okay because the target queue can run all stateless card\n+\t * functions.\n+\t */\n+\treturn (src_native != target_native) ? !src_native : true;\n+}\n+\n+static void report_class_compatibility(const char *mdev_name,\n+\t\t\t\t       unsigned long apqn,\n+\t\t\t\t       struct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t\t       struct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\tif (!classes_compatible(src_hwinfo, target_hwinfo)) {\n+\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Full native card function available on source queue %02lx.%04lx\\n\",\n+\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\t\tpr_err_ratelimited(\"vfio_ap_mdev %s: Only stateless functions available on target queue %02lx.%04lx\\n\",\n+\t\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\t}\n+}\n+\n+/*\n+ * Log a device error reporting that migration failed due to queue\n+ * incompatibilities followed by a device error for each incompatible feature.\n+ */\n+static void report_qinfo_incompatibilities(const char *mdev_name,\n+\t\t\t\t\t   unsigned long apqn,\n+\t\t\t\t\t   struct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t\t\t   struct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\tpr_err_ratelimited(\"vfio_ap_mdev %s: Migration failed: Source and target queue (%02lx.%04lx) not compatible\\n\",\n+\t\t\t   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));\n+\n+\treport_facilities_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);\n+\treport_mode_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);\n+\treport_apxa_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);\n+\treport_slcf_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);\n+\treport_aptype_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);\n+\treport_bs_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);\n+\treport_class_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);\n+}\n+\n+/**\n+ * queue_hardware_info_is_compatible:\n+ *\n+ * Verify whether the hardware information for a source queue is compatible with\n+ * the hardware info for the corresponding queue on this system.\n+ *\n+ * In order to be compatible, the hardware information for each queue must\n+ * meet the following requirements:\n+ *\n+ * 1. The hardware facilities bits much match\n+ * 2. The AP type of the source queue must be the same as or older than that\n+ *    of the target queue (target is backwards compatible)\n+ * 3. The classification bits must indicate:\n+ *    - Both queues have full native card function or both have stateless\n+ *      functions available\n+ *    - If the classification bits don't match, then the only acceptable\n+ *      configuration is stateless functions for the source queue and\n+ *      full native function for the target queue\n+ * 4. The BS bits for both queues must be 0 (Queue usable for all messages\n+ *    supported by the adapter)\n+ *\n+ * @mdev_name:\tThe mdev name to use in error messages\n+ * @apqn:\tThe APQN for the queues\n+ * @src_hwinfo: The hardware info for the source queue\n+ * @target_hwinfo: The hardware info for the corresponding queue on this system\n+ *\n+ * Returns: true if the hardware info for the two queues is compatible;\n+ *          otherwise, returns false.\n+ */\n+static bool queue_hardware_info_is_compatible(const char *mdev_name,\n+\t\t\t\t\t      unsigned long apqn,\n+\t\t\t\t\t      struct ap_tapq_hwinfo *src_hwinfo,\n+\t\t\t\t\t      struct ap_tapq_hwinfo *target_hwinfo)\n+{\n+\tunsigned long src_bits, target_bits;\n+\n+\tsrc_bits = src_hwinfo-\u003evalue \u0026 QINFO_DATA_MASK;\n+\ttarget_bits = target_hwinfo-\u003evalue \u0026 QINFO_DATA_MASK;\n+\n+\t/* If all bits match the queues are compatible */\n+\tif (src_bits == target_bits \u0026\u0026\n+\t    (src_hwinfo-\u003ebs == 0 \u0026\u0026 target_hwinfo-\u003ebs == 0))\n+\t\treturn true;\n+\n+\tif (src_hwinfo-\u003eapsc  == target_hwinfo-\u003eapsc     \u0026\u0026\n+\t    src_hwinfo-\u003emex4k == target_hwinfo-\u003emex4k    \u0026\u0026\n+\t    src_hwinfo-\u003ecrt4k == target_hwinfo-\u003ecrt4k    \u0026\u0026\n+\t    src_hwinfo-\u003ecca   == target_hwinfo-\u003ecca      \u0026\u0026\n+\t    src_hwinfo-\u003eaccel == target_hwinfo-\u003eaccel    \u0026\u0026\n+\t    src_hwinfo-\u003eep11  == target_hwinfo-\u003eep11     \u0026\u0026\n+\t    src_hwinfo-\u003eslcf  == target_hwinfo-\u003eslcf     \u0026\u0026\n+\t    src_hwinfo-\u003eapxa  == target_hwinfo-\u003eapxa     \u0026\u0026\n+\t    src_hwinfo-\u003eat    \u003c= target_hwinfo-\u003eat       \u0026\u0026\n+\t    classes_compatible(src_hwinfo, target_hwinfo) \u0026\u0026\n+\t    (src_hwinfo-\u003ebs == 0 \u0026\u0026 target_hwinfo-\u003ebs == 0))\n+\t\treturn true;\n+\n+\treport_qinfo_incompatibilities(mdev_name, apqn, src_hwinfo, target_hwinfo);\n+\n+\treturn false;\n+}\n+\n+/**\n+ * verify_ap_configs_are_compatible:\n+ *\n+ * Verifies that the queues in the source guest's AP configuration are\n+ * compatible with the corresponding queues on this system.\n+ *\n+ * @mdev_name:\t   The mdev name to use in error messages\n+ * @source_config: The object specifying the source guest's AP configuration\n+ *\n+ * Returns: an error indicating either a failure to retrieve a queue's\n+ *\t\t\thardware information or one or more source queues are not\n+ *\t\t\tcompatible with the corresponding queue on this system; otherwise,\n+ *\t\t\treturns zero to indicate compatibility.\n+ */\n+static int verify_ap_configs_are_compatible(const char *mdev_name,\n+\t\t\t\t\t    struct vfio_ap_config *source_config)\n+{\n+\tstruct ap_tapq_hwinfo src_hwinfo, dest_hwinfo;\n+\tunsigned long apqn;\n+\tint ret = 0, rc;\n+\n+\tfor (int i = 0; i \u003c source_config-\u003enum_queues; i++) {\n+\t\tapqn = source_config-\u003eqinfo[i].apqn;\n+\n+\t\t/*\n+\t\t * If we can't get the hardware info for a particular queue, then let's\n+\t\t * capture the function return code and continue so we can log all\n+\t\t * errors to aid in debugging of migration.\n+\t\t */\n+\t\trc = get_hardware_info_for_queue(mdev_name, \u0026dest_hwinfo, apqn);\n+\t\tif (rc) {\n+\t\t\tret = rc;\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\tsrc_hwinfo.value =  source_config-\u003eqinfo[i].data;\n+\n+\t\tif (!queue_hardware_info_is_compatible(mdev_name, apqn,\n+\t\t\t\t\t\t       \u0026src_hwinfo,\n+\t\t\t\t\t\t       \u0026dest_hwinfo))\n+\t\t\tret = -EINVAL;\n+\t}\n+\n+\treturn ret;\n+}\n+\n+static int do_post_copy_validation(const char *mdev_name,\n+\t\t\t\t   struct vfio_ap_config *source_config)\n+{\n+\tif (source_config-\u003emagic != VFIO_AP_MIG_MAGIC ||\n+\t    source_config-\u003eversion != VFIO_AP_MIG_VERSION)\n+\t\treturn -EINVAL;\n+\n+\tif (!queues_available(mdev_name, source_config))\n+\t\treturn -ENODEV;\n+\n+\tif (!control_domains_available(mdev_name, source_config))\n+\t\treturn -ENODEV;\n+\n+\treturn verify_ap_configs_are_compatible(mdev_name, source_config);\n+}\n+\n+/**\n+ * setup_ap_matrix_from_ap_config:\n+ *\n+ * Set the bits corresponding to the adapters, domains and control domains\n+ * from the source guest's AP configuration into an ap_matrix object to be\n+ * used to update the destination guest to run on this host.\n+ *\n+ * @ap_config:\t\tThe source guest's AP configuration\n+ * @guest_matrix:\tThe object to be used to update the destination guest's\n+ *\t\t\tAP configuration\n+ */\n+static void setup_ap_matrix_from_ap_config(struct vfio_ap_config *ap_config,\n+\t\t\t\t\t   struct ap_matrix *guest_matrix)\n+{\n+\tstruct ap_config_info host_config_info = { 0 };\n+\tunsigned long apid, apqi, *guest_adm;\n+\tstruct vfio_ap_queue_info qinfo;\n+\n+\tap_qci(\u0026host_config_info);\n+\t/*\n+\t * Zero the bitmaps before calling vfio_ap_matrix_init(), which only\n+\t * sets the apm_max/aqm_max/adm_max scalar fields and leaves the bitmap\n+\t * arrays untouched.  Without this, stack garbage in guest_matrix-\u003eapm,\n+\t * -\u003eaqm, and -\u003eadm would grant the destination guest access to\n+\t * arbitrary unassigned queues and control domains.\n+\t */\n+\tmemset(guest_matrix-\u003eapm, 0, sizeof(guest_matrix-\u003eapm));\n+\tmemset(guest_matrix-\u003eaqm, 0, sizeof(guest_matrix-\u003eaqm));\n+\tmemset(guest_matrix-\u003eadm, 0, sizeof(guest_matrix-\u003eadm));\n+\tvfio_ap_matrix_init(\u0026host_config_info, guest_matrix);\n+\n+\tfor (int i = 0; i \u003c ap_config-\u003enum_queues; i++) {\n+\t\tqinfo = ap_config-\u003eqinfo[i];\n+\t\tapid = AP_QID_CARD(qinfo.apqn);\n+\t\tapqi = AP_QID_QUEUE(qinfo.apqn);\n+\n+\t\tif (!test_bit_inv(apid, guest_matrix-\u003eapm))\n+\t\t\tset_bit_inv(apid, guest_matrix-\u003eapm);\n+\t\tif (!test_bit_inv(apqi, guest_matrix-\u003eaqm))\n+\t\t\tset_bit_inv(apqi, guest_matrix-\u003eaqm);\n+\t}\n+\n+\tguest_adm = (unsigned long *)ap_config-\u003eadm;\n+\tfor_each_set_bit_inv(apqi, guest_adm, AP_DOMAINS) {\n+\t\tif (!test_bit_inv(apqi, guest_matrix-\u003eadm))\n+\t\t\tset_bit_inv(apqi, guest_matrix-\u003eadm);\n+\t}\n+}\n+\n+static int do_post_copy_processing(struct ap_matrix_mdev *matrix_mdev,\n+\t\t\t\t   struct vfio_ap_config *ap_config)\n+{\n+\tconst char *mdev_name = dev_name(matrix_mdev-\u003evdev.dev);\n+\tstruct ap_matrix guest_matrix;\n+\tint ret;\n+\n+\tlockdep_assert_held(\u0026ap_attr_mutex);\n+\tassert_has_update_locks_for_mdev(matrix_mdev);\n+\n+\tret = do_post_copy_validation(mdev_name, ap_config);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tsetup_ap_matrix_from_ap_config(ap_config, \u0026guest_matrix);\n+\n+\treturn vfio_ap_set_new_guest_config(matrix_mdev, \u0026guest_matrix);\n+}\n+\n+static ssize_t vfio_ap_resuming_write(struct file *filp, const char __user *buf,\n+\t\t\t\t      size_t len, loff_t *pos)\n+{\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\tstruct vfio_ap_config *ap_config;\n+\tssize_t ret;\n+\n+\t/*\n+\t * This file was opened with stream_open(), so pos should be NULL for\n+\t * sequential write() calls; a non-NULL pointer will be passed only\n+\t * for positional pwrite() calls in which case we return an error\n+\t * indicating broken pipe/illegal seek on a non-seekable file.\n+\t */\n+\tif (pos)\n+\t\treturn -ESPIPE;\n+\n+\t/*\n+\t * Hold ap_attr_mutex for the full duration of the write, just as\n+\t * (un)assign_adapter_store() and (un)assign_domain_store() do.  This\n+\t * prevents the AP bus apmask/aqmask attributes from being changed\n+\t * while the guest's AP configuration is being updated.\n+\t *\n+\t * get_update_locks_for_mdev() then acquires guests_lock, kvm-\u003elock,\n+\t * and mdevs_lock in the correct order. This serialises\n+\t * the entire operation against concurrent AP attribute writers\n+\t * while the guest's AP configuration is being changed.\n+\t *\n+\t * Holding these locks for the full duration of a potentially chunked\n+\t * write could in theory affect performance, but this is acceptable for\n+\t * several reasons: migration is an infrequent operation; real-world\n+\t * guest AP configurations are small (each CEX8 card has 2 adapters and\n+\t * up to 16 domains, and the 85 cards in a system are shared across all\n+\t * LPARs and guests); and each chunk write completes quickly.\n+\t */\n+\tmatrix_mdev = filp-\u003eprivate_data;\n+\tmutex_lock(\u0026ap_attr_mutex);\n+\tget_update_locks_for_mdev(matrix_mdev);\n+\tpos = \u0026filp-\u003ef_pos;\n+\n+\tret = validate_resuming_write_parms(filp, len);\n+\tif (ret)\n+\t\tgoto out_unlock;\n+\n+\tap_config = matrix_mdev-\u003emig_data-\u003eresuming_mig_file.ap_config;\n+\n+\tif (copy_from_user((char *)ap_config + *pos, buf, len)) {\n+\t\tret = -EFAULT;\n+\t\tgoto out_unlock;\n+\t}\n+\n+\t*pos += len;\n+\n+\t/*\n+\t * Check whether we have received all the data.  We know the total\n+\t * expected size once num_queues has arrived, i.e. once *pos is past\n+\t * the fixed header.  Until then keep accumulating.\n+\t */\n+\tif (*pos \u003e= offsetofend(struct vfio_ap_config, num_queues)) {\n+\t\tsize_t expected_sz;\n+\n+\t\tif (ap_config-\u003enum_queues \u003e MAX_AP_QUEUES) {\n+\t\t\tret = -EINVAL;\n+\t\t\tgoto out_unlock;\n+\t\t}\n+\n+\t\texpected_sz = sizeof(struct vfio_ap_config) +\n+\t\t\t      ap_config-\u003enum_queues *\n+\t\t\t      sizeof(struct vfio_ap_queue_info);\n+\n+\t\tif (*pos \u003e (loff_t)expected_sz) {\n+\t\t\tret = -EINVAL;\n+\t\t\tgoto out_unlock;\n+\t\t}\n+\n+\t\tif (*pos == (loff_t)expected_sz)\n+\t\t\tret = do_post_copy_processing(matrix_mdev, ap_config);\n+\t}\n+\n+out_unlock:\n+\trelease_update_locks_for_mdev(matrix_mdev);\n+\tmutex_unlock(\u0026ap_attr_mutex);\n+\treturn ret ? ret : (ssize_t)len;\n+}\n+\n+static const struct file_operations vfio_ap_resume_fops = {\n+\t.owner = THIS_MODULE,\n+\t.write = vfio_ap_resuming_write,\n+\t.release = vfio_ap_release_mig_file,\n+};\n+\n+static struct file *vfio_ap_resuming_init(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tstruct vfio_ap_config *ap_config;\n+\tstruct file *filp;\n+\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\t/*\n+\t * Pre-allocate the maximum possible receive buffer so that\n+\t * vfio_ap_resuming_write() can copy directly into it without needing\n+\t * to know num_queues up front.  kvzalloc falls back to vmalloc for\n+\t * large allocations rather than failing a high-order kmalloc.\n+\t */\n+\tap_config = kvzalloc(VFIO_AP_CONFIG_MAX_SIZE, GFP_KERNEL_ACCOUNT);\n+\tif (!ap_config)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\n+\tfilp = vfio_ap_open_file_stream(matrix_mdev, \u0026vfio_ap_resume_fops, O_WRONLY);\n+\tif (IS_ERR(filp)) {\n+\t\tkvfree(ap_config);\n+\t\treturn filp;\n+\t}\n+\n+\tmatrix_mdev-\u003emig_data-\u003eresuming_mig_file.ap_config = ap_config;\n+\tmatrix_mdev-\u003emig_data-\u003eresuming_mig_file.config_sz = VFIO_AP_CONFIG_MAX_SIZE;\n+\n+\treturn filp;\n+}\n+\n+static struct file *\n+vfio_ap_transition_to_state(struct ap_matrix_mdev *matrix_mdev,\n+\t\t\t    enum vfio_device_mig_state new_state)\n+{\n+\tstruct vfio_ap_migration_data *mig_data;\n+\tenum vfio_device_mig_state cur_state;\n+\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\tmig_data = matrix_mdev-\u003emig_data;\n+\tcur_state = mig_data-\u003emig_state;\n+\tdev_dbg(matrix_mdev-\u003evdev.dev, \"%s: %d -\u003e %d\\n\", __func__, cur_state,\n+\t\tnew_state);\n+\n+\t/*\n+\t * Begins the process of saving the vfio device state by creating and\n+\t * returning a streaming data_fd to be used to read out the internal\n+\t * state of the vfio-ap device on the source host.\n+\t */\n+\tif (cur_state == VFIO_DEVICE_STATE_STOP \u0026\u0026\n+\t    new_state == VFIO_DEVICE_STATE_STOP_COPY) {\n+\t\tstruct file *filp = vfio_ap_open_file_stream(matrix_mdev,\n+\t\t\t\t\t\t\t     \u0026vfio_ap_stop_copy_fops,\n+\t\t\t\t\t\t\t     O_RDONLY);\n+\t\tif (IS_ERR(filp))\n+\t\t\treturn ERR_CAST(filp);\n+\n+\t\tmig_data-\u003estop_copy_mig_file.filp = filp;\n+\n+\t\treturn filp;\n+\t}\n+\n+\t/*\n+\t * Begins the process of restoring the vfio device state by creating and\n+\t * returning a streaming data_fd to be used to read in the internal\n+\t * state of the vfio-ap device on the destination host.\n+\t */\n+\tif (cur_state == VFIO_DEVICE_STATE_STOP \u0026\u0026\n+\t    new_state == VFIO_DEVICE_STATE_RESUMING) {\n+\t\tstruct file *filp = vfio_ap_resuming_init(matrix_mdev);\n+\n+\t\tif (IS_ERR(filp))\n+\t\t\treturn ERR_CAST(filp);\n+\n+\t\tmig_data-\u003eresuming_mig_file.filp = filp;\n+\t\treturn filp;\n+\t}\n+\n+\t/*\n+\t * Terminates the data transfer session of the vfio-ap device state\n+\t * between the source and target hosts. Since the vfio-ap device does\n+\t * not virtualize a DMA device, there is no internal device state to\n+\t * incorporate into the vfio-ap device on the target.\n+\t */\n+\tif ((cur_state == VFIO_DEVICE_STATE_RESUMING \u0026\u0026\n+\t     new_state == VFIO_DEVICE_STATE_STOP) ||\n+\t    (cur_state == VFIO_DEVICE_STATE_STOP_COPY \u0026\u0026\n+\t     new_state == VFIO_DEVICE_STATE_STOP)) {\n+\t\tvfio_ap_release_mig_files(matrix_mdev);\n+\t\treturn NULL;\n+\t}\n+\n+\t/*\n+\t * These states indicate migration has either not been initiated or\n+\t * has completed and the vfio-ap device is operating normally. Since the\n+\t * vfio-ap device does not virtualize a DMA device, there is no internal\n+\t * device state to incorporate into the vfio-ap device on the target.\n+\t */\n+\tif (cur_state == VFIO_DEVICE_STATE_STOP \u0026\u0026\n+\t    new_state == VFIO_DEVICE_STATE_RUNNING) {\n+\t\tvfio_ap_release_mig_files(matrix_mdev);\n+\t\treturn NULL;\n+\t}\n+\n+\tif (cur_state == VFIO_DEVICE_STATE_RUNNING \u0026\u0026\n+\t    new_state == VFIO_DEVICE_STATE_STOP) {\n+\t\treturn NULL;\n+\t}\n+\n+\t/* vfio_mig_get_next_state() does not use arcs other than the above */\n+\tWARN_ON(true);\n+\n+\treturn ERR_PTR(-EINVAL);\n+}\n+\n+static struct file *vfio_ap_set_state(struct vfio_device *vdev,\n+\t\t\t\t      enum vfio_device_mig_state  new_state)\n+{\n+\tint ret;\n+\tstruct file *filp = NULL;\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\tenum vfio_device_mig_state next_state;\n+\tstruct vfio_ap_migration_data *mig_data;\n+\n+\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tmatrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);\n+\n+\tif (ap_is_se_guest()) {\n+\t\tdev_err_once(matrix_mdev-\u003evdev.dev,\n+\t\t\t     \"Migration not allowed from or to a Secure Execution guest\\n\");\n+\t\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\t\treturn ERR_PTR(-EPERM);\n+\t}\n+\n+\tmig_data = matrix_mdev-\u003emig_data;\n+\n+\t/*\n+\t * The mig_data pointer is set in the vfio_ap_init_migration_data\n+\t * function which is called when the vfio-ap device fd is opened.\n+\t * Since the implicit pre-open state is RUNNING, a request to set\n+\t * RUNNING is a no-op. Any other state transition is invalid before\n+\t * open_device.\n+\t */\n+\tif (!mig_data) {\n+\t\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\t\tif (new_state == VFIO_DEVICE_STATE_RUNNING)\n+\t\t\treturn NULL;\n+\t\treturn ERR_PTR(-ENODEV);\n+\t}\n+\n+\tdev_dbg(vdev-\u003edev, \"%s -\u003e %d\\n\", __func__, new_state);\n+\n+\twhile (mig_data-\u003emig_state != new_state) {\n+\t\tret = vfio_mig_get_next_state(vdev, mig_data-\u003emig_state,\n+\t\t\t\t\t      new_state, \u0026next_state);\n+\t\tif (ret) {\n+\t\t\tfilp = ERR_PTR(ret);\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\tfilp = vfio_ap_transition_to_state(matrix_mdev, next_state);\n+\t\tif (IS_ERR(filp))\n+\t\t\tbreak;\n+\n+\t\tmig_data-\u003emig_state = next_state;\n+\n+\t\tif (WARN_ON(filp \u0026\u0026 new_state != next_state)) {\n+\t\t\tfput(filp);\n+\t\t\tfilp = ERR_PTR(-EINVAL);\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\n+\tif (mig_data-\u003emig_state == VFIO_DEVICE_STATE_ERROR)\n+\t\tfilp = ERR_PTR(-EIO);\n+\n+\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\treturn filp;\n+}\n+\n+static int vfio_ap_get_state(struct vfio_device *vdev,\n+\t\t\t     enum vfio_device_mig_state  *current_state)\n+{\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\tstruct vfio_ap_migration_data *mig_data;\n+\n+\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tmatrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);\n+\tmig_data =  matrix_mdev-\u003emig_data;\n+\n+\t/*\n+\t * The mig_data pointer is set in the vfio_ap_init_migration_data\n+\t * function which is called when the vfio-ap device fd is opened.\n+\t * If mig_data is NULL, report RUNNING as the implicit pre-open state\n+\t * so userspace doesn't need to perform any state transition before the\n+\t * device becomes active.\n+\t */\n+\t*current_state = (mig_data) ? mig_data-\u003emig_state :\n+\t\t\t\t      VFIO_DEVICE_STATE_RUNNING;\n+\n+\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\treturn 0;\n+}\n+\n+static int vfio_ap_get_data_size(struct vfio_device *vdev,\n+\t\t\t\t unsigned long *stop_copy_length)\n+{\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\tint num_queues;\n+\n+\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+\tmatrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);\n+\t*stop_copy_length = vfio_ap_config_size(matrix_mdev, \u0026num_queues);\n+\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\treturn 0;\n+}\n+\n+static const struct vfio_migration_ops vfio_ap_migration_ops = {\n+\t.migration_set_state = vfio_ap_set_state,\n+\t.migration_get_state = vfio_ap_get_state,\n+\t.migration_get_data_size = vfio_ap_get_data_size,\n+};\n+\n+/**\n+ * vfio_ap_init_migration_capabilities - initializes migration flags and operations\n+ *\n+ * @matrix_mdev: pointer to object containing the mdev state\n+ */\n+void vfio_ap_init_migration_capabilities(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\t/*\n+\t * Live guest migration is not supported for SE guests, so there is no\n+\t * need to initialize the migration capabilities.\n+\t */\n+\tif (ap_is_se_guest())\n+\t\treturn;\n+\n+\tmatrix_mdev-\u003evdev.migration_flags = VFIO_MIGRATION_STOP_COPY;\n+\tmatrix_mdev-\u003evdev.mig_ops = \u0026vfio_ap_migration_ops;\n+}\n+\n+/**\n+ * vfio_ap_init_migration_data - initialize migration data and functions\n+ *\n+ * @matrix_mdev: pointer to object containing the mdev state\n+ *\n+ * Return: zero if initialization is successful; otherwise, returns a error.\n+ */\n+int vfio_ap_init_migration_data(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tstruct vfio_ap_migration_data *mig_data;\n+\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\t/*\n+\t * Live guest migration is not supported for SE guests, so there is no\n+\t * need to initialize the migration data.\n+\t */\n+\tif (ap_is_se_guest())\n+\t\treturn 0;\n+\n+\tmig_data = kzalloc_obj(struct vfio_ap_migration_data, GFP_KERNEL);\n+\tif (!mig_data)\n+\t\treturn -ENOMEM;\n+\n+\tmig_data-\u003emig_state = VFIO_DEVICE_STATE_RUNNING;\n+\tmatrix_mdev-\u003emig_data = mig_data;\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * vfio_ap_release_mig_files:\n+ *\n+ * Free the ap_config buffers for any open migration FDs. Although a\n+ * migration FD may still be held open by userspace, it is safe to free\n+ * mig_data here because:\n+ *\n+ *   1. matrix_mdev remains valid for the lifetime of any open migration\n+ *      FD via the vfio_device registration reference taken in\n+ *      vfio_ap_open_file_stream() and dropped in\n+ *      vfio_ap_release_mig_file().\n+ *\n+ *   2. mig_data is only accessed by the migration file ops\n+ *      (vfio_ap_stop_copy_read, vfio_ap_resuming_write) under\n+ *      mdevs_lock. Once mig_data is set to NULL by the caller, those\n+ *      paths will see NULL and return -ENODEV before dereferencing it.\n+ *\n+ * @matrix_mdev: The object used to maintain the state for a mediated device\n+ */\n+static void vfio_ap_release_mig_files(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tstruct vfio_ap_migration_data *mig_data;\n+\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tmig_data = matrix_mdev-\u003emig_data;\n+\tvfio_ap_release_stop_copy_file(mig_data);\n+\tvfio_ap_release_resuming_file(mig_data);\n+}\n+\n+/**\n+ * vfio_ap_release_migration_data: reclaim private migration data\n+ *\n+ * @vdev: pointer to the mdev\n+ */\n+void vfio_ap_release_migration_data(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tif (!matrix_mdev-\u003emig_data)\n+\t\treturn;\n+\n+\tvfio_ap_release_mig_files(matrix_mdev);\n+\tkfree(matrix_mdev-\u003emig_data);\n+\tmatrix_mdev-\u003emig_data = NULL;\n+}\n+\n+/**\n+ * vfio_ap_reset_migration_state - Reset the vfio-ap migration state\n+ *\n+ * @matrix_mdev: pointer to the object maintaining the vfio-ap device state\n+ *\n+ * Called during VFIO_DEVICE_RESET to clean up any active migration\n+ * state and reset the device to RUNNING state as required by the VFIO\n+ * migration specification.\n+ */\n+void vfio_ap_reset_migration_state(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tif (!matrix_mdev-\u003emig_data)\n+\t\treturn;\n+\n+\tvfio_ap_release_mig_files(matrix_mdev);\n+\tmatrix_mdev-\u003emig_data-\u003emig_state = VFIO_DEVICE_STATE_RUNNING;\n+}\ndiff --git a/drivers/s390/crypto/vfio_ap_ops.c b/drivers/s390/crypto/vfio_ap_ops.c\nindex 4db878c18f41c..5803207e98460 100644\n--- a/drivers/s390/crypto/vfio_ap_ops.c\n+++ b/drivers/s390/crypto/vfio_ap_ops.c\n@@ -88,53 +88,6 @@ static inline void release_update_locks_for_kvm(struct kvm *kvm)\n \tmutex_unlock(\u0026matrix_dev-\u003eguests_lock);\n }\n \n-/**\n- * get_update_locks_for_mdev: Acquire the locks required to dynamically update a\n- *\t\t\t      KVM guest's APCB in the proper order.\n- *\n- * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP\n- *\t\t configuration data to use to update a KVM guest's APCB.\n- *\n- * The proper locking order is:\n- * 1. matrix_dev-\u003eguests_lock: required to use the KVM pointer to update a KVM\n- *\t\t\t       guest's APCB.\n- * 2. matrix_mdev-\u003ekvm-\u003elock:  required to update a guest's APCB\n- * 3. matrix_dev-\u003emdevs_lock:  required to access data stored in a matrix_mdev\n- *\n- * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM\n- *\t lock will not be taken.\n- */\n-static inline void get_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)\n-{\n-\tmutex_lock(\u0026matrix_dev-\u003eguests_lock);\n-\tif (matrix_mdev \u0026\u0026 matrix_mdev-\u003ekvm)\n-\t\tmutex_lock(\u0026matrix_mdev-\u003ekvm-\u003elock);\n-\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n-}\n-\n-/**\n- * release_update_locks_for_mdev: Release the locks used to dynamically update a\n- *\t\t\t\t  KVM guest's APCB in the proper order.\n- *\n- * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP\n- *\t\t configuration data to use to update a KVM guest's APCB.\n- *\n- * The proper unlocking order is:\n- * 1. matrix_dev-\u003emdevs_lock\n- * 2. matrix_mdev-\u003ekvm-\u003elock\n- * 3. matrix_dev-\u003eguests_lock\n- *\n- * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM\n- *\t lock will not be released.\n- */\n-static inline void release_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)\n-{\n-\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n-\tif (matrix_mdev \u0026\u0026 matrix_mdev-\u003ekvm)\n-\t\tmutex_unlock(\u0026matrix_mdev-\u003ekvm-\u003elock);\n-\tmutex_unlock(\u0026matrix_dev-\u003eguests_lock);\n-}\n-\n /**\n  * get_update_locks_by_apqn: Find the mdev to which an APQN is assigned and\n  *\t\t\t     acquire the locks required to update the APCB of\n@@ -649,8 +602,7 @@ static int handle_pqap(struct kvm_vcpu *vcpu)\n \treturn 0;\n }\n \n-static void vfio_ap_matrix_init(struct ap_config_info *info,\n-\t\t\t\tstruct ap_matrix *matrix)\n+void vfio_ap_matrix_init(struct ap_config_info *info, struct ap_matrix *matrix)\n {\n \tmatrix-\u003eapm_max = info-\u003eapxa ? info-\u003ena : 63;\n \tmatrix-\u003eaqm_max = info-\u003eapxa ? info-\u003end : 15;\n@@ -782,18 +734,30 @@ static bool vfio_ap_mdev_filter_matrix(struct ap_matrix_mdev *matrix_mdev,\n \n static int vfio_ap_mdev_init_dev(struct vfio_device *vdev)\n {\n-\tstruct ap_matrix_mdev *matrix_mdev =\n-\t\tcontainer_of(vdev, struct ap_matrix_mdev, vdev);\n+\tstruct ap_matrix_mdev *matrix_mdev;\n \n+\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+\tmatrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);\n \tmatrix_mdev-\u003emdev = to_mdev_device(vdev-\u003edev);\n \tvfio_ap_matrix_init(\u0026matrix_dev-\u003einfo, \u0026matrix_mdev-\u003ematrix);\n \tmatrix_mdev-\u003epqap_hook = handle_pqap;\n \tvfio_ap_matrix_init(\u0026matrix_dev-\u003einfo, \u0026matrix_mdev-\u003eshadow_apcb);\n \thash_init(matrix_mdev-\u003eqtable.queues);\n+\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n \n \treturn 0;\n }\n \n+static void vfio_ap_mdev_release_dev(struct vfio_device *vdev)\n+{\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\n+\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+\tmatrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);\n+\tvfio_ap_release_migration_data(matrix_mdev);\n+\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+}\n+\n static int vfio_ap_mdev_probe(struct mdev_device *mdev)\n {\n \tstruct ap_matrix_mdev *matrix_mdev;\n@@ -804,6 +768,20 @@ static int vfio_ap_mdev_probe(struct mdev_device *mdev)\n \tif (IS_ERR(matrix_mdev))\n \t\treturn PTR_ERR(matrix_mdev);\n \n+\t/*\n+\t * Migration capabilities must be initialized before calling\n+\t * vfio_register_emulated_iommu_dev; otherwise, the VFIO core\n+\t * will see mig_ops as NULL during the registration. This could\n+\t * prevent the VFIO core from properly setting up migration\n+\t * infrastructure like debugfs entries.\n+\t *\n+\t * This must be done before acquiring mdevs_lock to avoid an ABBA\n+\t * deadlock: vfio_register_emulated_iommu_dev() acquires dev_set-\u003elock\n+\t * internally, while vfio_ap_mdev_open_device() is called by the VFIO\n+\t * core with dev_set-\u003elock already held and then acquires mdevs_lock.\n+\t */\n+\tvfio_ap_init_migration_capabilities(matrix_mdev);\n+\n \tret = vfio_register_emulated_iommu_dev(\u0026matrix_mdev-\u003evdev);\n \tif (ret)\n \t\tgoto err_put_vdev;\n@@ -1003,8 +981,7 @@ static void vfio_ap_mdev_link_adapter(struct ap_matrix_mdev *matrix_mdev,\n \tunsigned long apqi;\n \n \tfor_each_set_bit_inv(apqi, matrix_mdev-\u003ematrix.aqm, AP_DOMAINS)\n-\t\tvfio_ap_mdev_link_apqn(matrix_mdev,\n-\t\t\t\t       AP_MKQID(apid, apqi));\n+\t\tvfio_ap_mdev_link_apqn(matrix_mdev, AP_MKQID(apid, apqi));\n }\n \n static void collect_queues_to_reset(struct ap_matrix_mdev *matrix_mdev,\n@@ -1714,54 +1691,98 @@ static void ap_matrix_copy(struct ap_matrix *dst, struct ap_matrix *src)\n \tbitmap_copy(dst-\u003eadm, src-\u003eadm, AP_DOMAINS);\n }\n \n-static ssize_t ap_config_store(struct device *dev, struct device_attribute *attr,\n-\t\t\t       const char *buf, size_t count)\n+static void get_removed_matrixes(struct ap_matrix *m_removed,\n+\t\t\t\t struct ap_matrix *m_old,\n+\t\t\t\t struct ap_matrix *m_new)\n {\n-\tstruct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);\n-\tstruct ap_matrix m_new, m_old, m_added, m_removed;\n+\tbitmap_andnot(m_removed-\u003eapm, m_old-\u003eapm, m_new-\u003eapm, AP_DEVICES);\n+\tbitmap_andnot(m_removed-\u003eaqm, m_old-\u003eaqm, m_new-\u003eaqm, AP_DOMAINS);\n+\tbitmap_andnot(m_removed-\u003eadm, m_old-\u003eadm, m_new-\u003eadm, AP_DOMAINS);\n+}\n+\n+static void get_added_matrixes(struct ap_matrix *m_added,\n+\t\t\t       struct ap_matrix *m_old,\n+\t\t\t       struct ap_matrix *m_new)\n+{\n+\tbitmap_andnot(m_added-\u003eapm, m_new-\u003eapm, m_old-\u003eapm, AP_DEVICES);\n+\tbitmap_andnot(m_added-\u003eaqm, m_new-\u003eaqm, m_old-\u003eaqm, AP_DOMAINS);\n+\tbitmap_andnot(m_added-\u003eadm, m_new-\u003eadm, m_old-\u003eadm, AP_DOMAINS);\n+}\n+\n+static int validate_new_state(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tint rc;\n+\n+\t/* Ensure new state is valid, else undo new state */\n+\trc = vfio_ap_mdev_validate_masks(matrix_mdev);\n+\tif (rc)\n+\t\treturn rc;\n+\n+\trc = ap_matrix_overflow_check(matrix_mdev);\n+\tif (rc)\n+\t\treturn rc;\n+\n+\treturn 0;\n+}\n+\n+static void link_new_queues(struct ap_matrix_mdev *matrix_mdev,\n+\t\t\t    struct ap_matrix *m_added)\n+{\n+\tunsigned long apid, apqi;\n+\n+\tfor_each_set_bit_inv(apid, m_added-\u003eapm, AP_DEVICES)\n+\t\tvfio_ap_mdev_link_adapter(matrix_mdev, apid);\n+\n+\tfor_each_set_bit_inv(apqi, m_added-\u003eaqm, AP_DOMAINS)\n+\t\tvfio_ap_mdev_link_domain(matrix_mdev, apqi);\n+}\n+\n+/**\n+ * vfio_ap_set_new_guest_config:\n+ *\n+ * Set a new AP configuration for a guest.\n+ *\n+ * @matrix_mdev: Object used to maintain the AP configuration for a guest\n+ * @m_new:\t\t Object used to set the new AP configuration\n+ *\n+ * Returns: zero (0) if the new AP configuration is successfully set; otherwise,\n+ *\t    returns an error:\n+ *\n+ *\t    ~ EADDRNOTAVAIL One or more APQNs are reserved for host use\n+ *\t    ~ EADDRINUSE    One or more APQNs are assigned to another mdev\n+ *\t    ~ ENODEV\t    An adapter, domain or control domain in the new\n+ *\t\t\t    AP configuration exceeds the max architected value\n+ */\n+int vfio_ap_set_new_guest_config(struct ap_matrix_mdev *matrix_mdev,\n+\t\t\t\t struct ap_matrix *m_new)\n+{\n+\tstruct ap_matrix m_old, m_added, m_removed;\n \tDECLARE_BITMAP(apm_filtered, AP_DEVICES);\n-\tunsigned long newbit;\n-\tchar *newbuf, *rest;\n-\tint rc = count;\n \tbool do_update;\n+\tint rc;\n \n-\tnewbuf = kstrndup(buf, AP_CONFIG_STRLEN, GFP_KERNEL);\n-\tif (!newbuf)\n-\t\treturn -ENOMEM;\n-\trest = newbuf;\n-\n-\tmutex_lock(\u0026ap_attr_mutex);\n-\tget_update_locks_for_mdev(matrix_mdev);\n+\tlockdep_assert_held(\u0026ap_attr_mutex);\n+\tassert_has_update_locks_for_mdev(matrix_mdev);\n \n-\t/* Save old state */\n+\t/* Save the old matrix to restore it if validation fails */\n \tap_matrix_copy(\u0026m_old, \u0026matrix_mdev-\u003ematrix);\n-\tif (parse_bitmap(\u0026rest, m_new.apm, AP_DEVICES) ||\n-\t    parse_bitmap(\u0026rest, m_new.aqm, AP_DOMAINS) ||\n-\t    parse_bitmap(\u0026rest, m_new.adm, AP_DOMAINS)) {\n-\t\trc = -EINVAL;\n-\t\tgoto out;\n-\t}\n \n-\tbitmap_andnot(m_removed.apm, m_old.apm, m_new.apm, AP_DEVICES);\n-\tbitmap_andnot(m_removed.aqm, m_old.aqm, m_new.aqm, AP_DOMAINS);\n-\tbitmap_andnot(m_added.apm, m_new.apm, m_old.apm, AP_DEVICES);\n-\tbitmap_andnot(m_added.aqm, m_new.aqm, m_old.aqm, AP_DOMAINS);\n+\t/*\n+\t * Get the adapters, domains and control domains added and/or removed\n+\t * from the existing configuration\n+\t */\n+\tget_removed_matrixes(\u0026m_removed, \u0026m_old, m_new);\n+\tget_added_matrixes(\u0026m_added, \u0026m_old, m_new);\n \n \t/* Need new bitmaps in matrix_mdev for validation */\n-\tap_matrix_copy(\u0026matrix_mdev-\u003ematrix, \u0026m_new);\n+\tap_matrix_copy(\u0026matrix_mdev-\u003ematrix, m_new);\n \n \t/* Ensure new state is valid, else undo new state */\n-\trc = vfio_ap_mdev_validate_masks(matrix_mdev);\n-\tif (rc) {\n-\t\tap_matrix_copy(\u0026matrix_mdev-\u003ematrix, \u0026m_old);\n-\t\tgoto out;\n-\t}\n-\trc = ap_matrix_overflow_check(matrix_mdev);\n+\trc = validate_new_state(matrix_mdev);\n \tif (rc) {\n \t\tap_matrix_copy(\u0026matrix_mdev-\u003ematrix, \u0026m_old);\n-\t\tgoto out;\n+\t\treturn rc;\n \t}\n-\trc = count;\n \n \t/* Need old bitmaps in matrix_mdev for unplug/unlink */\n \tap_matrix_copy(\u0026matrix_mdev-\u003ematrix, \u0026m_old);\n@@ -1771,14 +1792,10 @@ static ssize_t ap_config_store(struct device *dev, struct device_attribute *attr\n \tvfio_ap_mdev_hot_unplug_domains(matrix_mdev, m_removed.aqm);\n \n \t/* Need new bitmaps in matrix_mdev for linking new adapters/domains */\n-\tap_matrix_copy(\u0026matrix_mdev-\u003ematrix, \u0026m_new);\n-\n-\t/* Link newly added adapters */\n-\tfor_each_set_bit_inv(newbit, m_added.apm, AP_DEVICES)\n-\t\tvfio_ap_mdev_link_adapter(matrix_mdev, newbit);\n+\tap_matrix_copy(\u0026matrix_mdev-\u003ematrix, m_new);\n \n-\tfor_each_set_bit_inv(newbit, m_added.aqm, AP_DOMAINS)\n-\t\tvfio_ap_mdev_link_domain(matrix_mdev, newbit);\n+\t/* Link queues associated with the newly added adapters and domains */\n+\tlink_new_queues(matrix_mdev, \u0026m_added);\n \n \t/* filter resources not bound to vfio-ap */\n \tdo_update = vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered);\n@@ -1789,7 +1806,39 @@ static ssize_t ap_config_store(struct device *dev, struct device_attribute *attr\n \t\tvfio_ap_mdev_update_guest_apcb(matrix_mdev);\n \t\treset_queues_for_apids(matrix_mdev, apm_filtered);\n \t}\n-out:\n+\n+\treturn 0;\n+}\n+\n+static ssize_t ap_config_store(struct device *dev, struct device_attribute *attr,\n+\t\t\t       const char *buf, size_t count)\n+{\n+\tstruct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);\n+\tstruct ap_matrix m_new;\n+\tchar *newbuf, *rest;\n+\tssize_t rc;\n+\n+\tnewbuf = kstrndup(buf, AP_CONFIG_STRLEN, GFP_KERNEL);\n+\tif (!newbuf)\n+\t\treturn -ENOMEM;\n+\trest = newbuf;\n+\n+\tmutex_lock(\u0026ap_attr_mutex);\n+\tget_update_locks_for_mdev(matrix_mdev);\n+\n+\tif (parse_bitmap(\u0026rest, m_new.apm, AP_DEVICES) ||\n+\t    parse_bitmap(\u0026rest, m_new.aqm, AP_DOMAINS) ||\n+\t    parse_bitmap(\u0026rest, m_new.adm, AP_DOMAINS)) {\n+\t\tkfree(newbuf);\n+\t\trelease_update_locks_for_mdev(matrix_mdev);\n+\t\tmutex_unlock(\u0026ap_attr_mutex);\n+\t\treturn -EINVAL;\n+\t}\n+\n+\trc = vfio_ap_set_new_guest_config(matrix_mdev, \u0026m_new);\n+\tif (!rc)\n+\t\trc = count;\n+\n \trelease_update_locks_for_mdev(matrix_mdev);\n \tmutex_unlock(\u0026ap_attr_mutex);\n \tkfree(newbuf);\n@@ -2059,19 +2108,39 @@ static int vfio_ap_mdev_reset_qlist(struct list_head *qlist)\n \n static int vfio_ap_mdev_open_device(struct vfio_device *vdev)\n {\n-\tstruct ap_matrix_mdev *matrix_mdev =\n-\t\tcontainer_of(vdev, struct ap_matrix_mdev, vdev);\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\tint ret;\n \n \tif (!vdev-\u003ekvm)\n \t\treturn -EINVAL;\n \n-\treturn vfio_ap_mdev_set_kvm(matrix_mdev, vdev-\u003ekvm);\n+\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+\tmatrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);\n+\tret = vfio_ap_init_migration_data(matrix_mdev);\n+\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tret = vfio_ap_mdev_set_kvm(matrix_mdev, vdev-\u003ekvm);\n+\tif (ret) {\n+\t\t/* Clean up migration data on failure */\n+\t\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+\t\tvfio_ap_release_migration_data(matrix_mdev);\n+\t\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\t}\n+\n+\treturn ret;\n }\n \n static void vfio_ap_mdev_close_device(struct vfio_device *vdev)\n {\n-\tstruct ap_matrix_mdev *matrix_mdev =\n-\t\tcontainer_of(vdev, struct ap_matrix_mdev, vdev);\n+\tstruct ap_matrix_mdev *matrix_mdev;\n+\n+\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+\tmatrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);\n+\tvfio_ap_release_migration_data(matrix_mdev);\n+\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n \n \tvfio_ap_mdev_unset_kvm(matrix_mdev);\n }\n@@ -2105,6 +2174,14 @@ static void vfio_ap_mdev_request(struct vfio_device *vdev, unsigned int count)\n \trelease_update_locks_for_mdev(matrix_mdev);\n }\n \n+unsigned int vfio_ap_mdev_get_num_queues(struct ap_matrix *ap_matrix)\n+{\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+\n+\treturn bitmap_weight(ap_matrix-\u003eapm, AP_DEVICES) *\n+\t       bitmap_weight(ap_matrix-\u003eaqm, AP_DOMAINS);\n+}\n+\n static int vfio_ap_mdev_get_device_info(unsigned long arg)\n {\n \tunsigned long minsz;\n@@ -2282,6 +2359,17 @@ static ssize_t vfio_ap_mdev_ioctl(struct vfio_device *vdev,\n \t\tbreak;\n \tcase VFIO_DEVICE_RESET:\n \t\tret = vfio_ap_mdev_reset_queues(matrix_mdev);\n+\t\t/*\n+\t\t * Reset the migration state unconditionally, regardless of\n+\t\t * whether the hardware queue reset succeeded. The migration\n+\t\t * state tracks the AP configuration transfer lifecycle and is\n+\t\t * independent of the hardware queue reset outcome. The VFIO\n+\t\t * migration spec designates VFIO_DEVICE_RESET as the mechanism\n+\t\t * to return device_state to RUNNING (e.g. to recover from\n+\t\t * ERROR), so the migration state must be cleaned up even when\n+\t\t * one or more queues fail to reset.\n+\t\t */\n+\t\tvfio_ap_reset_migration_state(matrix_mdev);\n \t\tbreak;\n \tcase VFIO_DEVICE_GET_IRQ_INFO:\n \t\tret = vfio_ap_get_irq_info(arg);\n@@ -2389,6 +2477,7 @@ static const struct attribute_group vfio_queue_attr_group = {\n \n static const struct vfio_device_ops vfio_ap_matrix_dev_ops = {\n \t.init = vfio_ap_mdev_init_dev,\n+\t.release = vfio_ap_mdev_release_dev,\n \t.open_device = vfio_ap_mdev_open_device,\n \t.close_device = vfio_ap_mdev_close_device,\n \t.ioctl = vfio_ap_mdev_ioctl,\ndiff --git a/drivers/s390/crypto/vfio_ap_private.h b/drivers/s390/crypto/vfio_ap_private.h\nindex 9bff666b0b35d..3910b5c023c91 100644\n--- a/drivers/s390/crypto/vfio_ap_private.h\n+++ b/drivers/s390/crypto/vfio_ap_private.h\n@@ -91,6 +91,9 @@ struct ap_queue_table {\n \tDECLARE_HASHTABLE(queues, 8);\n };\n \n+/* Forward declaration for migration data structure */\n+struct vfio_ap_migration_data;\n+\n /**\n  * struct ap_matrix_mdev - Contains the data associated with a matrix mediated\n  *\t\t\t   device.\n@@ -110,6 +113,7 @@ struct ap_queue_table {\n  * @aqm_add:\tbitmap of APQIs added to the host's AP configuration\n  * @adm_add:\tbitmap of control domain numbers added to the host's AP\n  *\t\tconfiguration\n+ * @mig_data:  vfio device migration data\n  */\n struct ap_matrix_mdev {\n \tstruct vfio_device vdev;\n@@ -125,6 +129,7 @@ struct ap_matrix_mdev {\n \tDECLARE_BITMAP(apm_add, AP_DEVICES);\n \tDECLARE_BITMAP(aqm_add, AP_DOMAINS);\n \tDECLARE_BITMAP(adm_add, AP_DOMAINS);\n+\tstruct vfio_ap_migration_data *mig_data;\n };\n \n /**\n@@ -152,6 +157,8 @@ struct vfio_ap_queue {\n \tstruct work_struct reset_work;\n };\n \n+unsigned int vfio_ap_mdev_get_num_queues(struct ap_matrix *ap_matrix);\n+\n int vfio_ap_mdev_register(void);\n void vfio_ap_mdev_unregister(void);\n \n@@ -165,4 +172,72 @@ void vfio_ap_on_cfg_changed(struct ap_config_info *new_config_info,\n void vfio_ap_on_scan_complete(struct ap_config_info *new_config_info,\n \t\t\t      struct ap_config_info *old_config_info);\n \n+void vfio_ap_matrix_init(struct ap_config_info *info, struct ap_matrix *matrix);\n+\n+void vfio_ap_init_migration_capabilities(struct ap_matrix_mdev *matrix_mdev);\n+int vfio_ap_init_migration_data(struct ap_matrix_mdev *matrix_mdev);\n+void vfio_ap_release_migration_data(struct ap_matrix_mdev *matrix_mdev);\n+void vfio_ap_reset_migration_state(struct ap_matrix_mdev *matrix_mdev);\n+\n+/**\n+ * get_update_locks_for_mdev: Acquire the locks required to dynamically update a\n+ *\t\t\t      KVM guest's APCB in the proper order.\n+ *\n+ * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP\n+ *\t\t configuration data to use to update a KVM guest's APCB.\n+ *\n+ * The proper locking order is:\n+ * 1. matrix_dev-\u003eguests_lock: required to use the KVM pointer to update a KVM\n+ *\t\t\t       guest's APCB.\n+ * 2. matrix_mdev-\u003ekvm-\u003elock:  required to update a guest's APCB\n+ * 3. matrix_dev-\u003emdevs_lock:  required to access data stored in a matrix_mdev\n+ *\n+ * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM\n+ *\t lock will not be taken.\n+ */\n+static inline void get_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tmutex_lock(\u0026matrix_dev-\u003eguests_lock);\n+\tif (matrix_mdev \u0026\u0026 matrix_mdev-\u003ekvm)\n+\t\tmutex_lock(\u0026matrix_mdev-\u003ekvm-\u003elock);\n+\tmutex_lock(\u0026matrix_dev-\u003emdevs_lock);\n+}\n+\n+/**\n+ * release_update_locks_for_mdev: Release the locks used to dynamically update a\n+ *\t\t\t\t  KVM guest's APCB in the proper order.\n+ *\n+ * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP\n+ *\t\t configuration data to use to update a KVM guest's APCB.\n+ *\n+ * The proper unlocking order is:\n+ * 1. matrix_dev-\u003emdevs_lock\n+ * 2. matrix_mdev-\u003ekvm-\u003elock\n+ * 3. matrix_dev-\u003eguests_lock\n+ *\n+ * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM\n+ *\t lock will not be released.\n+ */\n+static inline void release_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tmutex_unlock(\u0026matrix_dev-\u003emdevs_lock);\n+\tif (matrix_mdev \u0026\u0026 matrix_mdev-\u003ekvm)\n+\t\tmutex_unlock(\u0026matrix_mdev-\u003ekvm-\u003elock);\n+\tmutex_unlock(\u0026matrix_dev-\u003eguests_lock);\n+}\n+\n+static inline void\n+assert_has_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)\n+{\n+\tlockdep_assert_held(\u0026matrix_dev-\u003eguests_lock);\n+\tif (matrix_mdev \u0026\u0026 matrix_mdev-\u003ekvm)\n+\t\tlockdep_assert_held(\u0026matrix_mdev-\u003ekvm-\u003elock);\n+\tlockdep_assert_held(\u0026matrix_dev-\u003emdevs_lock);\n+}\n+\n+void vfio_ap_matrix_init(struct ap_config_info *info, struct ap_matrix *matrix);\n+\n+int vfio_ap_set_new_guest_config(struct ap_matrix_mdev *matrix_mdev,\n+\t\t\t\t struct ap_matrix *m_new);\n+\n #endif /* _VFIO_AP_PRIVATE_H_ */\n"
}

2/1 2026/10/09 14:37 agent patch-evaluator
1m Model:
core

Args:
null

Results:
{
  "EnableConfigs": null,
  "FocusSymbols": [],
  "Reasoning": "The patch series adds live guest migration support for s390 VFIO-AP (Adjunct Processor) devices, modifying documentation and driver code strictly under drivers/s390/crypto/. These code paths are exclusive to the s390 architecture (CONFIG_S390 / CONFIG_VFIO_AP) and cannot be compiled or executed on the target architecture (amd64). Consequently, the changes are structurally unreachable for fuzzing on amd64.",
  "WorthFuzzing": false
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 2224a13792a5e8ace3c129e7390e3c29fac6d1d6
Author: syz-cluster <triage@syzkaller.com>
Date:   Fri Oct 9 14:36:58 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/arch/s390/vfio-ap.rst b/Documentation/arch/s390/vfio-ap.rst
index ac0c07f76ddd7..02d7cbe5e4791 100644
--- a/Documentation/arch/s390/vfio-ap.rst
+++ b/Documentation/arch/s390/vfio-ap.rst
@@ -1012,7 +1012,7 @@ guest_matrix dyn ap_config
 
 the following features are advertised:
 
----------------+---------------------------------------------------------------+
++--------------+---------------------------------------------------------------+
 | Flag         | Description                                                   |
 +==============+===============================================================+
 | guest_matrix | guest_matrix attribute exists. It reports the matrix of       |
@@ -1021,105 +1021,523 @@ the following features are advertised:
 +--------------+---------------------------------------------------------------+
 | dyn          | Indicates hot plug/unplug of AP adapters, domains and control |
 |              | domains for a guest to which the mdev is attached.            |
-+------------+-----------------------------------------------------------------+
++--------------+---------------------------------------------------------------+
 | ap_config    | ap_config interface for one-shot modifications to mdev config |
 +--------------+---------------------------------------------------------------+
+| migratable   | Indicates that live guest migration is supported for guests   |
+|              | to which crypto devices are passed through                    |
++--------------+---------------------------------------------------------------+
 
-Limitations
-===========
-Live guest migration is not supported for guests using AP devices without
-intervention by a system administrator. Before a KVM guest can be migrated,
-the vfio_ap mediated device must be removed. Unfortunately, it can not be
-removed manually (i.e., echo 1 > /sys/devices/vfio_ap/matrix/$UUID/remove) while
-the mdev is in use by a KVM guest. If the guest is being emulated by QEMU,
-its mdev can be hot unplugged from the guest in one of two ways:
-
-1. If the KVM guest was started with libvirt, you can hot unplug the mdev via
-   the following commands:
-
-      virsh detach-device <guestname> <path-to-device-xml>
-
-      For example, to hot unplug mdev 62177883-f1bb-47f0-914d-32a22e3a8804 from
-      the guest named 'my-guest':
-
-         virsh detach-device my-guest ~/config/my-guest-hostdev.xml
-
-            The contents of my-guest-hostdev.xml:
-
-.. code-block:: xml
-
-            <hostdev mode='subsystem' type='mdev' managed='no' model='vfio-ap'>
-              <source>
-                <address uuid='62177883-f1bb-47f0-914d-32a22e3a8804'/>
-              </source>
-            </hostdev>
-
-
-      virsh qemu-monitor-command <guest-name> --hmp "device-del <device-id>"
-
-      For example, to hot unplug the vfio_ap mediated device identified on the
-      qemu command line with 'id=hostdev0' from the guest named 'my-guest':
-
-.. code-block:: sh
-
-         virsh qemu-monitor-command my-guest --hmp "device_del hostdev0"
-
-2. A vfio_ap mediated device can be hot unplugged by attaching the qemu monitor
-   to the guest and using the following qemu monitor command:
-
-      (QEMU) device-del id=<device-id>
-
-      For example, to hot unplug the vfio_ap mediated device that was specified
-      on the qemu command line with 'id=hostdev0' when the guest was started:
-
-         (QEMU) device-del id=hostdev0
-
-After live migration of the KVM guest completes, an AP configuration can be
-restored to the KVM guest by hot plugging a vfio_ap mediated device on the target
-system into the guest in one of two ways:
-
-1. If the KVM guest was started with libvirt, you can hot plug a matrix mediated
-   device into the guest via the following virsh commands:
-
-   virsh attach-device <guestname> <path-to-device-xml>
-
-      For example, to hot plug mdev 62177883-f1bb-47f0-914d-32a22e3a8804 into
-      the guest named 'my-guest':
-
-         virsh attach-device my-guest ~/config/my-guest-hostdev.xml
-
-            The contents of my-guest-hostdev.xml:
-
-.. code-block:: xml
-
-            <hostdev mode='subsystem' type='mdev' managed='no' model='vfio-ap'>
-              <source>
-                <address uuid='62177883-f1bb-47f0-914d-32a22e3a8804'/>
-              </source>
-            </hostdev>
-
-
-   virsh qemu-monitor-command <guest-name> --hmp \
-   "device_add vfio-ap,sysfsdev=<path-to-mdev>,id=<device-id>"
-
-      For example, to hot plug the vfio_ap mediated device
-      62177883-f1bb-47f0-914d-32a22e3a8804 into the guest named 'my-guest' with
-      device-id hostdev0:
-
-      virsh qemu-monitor-command my-guest --hmp \
-      "device_add vfio-ap,\
-      sysfsdev=/sys/devices/vfio_ap/matrix/62177883-f1bb-47f0-914d-32a22e3a8804,\
-      id=hostdev0"
-
-2. A vfio_ap mediated device can be hot plugged by attaching the qemu monitor
-   to the guest and using the following qemu monitor command:
-
-      (qemu) device_add "vfio-ap,sysfsdev=<path-to-mdev>,id=<device-id>"
-
-      For example, to plug the vfio_ap mediated device
-      62177883-f1bb-47f0-914d-32a22e3a8804 into the guest with the device-id
-      hostdev0:
+Live Guest Migration
+====================
+The VFIO AP mediated device is not used to provide userspace with direct
+access to device memory as is the case with other devices that use the VFIO
+framework for device pass-through. Instead, it manages AP
+configuration metadata identifying the adapters, domains, and control
+domains to which a guest will be granted access. These AP resources are
+configured by assigning them to a vfio-ap mediated device via its sysfs
+assignment interfaces. When the guest is started, the vfio_ap device driver
+sets the guest's AP configuration from the metadata stored with the mediated
+device. The AP devices are not accessed directly through the vfio_ap driver,
+so the driver does not migrate the state of the AP devices themselves.
+Instead, it migrates the AP configuration metadata. The vfio_ap device
+driver on the destination host will then ensure that the AP configuration
+metadata migrated from the source host is compatible with the AP
+configuration available on the destination host and if
+so, will set the destination guest's AP configuration accordingly.
 
-         (QEMU) device-add "vfio-ap,\
-         sysfsdev=/sys/devices/vfio_ap/matrix/62177883-f1bb-47f0-914d-32a22e3a8804,\
-         id=hostdev0"
+To be considered compatible, the AP configuration for the destination host must
+meet these requirements:
+
+* Each AP adapter, domain and control domain number assigned to the source
+  guest's AP configuration must be in the destination host's AP
+  configuration. This can be verified as follows:
+
+  * On the source host, display the AP configuration of the source guest
+    with the following two commands:
+
+    .. code-block:: bash
+
+       cat /sys/devices/vfio_ap/matrix/$UUID/guest_matrix
+       cat /sys/devices/vfio_ap/matrix/$UUID/control_domains
+
+    .. note::
+       Replace ``$UUID`` with the actual UUID of your mediated device.
+
+       The ``guest_matrix`` lists the APQNs of the queue devices assigned
+       to the mediated device; for example:
+
+       .. code-block:: bash
+
+          00.0033
+          00.003a
+
+       The ``control_domains`` lists the domain numbers of the control
+       domains; for example:
+
+       .. code-block:: bash
+
+          0033
+          003a
+
+  * Display the AP configuration of the destination host with the following
+    two commands:
+
+    .. code-block:: bash
+
+       lszcrypt -V
+       cat /sys/bus/ap/ap_control_domain_mask
+
+    .. note::
+       The ``lszcrypt -V`` command lists the AP cards (adapters) and queue
+       devices on the host system; for example:
+
+       .. code-block:: bash
+
+          =========== ===== ============ ==========
+          CARD.DOMAIN TYPE  MODE         DRIVER
+          =========== ===== ============ ==========
+          00          CEX5C CCA-Coproc   cex4card
+          00.0033     CEX5C CCA-Coproc   vfio_ap
+          00.003a     CEX5C CCA-Coproc   vfio_ap
+          =========== ===== ============ ==========
+
+       Each bit in the ap_control_domain_mask corresponds to
+       domain numbers 0-255. If a bit is set to one, then
+       the control domain is available on the source host. For
+       example:
+
+       .. code-block:: bash
+
+          0x0000000000001020000000000000000000000000000000000000000000000000
+
+       This mask indicates that AP control domains 51 (0x33) and 58 (0x3a) are
+       in the AP configuration of the host system.
+
+  * Verify the configurations:
+
+    * Each APQN in the guest's sysfs ``guest_matrix`` file must match an
+      APQN returned from the ``lszcrypt -V`` command on the destination host. It
+      is important to note the driver to which the queue is bound which
+      is displayed in the ``driver`` column. Queues not bound to the vfio_ap
+      driver are not available to the destination guest. Even if the APQNs are
+      available to the driver, that does not guarantee they can be used by the
+      guest being migrated; for example, migration will fail if any of these APQNs
+      are assigned to a mediated device other than the one being migrated.
+
+    * Each domain number from the source guest's sysfs
+      ``control_domains`` attribute must correspond to a bit set to one in
+      the destination host's ``ap_control_domain_mask``.
+
+
+* Each APQN assigned to the source guest and destination guest must
+  reference a queue device with compatible hardware capabilities:
+
+  +--------------+---------------------------------------------------------------+
+  | Hardware     | Description                                                   |
+  | Capabilities |                                                               |
+  +==============+===============================================================+
+  | [1]          | * AP special command facility (APSC)                          |
+  | Facilities   | * AP 4096-bit ME PKU commands facility (AP4KM)                |
+  |              | * AP 4096-bit CRT PKU commands (AP4KC)                        |
+  +--------------+---------------------------------------------------------------+
+  | [1] Mode     | * CCA-mode                                                    |
+  |              | * Accelerator-mode                                            |
+  |              | * XCP-mode (EP11)                                             |
+  +--------------+---------------------------------------------------------------+
+  | [1] AP       |   APXA installed                                              |
+  | extended     |                                                               |
+  | addressing   |                                                               |
+  +--------------+---------------------------------------------------------------+
+  | [1] Command  |   Command filtering available                                 |
+  | filtering    |                                                               |
+  +--------------+---------------------------------------------------------------+
+  | [2]          | * Full native card function                                   |
+  | Functional   | * Only stateless functions                                    |
+  | capabilities |                                                               |
+  +--------------+---------------------------------------------------------------+
+  | [3] AP type  | * 10 (0x0a): CEX4                                             |
+  |              | * 11 (0x0b): CEX5                                             |
+  |              | * 12 (0x0c)  CEX6                                             |
+  |              | * 13 (0x0d)  CEX7                                             |
+  |              | * 14 (0x0e)  CEX8                                             |
+  +--------------+---------------------------------------------------------------+
+
+  +-----------------------------------------------------------------------------+
+  | Table Keys                                                                  |
+  +=============================================================================+
+  |                                                                             |
+  | [1]        The hardware capability must be the same for both the source     |
+  |            and destination queue device.                                    |
+  |                                                                             |
+  | [2]        The source and destination queues must either both have          |
+  |            full native card function or both have stateless functions.      |
+  |            If the functional capabilities don't match, then the source      |
+  |            queue can have stateless capabilities since full native card     |
+  |            function can handle stateless functions; otherwise, migration    |
+  |            will fail.                                                       |
+  |                                                                             |
+  | [3]        The AP type on the source and destination guests can             |
+  |            differ if the queue passed through to the target guest is a      |
+  |            newer model (backwards compatible)                               |
+  +-----------------------------------------------------------------------------+
+
+  * To verify the hardware capabilities are compatible:
+
+    * On both the source and destination hosts, display the hardware capabilities
+      for each AP adapter in the AP configuration for that host:
+
+      .. code-block:: bash
+
+         cat /sys/bus/ap/devices/card$APID/ap_functions
+
+      .. note::
+         The ``$APID`` is the two-character adapter number in hexadecimal format;
+         for example, ``card02`` or ``card1f``. The ``/sys/bus/ap/devices`` directory
+         also lists the APQNs of the queue devices installed in the respective
+         host system with the first two characters being the APID; for example:
+         ``02.0004`` or ``00.0033`` .
+
+    * Verify the hardware capabilities for each AP adapter device on the source
+      and destination host are compatible. The ``ap_functions`` attribute is a
+      bitmask. The bits in the mask read from left to right starting with bit 0.
+      Each bit that is set to one indicates the corresponding hardware capability
+      is installed:
+
+      * Bits 0-2 are the facilities bits. Each bit value must match for the AP
+        devices on the source and destination systems. The values indicate the
+        following:
+
+        * bit-0: APSC is installed
+        * bit-1: AP4KM is installed
+        * bit-2: AP4KC is installed
+
+      * Bits 3-5 specify the adapter Modes. Only one of these bits will be set to
+        one and must be the same for both the source and destination adapter
+        devices:
+
+        * bit-3: CCA-mode
+        * bit-4: Accelerator-mode
+        * bit-5: XCP-mode (EP11)
+
+      * Bit 6 specifies whether APXA is installed and must be the same for both
+        the source and destination adapter devices.
+
+      * Bit 7 specifies whether command filtering is installed
+        and must be the same for both the source and destination adapter devices.
+
+      * Bits 8-15 are the classification bits. There are only two relevant
+        bits and only one of them will be set to one. For the source and destination
+        adapter devices to be considered compatible:
+
+        * Bit 8 may be set to 1 on both hosts (full native card function)
+        * Bit 9 may be set to 1 on both hosts (only stateless functions available)
+        * Bit 9 may be set to 1 on the source host and bit 8 may be set to 1 on
+          the destination host
+
+      * Bits 16-17 are the binding state bits which must be 00
+
+  * To verify the AP types are compatible:
+
+    * On both the source and destination hosts, display the hardware type
+      for each AP adapter in the AP configuration for that host to ensure the
+      source and destination adapter types are the same, or the source type is
+      less than the destination type::
+
+       cat /sys/bus/ap/devices/card$APID/hwtype
+
+      .. note::
+         The ``$APID`` is the two-character adapter number in hexadecimal format;
+         for example, ``card02`` or ``card1f``.
+
+Setting up for live guest migration on the destination host
+-----------------------------------------------------------
+To set up a host as the destination for live guest migration, do the
+following:
+
+1. Create a mediated device
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Create a mediated device with the same name (UUID) as the mediated device
+used to supply the AP configuration to the source guest. For example, if
+the mediated device on the source guest is named
+62177883-f1bb-47f0-914d-32a22e3a8804:
+
+.. code-block:: bash
+
+   echo 62177883-f1bb-47f0-914d-32a22e3a8804 > \
+     /sys/devices/vfio_ap/matrix/mdev_supported_types/vfio_ap-passthrough/create
+
+2. Reserve adapters and domains for the vfio_ap device driver's use
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Reserve the same adapters, and domains passed through to the source guest
+for the vfio_ap device driver on the destination host by clearing the
+adapter numbers from the ``/sys/bus/ap/apmask`` and/or the domain numbers
+from the ``/sys/bus/ap/aqmask`` files.
+
+For example, suppose adapters 0, 20 (0x14) and 22 (0x16) as well as
+domains 51 (0x33) and 58 (0x3a) are passed through to the source guest. To
+ensure they can be passed through to the destination guest, they must be
+made available to the vfio_ap device driver on the destination host. To
+make them available, do one or both of the following on the destination host:
+
+.. code-block:: bash
+
+   echo -0,-0x14,-22 > /sys/bus/ap/apmask
+   echo -0,-0x33,-0x3a > /sys/bus/ap/aqmask
+
+.. note::
+
+    * It is not necessary to reserve both the adapters and domains.
+      Reserving an adapter implicitly allows the vfio_ap driver to assign
+      each of the domains available on the system along with the reserved
+      adapters to a guest's AP configuration and vice versa.
+
+    * The Cartesian product of the adapters and domains reserved for the
+      vfio_ap device driver identifies the APQNs of the AP queue devices to be
+      bound to the vfio_ap device driver. If an APQN does not reference a
+      queue device installed in the system at the time of live guest migration,
+      the migration will fail.
+
+    * It is not necessary to configure the destination mediated device with
+      adapters, domains and control domains because the source guest's AP
+      configuration will overlay the destination guest's during migration.
+
+    * To verify that the queue devices are reserved for the vfio_ap
+      device driver, issue the ``lszcrypt -V`` command and you should
+      see ``vfio_ap`` in the ``DRIVER`` column of the output.
+
+Live guest migration failures due to AP configuration errors
+------------------------------------------------------------
+This section describes the errors that may occur during live guest migration
+when the AP configuration of the source guest and destination host are not
+compatible and where to look for problem determination.
+
+The destination host is missing the mediated device
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+This error occurs when a mediated device with the same name (UUID) as the
+mediated device being migrated has not been created on the destination host.
+
+**Source host**
+
++--------------+----------------------------------------------------------------+
+| Log          | Message                                                        |
++==============+================================================================+
+| Console log: | error: device not found: mediated device '$UUID' not           |
+|              | found                                                          |
++--------------+----------------------------------------------------------------+
+| QEMU log:    | initiating migration                                           |
+|              | qemu-system-s390x: Sibling indicated error 1                   |
++--------------+----------------------------------------------------------------+
+
+.. note::
+   $UUID is the UUID of the mediated device being migrated from the source host.
+
+
+One or more queues are not bound to the vfio_ap driver on the destination host
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The queue devices passed through to the source guest are not installed in the
+destination host or are not bound to its vfio_ap device driver.
+
+**Source host**
+
++--------------+----------------------------------------------------------------+
+| Log          | Message                                                        |
++==============+================================================================+
+| Console log: | error: operation failed: migration failed. Message from the    |
+|              | source host: operation failed: job 'migration out' failed:     |
+|              | Sibling indicated error 1. Message from the destination host:  |
+|              | operation failed: job 'migration in' failed: load of migration |
+|              | failed: No such device: Failed to load vmstate version_id: 1,  |
+|              | ret: -19                                                       |
++--------------+----------------------------------------------------------------+
+
+**Destination host**
+
++--------------+----------------------------------------------------------------+
+| Kernel log:  | vfio_ap_mdev $UUID: Queue $APID.$APQI not available to         |
+|              | vfio_ap driver on target host                                  |
++--------------+----------------------------------------------------------------+
+| QEMU log:    | shutting down, reason=failed                                   |
+|              | qemu-system-s390x: terminating on signal $SIGNAL_NUM from      |
+|              | pid $PID $DAEMON                                               |
++--------------+----------------------------------------------------------------+
+
+
+One or more control domains are not available on the destination host
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The control domains passed through to the source guest are not installed on the
+destination host.
+
+**Source host**
+
++--------------+----------------------------------------------------------------+
+| Log          | Message                                                        |
++==============+================================================================+
+| Console log: | error: operation failed: migration failed. Message from the    |
+|              | source host: operation failed: job 'migration out' failed:     |
+|              | Sibling indicated error 1. Message from the destination host:  |
+|              | operation failed: job 'migration in' failed: load of migration |
+|              | failed: No such device: Failed to load vmstate version_id: 1,  |
+|              | ret: -19                                                       |
++--------------+----------------------------------------------------------------+
+
+**Destination host**
+
++--------------+----------------------------------------------------------------+
+| Kernel log:  | vfio_ap_mdev $UUID: Control domain $DOMAIN_NUM not available   |
+|              | on the destination host                                        |
++--------------+----------------------------------------------------------------+
+| QEMU log:    | shutting down, reason=failed                                   |
+|              | qemu-system-s390x: terminating on signal $SIGNAL_NUM from      |
+|              | pid $PID $DAEMON                                               |
++--------------+----------------------------------------------------------------+
+
+
+.. note::
+   * $UUID is the UUID of the mediated device being migrated from the source host.
+   * $APID.$APQI is adapter number and queue index (domain number) comprising the
+     $APQN (for example, 00.0033) of the queue device that is not available.
+   * $SIGNAL_NUM is the signal number that caused the QEMU process to terminate.
+   * $PID is the process ID of the QEMU process on the destination host.
+   * $DAEMON is the name of the QEMU daemon process.
+   * This message will be logged for each queue for which this error is detected.
+
+Failure to get hardware information for a queue device on destination host
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The vfio_ap device driver on the destination host will execute an AP instruction
+to get the hardware information for a queue device to perform queue compatibility
+checks. The instruction can fail for a number of reasons in which case the
+migration will be terminated.
+
+**Source host**
+
++--------------+----------------------------------------------------------------+
+| Log          | Message                                                        |
++==============+================================================================+
+| Console log: | error: operation failed: migration failed. Message from the    |
+|              | source host: operation failed: job 'migration out' failed:     |
+|              | Sibling indicated error 1. Message from the destination host:  |
+|              | operation failed: job 'migration in' failed: load of migration |
+|              | failed: failed to get hardware information for queue device    |
+|              | $APQN                                                          |
++--------------+----------------------------------------------------------------+
+
+**Destination host**
+
++--------------+----------------------------------------------------------------+
+| Log          | Message                                                        |
++==============+================================================================+
+| Console log: | vfio_ap_mdev $UUID: migration failed: Failed to get hwinfo for |
+|              | queue $APQN on target host: rc=$RESPONSE-CODE                  |
++--------------+----------------------------------------------------------------+
+| QEMU log:    | shutting down, reason=failed                                   |
+|              | qemu-system-s390x: terminating on signal $SIGNAL-ID from pid   |
+|              | $PID $DAEMON                                                   |
++--------------+----------------------------------------------------------------+
+
+.. note::
+   * $UUID is the UUID of the mediated device being migrated from the source host.
+   * $APQN (for example, 00.0033) of the queue device that is not compatible.
+   * $RESPONSE_CODE is the response code from the AP instruction.
+   * $SIGNAL_NUM is the signal number of the signal that caused the QEMU process
+     to terminate.
+   * $PID is the process ID of the QEMU process on the destination host.
+   * $DAEMON is the name of the QEMU daemon process.
+   * This message will be logged for each queue for which this error is detected.
+
+The AP configurations of the source guest and destination host not compatible
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The functional capabilities or facilities available on one or more of the queues
+passed through to the source guest are not compatible with the queue device with
+the same APQN on the destination system (see the Hardware Capabilities table above)
+
+**Source host**
+
++--------------+----------------------------------------------------------------+
+| Log          | Message                                                        |
++==============+================================================================+
+| Console log: | error: operation failed: migration failed. Message from the    |
+|              | source host: operation failed: job 'migration out' failed:     |
+|              | Sibling indicated error 1. Message from the destination host:  |
+|              | operation failed: job 'migration in' failed: load of migration |
+|              | failed: No such device: Failed to load vmstate version_id: 1,  |
+|              | ret: -19                                                       |
++--------------+----------------------------------------------------------------+
+| Kernel log:  | N/A                                                            |
++--------------+----------------------------------------------------------------+
+| QEMU log:    | *initiating migration*                                         |
+|              |                                                                |
+|              | *qemu-system-s390x: Sibling indicated error 1*                 |
++--------------+----------------------------------------------------------------+
+
+**Destination host**
+
++--------------+----------------------------------------------------------------+
+| Log          | Message                                                        |
++==============+================================================================+
+| Console log: | N/A                                                            |
++--------------+----------------------------------------------------------------+
+| Kernel log:  | *vfio_ap_mdev $UUID: Migration failed: Source and target       |
+|              | queue ($APQN) not compatible*                                  |
+|              |                                                                |
+|              | The message above will be followed by one or more messages     |
+|              | enumerating the incompatible features; for example:            |
+|              |                                                                |
+|              | ``vfio_ap_mdev $UUID: APSC facility installed in source queue  |
+|              | $APQN``                                                        |
+|              | ``vfio_ap_mdev $UUID: APSC facility not installed in target    |
+|              | queue $APQN``                                                  |
+|              |                                                                |
+|              | ``AP type of source ($APTYPE1) not compatible with target      |
+|              | ($APTYPE2)`` ...                                               |
++--------------+----------------------------------------------------------------+
+| QEMU log:    | *initiating migration*                                         |
+|              |                                                                |
+|              | *qemu-system-s390x: error while loading state section id ...*  |
+|              |                                                                |
+|              | *shutting down, reason=failed*                                 |
+|              |                                                                |
+|              | *terminating on signal $SIGNAL-ID from pid $PID $DAEMON*       |
++--------------+----------------------------------------------------------------+
+
+.. note::
+   * $UUID is the UUID of the mediated device being migrated from the source host.
+   * $APQN (for example, 00.0033) of the queue device that is incompatible.
+   * $APTYPE1 is the type of the source queue device.
+   * $APTYPE2 is the type of the target queue device.
+   * $SIGNAL-ID is the signal number of the signal that caused the QEMU process
+     to terminate.
+   * $PROCESS-ID is the process ID of the QEMU process on the source host.
+   * $PID is the process ID of the QEMU process on the destination host.
+   * $DAEMON is the name of the QEMU daemon process.
+   * Each follow-on message logging the incompatibility will be logged for each
+     error detected for the specified queue device.
+
+AP Configuration Management
+---------------------------
+The AP configurations of the source guest and destination host must be kept
+in synchronization or live guest migration will likely fail due to potential
+incompatibilities introduced by such changes. In particular, changing adapter
+or domain reservations via the sysfs ``apmask`` or ``aqmask`` attributes on
+either the source or destination host without coordinating such changes between
+the two hosts -especially while a migration is taking place - can result in
+migration failures.
+
+Configuration stability is an orchestration-layer or system administrator
+responsibility, which is consistent with other VFIO device types. The vfio_ap
+device driver will validate source and destination configurations and provide
+clear diagnostics when incompatibilities are detected, enabling orchestration
+tools to implement appropriate policies; for example, blocking migration when
+such changes are to be made.
+
+Master Key administration
+--------------------------
+It is imperative that s390 Common Cryptographic Architecture (CCA) master key
+administration be performed on both the source and destination AP
+devices to synchronize the key values prior to allowing live guest
+migration. If the master keys do not match, then crypto applications that
+rely on secure keys wrapped by a CCA master key will fail when the guest on
+which they are running is migrated to the destination host. Again, this is
+an orchestration-layer or system administrator responsibility and migration must
+be blocked while master key administration is being performed.
diff --git a/drivers/s390/crypto/Makefile b/drivers/s390/crypto/Makefile
index e83c6603c8587..20f29184825a7 100644
--- a/drivers/s390/crypto/Makefile
+++ b/drivers/s390/crypto/Makefile
@@ -34,5 +34,5 @@ pkey-uv-objs := pkey_uv.o
 obj-$(CONFIG_PKEY_UV) += pkey-uv.o
 
 # adjunct processor matrix
-vfio_ap-objs := vfio_ap_drv.o vfio_ap_ops.o
+vfio_ap-objs := vfio_ap_drv.o vfio_ap_ops.o vfio_ap_migration.o
 obj-$(CONFIG_VFIO_AP) += vfio_ap.o
diff --git a/drivers/s390/crypto/vfio_ap_drv.c b/drivers/s390/crypto/vfio_ap_drv.c
index 8e69ed286bb9c..c63a050a23569 100644
--- a/drivers/s390/crypto/vfio_ap_drv.c
+++ b/drivers/s390/crypto/vfio_ap_drv.c
@@ -26,9 +26,21 @@ MODULE_LICENSE("GPL v2");
 struct ap_matrix_dev *matrix_dev;
 debug_info_t *vfio_ap_dbf_info;
 
+#define VFIO_AP_BASE_FEATURES	"guest_matrix hotplug ap_config"
+#define VFIO_AP_SE_EXCLUDED_FEATURES "migration"
+
 static ssize_t features_show(struct device *dev, struct device_attribute *attr, char *buf)
 {
-	return sysfs_emit(buf, "guest_matrix hotplug ap_config\n");
+	/*
+	 * SE guests do not support live guest migration; emit only the base
+	 * feature set for them.
+	 */
+	if (ap_is_se_guest())
+		return sysfs_emit(buf, "%s\n", VFIO_AP_BASE_FEATURES);
+
+	/* Non-SE: base features plus those not available on SE guests */
+	return sysfs_emit(buf, "%s %s\n", VFIO_AP_BASE_FEATURES,
+			  VFIO_AP_SE_EXCLUDED_FEATURES);
 }
 static DEVICE_ATTR_RO(features);
 
diff --git a/drivers/s390/crypto/vfio_ap_migration.c b/drivers/s390/crypto/vfio_ap_migration.c
new file mode 100644
index 0000000000000..7fa58f0868125
--- /dev/null
+++ b/drivers/s390/crypto/vfio_ap_migration.c
@@ -0,0 +1,1494 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Drives vfio_ap mdev migration.
+ *
+ * Copyright IBM Corp. 2025
+ */
+#include <linux/anon_inodes.h>
+#include <linux/file.h>
+#include "vfio_ap_private.h"
+
+/* Magic number and version for the vfio_ap_config migration blob */
+#define VFIO_AP_MIG_MAGIC			0x76666170U  /* "vfap" */
+#define VFIO_AP_MIG_VERSION			1U
+
+/*
+ * Masks the fields of the queue information returned from the PQAP(TAPQ)
+ * command. In order to migrate a guest, it's AP configuration must be
+ * compatible with AP configuration assigned to the target guest's mdev.
+ * This mask is used to verify that the queue information for each source and
+ * target queue is compatible.
+ *
+ * The following bits must match for the source device and the corresponding
+ * destination device:
+ * -------------------------------------------------------------------------
+ * S bit 0: APSC  facility installed
+ * M bit 1: APQKM facility installed
+ * C bit 2: AP4KC facility installed
+ * Mode bits 3-5:
+ *     D bit 3: CCA-mode facility
+ *     A bit 4: accelerator-mode facility
+ *     X bit 5: XCP-mode facility
+ * N  bit 6: APXA facility installed
+ * SL bit 7: SLCF facility installed
+ *
+ * Either bit 8 or bit 9 will be set. If bit 8 is set for the source device,
+ * then it must also be set for the corresponding destination device:
+ * -------------------------------------------------------------------------
+ * Classification (functional capabilities) bits 8-16
+ *     bit 8: Native card function
+ *     bit 9: Only stateless functions
+ *
+ * The BS bits must be set to 0 for both the source and corresponding
+ * destination device:
+ * -------------------------------------------------------------------------
+ * BS bits 16-17:
+ *
+ * The AP type of the source device must be less than or equal to that of
+ * the corresponding destination device:
+ * -------------------------------------------------------------------------
+ * AP Type bits 32-40:
+ */
+#define QINFO_DATA_MASK		0xffffc000ff000000
+
+/*
+ * Masks the bit that indicates whether full native card function is available
+ * from the 8 bits specifying the functional capabilities of a queue
+ */
+#define CLASSIFICATION_NATIVE_FCN_MASK		0x80
+
+/* The maximum number of queues that can be installed in an s390 system */
+#define MAX_AP_QUEUES				(AP_DEVICES * AP_DOMAINS)
+
+/* The maximum size of a vfio_ap_config blob, used to pre-allocate the receive
+ * buffer on the destination host during the RESUMING phase of migration.
+ */
+#define VFIO_AP_CONFIG_MAX_SIZE \
+	(sizeof(struct vfio_ap_config) + \
+	 MAX_AP_QUEUES * sizeof(struct vfio_ap_queue_info))
+
+/**
+ * struct vfio_ap_migration_file
+ *
+ * This object is used for chunk processing of multiple reads and writes of
+ * AP configuration information.
+ *
+ * @filp:	file stream used to read or write AP configuration data
+ * @ap_config:	object used to store AP configuration data between read or write
+ *		calls
+ * @config_sz:	the size (in bytes) of @ap_config
+ */
+struct vfio_ap_migration_file {
+	struct file		*filp;
+	struct vfio_ap_config	*ap_config;
+	unsigned long		config_sz;
+};
+
+/**
+ * struct vfio_ap_migration_data:
+ *
+ * Manages the migration state for the VFIO device that maintains the AP
+ * configuration of the guest being migrated.
+ *
+ * @mig_state:		the current migration state
+ * @resuming_mig_file:	the object used to restore the state of the vfio-ap
+ *			device on the destination host.
+ * @stop_copy_mig_file:	the object used to store the AP configuration of the
+ *			source guest for transfer to the destination host.
+ */
+struct vfio_ap_migration_data {
+	enum vfio_device_mig_state	mig_state;
+	struct vfio_ap_migration_file	resuming_mig_file;
+	struct vfio_ap_migration_file	stop_copy_mig_file;
+};
+
+/**
+ * struct vfio_ap_queue_info - the information for an AP queue
+ *
+ * @data: contains the queue information returned in GR2 from the PQAP(TAPQ)
+ *	  command
+ * @apqn: the APQN of the queue
+ * @reserved: padding to ensure consistent structure size across platforms
+ */
+struct vfio_ap_queue_info {
+	u64 data;
+	u16 apqn;
+	u8  reserved[6];
+};
+
+/**
+ * struct vfio_ap_config:
+ *
+ * Stores the state of a guest's AP configuration.
+ *
+ * VFIO device migration state transition from STOP to STOP_COPY:
+ * -------------------------------------------------------------
+ * When the migration state transitions from STOP to STOP_COPY, the vfio_ap device
+ * driver will open a file stream in read-only mode and return the fd to userspace.
+ * This fd is used during the STOP_COPY phase to read the current state of the
+ * vfio-ap device on the source host. In response, the driver will store the
+ * source guest's AP configuration data in a vfio_ap_config object and copy it to
+ * userspace.
+ *
+ * VFIO device migration state transition from STOP to RESUMING:
+ * ------------------------------------------------------------
+ * When the VFIO migration state transitions from STOP to RESUMING,
+ * the vfio_ap device driver will open a file stream in write-only mode and
+ * return the fd to userspace. This fd is used during the RESUMING phase to
+ * write the source guest's vfio_ap_config data that was read in during the
+ * STOP_COPY phase to the vfio_ap device driver on the destination host. In
+ * response, the device driver will copy the data sent from userspace to a
+ * vfio_ap_config instance which is then used to update the destination guest's
+ * AP configuration.
+ *
+ * Since the source and destination hosts may be running different versions of
+ * the linux kernel, the vfio_ap_config object provides two fields (@magic and
+ * @version) which must be set by the source device driver and verified by the
+ * destination device driver to ensure the migration ABI of the source and
+ * destination hosts are compatible.
+ *
+ * Note: Since a guest's AP configuration could be comprised of a large number of
+ *	 AP queue devices, a vfio_ap_config object should be allocated using
+ *	 kvzalloc.
+ *
+ * @magic:	identifies this as a valid vfio_ap_config migration blob;
+ *		must equal VFIO_AP_MIG_MAGIC
+ * @version:	layout version; must equal VFIO_AP_MIG_VERSION
+ * @num_queues:	the number of queues passed through to the guest
+ * @reserved:	padding to ensure proper alignment of @adm
+ * @adm:	bitmap specifying the control domains in the AP configuration
+ * @qinfo:	an array of vfio_ap_queue_info objects, each specifying the
+ *		queue information for a queue passed through to the guest
+ */
+struct vfio_ap_config {
+	u32				magic;
+	u32				version;
+	u32				num_queues;
+	u8				reserved[4];
+	u64				adm[DIV_ROUND_UP(AP_DOMAINS, 64)];
+	struct vfio_ap_queue_info	qinfo[] __counted_by(num_queues);
+};
+
+static void
+vfio_ap_release_stop_copy_file(struct vfio_ap_migration_data *mig_data)
+{
+	kvfree(mig_data->stop_copy_mig_file.ap_config);
+	mig_data->stop_copy_mig_file.ap_config = NULL;
+	mig_data->stop_copy_mig_file.config_sz = 0;
+	mig_data->stop_copy_mig_file.filp = NULL;
+}
+
+static void vfio_ap_release_resuming_file(struct vfio_ap_migration_data *mig_data)
+{
+	kvfree(mig_data->resuming_mig_file.ap_config);
+	mig_data->resuming_mig_file.ap_config = NULL;
+	mig_data->resuming_mig_file.config_sz = 0;
+	mig_data->resuming_mig_file.filp = NULL;
+}
+
+static void vfio_ap_release_mig_files(struct ap_matrix_mdev *matrix_mdev);
+
+static int vfio_ap_release_mig_file(struct inode *file_inode, struct file *filp)
+{
+	struct ap_matrix_mdev *matrix_mdev = filp->private_data;
+
+	/*
+	 * The VFIO device lifetime is tied to migration FD lifetime (see
+	 * vfio_ap_open_file_stream() function) to guarantee that the
+	 * matrix_mdev remains valid for every read/write operation. Let's drop
+	 * it here since the migration FD is being released.
+	 */
+	vfio_device_put_registration(&matrix_mdev->vdev);
+	return 0;
+}
+
+/**
+ * validate_stop_copy_read_parms: Validate the input parameters to the
+ *                                vfio_ap_stop_copy_read function
+ *
+ * @filp: Pointer to the file stream used to read the vfio-ap device state
+ * @len:  The length of the data to be read
+ *
+ * Verify the following:
+ * - @filp private data is an ap_matrix_mdev instance
+ * - @filp is the instance opened when state transitioned from STOP to STOP_COPY
+ * - @filp->f_pos + @len does not cause integer overflow
+ *
+ * Returns: 0 if the parameters pass validation; otherwise returns an error
+ */
+static int validate_stop_copy_read_parms(struct file *filp, size_t len)
+{
+	struct vfio_ap_migration_data *mig_data;
+	struct ap_matrix_mdev *matrix_mdev;
+	loff_t total_len;
+
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	if (check_add_overflow((loff_t)len, filp->f_pos, &total_len))
+		return -EIO;
+
+	/*
+	 * matrix_mdev is guaranteed live here: vfio_ap_open_file_stream() took
+	 * a vfio_device registration reference that is held until
+	 * vfio_ap_release_mig_file() runs, so the embedding matrix_mdev cannot
+	 * be freed while this file descriptor is open.
+	 */
+	matrix_mdev = filp->private_data;
+
+	if (!matrix_mdev->mig_data)
+		return -ENODEV;
+
+	mig_data = matrix_mdev->mig_data;
+
+	if (mig_data->stop_copy_mig_file.filp != filp)
+		return -EINVAL;
+
+	return 0;
+}
+
+static size_t vfio_ap_config_size(struct ap_matrix_mdev *matrix_mdev,
+				  int *num_queues)
+{
+	size_t qinfo_size;
+
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	*num_queues = vfio_ap_mdev_get_num_queues(&matrix_mdev->shadow_apcb);
+	qinfo_size = *num_queues * sizeof(struct vfio_ap_queue_info);
+
+	return qinfo_size + sizeof(struct vfio_ap_config);
+}
+
+static int get_hardware_info_for_queue(const char *mdev_name,
+				       struct ap_tapq_hwinfo *hwinfo,
+				       unsigned long apqn)
+{
+	struct ap_queue_status status;
+
+	status = ap_tapq(apqn, hwinfo);
+
+	switch (status.response_code) {
+	case AP_RESPONSE_NORMAL:
+	case AP_RESPONSE_RESET_IN_PROGRESS:
+	case AP_RESPONSE_DECONFIGURED:
+	case AP_RESPONSE_CHECKSTOPPED:
+	case AP_RESPONSE_BUSY:
+		/* For all these RCs the tapq info should be available */
+		return 0;
+	case AP_RESPONSE_Q_NOT_AVAIL:
+		pr_err_ratelimited("vfio_ap_mdev %s: Failed to get hwinfo for queue %02lx.%04lx: TAPQ rc=%d\n",
+				   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn),
+				   status.response_code);
+		return -ENODEV;
+	default:
+		/*
+		 * Without a pending async error, the tapq info should be
+		 * available
+		 */
+		if (status.async)
+			return 0;
+
+		pr_err_ratelimited("vfio_ap_mdev %s: Failed to get hwinfo for queue %02lx.%04lx: TAPQ rc=%d\n",
+				   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn),
+				   status.response_code);
+		return -EIO;
+	}
+}
+
+/**
+ * vfio_ap_store_queue_info:
+ *
+ * Stores the hardware information returned from the PQAP(TAPQ) command for each
+ * queue device identified in the 'qinfo' field of the a vfio_ap_config
+ * object. The APQNs in the 'qinfo' field must already have been snapshotted
+ * prior to calling this function.
+ *
+ * @mdev_name:	The name (UUID) of the mediated device to use in log messages
+ * @ap_config:	A reference to the vfio_ap_config instance in which to store
+ *		the queue information. It is expected that each APQN identifying
+ *		a queue device for which hardware information is to be retrieved
+ *		shall be snapshotted prior to calling this function.
+ *
+ * Returns:	Zero (0) if the hardware information is retrieved for each queue
+ *		device in the AP configuration; otherwise, returns an error.
+ */
+static int vfio_ap_store_queue_info(const char *mdev_name,
+				    struct vfio_ap_config *ap_config)
+{
+	struct ap_tapq_hwinfo source_hwinfo;
+	unsigned long num_queues;
+	int ret;
+
+	for (num_queues = 0; num_queues < ap_config->num_queues; num_queues++) {
+		ret = get_hardware_info_for_queue(mdev_name, &source_hwinfo,
+						  ap_config->qinfo[num_queues].apqn);
+		if (ret)
+			return ret;
+
+		ap_config->qinfo[num_queues].data = source_hwinfo.value;
+	}
+
+	return 0;
+}
+
+static int vfio_ap_get_config(struct ap_matrix_mdev *matrix_mdev)
+{
+	struct vfio_ap_config *ap_configuration;
+	unsigned long *apm, *aqm, apid, apqi;
+	unsigned int num_queues;
+	const char *mdev_name;
+	size_t ap_config_size;
+	int ret, qindex;
+
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	ap_config_size = vfio_ap_config_size(matrix_mdev, &num_queues);
+
+	ap_configuration = kvzalloc(ap_config_size, GFP_KERNEL_ACCOUNT);
+	if (!ap_configuration)
+		return -ENOMEM;
+
+	ap_configuration->magic   = VFIO_AP_MIG_MAGIC;
+	ap_configuration->version = VFIO_AP_MIG_VERSION;
+
+	/*
+	 * num_queues must be set before writing qinfo[] elements; the
+	 * __counted_by(num_queues) annotation on qinfo[] causes the compiler to
+	 * insert bounds checks that evaluate against ap_configuration->num_queues.
+	 * Writing through qinfo[i] with num_queues still 0 would trap.
+	 */
+	ap_configuration->num_queues = num_queues;
+
+	apm = matrix_mdev->shadow_apcb.apm;
+	aqm = matrix_mdev->shadow_apcb.aqm;
+	qindex = 0;
+	for_each_set_bit_inv(apid, apm, AP_DEVICES) {
+		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS) {
+			ap_configuration->qinfo[qindex].apqn =
+				AP_MKQID(apid, apqi);
+			qindex += 1;
+		}
+	}
+	memcpy(ap_configuration->adm, matrix_mdev->shadow_apcb.adm,
+	       sizeof(ap_configuration->adm));
+	mdev_name = dev_name(matrix_mdev->vdev.dev);
+
+	ret = vfio_ap_store_queue_info(mdev_name, ap_configuration);
+	if (ret) {
+		kvfree(ap_configuration);
+		return ret;
+	}
+
+	matrix_mdev->mig_data->stop_copy_mig_file.ap_config = ap_configuration;
+	matrix_mdev->mig_data->stop_copy_mig_file.config_sz = ap_config_size;
+
+	return 0;
+}
+
+static ssize_t vfio_ap_stop_copy_read(struct file *filp, char __user *buf,
+				      size_t len, loff_t *pos)
+{
+	struct vfio_ap_migration_file *mig_file;
+	struct ap_matrix_mdev *matrix_mdev;
+	loff_t read_pos;
+	ssize_t ret;
+
+	/*
+	 * This file was opened with stream_open(), so pos should be NULL for
+	 * sequential read() calls; a non-NULL pointer will be passed only
+	 * for positional pread() calls in which case we return an error
+	 * indicating broken pipe/illegal seek on a non-seekable file
+	 */
+	if (pos)
+		return -ESPIPE;
+
+	mutex_lock(&matrix_dev->mdevs_lock);
+
+	pos = &filp->f_pos;
+
+	ret = validate_stop_copy_read_parms(filp, len);
+	if (ret) {
+		mutex_unlock(&matrix_dev->mdevs_lock);
+		return ret;
+	}
+
+	matrix_mdev = filp->private_data;
+	mig_file = &matrix_mdev->mig_data->stop_copy_mig_file;
+
+	/*
+	 * Lazy initialization: the migration config is generated on the first
+	 * read() call. vfio_ap_open_file_stream() initializes ap_config to NULL
+	 * and config_sz to 0. On first read, we generate the config by
+	 * snapshotting the guest's APQNs from shadow_apcb and retrieving hardware
+	 * info via TAPQ for each queue. The result is cached in mig_file->ap_config
+	 * for subsequent read() calls. The config is freed when the migration FD
+	 * is released (vfio_ap_release_mig_file -> vfio_ap_release_stop_copy_file).
+	 */
+	if (!mig_file->ap_config) {
+		ret = vfio_ap_get_config(matrix_mdev);
+		if (ret) {
+			mutex_unlock(&matrix_dev->mdevs_lock);
+			return ret;
+		}
+	}
+
+	/*
+	 * Compute the offset and clamped length fully under the lock so that
+	 * concurrent read()s on this stream file each see a consistent view of
+	 * the current position.  *pos is advanced here while we still hold the
+	 * lock; copy_to_user() then uses the snapshot read_pos.  This prevents
+	 * two threads from calculating the same offset and both copying the
+	 * same region (or one reading past the end of the buffer).
+	 */
+	if (*pos >= mig_file->config_sz) {
+		mutex_unlock(&matrix_dev->mdevs_lock);
+		return 0;
+	}
+
+	len = min_t(size_t, mig_file->config_sz - *pos, len);
+	if (len == 0) {
+		mutex_unlock(&matrix_dev->mdevs_lock);
+		return 0;
+	}
+
+	read_pos = *pos;
+	*pos += len;
+
+	/*
+	 * Keep mdevs_lock held across copy_to_user() to prevent a concurrent
+	 * vfio_ap_reset_migration_state() from freeing ap_config while we are
+	 * reading it.  copy_to_user() may fault on a non-resident user page,
+	 * but that is legal for a sleeping mutex.  The data transferred is at
+	 * most a few KB for any realistic AP configuration, so holding the lock
+	 * here is acceptable.
+	 */
+	if (copy_to_user(buf, (char *)mig_file->ap_config + read_pos, len)) {
+		mutex_unlock(&matrix_dev->mdevs_lock);
+		return -EFAULT;
+	}
+
+	mutex_unlock(&matrix_dev->mdevs_lock);
+
+	return len;
+}
+
+static const struct file_operations vfio_ap_stop_copy_fops = {
+	.owner = THIS_MODULE,
+	.read = vfio_ap_stop_copy_read,
+	.compat_ioctl = compat_ptr_ioctl,
+	.release = vfio_ap_release_mig_file,
+};
+
+static struct file *vfio_ap_open_file_stream(struct ap_matrix_mdev *matrix_mdev,
+					     const struct file_operations *fops,
+					     int flags)
+{
+	struct file *filp;
+
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	/*
+	 * Pin the vfio_device registration so that matrix_mdev cannot be freed
+	 * while the migration FD is still open. The matching put is in
+	 * vfio_ap_release_mig_file().
+	 */
+	if (!vfio_device_try_get_registration(&matrix_mdev->vdev))
+		return ERR_PTR(-ENODEV);
+
+	filp = anon_inode_getfile("vfio_ap_mig_file", fops, matrix_mdev, flags);
+	if (IS_ERR(filp)) {
+		vfio_device_put_registration(&matrix_mdev->vdev);
+		return filp;
+	}
+
+	stream_open(filp->f_inode, filp);
+
+	return filp;
+}
+
+static int validate_resuming_write_parms(struct file *filp, size_t len)
+{
+	struct vfio_ap_migration_data *mig_data;
+	struct ap_matrix_mdev *matrix_mdev;
+	loff_t total_len;
+
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	if (!len || filp->f_pos < 0)
+		return -EINVAL;
+
+	if (check_add_overflow((loff_t)len, filp->f_pos, &total_len))
+		return -ERANGE;
+
+	matrix_mdev = filp->private_data;
+	if (!matrix_mdev || !matrix_mdev->mig_data)
+		return -ENODEV;
+
+	mig_data = matrix_mdev->mig_data;
+
+	if (filp != mig_data->resuming_mig_file.filp)
+		return -ENXIO;
+
+	/* Reject writes that would overflow the pre-allocated buffer */
+	if (filp->f_pos + len > VFIO_AP_CONFIG_MAX_SIZE)
+		return -EIO;
+
+	return 0;
+}
+
+/**
+ * qdev_is_bound_to_vfio_ap:
+ *
+ * Query to determine whether a queue with the specified APQN is available on
+ * the host system and bound to the vfio_ap device driver.
+ *
+ * @apqn: The APQN of the queue device being queried
+ *
+ * Returns: True if there is a queue device with the specified @apqn installed
+ *	    in the system and is bound to the vfio_ap device driver; otherwise,
+ *	    returns false.
+ */
+static bool qdev_is_bound_to_vfio_ap(unsigned int apqn)
+{
+	struct ap_queue *queue;
+	bool is_bound = true;
+
+	queue = ap_get_qdev(apqn);
+	if (!queue)
+		return false;
+
+	if (queue->ap_dev.device.driver != &matrix_dev->vfio_ap_drv->driver)
+		is_bound = false;
+
+	put_device(&queue->ap_dev.device);
+
+	return is_bound;
+}
+
+/**
+ * queues_available:
+ *
+ * Query whether each queue from the source guest's AP configuration is
+ * available and bound to the vfio_ap device driver; if not, log an error
+ * message.
+ *
+ * @mdev_name:	   The mdev name to use in error messages
+ * @source_config: The object specifying the source guest's AP configuration
+ *
+ * Returns: true if each queue identified in @source_config is available and
+ *	    bound to the vfio_ap device driver; otherwise, returns false.
+ */
+static bool queues_available(const char *mdev_name,
+			     struct vfio_ap_config *source_config)
+{
+	unsigned long apqn;
+	bool ret = true;
+
+	for (int i = 0; i < source_config->num_queues; i++) {
+		apqn = source_config->qinfo[i].apqn;
+
+		/*
+		 * Find the queue device bound to the vfio_ap device driver. If it is
+		 * not found, log an error and continue so users see all problems
+		 * at once, not one-at-a-time through retries of the migration.
+		 */
+		if (!qdev_is_bound_to_vfio_ap(apqn)) {
+			pr_err_ratelimited("vfio_ap_mdev %s: Queue %02lx.%04lx not available to vfio_ap driver on target host\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+			ret = false;
+		}
+	}
+
+	return ret;
+}
+
+/**
+ * control_domains_available
+ *
+ * Query whether each control domain specified in the source guest's AP
+ * configuration is installed in the host system.
+ *
+ * @mdev_name:		The name of the mdev to use when logging messages
+ * @source_config:	The object specifying the source guest's AP config
+ *
+ * Returns:	True if each control domain is installed; otherwise, logs an
+ *		error message for each unavailable control domain and returns
+ *		false.
+ */
+static bool control_domains_available(const char *mdev_name,
+				      struct vfio_ap_config *source_config)
+{
+	unsigned long domain_num;
+	bool available = true;
+
+	for_each_set_bit_inv(domain_num, (unsigned long *)source_config->adm,
+			     AP_DOMAINS) {
+		if (ap_test_config_ctrl_domain(domain_num))
+			continue;
+
+		pr_err_ratelimited("vfio_ap_mdev: %s: Control domain %04lx not available on the destination host\n",
+				   mdev_name, domain_num);
+		available = false;
+	}
+
+	return available;
+}
+
+static void report_facilities_compatibility(const char *mdev_name,
+					    unsigned long apqn,
+					    struct ap_tapq_hwinfo *src_hwinfo,
+					    struct ap_tapq_hwinfo *target_hwinfo)
+{
+	if (src_hwinfo->apsc != target_hwinfo->apsc) {
+		if (src_hwinfo->apsc) {
+			pr_err_ratelimited("vfio_ap_mdev %s: APSC facility installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: APSC facility not installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		} else {
+			pr_err_ratelimited("vfio_ap_mdev %s: APSC facility not installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: APSC facility installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		}
+	}
+
+	if (src_hwinfo->mex4k != target_hwinfo->mex4k) {
+		if (src_hwinfo->mex4k) {
+			pr_err_ratelimited("vfio_ap_mdev %s: mex4k facility installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: mex4k facility not installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		} else {
+			pr_err_ratelimited("vfio_ap_mdev %s: mex4k facility not installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: mex4k facility installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		}
+	}
+
+	if (src_hwinfo->crt4k != target_hwinfo->crt4k) {
+		if (src_hwinfo->crt4k) {
+			pr_err_ratelimited("vfio_ap_mdev %s: crt4k facility installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: crt4k facility not installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		} else {
+			pr_err_ratelimited("vfio_ap_mdev %s: crt4k facility not installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: crt4k facility installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		}
+	}
+}
+
+static void report_mode_compatibility(const char *mdev_name,
+				      unsigned long apqn,
+				      struct ap_tapq_hwinfo *src_hwinfo,
+				      struct ap_tapq_hwinfo *target_hwinfo)
+{
+	if (src_hwinfo->cca != target_hwinfo->cca) {
+		if (src_hwinfo->cca) {
+			pr_err_ratelimited("vfio_ap_mdev %s: Coprocessor-mode facility installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: Coprocessor-mode facility not installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		} else {
+			pr_err_ratelimited("vfio_ap_mdev %s: Coprocessor-mode facility not installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: Coprocessor-mode facility installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		}
+	}
+
+	if (src_hwinfo->accel != target_hwinfo->accel) {
+		if (src_hwinfo->accel) {
+			pr_err_ratelimited("vfio_ap_mdev %s: Accelerator-mode facility installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: Accelerator-mode facility not installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		} else {
+			pr_err_ratelimited("vfio_ap_mdev %s: Accelerator-mode facility not installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: Accelerator-mode facility installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		}
+	}
+
+	if (src_hwinfo->ep11 != target_hwinfo->ep11) {
+		if (src_hwinfo->ep11) {
+			pr_err_ratelimited("vfio_ap_mdev %s: XCP-mode facility installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: XCP-mode facility not installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		} else {
+			pr_err_ratelimited("vfio_ap_mdev %s: XCP-mode facility not installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: XCP-mode facility installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		}
+	}
+}
+
+static void report_apxa_compatibility(const char *mdev_name,
+				      unsigned long apqn,
+				      struct ap_tapq_hwinfo *src_hwinfo,
+				      struct ap_tapq_hwinfo *target_hwinfo)
+{
+	if (src_hwinfo->apxa != target_hwinfo->apxa) {
+		if (src_hwinfo->apxa) {
+			pr_err_ratelimited("vfio_ap_mdev %s: AP-extended-addressing (APXA) facility installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: AP-extended-addressing (APXA) facility not installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		} else {
+			pr_err_ratelimited("vfio_ap_mdev %s: AP-extended-addressing (APXA) facility not installed in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: AP-extended-addressing (APXA) facility installed in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		}
+	}
+}
+
+static void report_slcf_compatibility(const char *mdev_name,
+				      unsigned long apqn,
+				      struct ap_tapq_hwinfo *src_hwinfo,
+				      struct ap_tapq_hwinfo *target_hwinfo)
+{
+	if (src_hwinfo->slcf != target_hwinfo->slcf) {
+		if (src_hwinfo->slcf) {
+			pr_err_ratelimited("vfio_ap_mdev %s: Stateless-command-filtering (SLCF) available in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: Stateless-command-filtering (SLCF) not available in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		} else {
+			pr_err_ratelimited("vfio_ap_mdev %s: Stateless-command-filtering (SLCF) not available in source queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+			pr_err_ratelimited("vfio_ap_mdev %s: Stateless-command-filtering (SLCF) available in target queue %02lx.%04lx\n",
+					   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+		}
+	}
+}
+
+static void report_bs_compatibility(const char *mdev_name,
+				    unsigned long apqn,
+				    struct ap_tapq_hwinfo *src_hwinfo,
+				    struct ap_tapq_hwinfo *target_hwinfo)
+{
+	/*
+	 * The BS field on both the source and destination must be 0, so if one
+	 * of them is not, then report an error.
+	 */
+	if (src_hwinfo->bs || target_hwinfo->bs) {
+		pr_err_ratelimited("vfio_ap_mdev %s: Bind/associate state for source (%01x) and target (%01x) queue %02lx.%04lx must be 0\n",
+				   mdev_name, src_hwinfo->bs, target_hwinfo->bs,
+				   AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+	}
+}
+
+static void report_aptype_compatibility(const char *mdev_name,
+					unsigned long apqn,
+					struct ap_tapq_hwinfo *src_hwinfo,
+					struct ap_tapq_hwinfo *target_hwinfo)
+{
+	if (src_hwinfo->at > target_hwinfo->at) {
+		pr_err_ratelimited("vfio_ap_mdev %s: AP type of source (%02x) not compatible with target (%02x)\n",
+				   mdev_name, src_hwinfo->at, target_hwinfo->at);
+	}
+}
+
+static bool classes_compatible(struct ap_tapq_hwinfo *src_hwinfo,
+			       struct ap_tapq_hwinfo *target_hwinfo)
+{
+	unsigned long src_native, target_native;
+
+	src_native = src_hwinfo->class & CLASSIFICATION_NATIVE_FCN_MASK;
+	target_native = target_hwinfo->class & CLASSIFICATION_NATIVE_FCN_MASK;
+
+	/*
+	 * If the source queue has full native card function and the
+	 * target queue has only stateless functions available, then
+	 * there may be instructions that will not execute on the
+	 * target queue. This shall be reported as an error.
+	 *
+	 * If the source queue has only stateless card functions and the
+	 * target queue has full native card function available, then
+	 * we are okay because the target queue can run all stateless card
+	 * functions.
+	 */
+	return (src_native != target_native) ? !src_native : true;
+}
+
+static void report_class_compatibility(const char *mdev_name,
+				       unsigned long apqn,
+				       struct ap_tapq_hwinfo *src_hwinfo,
+				       struct ap_tapq_hwinfo *target_hwinfo)
+{
+	if (!classes_compatible(src_hwinfo, target_hwinfo)) {
+		pr_err_ratelimited("vfio_ap_mdev %s: Full native card function available on source queue %02lx.%04lx\n",
+				   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+		pr_err_ratelimited("vfio_ap_mdev %s: Only stateless functions available on target queue %02lx.%04lx\n",
+				   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+	}
+}
+
+/*
+ * Log a device error reporting that migration failed due to queue
+ * incompatibilities followed by a device error for each incompatible feature.
+ */
+static void report_qinfo_incompatibilities(const char *mdev_name,
+					   unsigned long apqn,
+					   struct ap_tapq_hwinfo *src_hwinfo,
+					   struct ap_tapq_hwinfo *target_hwinfo)
+{
+	pr_err_ratelimited("vfio_ap_mdev %s: Migration failed: Source and target queue (%02lx.%04lx) not compatible\n",
+			   mdev_name, AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+	report_facilities_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);
+	report_mode_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);
+	report_apxa_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);
+	report_slcf_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);
+	report_aptype_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);
+	report_bs_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);
+	report_class_compatibility(mdev_name, apqn, src_hwinfo, target_hwinfo);
+}
+
+/**
+ * queue_hardware_info_is_compatible:
+ *
+ * Verify whether the hardware information for a source queue is compatible with
+ * the hardware info for the corresponding queue on this system.
+ *
+ * In order to be compatible, the hardware information for each queue must
+ * meet the following requirements:
+ *
+ * 1. The hardware facilities bits much match
+ * 2. The AP type of the source queue must be the same as or older than that
+ *    of the target queue (target is backwards compatible)
+ * 3. The classification bits must indicate:
+ *    - Both queues have full native card function or both have stateless
+ *      functions available
+ *    - If the classification bits don't match, then the only acceptable
+ *      configuration is stateless functions for the source queue and
+ *      full native function for the target queue
+ * 4. The BS bits for both queues must be 0 (Queue usable for all messages
+ *    supported by the adapter)
+ *
+ * @mdev_name:	The mdev name to use in error messages
+ * @apqn:	The APQN for the queues
+ * @src_hwinfo: The hardware info for the source queue
+ * @target_hwinfo: The hardware info for the corresponding queue on this system
+ *
+ * Returns: true if the hardware info for the two queues is compatible;
+ *          otherwise, returns false.
+ */
+static bool queue_hardware_info_is_compatible(const char *mdev_name,
+					      unsigned long apqn,
+					      struct ap_tapq_hwinfo *src_hwinfo,
+					      struct ap_tapq_hwinfo *target_hwinfo)
+{
+	unsigned long src_bits, target_bits;
+
+	src_bits = src_hwinfo->value & QINFO_DATA_MASK;
+	target_bits = target_hwinfo->value & QINFO_DATA_MASK;
+
+	/* If all bits match the queues are compatible */
+	if (src_bits == target_bits &&
+	    (src_hwinfo->bs == 0 && target_hwinfo->bs == 0))
+		return true;
+
+	if (src_hwinfo->apsc  == target_hwinfo->apsc     &&
+	    src_hwinfo->mex4k == target_hwinfo->mex4k    &&
+	    src_hwinfo->crt4k == target_hwinfo->crt4k    &&
+	    src_hwinfo->cca   == target_hwinfo->cca      &&
+	    src_hwinfo->accel == target_hwinfo->accel    &&
+	    src_hwinfo->ep11  == target_hwinfo->ep11     &&
+	    src_hwinfo->slcf  == target_hwinfo->slcf     &&
+	    src_hwinfo->apxa  == target_hwinfo->apxa     &&
+	    src_hwinfo->at    <= target_hwinfo->at       &&
+	    classes_compatible(src_hwinfo, target_hwinfo) &&
+	    (src_hwinfo->bs == 0 && target_hwinfo->bs == 0))
+		return true;
+
+	report_qinfo_incompatibilities(mdev_name, apqn, src_hwinfo, target_hwinfo);
+
+	return false;
+}
+
+/**
+ * verify_ap_configs_are_compatible:
+ *
+ * Verifies that the queues in the source guest's AP configuration are
+ * compatible with the corresponding queues on this system.
+ *
+ * @mdev_name:	   The mdev name to use in error messages
+ * @source_config: The object specifying the source guest's AP configuration
+ *
+ * Returns: an error indicating either a failure to retrieve a queue's
+ *			hardware information or one or more source queues are not
+ *			compatible with the corresponding queue on this system; otherwise,
+ *			returns zero to indicate compatibility.
+ */
+static int verify_ap_configs_are_compatible(const char *mdev_name,
+					    struct vfio_ap_config *source_config)
+{
+	struct ap_tapq_hwinfo src_hwinfo, dest_hwinfo;
+	unsigned long apqn;
+	int ret = 0, rc;
+
+	for (int i = 0; i < source_config->num_queues; i++) {
+		apqn = source_config->qinfo[i].apqn;
+
+		/*
+		 * If we can't get the hardware info for a particular queue, then let's
+		 * capture the function return code and continue so we can log all
+		 * errors to aid in debugging of migration.
+		 */
+		rc = get_hardware_info_for_queue(mdev_name, &dest_hwinfo, apqn);
+		if (rc) {
+			ret = rc;
+			continue;
+		}
+
+		src_hwinfo.value =  source_config->qinfo[i].data;
+
+		if (!queue_hardware_info_is_compatible(mdev_name, apqn,
+						       &src_hwinfo,
+						       &dest_hwinfo))
+			ret = -EINVAL;
+	}
+
+	return ret;
+}
+
+static int do_post_copy_validation(const char *mdev_name,
+				   struct vfio_ap_config *source_config)
+{
+	if (source_config->magic != VFIO_AP_MIG_MAGIC ||
+	    source_config->version != VFIO_AP_MIG_VERSION)
+		return -EINVAL;
+
+	if (!queues_available(mdev_name, source_config))
+		return -ENODEV;
+
+	if (!control_domains_available(mdev_name, source_config))
+		return -ENODEV;
+
+	return verify_ap_configs_are_compatible(mdev_name, source_config);
+}
+
+/**
+ * setup_ap_matrix_from_ap_config:
+ *
+ * Set the bits corresponding to the adapters, domains and control domains
+ * from the source guest's AP configuration into an ap_matrix object to be
+ * used to update the destination guest to run on this host.
+ *
+ * @ap_config:		The source guest's AP configuration
+ * @guest_matrix:	The object to be used to update the destination guest's
+ *			AP configuration
+ */
+static void setup_ap_matrix_from_ap_config(struct vfio_ap_config *ap_config,
+					   struct ap_matrix *guest_matrix)
+{
+	struct ap_config_info host_config_info = { 0 };
+	unsigned long apid, apqi, *guest_adm;
+	struct vfio_ap_queue_info qinfo;
+
+	ap_qci(&host_config_info);
+	/*
+	 * Zero the bitmaps before calling vfio_ap_matrix_init(), which only
+	 * sets the apm_max/aqm_max/adm_max scalar fields and leaves the bitmap
+	 * arrays untouched.  Without this, stack garbage in guest_matrix->apm,
+	 * ->aqm, and ->adm would grant the destination guest access to
+	 * arbitrary unassigned queues and control domains.
+	 */
+	memset(guest_matrix->apm, 0, sizeof(guest_matrix->apm));
+	memset(guest_matrix->aqm, 0, sizeof(guest_matrix->aqm));
+	memset(guest_matrix->adm, 0, sizeof(guest_matrix->adm));
+	vfio_ap_matrix_init(&host_config_info, guest_matrix);
+
+	for (int i = 0; i < ap_config->num_queues; i++) {
+		qinfo = ap_config->qinfo[i];
+		apid = AP_QID_CARD(qinfo.apqn);
+		apqi = AP_QID_QUEUE(qinfo.apqn);
+
+		if (!test_bit_inv(apid, guest_matrix->apm))
+			set_bit_inv(apid, guest_matrix->apm);
+		if (!test_bit_inv(apqi, guest_matrix->aqm))
+			set_bit_inv(apqi, guest_matrix->aqm);
+	}
+
+	guest_adm = (unsigned long *)ap_config->adm;
+	for_each_set_bit_inv(apqi, guest_adm, AP_DOMAINS) {
+		if (!test_bit_inv(apqi, guest_matrix->adm))
+			set_bit_inv(apqi, guest_matrix->adm);
+	}
+}
+
+static int do_post_copy_processing(struct ap_matrix_mdev *matrix_mdev,
+				   struct vfio_ap_config *ap_config)
+{
+	const char *mdev_name = dev_name(matrix_mdev->vdev.dev);
+	struct ap_matrix guest_matrix;
+	int ret;
+
+	lockdep_assert_held(&ap_attr_mutex);
+	assert_has_update_locks_for_mdev(matrix_mdev);
+
+	ret = do_post_copy_validation(mdev_name, ap_config);
+	if (ret)
+		return ret;
+
+	setup_ap_matrix_from_ap_config(ap_config, &guest_matrix);
+
+	return vfio_ap_set_new_guest_config(matrix_mdev, &guest_matrix);
+}
+
+static ssize_t vfio_ap_resuming_write(struct file *filp, const char __user *buf,
+				      size_t len, loff_t *pos)
+{
+	struct ap_matrix_mdev *matrix_mdev;
+	struct vfio_ap_config *ap_config;
+	ssize_t ret;
+
+	/*
+	 * This file was opened with stream_open(), so pos should be NULL for
+	 * sequential write() calls; a non-NULL pointer will be passed only
+	 * for positional pwrite() calls in which case we return an error
+	 * indicating broken pipe/illegal seek on a non-seekable file.
+	 */
+	if (pos)
+		return -ESPIPE;
+
+	/*
+	 * Hold ap_attr_mutex for the full duration of the write, just as
+	 * (un)assign_adapter_store() and (un)assign_domain_store() do.  This
+	 * prevents the AP bus apmask/aqmask attributes from being changed
+	 * while the guest's AP configuration is being updated.
+	 *
+	 * get_update_locks_for_mdev() then acquires guests_lock, kvm->lock,
+	 * and mdevs_lock in the correct order. This serialises
+	 * the entire operation against concurrent AP attribute writers
+	 * while the guest's AP configuration is being changed.
+	 *
+	 * Holding these locks for the full duration of a potentially chunked
+	 * write could in theory affect performance, but this is acceptable for
+	 * several reasons: migration is an infrequent operation; real-world
+	 * guest AP configurations are small (each CEX8 card has 2 adapters and
+	 * up to 16 domains, and the 85 cards in a system are shared across all
+	 * LPARs and guests); and each chunk write completes quickly.
+	 */
+	matrix_mdev = filp->private_data;
+	mutex_lock(&ap_attr_mutex);
+	get_update_locks_for_mdev(matrix_mdev);
+	pos = &filp->f_pos;
+
+	ret = validate_resuming_write_parms(filp, len);
+	if (ret)
+		goto out_unlock;
+
+	ap_config = matrix_mdev->mig_data->resuming_mig_file.ap_config;
+
+	if (copy_from_user((char *)ap_config + *pos, buf, len)) {
+		ret = -EFAULT;
+		goto out_unlock;
+	}
+
+	*pos += len;
+
+	/*
+	 * Check whether we have received all the data.  We know the total
+	 * expected size once num_queues has arrived, i.e. once *pos is past
+	 * the fixed header.  Until then keep accumulating.
+	 */
+	if (*pos >= offsetofend(struct vfio_ap_config, num_queues)) {
+		size_t expected_sz;
+
+		if (ap_config->num_queues > MAX_AP_QUEUES) {
+			ret = -EINVAL;
+			goto out_unlock;
+		}
+
+		expected_sz = sizeof(struct vfio_ap_config) +
+			      ap_config->num_queues *
+			      sizeof(struct vfio_ap_queue_info);
+
+		if (*pos > (loff_t)expected_sz) {
+			ret = -EINVAL;
+			goto out_unlock;
+		}
+
+		if (*pos == (loff_t)expected_sz)
+			ret = do_post_copy_processing(matrix_mdev, ap_config);
+	}
+
+out_unlock:
+	release_update_locks_for_mdev(matrix_mdev);
+	mutex_unlock(&ap_attr_mutex);
+	return ret ? ret : (ssize_t)len;
+}
+
+static const struct file_operations vfio_ap_resume_fops = {
+	.owner = THIS_MODULE,
+	.write = vfio_ap_resuming_write,
+	.release = vfio_ap_release_mig_file,
+};
+
+static struct file *vfio_ap_resuming_init(struct ap_matrix_mdev *matrix_mdev)
+{
+	struct vfio_ap_config *ap_config;
+	struct file *filp;
+
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	/*
+	 * Pre-allocate the maximum possible receive buffer so that
+	 * vfio_ap_resuming_write() can copy directly into it without needing
+	 * to know num_queues up front.  kvzalloc falls back to vmalloc for
+	 * large allocations rather than failing a high-order kmalloc.
+	 */
+	ap_config = kvzalloc(VFIO_AP_CONFIG_MAX_SIZE, GFP_KERNEL_ACCOUNT);
+	if (!ap_config)
+		return ERR_PTR(-ENOMEM);
+
+	filp = vfio_ap_open_file_stream(matrix_mdev, &vfio_ap_resume_fops, O_WRONLY);
+	if (IS_ERR(filp)) {
+		kvfree(ap_config);
+		return filp;
+	}
+
+	matrix_mdev->mig_data->resuming_mig_file.ap_config = ap_config;
+	matrix_mdev->mig_data->resuming_mig_file.config_sz = VFIO_AP_CONFIG_MAX_SIZE;
+
+	return filp;
+}
+
+static struct file *
+vfio_ap_transition_to_state(struct ap_matrix_mdev *matrix_mdev,
+			    enum vfio_device_mig_state new_state)
+{
+	struct vfio_ap_migration_data *mig_data;
+	enum vfio_device_mig_state cur_state;
+
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+	mig_data = matrix_mdev->mig_data;
+	cur_state = mig_data->mig_state;
+	dev_dbg(matrix_mdev->vdev.dev, "%s: %d -> %d\n", __func__, cur_state,
+		new_state);
+
+	/*
+	 * Begins the process of saving the vfio device state by creating and
+	 * returning a streaming data_fd to be used to read out the internal
+	 * state of the vfio-ap device on the source host.
+	 */
+	if (cur_state == VFIO_DEVICE_STATE_STOP &&
+	    new_state == VFIO_DEVICE_STATE_STOP_COPY) {
+		struct file *filp = vfio_ap_open_file_stream(matrix_mdev,
+							     &vfio_ap_stop_copy_fops,
+							     O_RDONLY);
+		if (IS_ERR(filp))
+			return ERR_CAST(filp);
+
+		mig_data->stop_copy_mig_file.filp = filp;
+
+		return filp;
+	}
+
+	/*
+	 * Begins the process of restoring the vfio device state by creating and
+	 * returning a streaming data_fd to be used to read in the internal
+	 * state of the vfio-ap device on the destination host.
+	 */
+	if (cur_state == VFIO_DEVICE_STATE_STOP &&
+	    new_state == VFIO_DEVICE_STATE_RESUMING) {
+		struct file *filp = vfio_ap_resuming_init(matrix_mdev);
+
+		if (IS_ERR(filp))
+			return ERR_CAST(filp);
+
+		mig_data->resuming_mig_file.filp = filp;
+		return filp;
+	}
+
+	/*
+	 * Terminates the data transfer session of the vfio-ap device state
+	 * between the source and target hosts. Since the vfio-ap device does
+	 * not virtualize a DMA device, there is no internal device state to
+	 * incorporate into the vfio-ap device on the target.
+	 */
+	if ((cur_state == VFIO_DEVICE_STATE_RESUMING &&
+	     new_state == VFIO_DEVICE_STATE_STOP) ||
+	    (cur_state == VFIO_DEVICE_STATE_STOP_COPY &&
+	     new_state == VFIO_DEVICE_STATE_STOP)) {
+		vfio_ap_release_mig_files(matrix_mdev);
+		return NULL;
+	}
+
+	/*
+	 * These states indicate migration has either not been initiated or
+	 * has completed and the vfio-ap device is operating normally. Since the
+	 * vfio-ap device does not virtualize a DMA device, there is no internal
+	 * device state to incorporate into the vfio-ap device on the target.
+	 */
+	if (cur_state == VFIO_DEVICE_STATE_STOP &&
+	    new_state == VFIO_DEVICE_STATE_RUNNING) {
+		vfio_ap_release_mig_files(matrix_mdev);
+		return NULL;
+	}
+
+	if (cur_state == VFIO_DEVICE_STATE_RUNNING &&
+	    new_state == VFIO_DEVICE_STATE_STOP) {
+		return NULL;
+	}
+
+	/* vfio_mig_get_next_state() does not use arcs other than the above */
+	WARN_ON(true);
+
+	return ERR_PTR(-EINVAL);
+}
+
+static struct file *vfio_ap_set_state(struct vfio_device *vdev,
+				      enum vfio_device_mig_state  new_state)
+{
+	int ret;
+	struct file *filp = NULL;
+	struct ap_matrix_mdev *matrix_mdev;
+	enum vfio_device_mig_state next_state;
+	struct vfio_ap_migration_data *mig_data;
+
+	mutex_lock(&matrix_dev->mdevs_lock);
+
+	matrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);
+
+	if (ap_is_se_guest()) {
+		dev_err_once(matrix_mdev->vdev.dev,
+			     "Migration not allowed from or to a Secure Execution guest\n");
+		mutex_unlock(&matrix_dev->mdevs_lock);
+		return ERR_PTR(-EPERM);
+	}
+
+	mig_data = matrix_mdev->mig_data;
+
+	/*
+	 * The mig_data pointer is set in the vfio_ap_init_migration_data
+	 * function which is called when the vfio-ap device fd is opened.
+	 * Since the implicit pre-open state is RUNNING, a request to set
+	 * RUNNING is a no-op. Any other state transition is invalid before
+	 * open_device.
+	 */
+	if (!mig_data) {
+		mutex_unlock(&matrix_dev->mdevs_lock);
+		if (new_state == VFIO_DEVICE_STATE_RUNNING)
+			return NULL;
+		return ERR_PTR(-ENODEV);
+	}
+
+	dev_dbg(vdev->dev, "%s -> %d\n", __func__, new_state);
+
+	while (mig_data->mig_state != new_state) {
+		ret = vfio_mig_get_next_state(vdev, mig_data->mig_state,
+					      new_state, &next_state);
+		if (ret) {
+			filp = ERR_PTR(ret);
+			break;
+		}
+
+		filp = vfio_ap_transition_to_state(matrix_mdev, next_state);
+		if (IS_ERR(filp))
+			break;
+
+		mig_data->mig_state = next_state;
+
+		if (WARN_ON(filp && new_state != next_state)) {
+			fput(filp);
+			filp = ERR_PTR(-EINVAL);
+			break;
+		}
+	}
+
+	if (mig_data->mig_state == VFIO_DEVICE_STATE_ERROR)
+		filp = ERR_PTR(-EIO);
+
+	mutex_unlock(&matrix_dev->mdevs_lock);
+
+	return filp;
+}
+
+static int vfio_ap_get_state(struct vfio_device *vdev,
+			     enum vfio_device_mig_state  *current_state)
+{
+	struct ap_matrix_mdev *matrix_mdev;
+	struct vfio_ap_migration_data *mig_data;
+
+	mutex_lock(&matrix_dev->mdevs_lock);
+
+	matrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);
+	mig_data =  matrix_mdev->mig_data;
+
+	/*
+	 * The mig_data pointer is set in the vfio_ap_init_migration_data
+	 * function which is called when the vfio-ap device fd is opened.
+	 * If mig_data is NULL, report RUNNING as the implicit pre-open state
+	 * so userspace doesn't need to perform any state transition before the
+	 * device becomes active.
+	 */
+	*current_state = (mig_data) ? mig_data->mig_state :
+				      VFIO_DEVICE_STATE_RUNNING;
+
+	mutex_unlock(&matrix_dev->mdevs_lock);
+
+	return 0;
+}
+
+static int vfio_ap_get_data_size(struct vfio_device *vdev,
+				 unsigned long *stop_copy_length)
+{
+	struct ap_matrix_mdev *matrix_mdev;
+	int num_queues;
+
+	mutex_lock(&matrix_dev->mdevs_lock);
+	matrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);
+	*stop_copy_length = vfio_ap_config_size(matrix_mdev, &num_queues);
+	mutex_unlock(&matrix_dev->mdevs_lock);
+
+	return 0;
+}
+
+static const struct vfio_migration_ops vfio_ap_migration_ops = {
+	.migration_set_state = vfio_ap_set_state,
+	.migration_get_state = vfio_ap_get_state,
+	.migration_get_data_size = vfio_ap_get_data_size,
+};
+
+/**
+ * vfio_ap_init_migration_capabilities - initializes migration flags and operations
+ *
+ * @matrix_mdev: pointer to object containing the mdev state
+ */
+void vfio_ap_init_migration_capabilities(struct ap_matrix_mdev *matrix_mdev)
+{
+	/*
+	 * Live guest migration is not supported for SE guests, so there is no
+	 * need to initialize the migration capabilities.
+	 */
+	if (ap_is_se_guest())
+		return;
+
+	matrix_mdev->vdev.migration_flags = VFIO_MIGRATION_STOP_COPY;
+	matrix_mdev->vdev.mig_ops = &vfio_ap_migration_ops;
+}
+
+/**
+ * vfio_ap_init_migration_data - initialize migration data and functions
+ *
+ * @matrix_mdev: pointer to object containing the mdev state
+ *
+ * Return: zero if initialization is successful; otherwise, returns a error.
+ */
+int vfio_ap_init_migration_data(struct ap_matrix_mdev *matrix_mdev)
+{
+	struct vfio_ap_migration_data *mig_data;
+
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	/*
+	 * Live guest migration is not supported for SE guests, so there is no
+	 * need to initialize the migration data.
+	 */
+	if (ap_is_se_guest())
+		return 0;
+
+	mig_data = kzalloc_obj(struct vfio_ap_migration_data, GFP_KERNEL);
+	if (!mig_data)
+		return -ENOMEM;
+
+	mig_data->mig_state = VFIO_DEVICE_STATE_RUNNING;
+	matrix_mdev->mig_data = mig_data;
+
+	return 0;
+}
+
+/**
+ * vfio_ap_release_mig_files:
+ *
+ * Free the ap_config buffers for any open migration FDs. Although a
+ * migration FD may still be held open by userspace, it is safe to free
+ * mig_data here because:
+ *
+ *   1. matrix_mdev remains valid for the lifetime of any open migration
+ *      FD via the vfio_device registration reference taken in
+ *      vfio_ap_open_file_stream() and dropped in
+ *      vfio_ap_release_mig_file().
+ *
+ *   2. mig_data is only accessed by the migration file ops
+ *      (vfio_ap_stop_copy_read, vfio_ap_resuming_write) under
+ *      mdevs_lock. Once mig_data is set to NULL by the caller, those
+ *      paths will see NULL and return -ENODEV before dereferencing it.
+ *
+ * @matrix_mdev: The object used to maintain the state for a mediated device
+ */
+static void vfio_ap_release_mig_files(struct ap_matrix_mdev *matrix_mdev)
+{
+	struct vfio_ap_migration_data *mig_data;
+
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	mig_data = matrix_mdev->mig_data;
+	vfio_ap_release_stop_copy_file(mig_data);
+	vfio_ap_release_resuming_file(mig_data);
+}
+
+/**
+ * vfio_ap_release_migration_data: reclaim private migration data
+ *
+ * @vdev: pointer to the mdev
+ */
+void vfio_ap_release_migration_data(struct ap_matrix_mdev *matrix_mdev)
+{
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	if (!matrix_mdev->mig_data)
+		return;
+
+	vfio_ap_release_mig_files(matrix_mdev);
+	kfree(matrix_mdev->mig_data);
+	matrix_mdev->mig_data = NULL;
+}
+
+/**
+ * vfio_ap_reset_migration_state - Reset the vfio-ap migration state
+ *
+ * @matrix_mdev: pointer to the object maintaining the vfio-ap device state
+ *
+ * Called during VFIO_DEVICE_RESET to clean up any active migration
+ * state and reset the device to RUNNING state as required by the VFIO
+ * migration specification.
+ */
+void vfio_ap_reset_migration_state(struct ap_matrix_mdev *matrix_mdev)
+{
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	if (!matrix_mdev->mig_data)
+		return;
+
+	vfio_ap_release_mig_files(matrix_mdev);
+	matrix_mdev->mig_data->mig_state = VFIO_DEVICE_STATE_RUNNING;
+}
diff --git a/drivers/s390/crypto/vfio_ap_ops.c b/drivers/s390/crypto/vfio_ap_ops.c
index 4db878c18f41c..5803207e98460 100644
--- a/drivers/s390/crypto/vfio_ap_ops.c
+++ b/drivers/s390/crypto/vfio_ap_ops.c
@@ -88,53 +88,6 @@ static inline void release_update_locks_for_kvm(struct kvm *kvm)
 	mutex_unlock(&matrix_dev->guests_lock);
 }
 
-/**
- * get_update_locks_for_mdev: Acquire the locks required to dynamically update a
- *			      KVM guest's APCB in the proper order.
- *
- * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP
- *		 configuration data to use to update a KVM guest's APCB.
- *
- * The proper locking order is:
- * 1. matrix_dev->guests_lock: required to use the KVM pointer to update a KVM
- *			       guest's APCB.
- * 2. matrix_mdev->kvm->lock:  required to update a guest's APCB
- * 3. matrix_dev->mdevs_lock:  required to access data stored in a matrix_mdev
- *
- * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM
- *	 lock will not be taken.
- */
-static inline void get_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)
-{
-	mutex_lock(&matrix_dev->guests_lock);
-	if (matrix_mdev && matrix_mdev->kvm)
-		mutex_lock(&matrix_mdev->kvm->lock);
-	mutex_lock(&matrix_dev->mdevs_lock);
-}
-
-/**
- * release_update_locks_for_mdev: Release the locks used to dynamically update a
- *				  KVM guest's APCB in the proper order.
- *
- * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP
- *		 configuration data to use to update a KVM guest's APCB.
- *
- * The proper unlocking order is:
- * 1. matrix_dev->mdevs_lock
- * 2. matrix_mdev->kvm->lock
- * 3. matrix_dev->guests_lock
- *
- * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM
- *	 lock will not be released.
- */
-static inline void release_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)
-{
-	mutex_unlock(&matrix_dev->mdevs_lock);
-	if (matrix_mdev && matrix_mdev->kvm)
-		mutex_unlock(&matrix_mdev->kvm->lock);
-	mutex_unlock(&matrix_dev->guests_lock);
-}
-
 /**
  * get_update_locks_by_apqn: Find the mdev to which an APQN is assigned and
  *			     acquire the locks required to update the APCB of
@@ -649,8 +602,7 @@ static int handle_pqap(struct kvm_vcpu *vcpu)
 	return 0;
 }
 
-static void vfio_ap_matrix_init(struct ap_config_info *info,
-				struct ap_matrix *matrix)
+void vfio_ap_matrix_init(struct ap_config_info *info, struct ap_matrix *matrix)
 {
 	matrix->apm_max = info->apxa ? info->na : 63;
 	matrix->aqm_max = info->apxa ? info->nd : 15;
@@ -782,18 +734,30 @@ static bool vfio_ap_mdev_filter_matrix(struct ap_matrix_mdev *matrix_mdev,
 
 static int vfio_ap_mdev_init_dev(struct vfio_device *vdev)
 {
-	struct ap_matrix_mdev *matrix_mdev =
-		container_of(vdev, struct ap_matrix_mdev, vdev);
+	struct ap_matrix_mdev *matrix_mdev;
 
+	mutex_lock(&matrix_dev->mdevs_lock);
+	matrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);
 	matrix_mdev->mdev = to_mdev_device(vdev->dev);
 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->matrix);
 	matrix_mdev->pqap_hook = handle_pqap;
 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->shadow_apcb);
 	hash_init(matrix_mdev->qtable.queues);
+	mutex_unlock(&matrix_dev->mdevs_lock);
 
 	return 0;
 }
 
+static void vfio_ap_mdev_release_dev(struct vfio_device *vdev)
+{
+	struct ap_matrix_mdev *matrix_mdev;
+
+	mutex_lock(&matrix_dev->mdevs_lock);
+	matrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);
+	vfio_ap_release_migration_data(matrix_mdev);
+	mutex_unlock(&matrix_dev->mdevs_lock);
+}
+
 static int vfio_ap_mdev_probe(struct mdev_device *mdev)
 {
 	struct ap_matrix_mdev *matrix_mdev;
@@ -804,6 +768,20 @@ static int vfio_ap_mdev_probe(struct mdev_device *mdev)
 	if (IS_ERR(matrix_mdev))
 		return PTR_ERR(matrix_mdev);
 
+	/*
+	 * Migration capabilities must be initialized before calling
+	 * vfio_register_emulated_iommu_dev; otherwise, the VFIO core
+	 * will see mig_ops as NULL during the registration. This could
+	 * prevent the VFIO core from properly setting up migration
+	 * infrastructure like debugfs entries.
+	 *
+	 * This must be done before acquiring mdevs_lock to avoid an ABBA
+	 * deadlock: vfio_register_emulated_iommu_dev() acquires dev_set->lock
+	 * internally, while vfio_ap_mdev_open_device() is called by the VFIO
+	 * core with dev_set->lock already held and then acquires mdevs_lock.
+	 */
+	vfio_ap_init_migration_capabilities(matrix_mdev);
+
 	ret = vfio_register_emulated_iommu_dev(&matrix_mdev->vdev);
 	if (ret)
 		goto err_put_vdev;
@@ -1003,8 +981,7 @@ static void vfio_ap_mdev_link_adapter(struct ap_matrix_mdev *matrix_mdev,
 	unsigned long apqi;
 
 	for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, AP_DOMAINS)
-		vfio_ap_mdev_link_apqn(matrix_mdev,
-				       AP_MKQID(apid, apqi));
+		vfio_ap_mdev_link_apqn(matrix_mdev, AP_MKQID(apid, apqi));
 }
 
 static void collect_queues_to_reset(struct ap_matrix_mdev *matrix_mdev,
@@ -1714,54 +1691,98 @@ static void ap_matrix_copy(struct ap_matrix *dst, struct ap_matrix *src)
 	bitmap_copy(dst->adm, src->adm, AP_DOMAINS);
 }
 
-static ssize_t ap_config_store(struct device *dev, struct device_attribute *attr,
-			       const char *buf, size_t count)
+static void get_removed_matrixes(struct ap_matrix *m_removed,
+				 struct ap_matrix *m_old,
+				 struct ap_matrix *m_new)
 {
-	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
-	struct ap_matrix m_new, m_old, m_added, m_removed;
+	bitmap_andnot(m_removed->apm, m_old->apm, m_new->apm, AP_DEVICES);
+	bitmap_andnot(m_removed->aqm, m_old->aqm, m_new->aqm, AP_DOMAINS);
+	bitmap_andnot(m_removed->adm, m_old->adm, m_new->adm, AP_DOMAINS);
+}
+
+static void get_added_matrixes(struct ap_matrix *m_added,
+			       struct ap_matrix *m_old,
+			       struct ap_matrix *m_new)
+{
+	bitmap_andnot(m_added->apm, m_new->apm, m_old->apm, AP_DEVICES);
+	bitmap_andnot(m_added->aqm, m_new->aqm, m_old->aqm, AP_DOMAINS);
+	bitmap_andnot(m_added->adm, m_new->adm, m_old->adm, AP_DOMAINS);
+}
+
+static int validate_new_state(struct ap_matrix_mdev *matrix_mdev)
+{
+	int rc;
+
+	/* Ensure new state is valid, else undo new state */
+	rc = vfio_ap_mdev_validate_masks(matrix_mdev);
+	if (rc)
+		return rc;
+
+	rc = ap_matrix_overflow_check(matrix_mdev);
+	if (rc)
+		return rc;
+
+	return 0;
+}
+
+static void link_new_queues(struct ap_matrix_mdev *matrix_mdev,
+			    struct ap_matrix *m_added)
+{
+	unsigned long apid, apqi;
+
+	for_each_set_bit_inv(apid, m_added->apm, AP_DEVICES)
+		vfio_ap_mdev_link_adapter(matrix_mdev, apid);
+
+	for_each_set_bit_inv(apqi, m_added->aqm, AP_DOMAINS)
+		vfio_ap_mdev_link_domain(matrix_mdev, apqi);
+}
+
+/**
+ * vfio_ap_set_new_guest_config:
+ *
+ * Set a new AP configuration for a guest.
+ *
+ * @matrix_mdev: Object used to maintain the AP configuration for a guest
+ * @m_new:		 Object used to set the new AP configuration
+ *
+ * Returns: zero (0) if the new AP configuration is successfully set; otherwise,
+ *	    returns an error:
+ *
+ *	    ~ EADDRNOTAVAIL One or more APQNs are reserved for host use
+ *	    ~ EADDRINUSE    One or more APQNs are assigned to another mdev
+ *	    ~ ENODEV	    An adapter, domain or control domain in the new
+ *			    AP configuration exceeds the max architected value
+ */
+int vfio_ap_set_new_guest_config(struct ap_matrix_mdev *matrix_mdev,
+				 struct ap_matrix *m_new)
+{
+	struct ap_matrix m_old, m_added, m_removed;
 	DECLARE_BITMAP(apm_filtered, AP_DEVICES);
-	unsigned long newbit;
-	char *newbuf, *rest;
-	int rc = count;
 	bool do_update;
+	int rc;
 
-	newbuf = kstrndup(buf, AP_CONFIG_STRLEN, GFP_KERNEL);
-	if (!newbuf)
-		return -ENOMEM;
-	rest = newbuf;
-
-	mutex_lock(&ap_attr_mutex);
-	get_update_locks_for_mdev(matrix_mdev);
+	lockdep_assert_held(&ap_attr_mutex);
+	assert_has_update_locks_for_mdev(matrix_mdev);
 
-	/* Save old state */
+	/* Save the old matrix to restore it if validation fails */
 	ap_matrix_copy(&m_old, &matrix_mdev->matrix);
-	if (parse_bitmap(&rest, m_new.apm, AP_DEVICES) ||
-	    parse_bitmap(&rest, m_new.aqm, AP_DOMAINS) ||
-	    parse_bitmap(&rest, m_new.adm, AP_DOMAINS)) {
-		rc = -EINVAL;
-		goto out;
-	}
 
-	bitmap_andnot(m_removed.apm, m_old.apm, m_new.apm, AP_DEVICES);
-	bitmap_andnot(m_removed.aqm, m_old.aqm, m_new.aqm, AP_DOMAINS);
-	bitmap_andnot(m_added.apm, m_new.apm, m_old.apm, AP_DEVICES);
-	bitmap_andnot(m_added.aqm, m_new.aqm, m_old.aqm, AP_DOMAINS);
+	/*
+	 * Get the adapters, domains and control domains added and/or removed
+	 * from the existing configuration
+	 */
+	get_removed_matrixes(&m_removed, &m_old, m_new);
+	get_added_matrixes(&m_added, &m_old, m_new);
 
 	/* Need new bitmaps in matrix_mdev for validation */
-	ap_matrix_copy(&matrix_mdev->matrix, &m_new);
+	ap_matrix_copy(&matrix_mdev->matrix, m_new);
 
 	/* Ensure new state is valid, else undo new state */
-	rc = vfio_ap_mdev_validate_masks(matrix_mdev);
-	if (rc) {
-		ap_matrix_copy(&matrix_mdev->matrix, &m_old);
-		goto out;
-	}
-	rc = ap_matrix_overflow_check(matrix_mdev);
+	rc = validate_new_state(matrix_mdev);
 	if (rc) {
 		ap_matrix_copy(&matrix_mdev->matrix, &m_old);
-		goto out;
+		return rc;
 	}
-	rc = count;
 
 	/* Need old bitmaps in matrix_mdev for unplug/unlink */
 	ap_matrix_copy(&matrix_mdev->matrix, &m_old);
@@ -1771,14 +1792,10 @@ static ssize_t ap_config_store(struct device *dev, struct device_attribute *attr
 	vfio_ap_mdev_hot_unplug_domains(matrix_mdev, m_removed.aqm);
 
 	/* Need new bitmaps in matrix_mdev for linking new adapters/domains */
-	ap_matrix_copy(&matrix_mdev->matrix, &m_new);
-
-	/* Link newly added adapters */
-	for_each_set_bit_inv(newbit, m_added.apm, AP_DEVICES)
-		vfio_ap_mdev_link_adapter(matrix_mdev, newbit);
+	ap_matrix_copy(&matrix_mdev->matrix, m_new);
 
-	for_each_set_bit_inv(newbit, m_added.aqm, AP_DOMAINS)
-		vfio_ap_mdev_link_domain(matrix_mdev, newbit);
+	/* Link queues associated with the newly added adapters and domains */
+	link_new_queues(matrix_mdev, &m_added);
 
 	/* filter resources not bound to vfio-ap */
 	do_update = vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered);
@@ -1789,7 +1806,39 @@ static ssize_t ap_config_store(struct device *dev, struct device_attribute *attr
 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
 		reset_queues_for_apids(matrix_mdev, apm_filtered);
 	}
-out:
+
+	return 0;
+}
+
+static ssize_t ap_config_store(struct device *dev, struct device_attribute *attr,
+			       const char *buf, size_t count)
+{
+	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
+	struct ap_matrix m_new;
+	char *newbuf, *rest;
+	ssize_t rc;
+
+	newbuf = kstrndup(buf, AP_CONFIG_STRLEN, GFP_KERNEL);
+	if (!newbuf)
+		return -ENOMEM;
+	rest = newbuf;
+
+	mutex_lock(&ap_attr_mutex);
+	get_update_locks_for_mdev(matrix_mdev);
+
+	if (parse_bitmap(&rest, m_new.apm, AP_DEVICES) ||
+	    parse_bitmap(&rest, m_new.aqm, AP_DOMAINS) ||
+	    parse_bitmap(&rest, m_new.adm, AP_DOMAINS)) {
+		kfree(newbuf);
+		release_update_locks_for_mdev(matrix_mdev);
+		mutex_unlock(&ap_attr_mutex);
+		return -EINVAL;
+	}
+
+	rc = vfio_ap_set_new_guest_config(matrix_mdev, &m_new);
+	if (!rc)
+		rc = count;
+
 	release_update_locks_for_mdev(matrix_mdev);
 	mutex_unlock(&ap_attr_mutex);
 	kfree(newbuf);
@@ -2059,19 +2108,39 @@ static int vfio_ap_mdev_reset_qlist(struct list_head *qlist)
 
 static int vfio_ap_mdev_open_device(struct vfio_device *vdev)
 {
-	struct ap_matrix_mdev *matrix_mdev =
-		container_of(vdev, struct ap_matrix_mdev, vdev);
+	struct ap_matrix_mdev *matrix_mdev;
+	int ret;
 
 	if (!vdev->kvm)
 		return -EINVAL;
 
-	return vfio_ap_mdev_set_kvm(matrix_mdev, vdev->kvm);
+	mutex_lock(&matrix_dev->mdevs_lock);
+	matrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);
+	ret = vfio_ap_init_migration_data(matrix_mdev);
+	mutex_unlock(&matrix_dev->mdevs_lock);
+
+	if (ret)
+		return ret;
+
+	ret = vfio_ap_mdev_set_kvm(matrix_mdev, vdev->kvm);
+	if (ret) {
+		/* Clean up migration data on failure */
+		mutex_lock(&matrix_dev->mdevs_lock);
+		vfio_ap_release_migration_data(matrix_mdev);
+		mutex_unlock(&matrix_dev->mdevs_lock);
+	}
+
+	return ret;
 }
 
 static void vfio_ap_mdev_close_device(struct vfio_device *vdev)
 {
-	struct ap_matrix_mdev *matrix_mdev =
-		container_of(vdev, struct ap_matrix_mdev, vdev);
+	struct ap_matrix_mdev *matrix_mdev;
+
+	mutex_lock(&matrix_dev->mdevs_lock);
+	matrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);
+	vfio_ap_release_migration_data(matrix_mdev);
+	mutex_unlock(&matrix_dev->mdevs_lock);
 
 	vfio_ap_mdev_unset_kvm(matrix_mdev);
 }
@@ -2105,6 +2174,14 @@ static void vfio_ap_mdev_request(struct vfio_device *vdev, unsigned int count)
 	release_update_locks_for_mdev(matrix_mdev);
 }
 
+unsigned int vfio_ap_mdev_get_num_queues(struct ap_matrix *ap_matrix)
+{
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+
+	return bitmap_weight(ap_matrix->apm, AP_DEVICES) *
+	       bitmap_weight(ap_matrix->aqm, AP_DOMAINS);
+}
+
 static int vfio_ap_mdev_get_device_info(unsigned long arg)
 {
 	unsigned long minsz;
@@ -2282,6 +2359,17 @@ static ssize_t vfio_ap_mdev_ioctl(struct vfio_device *vdev,
 		break;
 	case VFIO_DEVICE_RESET:
 		ret = vfio_ap_mdev_reset_queues(matrix_mdev);
+		/*
+		 * Reset the migration state unconditionally, regardless of
+		 * whether the hardware queue reset succeeded. The migration
+		 * state tracks the AP configuration transfer lifecycle and is
+		 * independent of the hardware queue reset outcome. The VFIO
+		 * migration spec designates VFIO_DEVICE_RESET as the mechanism
+		 * to return device_state to RUNNING (e.g. to recover from
+		 * ERROR), so the migration state must be cleaned up even when
+		 * one or more queues fail to reset.
+		 */
+		vfio_ap_reset_migration_state(matrix_mdev);
 		break;
 	case VFIO_DEVICE_GET_IRQ_INFO:
 		ret = vfio_ap_get_irq_info(arg);
@@ -2389,6 +2477,7 @@ static const struct attribute_group vfio_queue_attr_group = {
 
 static const struct vfio_device_ops vfio_ap_matrix_dev_ops = {
 	.init = vfio_ap_mdev_init_dev,
+	.release = vfio_ap_mdev_release_dev,
 	.open_device = vfio_ap_mdev_open_device,
 	.close_device = vfio_ap_mdev_close_device,
 	.ioctl = vfio_ap_mdev_ioctl,
diff --git a/drivers/s390/crypto/vfio_ap_private.h b/drivers/s390/crypto/vfio_ap_private.h
index 9bff666b0b35d..3910b5c023c91 100644
--- a/drivers/s390/crypto/vfio_ap_private.h
+++ b/drivers/s390/crypto/vfio_ap_private.h
@@ -91,6 +91,9 @@ struct ap_queue_table {
 	DECLARE_HASHTABLE(queues, 8);
 };
 
+/* Forward declaration for migration data structure */
+struct vfio_ap_migration_data;
+
 /**
  * struct ap_matrix_mdev - Contains the data associated with a matrix mediated
  *			   device.
@@ -110,6 +113,7 @@ struct ap_queue_table {
  * @aqm_add:	bitmap of APQIs added to the host's AP configuration
  * @adm_add:	bitmap of control domain numbers added to the host's AP
  *		configuration
+ * @mig_data:  vfio device migration data
  */
 struct ap_matrix_mdev {
 	struct vfio_device vdev;
@@ -125,6 +129,7 @@ struct ap_matrix_mdev {
 	DECLARE_BITMAP(apm_add, AP_DEVICES);
 	DECLARE_BITMAP(aqm_add, AP_DOMAINS);
 	DECLARE_BITMAP(adm_add, AP_DOMAINS);
+	struct vfio_ap_migration_data *mig_data;
 };
 
 /**
@@ -152,6 +157,8 @@ struct vfio_ap_queue {
 	struct work_struct reset_work;
 };
 
+unsigned int vfio_ap_mdev_get_num_queues(struct ap_matrix *ap_matrix);
+
 int vfio_ap_mdev_register(void);
 void vfio_ap_mdev_unregister(void);
 
@@ -165,4 +172,72 @@ void vfio_ap_on_cfg_changed(struct ap_config_info *new_config_info,
 void vfio_ap_on_scan_complete(struct ap_config_info *new_config_info,
 			      struct ap_config_info *old_config_info);
 
+void vfio_ap_matrix_init(struct ap_config_info *info, struct ap_matrix *matrix);
+
+void vfio_ap_init_migration_capabilities(struct ap_matrix_mdev *matrix_mdev);
+int vfio_ap_init_migration_data(struct ap_matrix_mdev *matrix_mdev);
+void vfio_ap_release_migration_data(struct ap_matrix_mdev *matrix_mdev);
+void vfio_ap_reset_migration_state(struct ap_matrix_mdev *matrix_mdev);
+
+/**
+ * get_update_locks_for_mdev: Acquire the locks required to dynamically update a
+ *			      KVM guest's APCB in the proper order.
+ *
+ * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP
+ *		 configuration data to use to update a KVM guest's APCB.
+ *
+ * The proper locking order is:
+ * 1. matrix_dev->guests_lock: required to use the KVM pointer to update a KVM
+ *			       guest's APCB.
+ * 2. matrix_mdev->kvm->lock:  required to update a guest's APCB
+ * 3. matrix_dev->mdevs_lock:  required to access data stored in a matrix_mdev
+ *
+ * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM
+ *	 lock will not be taken.
+ */
+static inline void get_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)
+{
+	mutex_lock(&matrix_dev->guests_lock);
+	if (matrix_mdev && matrix_mdev->kvm)
+		mutex_lock(&matrix_mdev->kvm->lock);
+	mutex_lock(&matrix_dev->mdevs_lock);
+}
+
+/**
+ * release_update_locks_for_mdev: Release the locks used to dynamically update a
+ *				  KVM guest's APCB in the proper order.
+ *
+ * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP
+ *		 configuration data to use to update a KVM guest's APCB.
+ *
+ * The proper unlocking order is:
+ * 1. matrix_dev->mdevs_lock
+ * 2. matrix_mdev->kvm->lock
+ * 3. matrix_dev->guests_lock
+ *
+ * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM
+ *	 lock will not be released.
+ */
+static inline void release_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)
+{
+	mutex_unlock(&matrix_dev->mdevs_lock);
+	if (matrix_mdev && matrix_mdev->kvm)
+		mutex_unlock(&matrix_mdev->kvm->lock);
+	mutex_unlock(&matrix_dev->guests_lock);
+}
+
+static inline void
+assert_has_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)
+{
+	lockdep_assert_held(&matrix_dev->guests_lock);
+	if (matrix_mdev && matrix_mdev->kvm)
+		lockdep_assert_held(&matrix_mdev->kvm->lock);
+	lockdep_assert_held(&matrix_dev->mdevs_lock);
+}
+
+void vfio_ap_matrix_init(struct ap_config_info *info, struct ap_matrix *matrix);
+
+int vfio_ap_set_new_guest_config(struct ap_matrix_mdev *matrix_mdev,
+				 struct ap_matrix *m_new);
+
 #endif /* _VFIO_AP_PRIVATE_H_ */

3/2 2026/10/09 14:37 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37967
							output: 19
							thoughts: 259
						

Thoughts:
**Initial Assessment of a Potential Issue**

Okay, so I'm being asked to evaluate a patch series for syzkaller fuzzing. The target architecture is amd64, which is crucial. My first instinct is always to dive straight into the diff, right? Gotta understand what's actually changing. Let's see... the diff touches:

*   `Documentation/arch/s390/vfio-ap.rst`
*   `drivers/s390/crypto/Makefile`
*   `drivers/s390/crypto/vfio_ap_drv.c`
*   `drivers/s390/crypto/vfio_ap_migration.c`
*   `drivers/s390/crypto/vfio_ap_ops.c`
*   `drivers/s390/crypto/vfio_ap_private.h`

Wait a second... hold up. Architecture and path are screaming something at me. It's touching `drivers/s390/...` files. That's a red flag! We're talking amd64, not s390. Is `drivers/s390/crypto/` even compiled or reachable on amd64? I have to know. This needs immediate investigation.

Alright, time to get to the Kconfig files. I'm going to check `drivers/s390/Kconfig`, `drivers/s390/crypto/Kconfig`, or surrounding Kconfig files. Then I'll use `grepper` to quickly determine where `CONFIG_VFIO_AP` is defined, and what dependencies it might have. This should tell me if the patch is even relevant to the target architecture. This is likely an error.



4/2 2026/10/09 14:37 tool grepper
0m Args:
{
  "Expression": "config VFIO_AP"
}

Results:
{
  "Output": "arch/s390/Kconfig=835=config VFIO_CCW\n--\narch/s390/Kconfig-845-\narch/s390/Kconfig:846:config VFIO_AP\narch/s390/Kconfig-847-\tdef_tristate n\n"
}

5/2 2026/10/09 14:37 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38717
							output: 37
							thoughts: 27
						

Thoughts:
Here's a summary of my thought process, as requested:

**Navigating the S390 Architecture Configuration**

Okay, so I need to dive into the s390 architecture's configuration options. Let's see... I'll start by checking the `arch/s390/Kconfig` file. I'm thinking that somewhere around line 846 might hold some relevant information, so I'll zero in on that area. I'll use `read-file` to get the context I need. Hopefully, this will give me a better understanding of the options available and their dependencies. This is just a starting point, of course, but it's a good way to get my bearings and narrow down the scope of what I'm looking for. Let's see what we can find!



6/2 2026/10/09 14:37 tool read-file
0m Args:
{
  "File": "arch/s390/Kconfig",
  "FirstLine": 840,
  "LineCount": 25
}

Results:
{
  "Contents": " 840:\t\thelp\n 841:\t\t  This driver allows usage of I/O subchannels via VFIO-CCW.\n 842:\t\n 843:\t\t  To compile this driver as a module, choose M here: the\n 844:\t\t  module will be called vfio_ccw.\n 845:\t\n 846:\tconfig VFIO_AP\n 847:\t\tdef_tristate n\n 848:\t\tprompt \"VFIO support for AP devices\"\n 849:\t\tdepends on KVM\n 850:\t\tdepends on VFIO\n 851:\t\tdepends on AP\n 852:\t\tselect VFIO_MDEV\n 853:\t\thelp\n 854:\t\t  This driver grants access to Adjunct Processor (AP) devices\n 855:\t\t  via the VFIO mediated device interface.\n 856:\t\n 857:\t\t  To compile this driver as a module, choose M here: the module\n 858:\t\t  will be called vfio_ap.\n 859:\t\n 860:\tendmenu\n 861:\t\n 862:\tconfig CCW\n 863:\t\tdef_bool y\n 864:\t\n"
}

7/2 2026/10/09 14:37 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39281
							output: 18
							thoughts: 61
						

Thoughts:
Okay, let's see what we're dealing with here.

**Investigating the Build Configuration of Drivers/S390 and VFIO_AP Dependencies**

My initial thought is to quickly verify the build architecture for `drivers/s390`. Is this thing even getting compiled on amd64 systems? If not, that's a key piece of information. Related to this I should check the dependency tree to see if the `CONFIG_VFIO_AP` option is somehow tied to either the `S390` architecture or the `AP` feature. I need to understand this relationship.

Now, where exactly is `config AP` being defined? Time to employ my trusty `grepper` tool and get a precise answer. This should quickly reveal any relevant configuration files or dependencies. This will help me unravel the context.



8/2 2026/10/09 14:37 tool grepper
0m Args:
{
  "Expression": "config AP\\b"
}

Results:
{
  "Output": "arch/s390/Kconfig=797=config EADM_SCH\n--\narch/s390/Kconfig-807-\narch/s390/Kconfig:808:config AP\narch/s390/Kconfig-809-\tdef_tristate y\n"
}

9/2 2026/10/09 14:37 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39625
							output: 35
							thoughts: 44
						

Thoughts:
Here's my thought process, as if I were considering this myself:

**VFIO-AP Configuration Discovery**

Okay, so `VFIO_AP` is a configuration option, and the text just told me it's located in `arch/s390/Kconfig`. That's a good starting point. I need to figure out how this is connected to the rest of the driver infrastructure, specifically for the s390 architecture.

My next move is obvious: I'll check the main `drivers/Kconfig` file, then, if I don't find it there, I'll need to dig into `drivers/Makefile` in the s390-specific section to see if there's any relevant build logic or dependencies that might shed light on this `VFIO_AP` option. I'm expecting to find at least some pointer to where the relevant code for VFIO-AP on s390 is actually defined, or at least how it's integrated with the s390 kernel build. It's likely that a configuration option this specific has some very particular implementation details for the architecture.



10/2 2026/10/09 14:38 tool grepper
0m Args:
{
  "Expression": "s390",
  "PathPrefixes": [
    "drivers/Makefile",
    "drivers/Kconfig"
  ]
}

Results:
{
  "Output": "drivers/Makefile=199=obj-$(CONFIG_DIBS)\t\t+= dibs/\ndrivers/Makefile:200:obj-$(CONFIG_S390)\t\t+= s390/\n"
}

11/2 2026/10/09 14:38 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40005
							output: 27
							thoughts: 419
						

Thoughts:
**WorthFuzzing=false: A Clear Case**

Okay, let's break this down. That `drivers/Makefile` line, `obj-$(CONFIG_S390) += s390/`, immediately jumps out. And as expected, `CONFIG_S390` is, of course, only enabled when building for the s390 architecture. This seems pretty clear, but let's be thorough.

Now, let's recall the CORE TRIAGE PHILOSOPHY – specifically Section 2 on *negative criteria* and when to return `WorthFuzzing=false`. The rule is: return `false` *only* if **all** modified code falls into one or more specific categories. And one of those categories? "Code paths exclusive to architectures other than the target architecture". Bingo!

My target architecture is amd64. Let's look at the modified files:

*   `Documentation/arch/s390/vfio-ap.rst`
*   `drivers/s390/crypto/Makefile`
*   `drivers/s390/crypto/vfio_ap_drv.c`
*   `drivers/s390/crypto/vfio_ap_migration.c`
*   `drivers/s390/crypto/vfio_ap_ops.c`
*   `drivers/s390/crypto/vfio_ap_private.h`

Every single file in this patch series is either documentation for s390 *or* code within `drivers/s390/crypto/`. And this code is unequivocally exclusive to the s390 architecture. It requires `CONFIG_S390`, `CONFIG_AP`, and `CONFIG_VFIO_AP`, all of which are defined within `arch/s390/Kconfig`. There's no way these files can be built or executed on an amd64 system.

To be absolutely certain, just a quick sanity check with `git log -1 --stat` or `git grep` or `git diff` to make sure nothing else was sneakily touched by the `HEAD` commit. Just to be sure. But the initial analysis is incredibly strong. This looks like a definite `WorthFuzzing=false` situation.



12/2 2026/10/09 14:38 tool grepper
0m Args:
{
  "Expression": ".*",
  "PathPrefixes": [
    "arch/x86"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 484324 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (1408 files in total):\narch/x86/.gitignore:6\narch/x86/Kbuild:40\narch/x86/Kconfig:3143\narch/x86/Kconfig.assembler:7\narch/x86/Kconfig.cpu:412\narch/x86/Kconfig.cpufeatures:207\narch/x86/Kconfig.debug:274\narch/x86/Makefile:360\narch/x86/Makefile.um:73\narch/x86/Makefile_32.cpu:36\narch/x86/boot/.gitignore:15\narch/x86/boot/Makefile:139\narch/x86/boot/a20.c:163\narch/x86/boot/apm.c:73\narch/x86/boot/bioscall.S:79\narch/x86/boot/bitops.h:44\narch/x86/boot/boot.h:330\narch/x86/boot/cmdline.c:156\narch/x86/boot/compressed/.gitignore:7\narch/x86/boot/compressed/Makefile:163\narch/x86/boot/compressed/acpi.c:322\narch/x86/boot/compressed/cmdline.c:32\narch/x86/boot/compressed/cpuflags.c:9\narch/x86/boot/compressed/early_serial_console.c:6\narch/x86/boot/compressed/efi.c:236\narch/x86/boot/compressed/efi.h:127\narch/x86/boot/compressed/error.c:43\narch/x86/boot/compressed/error.h:11\narch/x86/boot/compressed/head_32.S:188\narch/x86/boot/compressed/head_64.S:543\narch/x86/boot/compressed/ident_map_64.c:393\narch/x86/boot/compressed/idt_64.c:92\narch/x86/boot/compressed/idt_handlers_64.S:78\narch/x86/boot/compressed/kaslr.c:911\narch/x86/boot/compressed/kernel_info.S:22\narch/x86/boot/compressed/mem.c:86\narch/x86/boot/compressed/mem_encrypt.S:324\narch/x86/boot/compressed/misc.c:537\narch/x86/boot/compressed/misc.h:259\narch/x86/boot/compressed/mkpiggy.c:74\narch/x86/boot/compressed/pgtable_64.c:201\narch/x86/boot/compressed/sbat.S:7\narch/x86/boot/compressed/sev-handle-vc.c:136\narch/x86/boot/compressed/sev.c:513\narch/x86/boot/compressed/sev.h:44\narch/x86/boot/compressed/string.c:81\narch/x86/boot/compressed/tdcall.S:3\narch/x86/boot/compressed/tdx-shared.c:2\narch/x86/boot/compressed/tdx.c:77\narch/x86/boot/compressed/tdx.h:13\n... and 1358 more files\n\narch/x86/.gitignore:1:# SPDX-License-Identifier: GPL-2.0-only\narch/x86/.gitignore:2:boot/compressed/vmlinux\narch/x86/.gitignore:3:tools/test_get_len\narch/x86/.gitignore:4:tools/insn_sanity\narch/x86/.gitignore:5:tools/insn_decoder_test\narch/x86/.gitignore:6:purgatory/purgatory.ro\n--\narch/x86/Kbuild:1:# SPDX-License-Identifier: GPL-2.0\narch/x86/Kbuild:2:\narch/x86/Kbuild:3:# Branch profiling isn't noinstr-safe.  Disable it for arch/x86/*\narch/x86/Kbuild:4:subdir-ccflags-$(CONFIG_TRACE_BRANCH_PROFILING) += -DDISABLE_BRANCH_PROFILING\narch/x86/Kbuild:5:\narch/x86/Kbuild:6:obj-y += boot/startup/\narch/x86/Kbuild:7:\narch/x86/Kbuild:8:obj-$(CONFIG_ARCH_HAS_CC_PLATFORM) += coco/\narch/x86/Kbuild:9:\narch/x86/Kbuild:10:obj-y += entry/\narch/x86/Kbuild:11:\narch/x86/Kbuild:12:obj-$(CONFIG_PERF_EVENTS) += events/\narch/x86/Kbuild:13:\narch/x86/Kbuild:14:obj-$(CONFIG_KVM) += kvm/\narch/x86/Kbuild:15:\narch/x86/Kbuild:16:# Xen paravirtualization support\narch/x86/Kbuild:17:obj-$(CONFIG_XEN) += xen/\narch/x86/Kbuild:18:\narch/x86/Kbuild:19:obj-$(CONFIG_PVH) += platform/pvh/\narch/x86/Kbuild:20:\narch/x86/Kbuild:21:# Hyper-V paravirtualization support\narch/x86/Kbuild:22:obj-$(subst m,y,$(CONFIG_HYPERV)) += hyperv/\narch/x86/Kbuild:23:\narch/x86/Kbuild:24:obj-y += realmode/\narch/x86/Kbuild:25:obj-y += kernel/\narch/x86/Kbuild:26:obj-y += mm/\narch/x86/Kbuild:27:\narch/x86/Kbuild:28:obj-y += crypto/\narch/x86/Kbuild:29:\narch/x86/Kbuild:30:obj-$(CONFIG_IA32_EMULATION) += ia32/\narch/x86/Kbuild:31:\narch/x86/Kbuild:32:obj-y += platform/\narch/x86/Kbuild:33:obj-y += net/\narch/x86/Kbuild:34:\narch/x86/Kbuild:35:obj-$(CONFIG_KEXEC_FILE) += purgatory/\narch/x86/Kbuild:36:\narch/x86/Kbuild:37:obj-y += virt/\narch/x86/Kbuild:38:\narch/x86/Kbuild:39:# for cleaning\narch/x86/Kbuild:40:subdir- += boot tools\n--\narch/x86/Kconfig:1:# SPDX-License-Identifier: GPL-2.0\narch/x86/Kconfig:2:# Select 32 or 64 bit\narch/x86/Kconfig:3:config 64BIT\narch/x86/Kconfig:4:\tbool \"64-bit kernel\" if \"$(ARCH)\" = \"x86\"\narch/x86/Kconfig:5:\tdefault \"$(ARCH)\" != \"i386\"\narch/x86/Kconfig:6:\thelp\narch/x86/Kconfig:7:\t  Say yes to build a 64-bit kernel - formerly known as x86_64\narch/x86/Kconfig:8:\t  Say no to build a 32-bit kernel - formerly known as i386\narch/x86/Kconfig:9:\narch/x86/Kconfig:10:config X86_32\narch/x86/Kconfig:11:\tdef_bool y\narch/x86/Kconfig:12:\tdepends on !64BIT\narch/x86/Kconfig:13:\t# Options that are inherently 32-bit kernel only:\narch/x86/Kconfig:14:\tselect ARCH_WANT_IPC_PARSE_VERSION\narch/x86/Kconfig:15:\tselect CLKSRC_I8253\narch/x86/Kconfig:16:\tselect CLONE_BACKWARDS\narch/x86/Kconfig:17:\tselect HAVE_DEBUG_STACKOVERFLOW\narch/x86/Kconfig:18:\tselect KMAP_LOCAL\narch/x86/Kconfig:19:\tselect MODULES_USE_ELF_REL\narch/x86/Kconfig:20:\tselect OLD_SIGACTION\narch/x86/Kconfig:21:\tselect ARCH_SPLIT_ARG64\narch/x86/Kconfig:22:\narch/x86/Kconfig:23:config X86_64\narch/x86/Kconfig:24:\tdef_bool y\narch/x86/Kconfig:25:\tdepends on 64BIT\narch/x86/Kconfig:26:\t# Options that are inherently 64-bit kernel only:\narch/x86/Kconfig:27:\tselect ARCH_HAS_GIGANTIC_PAGE\narch/x86/Kconfig:28:\tselect ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS\narch/x86/Kconfig:29:\tselect ARCH_SUPPORTS_INT128 if CC_HAS_INT128\narch/x86/Kconfig:30:\tselect ARCH_SUPPORTS_PER_VMA_LOCK\narch/x86/Kconfig:31:\tselect ARCH_SUPPORTS_HUGE_PFNMAP if TRANSPARENT_HUGEPAGE\narch/x86/Kconfig:32:\tselect HAVE_ARCH_SOFT_DIRTY\narch/x86/Kconfig:33:\tselect MODULES_USE_ELF_RELA\narch/x86/Kconfig:34:\tselect NEED_DMA_MAP_STATE\narch/x86/Kconfig:35:\tselect SWIOTLB\narch/x86/Kconfig:36:\tselect ARCH_HAS_ELFCORE_COMPAT\narch/x86/Kconfig:37:\tselect ZONE_DMA32\narch/x86/Kconfig:38:\tselect EXECMEM if DYNAMIC_FTRACE\narch/x86/Kconfig:39:\tselect ACPI_MRRM if ACPI\narch/x86/Kconfig:40:\narch/x86/Kconfig:41:config FORCE_DYNAMIC_FTRACE\narch/x86/Kconfig:42:\tdef_bool y\narch/x86/Kconfig:43:\tdepends on X86_32\narch/x86/Kconfig:44:\tdepends on FUNCTION_TRACER\narch/x86/Kconfig:45:\tselect DYNAMIC_FTRACE\narch/x86/Kconfig:46:\thelp\narch/x86/Kconfig:47:\t  We keep the static function tracing (!DYNAMIC_FTRACE) around\narch/x86/Kconfig:48:\t  in order to test the non static function tracing in the\narch/x86/Kconfig:49:\t  generic code, as other architectures still use it. But we\narch/x86/Kconfig:50:\t  only need to keep it around for x86_64. No need to keep it\narch/x86/Kconfig:51:\t  for x86_32. For x86_32, force DYNAMIC_FTRACE.\narch/x86/Kconfig:52:#\narch/x86/Kconfig:53:# Arch settings\narch/x86/Kconfig:54:#\narch/x86/Kconfig:55:# ( Note that options that are marked 'if X86_64' could in principle be\narch/x86/Kconfig:56:#   ported to 32-bit as well. )\narch/x86/Kconfig:57:#\narch/x86/Kconfig:58:config X86\narch/x86/Kconfig:59:\tdef_bool y\narch/x86/Kconfig:60:\t#\narch/x86/Kconfig:61:\t# Note: keep this list sorted alphabetically\narch/x86/Kconfig:62:\t#\narch/x86/Kconfig:63:\tselect ACPI_LEGACY_TABLES_LOOKUP\tif ACPI\narch/x86/Kconfig:64:\tselect ACPI_SYSTEM_POWER_STATES_SUPPORT\tif ACPI\narch/x86/Kconfig:65:\tselect ACPI_HOTPLUG_CPU\t\t\tif ACPI_PROCESSOR \u0026\u0026 HOTPLUG_CPU\narch/x86/Kconfig:66:\tselect ARCH_32BIT_OFF_T\t\t\tif X86_32\narch/x86/Kconfig:67:\tselect ARCH_CLOCKSOURCE_INIT\narch/x86/Kconfig:68:\tselect ARCH_CONFIGURES_CPU_MITIGATIONS\narch/x86/Kconfig:69:\tselect ARCH_CORRECT_STACKTRACE_ON_KRETPROBE\narch/x86/Kconfig:70:\tselect ARCH_ENABLE_HUGEPAGE_MIGRATION if X86_64 \u0026\u0026 HUGETLB_PAGE \u0026\u0026 MIGRATION\narch/x86/Kconfig:71:\tselect ARCH_ENABLE_MEMORY_HOTPLUG if X86_64\narch/x86/Kconfig:72:\tselect ARCH_ENABLE_SPLIT_PMD_PTLOCK if (PGTABLE_LEVELS \u003e 2) \u0026\u0026 (X86_64 || X86_PAE)\narch/x86/Kconfig:73:\tselect ARCH_HAS_PMD_SOFTLEAVES if X86_64 \u0026\u0026 TRANSPARENT_HUGEPAGE\narch/x86/Kconfig:74:\tselect ARCH_HAS_ACPI_TABLE_UPGRADE\tif ACPI\narch/x86/Kconfig:75:\tselect ARCH_HAS_CPU_ATTACK_VECTORS\tif CPU_MITIGATIONS\narch/x86/Kconfig:76:\tselect ARCH_HAS_CACHE_LINE_SIZE\narch/x86/Kconfig:77:\tselect ARCH_HAS_CPU_CACHE_INVALIDATE_MEMREGION\narch/x86/Kconfig:78:\tselect ARCH_HAS_CPU_FINALIZE_INIT\narch/x86/Kconfig:79:\tselect ARCH_HAS_CPU_PASID\t\tif IOMMU_SVA\narch/x86/Kconfig:80:\tselect ARCH_HAS_CURRENT_STACK_POINTER\narch/x86/Kconfig:81:\tselect ARCH_HAS_DEBUG_VIRTUAL\narch/x86/Kconfig:82:\tselect ARCH_HAS_DEBUG_VM_PGTABLE\tif !X86_PAE\narch/x86/Kconfig:83:\tselect ARCH_HAS_DELAY_TIMER\narch/x86/Kconfig:84:\tselect ARCH_HAS_DEVMEM_IS_ALLOWED\narch/x86/Kconfig:85:\tselect ARCH_HAS_DMA_OPS\t\t\tif GART_IOMMU || XEN\narch/x86/Kconfig:86:\tselect ARCH_HAS_EARLY_DEBUG\t\tif KGDB\narch/x86/Kconfig:87:\tselect ARCH_HAS_ELF_RANDOMIZE\narch/x86/Kconfig:88:\tselect ARCH_HAS_EXECMEM_ROX\t\tif X86_64 \u0026\u0026 STRICT_MODULE_RWX\narch/x86/Kconfig:89:\tselect ARCH_HAS_FAST_MULTIPLIER\narch/x86/Kconfig:90:\tselect ARCH_HAS_FORTIFY_SOURCE\narch/x86/Kconfig:91:\tselect ARCH_HAS_GCOV_PROFILE_ALL\narch/x86/Kconfig:92:\tselect ARCH_HAS_KCOV\t\t\tif X86_64\narch/x86/Kconfig:93:\tselect ARCH_HAS_KERNEL_FPU_SUPPORT\narch/x86/Kconfig:94:\tselect ARCH_HAS_MEM_ENCRYPT\narch/x86/Kconfig:95:\tselect ARCH_HAS_MEMBARRIER_SYNC_CORE\narch/x86/Kconfig:96:\tselect ARCH_HAS_NMI_SAFE_THIS_CPU_OPS\narch/x86/Kconfig:97:\tselect ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE\narch/x86/Kconfig:98:\tselect ARCH_HAS_PMEM_API\t\tif X86_64\narch/x86/Kconfig:99:\tselect ARCH_HAS_PREEMPT_LAZY\narch/x86/Kconfig:100:\tselect ARCH_HAS_PTDUMP\narch/x86/Kconfig:101:\tselect ARCH_HAS_PTE_SPECIAL\narch/x86/Kconfig:102:\tselect ARCH_HAS_HW_PTE_YOUNG\narch/x86/Kconfig:103:\tselect ARCH_HAS_NONLEAF_PMD_YOUNG\tif PGTABLE_LEVELS \u003e 2\narch/x86/Kconfig:104:\tselect ARCH_HAS_UACCESS_FLUSHCACHE\tif X86_64\narch/x86/Kconfig:105:\tselect ARCH_HAS_COPY_MC\t\t\tif X86_64\narch/x86/Kconfig:106:\tselect ARCH_HAS_SET_MEMORY\narch/x86/Kconfig:107:\tselect ARCH_HAS_SET_DIRECT_MAP\narch/x86/Kconfig:108:\tselect ARCH_HAS_STRICT_KERNEL_RWX\narch/x86/Kconfig:109:\tselect ARCH_HAS_STRICT_MODULE_RWX\narch/x86/Kconfig:110:\tselect ARCH_HAS_SYNC_CORE_BEFORE_USERMODE\narch/x86/Kconfig:111:\tselect ARCH_HAS_SYSCALL_WRAPPER\narch/x86/Kconfig:112:\tselect ARCH_HAS_UBSAN\narch/x86/Kconfig:113:\tselect ARCH_HAS_DEBUG_WX\narch/x86/Kconfig:114:\tselect ARCH_HAS_ZONE_DMA_SET if EXPERT\narch/x86/Kconfig:115:\tselect ARCH_HAVE_NMI_SAFE_CMPXCHG\narch/x86/Kconfig:116:\tselect ARCH_HAVE_EXTRA_ELF_NOTES\narch/x86/Kconfig:117:\tselect ARCH_MEMORY_ORDER_TSO\narch/x86/Kconfig:118:\tselect ARCH_MHP_MEMMAP_ON_MEMORY_ENABLE\narch/x86/Kconfig:119:\tselect ARCH_MIGHT_HAVE_ACPI_PDC\t\tif ACPI\narch/x86/Kconfig:120:\tselect ARCH_MIGHT_HAVE_PC_PARPORT\narch/x86/Kconfig:121:\tselect ARCH_MIGHT_HAVE_PC_SERIO\narch/x86/Kconfig:122:\tselect ARCH_STACKWALK\narch/x86/Kconfig:123:\tselect ARCH_SUPPORTS_ACPI\narch/x86/Kconfig:124:\tselect ARCH_SUPPORTS_ATOMIC_RMW\narch/x86/Kconfig:125:\tselect ARCH_SUPPORTS_DEBUG_PAGEALLOC\narch/x86/Kconfig:126:\tselect ARCH_SUPPORTS_HUGETLBFS\narch/x86/Kconfig:127:\tselect ARCH_SUPPORTS_PAGE_TABLE_CHECK\tif X86_64\narch/x86/Kconfig:128:\tselect ARCH_HAS_PTE_PROTNONE\t\tif X86_64\narch/x86/Kconfig:129:\tselect ARCH_SUPPORTS_NUMA_BALANCING\tif X86_64\narch/x86/Kconfig:130:\tselect ARCH_SUPPORTS_KMAP_LOCAL_FORCE_MAP\tif NR_CPUS \u003c= 4096\narch/x86/Kconfig:131:\tselect ARCH_SUPPORTS_CFI\t\tif X86_64\narch/x86/Kconfig:132:\tselect ARCH_SUPPORTS_CMDLINE_FROM_BOOTCONFIG\narch/x86/Kconfig:133:\tselect ARCH_USES_CFI_TRAPS\t\tif X86_64 \u0026\u0026 CFI\narch/x86/Kconfig:134:\tselect ARCH_SUPPORTS_LTO_CLANG\narch/x86/Kconfig:135:\tselect ARCH_SUPPORTS_LTO_CLANG_THIN\narch/x86/Kconfig:136:\tselect ARCH_SUPPORTS_RT\narch/x86/Kconfig:137:\tselect ARCH_USE_BUILTIN_BSWAP\narch/x86/Kconfig:138:\tselect ARCH_USE_CMPXCHG_LOCKREF\narch/x86/Kconfig:139:\tselect ARCH_USE_MEMTEST\narch/x86/Kconfig:140:\tselect ARCH_USE_QUEUED_RWLOCKS\narch/x86/Kconfig:141:\tselect ARCH_USE_QUEUED_SPINLOCKS\narch/x86/Kconfig:142:\tselect ARCH_USE_SYM_ANNOTATIONS\narch/x86/Kconfig:143:\tselect ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH\narch/x86/Kconfig:144:\tselect ARCH_WANT_DEFAULT_BPF_JIT\tif X86_64\narch/x86/Kconfig:145:\tselect ARCH_WANTS_CLOCKSOURCE_READ_INLINE\tif X86_64\narch/x86/Kconfig:146:\tselect ARCH_WANTS_DYNAMIC_TASK_STRUCT\narch/x86/Kconfig:147:\tselect ARCH_WANTS_NO_INSTR\narch/x86/Kconfig:148:\tselect ARCH_WANT_GENERAL_HUGETLB\narch/x86/Kconfig:149:\tselect ARCH_WANT_HUGE_PMD_SHARE\t\tif X86_64\narch/x86/Kconfig:150:\tselect ARCH_WANT_LD_ORPHAN_WARN\narch/x86/Kconfig:151:\tselect ARCH_WANT_OPTIMIZE_DAX_VMEMMAP\tif X86_64\narch/x86/Kconfig:152:\tselect ARCH_WANT_OPTIMIZE_HUGETLB_VMEMMAP\tif X86_64\n\n"
}

13/2 2026/10/09 14:38 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 46735
							output: 128
							thoughts: 604
						

Thoughts:
**My Analysis of the WorthFuzzing Criteria**

Okay, let's break this down. First, I need to confirm the negative criteria for `WorthFuzzing=false`. I recall the rules: changes must fall *strictly* into categories like documentation, comments, spelling fixes, or unreachable execution paths. Specifically, I'm focusing on "Unreachable execution paths".

Now, let's examine the changes. I see modifications to `Documentation/arch/s390/vfio-ap.rst`, and source files within `drivers/s390/crypto/`. I'm seeing `Makefile`, `.c` files, and `.h` files all specific to that directory. The key here is the `s390` directory. I know that this directory is gated by `CONFIG_S390` in the `drivers/Makefile`. Further, `CONFIG_VFIO_AP` depends on `AP` (s390 Adjunct Processor) and `KVM`, which are defined in `arch/s390/Kconfig`. This means this code is inherently tied to the s390 architecture.

Crucially, on my target architecture, amd64 (x86_64), `CONFIG_S390` isn't even defined. Consequently, `CONFIG_VFIO_AP` cannot be built or executed. Therefore, *all* the modified code is exclusive to s390 and is, for all intents and purposes, unreachable on amd64. Thus, it's structurally unreachable for fuzzing on my target.

Therefore, `WorthFuzzing` must be `false`. `EnableConfigs` and `FocusSymbols` are empty as expected, given the nature of the changes.

My reasoning is straightforward: this patch introduces migration support and related updates for vfio-ap devices, touching documentation and s390-specific driver code (drivers/s390/crypto/*). These code paths are exclusively for the s390 architecture and cannot be built or executed on amd64; thus, they are unreachable for fuzzing on amd64. Time to call `set-results`.



14/2 2026/10/09 14:38 tool set-results
0m Args:
{
  "EnableConfigs": [],
  "FocusSymbols": [],
  "Reasoning": "The patch series adds live guest migration support for s390 VFIO-AP (Adjunct Processor) devices, modifying documentation and driver code strictly under drivers/s390/crypto/. These code paths are exclusive to the s390 architecture (CONFIG_S390 / CONFIG_VFIO_AP) and cannot be compiled or executed on the target architecture (amd64). Consequently, the changes are structurally unreachable for fuzzing on amd64.",
  "WorthFuzzing": false
}

Results:
{
  "EnableConfigs": null,
  "FocusSymbols": [],
  "Reasoning": "The patch series adds live guest migration support for s390 VFIO-AP (Adjunct Processor) devices, modifying documentation and driver code strictly under drivers/s390/crypto/. These code paths are exclusive to the s390 architecture (CONFIG_S390 / CONFIG_VFIO_AP) and cannot be compiled or executed on the target architecture (amd64). Consequently, the changes are structurally unreachable for fuzzing on amd64.",
  "WorthFuzzing": false
}

15/1 2026/10/09 14:38 action If
0m Args:
{
  "WorthFuzzing": false
}

Results:
null

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)