Skip to contentSkip to conversation

PCI devices passthrough on Arm, part 3

PATCH Superseded Stewart Hildebrand 3 participants 41 messages Feb 2, 2024 – Mar 19, 2024

v13 of 21 Superseded Latest is v21 →

lore
Share & tools
lore
#0 lore raw

v13 cover PCI devices passthrough on Arm, part 3

This is next version of vPCI rework. Aim of this series is to prepare ground for introducing PCI support on ARM platform.

in v13:
- drop ("xen/arm: vpci: permit access to guest vpci space") as it was unnecessary

in v12:
- I (Stewart) coordinated with Volodomyr to send this whole series. So, add my (Stewart) Signed-off-by to all patches.
- The biggest change is to re-work the PCI_COMMAND register patch. Additional feedback has also been addressed - see individual patches.
- Drop ("pci: msi: pass pdev to pci_enable_msi() function") and ("pci: introduce per-domain PCI rwlock") as they were committed
- Rename ("rangeset: add rangeset_empty() function")
to ("rangeset: add rangeset_purge() function")
- Rename ("vpci/header: rework exit path in init_bars")
to ("vpci/header: rework exit path in init_header()")

in v11:
- Added my (Volodymyr) Signed-off-by tag to all patches
- Patch "vpci/header: emulate PCI_COMMAND register for guests" is in intermediate state, because it was agreed to rework it once Stewart's series on register handling are in.
- Addressed comments, please see patch descriptions for details.

in v10:

- Removed patch ("xen/arm: vpci: check guest range"), proper fix for the issue is part of ("vpci/header: emulate PCI_COMMAND register for guests")
- Removed patch ("pci/header: reset the command register when adding devices")
- Added patch ("rangeset: add rangeset_empty() function") because this function is needed in ("vpci/header: handle p2m range sets per BAR")
- Added ("vpci/header: handle p2m range sets per BAR") which addressed an issue discovered by Andrii Chepurnyi during virtio integration
- Added ("pci: msi: pass pdev to pci_enable_msi() function"), which is prereq for ("pci: introduce per-domain PCI rwlock")
- Fixed "Since v9/v8/... " comments in changelogs to reduce confusion. I left "Since" entries for older versions, because they were added by original author of the patches.

in v9:

v9 includes addressed commentes from a previous one. Also it introduces a couple patches from Stewart. This patches are related to vPCI use on ARM. Patch "vpci/header: rework exit path in init_bars" was factored-out from "vpci/header: handle p2m range sets per BAR".

in v8:

The biggest change from previous, mistakenly named, v7 series is how locking is implemented. Instead of d->vpci_rwlock we introduce d->pci_lock which has broader scope, as it protects not only domain's vpci state, but domain's list of PCI devices as well.

As we discussed in IRC with Roger, it is not feasible to rework all the existing code to use the new lock right away. It was agreed that any write access to d->pdev_list will be protected by **both** d->pci_lock in write mode and pcidevs_lock(). Read access on other hand should be protected by either d->pci_lock in read mode or pcidevs_lock(). It is expected that existing code will use pcidevs_lock() and new users will use new rw lock. Of course, this does not mean that new users shall not use pcidevs_lock() when it is appropriate.

Changes from previous versions are described in each separate patch.

Oleksandr Andrushchenko (11):
vpci: use per-domain PCI lock to protect vpci structure
vpci: restrict unhandled read/write operations for guests
vpci: add hooks for PCI device assign/de-assign vpci/header: implement guest BAR register handlers
rangeset: add RANGESETF_no_print flag vpci/header: handle p2m range sets per BAR vpci/header: program p2m with guest BAR view vpci/header: emulate PCI_COMMAND register for guests
vpci: add initial support for virtual PCI bus topology xen/arm: translate virtual PCI bus topology for guests xen/arm: account IO handlers for emulated PCI MSI-X

Volodymyr Babchuk (3):
vpci/header: rework exit path in init_header()
rangeset: add rangeset_purge() function arm/vpci: honor access size when returning an error

 xen/arch/arm/vpci.c           |  63 ++++-
 xen/arch/x86/hvm/vmsi.c       |  31 ++-
 xen/arch/x86/hvm/vmx/vmx.c    |   2 +-
 xen/arch/x86/irq.c            |   8 +-
 xen/arch/x86/msi.c            |  20 +-
 xen/arch/x86/physdev.c        |   2 +
 xen/common/rangeset.c         |  21 +-
 xen/drivers/Kconfig           |   4 +
 xen/drivers/passthrough/pci.c |  35 ++-
 xen/drivers/vpci/header.c     | 495 +++++++++++++++++++++++++++-------
 xen/drivers/vpci/msi.c        |  37 ++-
 xen/drivers/vpci/msix.c       |  59 +++-
 xen/drivers/vpci/vpci.c       | 125 ++++++++-
 xen/include/xen/pci_regs.h    |   1 +
 xen/include/xen/rangeset.h    |   8 +-
 xen/include/xen/sched.h       |  25 +-
 xen/include/xen/vpci.h        |  45 +++-
 17 files changed, 808 insertions(+), 173 deletions(-)

base-commit: 3f819af8a796c0e2f798dd301ec8c3f8cccbc9fc

Signature · 1 line
2.43.0
#1 lore raw

PATCH v13 1/14 vpci: use per-domain PCI lock to protect vpci structure

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away. Existing non-vPCI callers of these MSI-related functions will remain (ab)using the global pcidevs_lock() to ensure pdevs do not go away so as to minimize changes to existing non-vPCI call paths.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

---
Changes in v13:
- hold off adding Roger's R-b tag even though it was provided on v12.2
- use a wrapper construct to ease readability of odd-looking ASSERTs
- new placement of ASSERT in __pci_enable_msix(), __pci_enable_msi(), and pci_enable_msi(). Rearrange/add pdev NULL check.
- expand commit description with details about using either pcidevs_lock() or d->pci_lock

Changes in v12.2:
- drop Roger's R-b
- drop both locks on error paths in vpci_msix_arch_print()
- add another ASSERT in vpci_msix_arch_print(), to enforce the expectation both locks are held before calling vpci_msix_arch_print()
- move pdev_done label in vpci_dump_msi()
- update comments in vpci_dump_msi() to say locks (plural)

Changes in v12.1:
- use read_trylock() in vpci_msix_arch_print()
- fixup in-code comments (revert double space, use DomXEN) in vpci_{read,write}()
- minor updates in commit message
- add Roger's R-b

Changes in v12:
- s/pci_rwlock/pci_lock/ in commit message
- expand comment about scope of pci_lock in sched.h
- in vpci_{read,write}, if hwdom is trying to access a device assigned to dom_xen, holding hwdom->pci_lock is sufficient (no need to hold dom_xen->pci_lock)
- reintroduce ASSERT in vmx_pi_update_irte()
- reintroduce ASSERT in __pci_enable_msi{x}()
- delete note 6. in commit message about removing ASSERTs since we have reintroduced them

Changes in v11:
- Fixed commit message regarding possible spinlocks
- Removed parameter from allocate_and_map_msi_pirq(), which was added in the prev version. Now we are taking pcidevs_lock in physdev_map_pirq()
- Returned ASSERT to pci_enable_msi
- Fixed case when we took read lock instead of write one
- Fixed label indentation

Changes in v10:
- Moved printk pas locked area
- Returned back ASSERTs
- Added new parameter to allocate_and_map_msi_pirq() so it knows if it should take the global pci lock
- Added comment about possible improvement in vpci_write
- Changed ASSERT(rw_is_locked()) to rw_is_write_locked() in appropriate places
- Renamed release_domain_locks() to release_domain_write_locks()
- moved domain_done label in vpci_dump_msi() to correct place
Changes in v9:
- extended locked region to protect vpci_remove_device and vpci_add_handlers() calls
- vpci_write() takes lock in the write mode to protect potential call to modify_bars()
- renamed lock releasing function
- removed ASSERT()s from msi code
- added trylock in vpci_dump_msi

Changes in v8:
- changed d->vpci_lock to d->pci_lock
- introducing d->pci_lock in a separate patch
- extended locked region in vpci_process_pending
- removed pcidevs_lockis vpci_dump_msi()
- removed some changes as they are not needed with the new locking scheme
- added handling for hwdom && dom_xen case

---
 xen/arch/x86/hvm/vmsi.c       | 31 +++++++++++++--------
 xen/arch/x86/hvm/vmx/vmx.c    |  2 +-
 xen/arch/x86/irq.c            |  8 +++---
 xen/arch/x86/msi.c            | 20 +++++++++-----
 xen/arch/x86/physdev.c        |  2 ++
 xen/drivers/passthrough/pci.c |  9 +++---
 xen/drivers/vpci/header.c     | 18 ++++++++++++
 xen/drivers/vpci/msi.c        | 30 +++++++++++++++++---
 xen/drivers/vpci/msix.c       | 52 ++++++++++++++++++++++++++++++-----
 xen/drivers/vpci/vpci.c       | 24 ++++++++++++++--
 xen/include/xen/sched.h       | 15 +++++++++-
 11 files changed, 170 insertions(+), 41 deletions(-)
xen/arch/x86/hvm/vmsi.c +20 -11
index 128f23636279..f29089178a59 100644
@@ -468,7 +468,7 @@ int msixtbl_pt_register(struct domain *d, struct pirq *pirq, uint64_t gtable)
     struct msixtbl_entry *entry, *new_entry;
     int r = -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -538,7 +538,7 @@ void msixtbl_pt_unregister(struct domain *d, struct pirq *pirq)
     struct pci_dev *pdev;
     struct msixtbl_entry *entry;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -684,7 +684,7 @@ static int vpci_msi_update(const struct pci_dev *pdev, uint32_t data,
 {
     unsigned int i;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(rw_is_locked(&pdev->domain->pci_lock));
 
     if ( (address & MSI_ADDR_BASE_MASK) != MSI_ADDR_HEADER )
     {
@@ -725,8 +725,8 @@ void vpci_msi_arch_update(struct vpci_msi *msi, const struct pci_dev *pdev)
     int rc;
 
     ASSERT(msi->arch.pirq != INVALID_PIRQ);
+    ASSERT(rw_is_locked(&pdev->domain->pci_lock));
 
-    pcidevs_lock();
     for ( i = 0; i < msi->vectors && msi->arch.bound; i++ )
     {
         struct xen_domctl_bind_pt_irq unbind = {
@@ -745,7 +745,6 @@ void vpci_msi_arch_update(struct vpci_msi *msi, const struct pci_dev *pdev)
 
     msi->arch.bound = !vpci_msi_update(pdev, msi->data, msi->address,
                                        msi->vectors, msi->arch.pirq, msi->mask);
-    pcidevs_unlock();
 }
 
 static int vpci_msi_enable(const struct pci_dev *pdev, unsigned int nr,
@@ -778,15 +777,14 @@ int vpci_msi_arch_enable(struct vpci_msi *msi, const struct pci_dev *pdev,
     int rc;
 
     ASSERT(msi->arch.pirq == INVALID_PIRQ);
+    ASSERT(rw_is_locked(&pdev->domain->pci_lock));
     rc = vpci_msi_enable(pdev, vectors, 0);
     if ( rc < 0 )
         return rc;
     msi->arch.pirq = rc;
 
-    pcidevs_lock();
     msi->arch.bound = !vpci_msi_update(pdev, msi->data, msi->address, vectors,
                                        msi->arch.pirq, msi->mask);
-    pcidevs_unlock();
 
     return 0;
 }
@@ -797,8 +795,8 @@ static void vpci_msi_disable(const struct pci_dev *pdev, int pirq,
     unsigned int i;
 
     ASSERT(pirq != INVALID_PIRQ);
+    ASSERT(rw_is_locked(&pdev->domain->pci_lock));
 
-    pcidevs_lock();
     for ( i = 0; i < nr && bound; i++ )
     {
         struct xen_domctl_bind_pt_irq bind = {
@@ -814,7 +812,6 @@ static void vpci_msi_disable(const struct pci_dev *pdev, int pirq,
     write_lock(&pdev->domain->event_lock);
     unmap_domain_pirq(pdev->domain, pirq);
     write_unlock(&pdev->domain->event_lock);
-    pcidevs_unlock();
 }
 
 void vpci_msi_arch_disable(struct vpci_msi *msi, const struct pci_dev *pdev)
@@ -854,6 +851,7 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
     int rc;
 
     ASSERT(entry->arch.pirq == INVALID_PIRQ);
+    ASSERT(rw_is_locked(&pdev->domain->pci_lock));
     rc = vpci_msi_enable(pdev, vmsix_entry_nr(pdev->vpci->msix, entry),
                          table_base);
     if ( rc < 0 )
@@ -861,7 +859,6 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
 
     entry->arch.pirq = rc;
 
-    pcidevs_lock();
     rc = vpci_msi_update(pdev, entry->data, entry->addr, 1, entry->arch.pirq,
                          entry->masked);
     if ( rc )
@@ -869,7 +866,6 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
         vpci_msi_disable(pdev, entry->arch.pirq, 1, false);
         entry->arch.pirq = INVALID_PIRQ;
     }
-    pcidevs_unlock();
 
     return rc;
 }
@@ -895,6 +891,9 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));
+
     for ( i = 0; i < msix->max_entries; i++ )
     {
         const struct vpci_msix_entry *entry = &msix->entries[i];
@@ -913,13 +912,23 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
             struct pci_dev *pdev = msix->pdev;
 
             spin_unlock(&msix->pdev->vpci->lock);
+            read_unlock(&pdev->domain->pci_lock);
             process_pending_softirqs();
+
+            if ( !read_trylock(&pdev->domain->pci_lock) )
+                return -EBUSY;
+
             /* NB: we assume that pdev cannot go away for an alive domain. */
             if ( !pdev->vpci || !spin_trylock(&pdev->vpci->lock) )
+            {
+                read_unlock(&pdev->domain->pci_lock);
                 return -EBUSY;
+            }
+
             if ( pdev->vpci->msix != msix )
             {
                 spin_unlock(&pdev->vpci->lock);
+                read_unlock(&pdev->domain->pci_lock);
                 return -EAGAIN;
             }
         }
xen/arch/x86/hvm/vmx/vmx.c +1 -1
index 1500dca6039f..5aac4863d30a 100644
@@ -413,7 +413,7 @@ static int cf_check vmx_pi_update_irte(const struct vcpu *v,
 
     spin_unlock_irq(&desc->lock);
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(msi_desc->dev->domain));
 
     return iommu_update_ire_from_msi(msi_desc, &msi_desc->msg);
 
xen/arch/x86/irq.c +4 -4
index bbae7751e494..e31144d82fd4 100644
@@ -2164,7 +2164,7 @@ int map_domain_pirq(
         struct pci_dev *pdev;
         unsigned int nr = 0;
 
-        ASSERT(pcidevs_locked());
+        ASSERT(pdev_list_is_read_locked(d));
 
         ret = -ENODEV;
         if ( !cpu_has_apic )
@@ -2321,7 +2321,7 @@ int unmap_domain_pirq(struct domain *d, int pirq)
     if ( (pirq < 0) || (pirq >= d->nr_pirqs) )
         return -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     info = pirq_info(d, pirq);
@@ -2886,6 +2886,8 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 {
     int irq, pirq, ret;
 
+    ASSERT(pdev_list_is_read_locked(d));
+
     switch ( type )
     {
     case MAP_PIRQ_TYPE_MSI:
@@ -2915,7 +2917,6 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 
     msi->irq = irq;
 
-    pcidevs_lock();
     /* Verify or get pirq. */
     write_lock(&d->event_lock);
     pirq = allocate_pirq(d, index, *pirq_p, irq, type, &msi->entry_nr);
@@ -2931,7 +2932,6 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 
  done:
     write_unlock(&d->event_lock);
-    pcidevs_unlock();
     if ( ret )
     {
         switch ( type )
xen/arch/x86/msi.c +13 -7
index 335c0868a225..e008b6789a28 100644
@@ -602,7 +602,7 @@ static int msi_capability_init(struct pci_dev *dev,
     unsigned int i, mpos;
     uint16_t control;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(dev->domain));
     pos = pci_find_cap_offset(dev->sbdf, PCI_CAP_ID_MSI);
     if ( !pos )
         return -ENODEV;
@@ -771,7 +771,7 @@ static int msix_capability_init(struct pci_dev *dev,
     if ( !pos )
         return -ENODEV;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(dev->domain));
 
     control = pci_conf_read16(dev->sbdf, msix_control_reg(pos));
     /*
@@ -988,11 +988,11 @@ static int __pci_enable_msi(struct pci_dev *pdev, struct msi_info *msi,
 {
     struct msi_desc *old_desc;
 
-    ASSERT(pcidevs_locked());
-
     if ( !pdev )
         return -ENODEV;
 
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
+
     old_desc = find_msi_entry(pdev, msi->irq, PCI_CAP_ID_MSI);
     if ( old_desc )
     {
@@ -1043,9 +1043,12 @@ static int __pci_enable_msix(struct pci_dev *pdev, struct msi_info *msi,
 {
     struct msi_desc *old_desc;
 
-    ASSERT(pcidevs_locked());
+    if ( !pdev )
+        return -ENODEV;
+
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
 
-    if ( !pdev || !pdev->msix )
+    if ( !pdev->msix )
         return -ENODEV;
 
     if ( msi->entry_nr >= pdev->msix->nr_entries )
@@ -1154,7 +1157,10 @@ int pci_prepare_msix(u16 seg, u8 bus, u8 devfn, bool off)
 int pci_enable_msi(struct pci_dev *pdev, struct msi_info *msi,
                    struct msi_desc **desc)
 {
-    ASSERT(pcidevs_locked());
+    if ( !pdev )
+        return -ENODEV;
+
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
 
     if ( !use_msi )
         return -EPERM;
xen/arch/x86/physdev.c +2 -0
index 47c4da0af7e1..369c9e788c1c 100644
@@ -123,7 +123,9 @@ int physdev_map_pirq(domid_t domid, int type, int *index, int *pirq_p,
 
     case MAP_PIRQ_TYPE_MSI:
     case MAP_PIRQ_TYPE_MULTI_MSI:
+        pcidevs_lock();
         ret = allocate_and_map_msi_pirq(d, *index, pirq_p, type, msi);
+        pcidevs_unlock();
         break;
 
     default:
xen/drivers/passthrough/pci.c +5 -4
index 47c0eee7bdcc..c97dd4504a7a 100644
@@ -750,7 +750,6 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
         pdev->domain = hardware_domain;
         write_lock(&hardware_domain->pci_lock);
         list_add(&pdev->domain_list, &hardware_domain->pdev_list);
-        write_unlock(&hardware_domain->pci_lock);
 
         /*
          * For devices not discovered by Xen during boot, add vPCI handlers
@@ -759,18 +758,18 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
         ret = vpci_add_handlers(pdev);
         if ( ret )
         {
-            printk(XENLOG_ERR "Setup of vPCI failed: %d\n", ret);
-            write_lock(&hardware_domain->pci_lock);
             list_del(&pdev->domain_list);
             write_unlock(&hardware_domain->pci_lock);
             pdev->domain = NULL;
+            printk(XENLOG_ERR "Setup of vPCI failed: %d\n", ret);
             goto out;
         }
+        write_unlock(&hardware_domain->pci_lock);
         ret = iommu_add_device(pdev);
         if ( ret )
         {
-            vpci_remove_device(pdev);
             write_lock(&hardware_domain->pci_lock);
+            vpci_remove_device(pdev);
             list_del(&pdev->domain_list);
             write_unlock(&hardware_domain->pci_lock);
             pdev->domain = NULL;
@@ -1146,7 +1145,9 @@ static void __hwdom_init setup_one_hwdom_device(const struct setup_hwdom *ctxt,
     } while ( devfn != pdev->devfn &&
               PCI_SLOT(devfn) == PCI_SLOT(pdev->devfn) );
 
+    write_lock(&ctxt->d->pci_lock);
     err = vpci_add_handlers(pdev);
+    write_unlock(&ctxt->d->pci_lock);
     if ( err )
         printk(XENLOG_ERR "setup of vPCI for d%d failed: %d\n",
                ctxt->d->domain_id, err);
xen/drivers/vpci/header.c +18 -0
index 58195549d50a..8f5850b8cf6d 100644
@@ -173,6 +173,7 @@ bool vpci_process_pending(struct vcpu *v)
         if ( rc == -ERESTART )
             return true;
 
+        write_lock(&v->domain->pci_lock);
         spin_lock(&v->vpci.pdev->vpci->lock);
         /* Disable memory decoding unconditionally on failure. */
         modify_decoding(v->vpci.pdev,
@@ -191,6 +192,7 @@ bool vpci_process_pending(struct vcpu *v)
              * failure.
              */
             vpci_remove_device(v->vpci.pdev);
+        write_unlock(&v->domain->pci_lock);
     }
 
     return false;
@@ -202,8 +204,20 @@ static int __init apply_map(struct domain *d, const struct pci_dev *pdev,
     struct map_data data = { .d = d, .map = true };
     int rc;
 
+    ASSERT(rw_is_write_locked(&d->pci_lock));
+
     while ( (rc = rangeset_consume_ranges(mem, map_range, &data)) == -ERESTART )
+    {
+        /*
+         * It's safe to drop and reacquire the lock in this context
+         * without risking pdev disappearing because devices cannot be
+         * removed until the initial domain has been started.
+         */
+        write_unlock(&d->pci_lock);
         process_pending_softirqs();
+        write_lock(&d->pci_lock);
+    }
+
     rangeset_destroy(mem);
     if ( !rc )
         modify_decoding(pdev, cmd, false);
@@ -244,6 +258,8 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
     unsigned int i;
     int rc;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !mem )
         return -ENOMEM;
 
@@ -524,6 +540,8 @@ static int cf_check init_header(struct pci_dev *pdev)
     int rc;
     bool mask_cap_list = false;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     switch ( pci_conf_read8(pdev->sbdf, PCI_HEADER_TYPE) & 0x7f )
     {
     case PCI_HEADER_TYPE_NORMAL:
xen/drivers/vpci/msi.c +26 -4
index a253ccbd7db7..dc71938e23f5 100644
@@ -263,7 +263,7 @@ REGISTER_VPCI_INIT(init_msi, VPCI_PRIORITY_LOW);
 
 void vpci_dump_msi(void)
 {
-    const struct domain *d;
+    struct domain *d;
 
     rcu_read_lock(&domlist_read_lock);
     for_each_domain ( d )
@@ -275,6 +275,9 @@ void vpci_dump_msi(void)
 
         printk("vPCI MSI/MSI-X d%d\n", d->domain_id);
 
+        if ( !read_trylock(&d->pci_lock) )
+            continue;
+
         for_each_pdev ( d, pdev )
         {
             const struct vpci_msi *msi;
@@ -313,17 +316,36 @@ void vpci_dump_msi(void)
                 {
                     /*
                      * On error vpci_msix_arch_print will always return without
-                     * holding the lock.
+                     * holding the locks.
                      */
                     printk("unable to print all MSI-X entries: %d\n", rc);
-                    process_pending_softirqs();
-                    continue;
+                    goto pdev_done;
                 }
             }
 
+            /*
+             * Unlock locks to process pending softirqs. This is
+             * potentially unsafe, as d->pdev_list can be changed in
+             * meantime.
+             */
             spin_unlock(&pdev->vpci->lock);
+            read_unlock(&d->pci_lock);
+        pdev_done:
             process_pending_softirqs();
+            if ( !read_trylock(&d->pci_lock) )
+            {
+                printk("unable to access other devices for the domain\n");
+                goto domain_done;
+            }
         }
+        read_unlock(&d->pci_lock);
+    domain_done:
+        /*
+         * We need this label at the end of the loop, but some
+         * compilers might not be happy about label at the end of the
+         * compound statement so we adding an empty statement here.
+         */
+        ;
     }
     rcu_read_unlock(&domlist_read_lock);
 }
xen/drivers/vpci/msix.c +45 -7

110 lines not on this page · raw message

xen/drivers/vpci/vpci.c +22 -2
index 72ef277c4f8e..475272b173f3 100644
@@ -42,6 +42,8 @@ extern vpci_register_init_t *const __end_vpci_array[];
 
 void vpci_remove_device(struct pci_dev *pdev)
 {
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !has_vpci(pdev->domain) || !pdev->vpci )
         return;
 
@@ -77,6 +79,8 @@ int vpci_add_handlers(struct pci_dev *pdev)
     const unsigned long *ro_map;
     int rc = 0;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !has_vpci(pdev->domain) )
         return 0;
 
@@ -361,7 +365,7 @@ static uint32_t merge_result(uint32_t data, uint32_t new, unsigned int size,
 
 uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
 {
-    const struct domain *d = current->domain;
+    struct domain *d = current->domain;
     const struct pci_dev *pdev;
     const struct vpci_register *r;
     unsigned int data_offset = 0;
@@ -376,12 +380,18 @@ uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
     /*
      * Find the PCI dev matching the address, which for hwdom also requires
      * consulting DomXEN.  Passthrough everything that's not trapped.
+     * If this is hwdom and the device is assigned to DomXEN, acquiring hwdom's
+     * pci_lock is sufficient.
      */
+    read_lock(&d->pci_lock);
     pdev = pci_get_pdev(d, sbdf);
     if ( !pdev && is_hardware_domain(d) )
         pdev = pci_get_pdev(dom_xen, sbdf);
     if ( !pdev || !pdev->vpci )
+    {
+        read_unlock(&d->pci_lock);
         return vpci_read_hw(sbdf, reg, size);
+    }
 
     spin_lock(&pdev->vpci->lock);
 
@@ -428,6 +438,7 @@ uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
         ASSERT(data_offset < size);
     }
     spin_unlock(&pdev->vpci->lock);
+    read_unlock(&d->pci_lock);
 
     if ( data_offset < size )
     {
@@ -470,7 +481,7 @@ static void vpci_write_helper(const struct pci_dev *pdev,
 void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
                 uint32_t data)
 {
-    const struct domain *d = current->domain;
+    struct domain *d = current->domain;
     const struct pci_dev *pdev;
     const struct vpci_register *r;
     unsigned int data_offset = 0;
@@ -484,7 +495,13 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
     /*
      * Find the PCI dev matching the address, which for hwdom also requires
      * consulting DomXEN.  Passthrough everything that's not trapped.
+     * If this is hwdom and the device is assigned to DomXEN, acquiring hwdom's
+     * pci_lock is sufficient.
+     *
+     * TODO: We need to take pci_locks in exclusive mode only if we
+     * are modifying BARs, so there is a room for improvement.
      */
+    write_lock(&d->pci_lock);
     pdev = pci_get_pdev(d, sbdf);
     if ( !pdev && is_hardware_domain(d) )
         pdev = pci_get_pdev(dom_xen, sbdf);
@@ -493,6 +510,8 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
         /* Ignore writes to read-only devices, which have no ->vpci. */
         const unsigned long *ro_map = pci_get_ro_map(sbdf.seg);
 
+        write_unlock(&d->pci_lock);
+
         if ( !ro_map || !test_bit(sbdf.bdf, ro_map) )
             vpci_write_hw(sbdf, reg, size, data);
         return;
@@ -534,6 +553,7 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
         ASSERT(data_offset < size);
     }
     spin_unlock(&pdev->vpci->lock);
+    write_unlock(&d->pci_lock);
 
     if ( data_offset < size )
         /* Tailing gap, write the remaining. */
xen/include/xen/sched.h +14 -1
index 9da91e0e6244..c3adec1aca3c 100644
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,
@@ -628,6 +629,18 @@ struct domain
     unsigned int cdf;
 };
 
+/*
+ * Check for use in ASSERTs to ensure that:
+ *   1. we can *read* d->pdev_list
+ *   2. pdevs (belonging to this domain) do not go away
+ *   3. pdevs (belonging to this domain) do not get assigned to other domains
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                           \
+        struct domain *d_ = (d);                                 \
+        pcidevs_locked() || (d_ && rw_is_locked(&d_->pci_lock)); \
+    })
+
 static inline struct page_list_head *page_to_list(
     struct domain *d, const struct page_info *pg)
 {
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 9 lines · Stewart Hildebrand

---
Changes in v13:
- hold off adding Roger's R-b tag even though it was provided on v12.2
- use a wrapper construct to ease readability of odd-looking ASSERTs
- new placement of ASSERT in __pci_enable_msix(), __pci_enable_msi(), and pci_enable_msi(). Rearrange/add pdev NULL check.
- expand commit description with details about using either pcidevs_lock() or d->pci_lock

Quoted 7 lines

Changes in v12.2:
- drop Roger's R-b
- drop both locks on error paths in vpci_msix_arch_print()
- add another ASSERT in vpci_msix_arch_print(), to enforce the expectation both locks are held before calling vpci_msix_arch_print()
- move pdev_done label in vpci_dump_msi()
- update comments in vpci_dump_msi() to say locks (plural)

Here's a patchew link to show just the diff-of-diff from v12.2 (where Roger had given a R-b) to v13.

https://patchew.org/Xen/[email protected]/diff/[email protected]/

#3 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

In reply to Stewart Hildebrand
Quoted 55 lines · Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away. Existing non-vPCI callers of these MSI-related functions will remain (ab)using the global pcidevs_lock() to ensure pdevs do not go away so as to minimize changes to existing non-vPCI call paths.

Quoted 3 lines

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

I would add that when possible, the existing callers haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs lock. This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time.

IIRC Jan had concerns about why some existing use-cases are not switched straight to use the new per-domain pci_lock in this patch.

Quoted 114 lines

---
Changes in v13:
- hold off adding Roger's R-b tag even though it was provided on v12.2
- use a wrapper construct to ease readability of odd-looking ASSERTs
- new placement of ASSERT in __pci_enable_msix(), __pci_enable_msi(), and pci_enable_msi(). Rearrange/add pdev NULL check.
- expand commit description with details about using either pcidevs_lock() or d->pci_lock

Changes in v12.2:
- drop Roger's R-b
- drop both locks on error paths in vpci_msix_arch_print()
- add another ASSERT in vpci_msix_arch_print(), to enforce the expectation both locks are held before calling vpci_msix_arch_print()
- move pdev_done label in vpci_dump_msi()
- update comments in vpci_dump_msi() to say locks (plural)

Changes in v12.1:
- use read_trylock() in vpci_msix_arch_print()
- fixup in-code comments (revert double space, use DomXEN) in vpci_{read,write}()
- minor updates in commit message
- add Roger's R-b

Changes in v12:
- s/pci_rwlock/pci_lock/ in commit message
- expand comment about scope of pci_lock in sched.h
- in vpci_{read,write}, if hwdom is trying to access a device assigned to dom_xen, holding hwdom->pci_lock is sufficient (no need to hold dom_xen->pci_lock)
- reintroduce ASSERT in vmx_pi_update_irte()
- reintroduce ASSERT in __pci_enable_msi{x}()
- delete note 6. in commit message about removing ASSERTs since we have reintroduced them

Changes in v11:
- Fixed commit message regarding possible spinlocks
- Removed parameter from allocate_and_map_msi_pirq(), which was added in the prev version. Now we are taking pcidevs_lock in physdev_map_pirq()
- Returned ASSERT to pci_enable_msi
- Fixed case when we took read lock instead of write one
- Fixed label indentation

Changes in v10:
- Moved printk pas locked area
- Returned back ASSERTs
- Added new parameter to allocate_and_map_msi_pirq() so it knows if it should take the global pci lock
- Added comment about possible improvement in vpci_write
- Changed ASSERT(rw_is_locked()) to rw_is_write_locked() in appropriate places
- Renamed release_domain_locks() to release_domain_write_locks()
- moved domain_done label in vpci_dump_msi() to correct place
Changes in v9:
- extended locked region to protect vpci_remove_device and vpci_add_handlers() calls
- vpci_write() takes lock in the write mode to protect potential call to modify_bars()
- renamed lock releasing function
- removed ASSERT()s from msi code
- added trylock in vpci_dump_msi

Changes in v8:
- changed d->vpci_lock to d->pci_lock
- introducing d->pci_lock in a separate patch
- extended locked region in vpci_process_pending
- removed pcidevs_lockis vpci_dump_msi()
- removed some changes as they are not needed with the new locking scheme
- added handling for hwdom && dom_xen case

---
 xen/arch/x86/hvm/vmsi.c       | 31 +++++++++++++--------
 xen/arch/x86/hvm/vmx/vmx.c    |  2 +-
 xen/arch/x86/irq.c            |  8 +++---
 xen/arch/x86/msi.c            | 20 +++++++++-----
 xen/arch/x86/physdev.c        |  2 ++
 xen/drivers/passthrough/pci.c |  9 +++---
 xen/drivers/vpci/header.c     | 18 ++++++++++++
 xen/drivers/vpci/msi.c        | 30 +++++++++++++++++---
 xen/drivers/vpci/msix.c       | 52 ++++++++++++++++++++++++++++++-----
 xen/drivers/vpci/vpci.c       | 24 ++++++++++++++--
 xen/include/xen/sched.h       | 15 +++++++++-
 11 files changed, 170 insertions(+), 41 deletions(-)
xen/arch/x86/hvm/vmsi.c +2 -2
index 128f23636279..f29089178a59 100644
@@ -468,7 +468,7 @@ int msixtbl_pt_register(struct domain *d, struct pirq *pirq, uint64_t gtable)
     struct msixtbl_entry *entry, *new_entry;
     int r = -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -538,7 +538,7 @@ void msixtbl_pt_unregister(struct domain *d, struct pirq *pirq)
     struct pci_dev *pdev;
     struct msixtbl_entry *entry;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )

xen/arch/x86/hvm/vmsi.c static int vpci_msi_update(const struct pci_dev *pdev, uint32_t data, · line 687

Quoted 5 lines
xen/arch/x86/hvm/vmsi.c +1 -1
@@ -684,7 +684,7 @@ static int vpci_msi_update(const struct pci_dev *pdev, uint32_t data,
 {
     unsigned int i;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(rw_is_locked(&pdev->domain->pci_lock));

Any reason to not use the newly introduced helper here? I know the pcidevs will never be locked here given the new lock usage, but still it would be less confusing if the new helper was used consistently.

Otherwise we need a comment here as to why the helper can't be used, in order to avoid confusion in the future.

Quoted 15 lines

xen/include/xen/sched.h

Quoted 1 line
xen/include/xen/sched.h +0 -0

index 9da91e0e6244..c3adec1aca3c 100644

xen/include/xen/sched.h +2 -1
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,

xen/include/xen/sched.h struct domain · line 636

Quoted 8 lines
xen/include/xen/sched.h +5 -0
@@ -628,6 +629,18 @@ struct domain
     unsigned int cdf;
 };
 
+/*
+ * Check for use in ASSERTs to ensure that:
+ *   1. we can *read* d->pdev_list
+ *   2. pdevs (belonging to this domain) do not go away
+ *   3. pdevs (belonging to this domain) do not get assigned to other domains

I think you can just state that this check ensures there will be no changes to the entries in d->pdev_list, but not the contents of each entry. No changes to d->pdev_list already ensures not devices can be deassigned or removed from the system, and obviously makes the list safe to iterate against.

I would also drop the explicitly mention this is intended for ASSERT
usage: there's nothing specific in the code that prevents it from being used in other places (albeit I think that's unlikely).

xen/include/xen/sched.h struct domain · line 639

Quoted 3 lines
xen/include/xen/sched.h +3 -0
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                           \

I would be tempted to drop at least the '_read_' part from the name, the name is getting a bit too long for my taste.

xen/include/xen/sched.h struct domain · line 640

Quoted 1 line
xen/include/xen/sched.h +1 -0
+        struct domain *d_ = (d);                                 \

Why do you need this local domain variable? Can't you use the d parameter directly?

Such assign will prevent using a const 'd' parameter, and 'd_' itself should be const IMO (iff we really need this).

Also sched.h is not the best place, can't you just place it in pci.h?

Thanks, Roger.

#4 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 29 lines · Roger Pau Monné
Quoted 13 lines · Stewart Hildebrand
xen/include/xen/sched.h +2 -1
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,

xen/include/xen/sched.h struct domain · line 636

Quoted 8 lines
xen/include/xen/sched.h +5 -0
@@ -628,6 +629,18 @@ struct domain
     unsigned int cdf;
 };
 
+/*
+ * Check for use in ASSERTs to ensure that:
+ *   1. we can *read* d->pdev_list
+ *   2. pdevs (belonging to this domain) do not go away
+ *   3. pdevs (belonging to this domain) do not get assigned to other domains

I think you can just state that this check ensures there will be no changes to the entries in d->pdev_list, but not the contents of each entry. No changes to d->pdev_list already ensures not devices can be deassigned or removed from the system, and obviously makes the list safe to iterate against.

Quoted 3 lines

I would also drop the explicitly mention this is intended for ASSERT
usage: there's nothing specific in the code that prevents it from being used in other places (albeit I think that's unlikely).

But pcidevs_locked(), resolving to spin_is_locked(), isn't reliable. The assertion usage is best-effort only, without a guarantee that all wrong uses would be caught.

Quoted 6 lines

xen/include/xen/sched.h struct domain · line 639

Quoted 3 lines
xen/include/xen/sched.h +3 -0
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                           \

I would be tempted to drop at least the '_read_' part from the name, the name is getting a bit too long for my taste.

While I agree with the long-ish aspect, I'm afraid the "read" part is crucial. As a result I see no room for shortening.

Quoted 4 lines

xen/include/xen/sched.h struct domain · line 640

Quoted 1 line
xen/include/xen/sched.h +1 -0
+        struct domain *d_ = (d);                                 \

Why do you need this local domain variable? Can't you use the d parameter directly?

It would be evaluated then somewhere between 0 and 2 times.

Jan

#5 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 30 lines · Jan Beulich
Quoted 29 lines · Roger Pau Monné
Quoted 13 lines · Stewart Hildebrand
xen/include/xen/sched.h +2 -1
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,

xen/include/xen/sched.h struct domain · line 636

Quoted 8 lines
xen/include/xen/sched.h +5 -0
@@ -628,6 +629,18 @@ struct domain
     unsigned int cdf;
 };
 
+/*
+ * Check for use in ASSERTs to ensure that:
+ *   1. we can *read* d->pdev_list
+ *   2. pdevs (belonging to this domain) do not go away
+ *   3. pdevs (belonging to this domain) do not get assigned to other domains

I think you can just state that this check ensures there will be no changes to the entries in d->pdev_list, but not the contents of each entry. No changes to d->pdev_list already ensures not devices can be deassigned or removed from the system, and obviously makes the list safe to iterate against.

Quoted 7 lines
Quoted 3 lines

I would also drop the explicitly mention this is intended for ASSERT
usage: there's nothing specific in the code that prevents it from being used in other places (albeit I think that's unlikely).

But pcidevs_locked(), resolving to spin_is_locked(), isn't reliable. The assertion usage is best-effort only, without a guarantee that all wrong uses would be caught.

Do we want to protect this with !NDEBUG guards then?

Quoted 9 lines
Quoted 6 lines

xen/include/xen/sched.h struct domain · line 639

Quoted 3 lines
xen/include/xen/sched.h +3 -0
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                           \

I would be tempted to drop at least the '_read_' part from the name, the name is getting a bit too long for my taste.

While I agree with the long-ish aspect, I'm afraid the "read" part is crucial. As a result I see no room for shortening.

OK, if you think that's crucial then I'm not going to argue.

Quoted 6 lines
Quoted 4 lines

xen/include/xen/sched.h struct domain · line 640

Quoted 1 line
xen/include/xen/sched.h +1 -0
+        struct domain *d_ = (d);                                 \

Why do you need this local domain variable? Can't you use the d parameter directly?

It would be evaluated then somewhere between 0 and 2 times.

It's ASSERT code only, so I don't see that as an issue. Otherwise d_ needs to be made const.

Thanks, Roger.

#6 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 35 lines · Roger Pau Monné
Quoted 34 lines · Jan Beulich
Quoted 32 lines · Roger Pau Monné
Quoted 13 lines · Stewart Hildebrand
xen/include/xen/sched.h +2 -1
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,

xen/include/xen/sched.h struct domain · line 636

Quoted 8 lines
xen/include/xen/sched.h +5 -0
@@ -628,6 +629,18 @@ struct domain
     unsigned int cdf;
 };
 
+/*
+ * Check for use in ASSERTs to ensure that:
+ *   1. we can *read* d->pdev_list
+ *   2. pdevs (belonging to this domain) do not go away
+ *   3. pdevs (belonging to this domain) do not get assigned to other domains

I think you can just state that this check ensures there will be no changes to the entries in d->pdev_list, but not the contents of each entry. No changes to d->pdev_list already ensures not devices can be deassigned or removed from the system, and obviously makes the list safe to iterate against.

I would also drop the explicitly mention this is intended for ASSERT
usage: there's nothing specific in the code that prevents it from being used in other places (albeit I think that's unlikely).

Quoted 5 lines
Quoted 3 lines

But pcidevs_locked(), resolving to spin_is_locked(), isn't reliable. The assertion usage is best-effort only, without a guarantee that all wrong uses would be caught.

Do we want to protect this with !NDEBUG guards then?

Yes, that would look to be desirable.

Quoted 12 lines
Quoted 9 lines
Quoted 6 lines

xen/include/xen/sched.h struct domain · line 639

Quoted 3 lines
xen/include/xen/sched.h +3 -0
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                           \

I would be tempted to drop at least the '_read_' part from the name, the name is getting a bit too long for my taste.

While I agree with the long-ish aspect, I'm afraid the "read" part is crucial. As a result I see no room for shortening.

OK, if you think that's crucial then I'm not going to argue.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

xen/include/xen/sched.h struct domain · line 640

Quoted 1 line
xen/include/xen/sched.h +1 -0
+        struct domain *d_ = (d);                                 \

Why do you need this local domain variable? Can't you use the d parameter directly?

It would be evaluated then somewhere between 0 and 2 times.

It's ASSERT code only, so I don't see that as an issue.

Fair point.

Quoted 1 line

Otherwise d_ needs to be made const.

Indeed, but for assert-only code I agree the option is slightly better, ideally suitably commented upon.

Jan

#7 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 36 lines · Jan Beulich
Quoted 35 lines · Roger Pau Monné
Quoted 34 lines · Jan Beulich
Quoted 32 lines · Roger Pau Monné
Quoted 13 lines · Stewart Hildebrand
xen/include/xen/sched.h +2 -1
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,

xen/include/xen/sched.h struct domain · line 636

Quoted 8 lines
xen/include/xen/sched.h +5 -0
@@ -628,6 +629,18 @@ struct domain
     unsigned int cdf;
 };
 
+/*
+ * Check for use in ASSERTs to ensure that:
+ *   1. we can *read* d->pdev_list
+ *   2. pdevs (belonging to this domain) do not go away
+ *   3. pdevs (belonging to this domain) do not get assigned to other domains

I think you can just state that this check ensures there will be no changes to the entries in d->pdev_list, but not the contents of each entry. No changes to d->pdev_list already ensures not devices can be deassigned or removed from the system, and obviously makes the list safe to iterate against.

I would also drop the explicitly mention this is intended for ASSERT
usage: there's nothing specific in the code that prevents it from being used in other places (albeit I think that's unlikely).

Quoted 7 lines
Quoted 5 lines
Quoted 3 lines

But pcidevs_locked(), resolving to spin_is_locked(), isn't reliable. The assertion usage is best-effort only, without a guarantee that all wrong uses would be caught.

Do we want to protect this with !NDEBUG guards then?

Yes, that would look to be desirable.

We will then also need a definition of pdev_list_is_read_locked() in the #else case so we don't risk running into "error: implicit declaration of function 'pdev_list_is_read_locked'".

Such a definition might look like:

#define pdev_list_is_read_locked(d) ({ (void)d; ASSERT_UNREACHABLE(); false; })

so that we still evaluate d exactly once in the NDEBUG case.

Quoted 19 lines
Quoted 19 lines
Quoted 9 lines
Quoted 6 lines

xen/include/xen/sched.h struct domain · line 639

Quoted 3 lines
xen/include/xen/sched.h +3 -0
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                           \

I would be tempted to drop at least the '_read_' part from the name, the name is getting a bit too long for my taste.

While I agree with the long-ish aspect, I'm afraid the "read" part is crucial. As a result I see no room for shortening.

OK, if you think that's crucial then I'm not going to argue.

Quoted 6 lines
Quoted 4 lines

xen/include/xen/sched.h struct domain · line 640

Quoted 1 line
xen/include/xen/sched.h +1 -0
+        struct domain *d_ = (d);                                 \

Why do you need this local domain variable? Can't you use the d parameter directly?

It would be evaluated then somewhere between 0 and 2 times.

Quoted 8 lines
Quoted 1 line

It's ASSERT code only, so I don't see that as an issue.

Fair point.

Quoted 1 line

Otherwise d_ needs to be made const.

Indeed, but for assert-only code I agree the option is slightly better, ideally suitably commented upon.

Is "the option" here referring to making d_ const, or using d directly (with suitable comment)?

#8 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 49 lines · Stewart Hildebrand
Quoted 36 lines · Jan Beulich
Quoted 35 lines · Roger Pau Monné
Quoted 34 lines · Jan Beulich
Quoted 32 lines · Roger Pau Monné
Quoted 13 lines · Stewart Hildebrand
xen/include/xen/sched.h +2 -1
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,

xen/include/xen/sched.h struct domain · line 636

Quoted 8 lines
xen/include/xen/sched.h +5 -0
@@ -628,6 +629,18 @@ struct domain
     unsigned int cdf;
 };
 
+/*
+ * Check for use in ASSERTs to ensure that:
+ *   1. we can *read* d->pdev_list
+ *   2. pdevs (belonging to this domain) do not go away
+ *   3. pdevs (belonging to this domain) do not get assigned to other domains

I think you can just state that this check ensures there will be no changes to the entries in d->pdev_list, but not the contents of each entry. No changes to d->pdev_list already ensures not devices can be deassigned or removed from the system, and obviously makes the list safe to iterate against.

I would also drop the explicitly mention this is intended for ASSERT
usage: there's nothing specific in the code that prevents it from being used in other places (albeit I think that's unlikely).

Quoted 7 lines
Quoted 5 lines
Quoted 3 lines

But pcidevs_locked(), resolving to spin_is_locked(), isn't reliable. The assertion usage is best-effort only, without a guarantee that all wrong uses would be caught.

Do we want to protect this with !NDEBUG guards then?

Yes, that would look to be desirable.

We will then also need a definition of pdev_list_is_read_locked() in the #else case so we don't risk running into "error: implicit declaration of function 'pdev_list_is_read_locked'".

Quoted 5 lines

Such a definition might look like:

#define pdev_list_is_read_locked(d) ({ (void)d; ASSERT_UNREACHABLE(); false; })

so that we still evaluate d exactly once in the NDEBUG case.

Except that ASSERT_UNREACHABLE() use is bogus in the NDEBUG case. The way our ASSERT() works in the NDEBUG case looks to make it sufficient for there to be

bool pdev_list_is_read_locked(const struct domain *d);

in the #else case (with no implementation anywhere).

Quoted 23 lines
Quoted 23 lines
Quoted 12 lines
Quoted 9 lines
Quoted 6 lines

xen/include/xen/sched.h struct domain · line 639

Quoted 3 lines
xen/include/xen/sched.h +3 -0
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                           \

I would be tempted to drop at least the '_read_' part from the name, the name is getting a bit too long for my taste.

While I agree with the long-ish aspect, I'm afraid the "read" part is crucial. As a result I see no room for shortening.

OK, if you think that's crucial then I'm not going to argue.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

xen/include/xen/sched.h struct domain · line 640

Quoted 1 line
xen/include/xen/sched.h +1 -0
+        struct domain *d_ = (d);                                 \

Why do you need this local domain variable? Can't you use the d parameter directly?

It would be evaluated then somewhere between 0 and 2 times.

It's ASSERT code only, so I don't see that as an issue.

Fair point.

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

Otherwise d_ needs to be made const.

Indeed, but for assert-only code I agree the option is slightly better, ideally suitably commented upon.

Is "the option" here referring to making d_ const, or using d directly (with suitable comment)?

The latter.

Jan

#9 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

In reply to Roger Pau Monné
Quoted 60 lines · Roger Pau Monné
Quoted 55 lines · Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away. Existing non-vPCI callers of these MSI-related functions will remain (ab)using the global pcidevs_lock() to ensure pdevs do not go away so as to minimize changes to existing non-vPCI call paths.

Quoted 3 lines

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

Quoted 5 lines

I would add that when possible, the existing callers haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs lock. This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time.

I'll use this wording, thanks

Quoted 3 lines

IIRC Jan had concerns about why some existing use-cases are not switched straight to use the new per-domain pci_lock in this patch.

I hope the clarified commit description addresses this

Quoted 118 lines
Quoted 118 lines

---
Changes in v13:
- hold off adding Roger's R-b tag even though it was provided on v12.2
- use a wrapper construct to ease readability of odd-looking ASSERTs
- new placement of ASSERT in __pci_enable_msix(), __pci_enable_msi(), and pci_enable_msi(). Rearrange/add pdev NULL check.
- expand commit description with details about using either pcidevs_lock() or d->pci_lock

Changes in v12.2:
- drop Roger's R-b
- drop both locks on error paths in vpci_msix_arch_print()
- add another ASSERT in vpci_msix_arch_print(), to enforce the expectation both locks are held before calling vpci_msix_arch_print()
- move pdev_done label in vpci_dump_msi()
- update comments in vpci_dump_msi() to say locks (plural)

Changes in v12.1:
- use read_trylock() in vpci_msix_arch_print()
- fixup in-code comments (revert double space, use DomXEN) in vpci_{read,write}()
- minor updates in commit message
- add Roger's R-b

Changes in v12:
- s/pci_rwlock/pci_lock/ in commit message
- expand comment about scope of pci_lock in sched.h
- in vpci_{read,write}, if hwdom is trying to access a device assigned to dom_xen, holding hwdom->pci_lock is sufficient (no need to hold dom_xen->pci_lock)
- reintroduce ASSERT in vmx_pi_update_irte()
- reintroduce ASSERT in __pci_enable_msi{x}()
- delete note 6. in commit message about removing ASSERTs since we have reintroduced them

Changes in v11:
- Fixed commit message regarding possible spinlocks
- Removed parameter from allocate_and_map_msi_pirq(), which was added in the prev version. Now we are taking pcidevs_lock in physdev_map_pirq()
- Returned ASSERT to pci_enable_msi
- Fixed case when we took read lock instead of write one
- Fixed label indentation

Changes in v10:
- Moved printk pas locked area
- Returned back ASSERTs
- Added new parameter to allocate_and_map_msi_pirq() so it knows if it should take the global pci lock
- Added comment about possible improvement in vpci_write
- Changed ASSERT(rw_is_locked()) to rw_is_write_locked() in appropriate places
- Renamed release_domain_locks() to release_domain_write_locks()
- moved domain_done label in vpci_dump_msi() to correct place
Changes in v9:
- extended locked region to protect vpci_remove_device and vpci_add_handlers() calls
- vpci_write() takes lock in the write mode to protect potential call to modify_bars()
- renamed lock releasing function
- removed ASSERT()s from msi code
- added trylock in vpci_dump_msi

Changes in v8:
- changed d->vpci_lock to d->pci_lock
- introducing d->pci_lock in a separate patch
- extended locked region in vpci_process_pending
- removed pcidevs_lockis vpci_dump_msi()
- removed some changes as they are not needed with the new locking scheme
- added handling for hwdom && dom_xen case

---
 xen/arch/x86/hvm/vmsi.c       | 31 +++++++++++++--------
 xen/arch/x86/hvm/vmx/vmx.c    |  2 +-
 xen/arch/x86/irq.c            |  8 +++---
 xen/arch/x86/msi.c            | 20 +++++++++-----
 xen/arch/x86/physdev.c        |  2 ++
 xen/drivers/passthrough/pci.c |  9 +++---
 xen/drivers/vpci/header.c     | 18 ++++++++++++
 xen/drivers/vpci/msi.c        | 30 +++++++++++++++++---
 xen/drivers/vpci/msix.c       | 52 ++++++++++++++++++++++++++++++-----
 xen/drivers/vpci/vpci.c       | 24 ++++++++++++++--
 xen/include/xen/sched.h       | 15 +++++++++-
 11 files changed, 170 insertions(+), 41 deletions(-)
xen/arch/x86/hvm/vmsi.c +2 -2
index 128f23636279..f29089178a59 100644
@@ -468,7 +468,7 @@ int msixtbl_pt_register(struct domain *d, struct pirq *pirq, uint64_t gtable)
     struct msixtbl_entry *entry, *new_entry;
     int r = -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -538,7 +538,7 @@ void msixtbl_pt_unregister(struct domain *d, struct pirq *pirq)
     struct pci_dev *pdev;
     struct msixtbl_entry *entry;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -684,7 +684,7 @@ static int vpci_msi_update(const struct pci_dev *pdev, uint32_t data,
 {
     unsigned int i;
 
Quoted 6 lines

xen/arch/x86/hvm/vmsi.c static int vpci_msi_update(const struct pci_dev *pdev, uint32_t data, · line 687

Quoted 2 lines
xen/arch/x86/hvm/vmsi.c +1 -1
-    ASSERT(pcidevs_locked());
+    ASSERT(rw_is_locked(&pdev->domain->pci_lock));

Any reason to not use the newly introduced helper here? I know the pcidevs will never be locked here given the new lock usage, but still it would be less confusing if the new helper was used consistently.

Nope. Agreed, it would help readability, I'll switch to the helper. In addition to vpci_msi_update(), I assume this comment also applies to the remaining occurrences:

xen/arch/x86/hvm/vmsi.c:vpci_msi_arch_update() xen/arch/x86/hvm/vmsi.c:vpci_msi_arch_enable() xen/arch/x86/hvm/vmsi.c:vpci_msi_disable() xen/arch/x86/hvm/vmsi.c:vpci_msix_arch_enable_entry() xen/drivers/vpci/msix.c:msix_find()

But not:

xen/arch/x86/hvm/vmsi.c:vpci_msix_arch_print()

I'll add a suitable comment to this one exception.

Quoted 22 lines

Otherwise we need a comment here as to why the helper can't be used, in order to avoid confusion in the future.

Quoted 18 lines

xen/include/xen/sched.h

Quoted 1 line
xen/include/xen/sched.h +0 -0

index 9da91e0e6244..c3adec1aca3c 100644

xen/include/xen/sched.h +2 -1
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,
@@ -628,6 +629,18 @@ struct domain
     unsigned int cdf;
 };
 
Quoted 11 lines

xen/include/xen/sched.h struct domain · line 636

Quoted 5 lines
xen/include/xen/sched.h +5 -0
+/*
+ * Check for use in ASSERTs to ensure that:
+ *   1. we can *read* d->pdev_list
+ *   2. pdevs (belonging to this domain) do not go away
+ *   3. pdevs (belonging to this domain) do not get assigned to other domains

I think you can just state that this check ensures there will be no changes to the entries in d->pdev_list, but not the contents of each entry. No changes to d->pdev_list already ensures not devices can be deassigned or removed from the system, and obviously makes the list safe to iterate against.

OK, I'll simplify the comment

Quoted 14 lines

I would also drop the explicitly mention this is intended for ASSERT
usage: there's nothing specific in the code that prevents it from being used in other places (albeit I think that's unlikely).

xen/include/xen/sched.h struct domain · line 639

Quoted 3 lines
xen/include/xen/sched.h +3 -0
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                           \

I would be tempted to drop at least the '_read_' part from the name, the name is getting a bit too long for my taste.

xen/include/xen/sched.h struct domain · line 640

Quoted 1 line
xen/include/xen/sched.h +1 -0
+        struct domain *d_ = (d);                                 \
Quoted 8 lines

Why do you need this local domain variable? Can't you use the d parameter directly?

Such assign will prevent using a const 'd' parameter, and 'd_' itself should be const IMO (iff we really need this).

Also sched.h is not the best place, can't you just place it in pci.h?

Yes, I'll move it to xen/include/xen/pci.h

#10 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

In reply to Stewart Hildebrand

xen/arch/x86/physdev.c int physdev_map_pirq(domid_t domid, int type, int *index, int *pirq_p, · line 129

Quoted 10 lines · Stewart Hildebrand
xen/arch/x86/physdev.c +2 -0
@@ -123,7 +123,9 @@ int physdev_map_pirq(domid_t domid, int type, int *index, int *pirq_p,
 
     case MAP_PIRQ_TYPE_MSI:
     case MAP_PIRQ_TYPE_MULTI_MSI:
+        pcidevs_lock();
         ret = allocate_and_map_msi_pirq(d, *index, pirq_p, type, msi);
+        pcidevs_unlock();
         break;

I'm afraid I need to come back to this: This is the only place where this patch retains (moves) use of the global lock. By moving, its scope is actually extended. It was previously said that conversion doesn't happen to limit the scope of what is changing. But with allocate_and_map_msi_pirq() being happy about either lock being held, I'm having a hard time seeing why here the global lock would continue to need using. To me doing so suggests uncertainty whether the checking in the function is actually correct.

Jan

#11 lore raw

Re: [PATCH v13 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 5 lines · Jan Beulich
Quoted 4 lines · Stewart Hildebrand
xen/arch/x86/physdev.c +0 -0
@@ -123,7 +123,9 @@ int physdev_map_pirq(domid_t domid, int type, int *index, int *pirq_p,
 
Quoted 14 lines

xen/arch/x86/physdev.c int physdev_map_pirq(domid_t domid, int type, int *index, int *pirq_p, · line 129

Quoted 6 lines
xen/arch/x86/physdev.c +2 -0
     case MAP_PIRQ_TYPE_MSI:
     case MAP_PIRQ_TYPE_MULTI_MSI:
+        pcidevs_lock();
         ret = allocate_and_map_msi_pirq(d, *index, pirq_p, type, msi);
+        pcidevs_unlock();
         break;

I'm afraid I need to come back to this: This is the only place where this patch retains (moves) use of the global lock. By moving, its scope is actually extended. It was previously said that conversion doesn't happen to limit the scope of what is changing. But with allocate_and_map_msi_pirq() being happy about either lock being held, I'm having a hard time seeing why here the global lock would continue to need using. To me doing so suggests uncertainty whether the checking in the function is actually correct.

I understand the concern. I've gone back and forth on this one in particular myself [1]. I've tested it both ways (i.e. as shown here with pcidevs_lock() and replacing it with read_lock(&d->pci_lock)). In the analysis I've done, I also cannot find a need to continue using pcidevs_lock() here. read_lock(&d->pci_lock) is sufficient. Let's be
clear: both ways are correct. The only reason I left it at pcidevs_lock() for v13 was to make sure the code was doing what the commit description and notes in the cover letter say.

allocate_and_map_msi_pirq() acquires write_lock(&d->event_lock), and accesses to non-domain-specific data fall in the category of reading __read_mostly globals or are appropriately protected by desc->lock and/or vector_lock and/or cmpxchg.

I'll change it to read_lock(&d->pci_lock) in this one particular instance (and update the description appropriately).

[1] https://lore.kernel.org/xen-devel/[email protected]/

#12 lore raw

PATCH v13 1/14 vpci: use per-domain PCI lock to protect vpci structure

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

8. When possible, the existing non-vPCI callers of these MSI-related functions haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs_lock(). This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time. One exception is where the pcidevs_lock() in allocate_and_map_msi_pirq() is moved to the caller, physdev_map_pirq(): this instance is switched to read_lock(&d->pci_lock) right away.

---
Changes in v13.1:
* move pdev_list_is_read_locked() to pci.h
* use pdev_list_is_read_locked() in more places
* use d directly in pdev_list_is_read_locked()
* wrap pdev_list_is_read_locked() helper in #ifndef NDEBUG, and add declaration in the #else case with no implementation
* replace pcidevs_lock() with read_lock(&d->pci_lock) in physdev.c

Changes in v13:
- hold off adding Roger's R-b tag even though it was provided on v12.2
- use a wrapper construct to ease readability of odd-looking ASSERTs
- new placement of ASSERT in __pci_enable_msix(), __pci_enable_msi(), and pci_enable_msi(). Rearrange/add pdev NULL check.
- expand commit description with details about using either pcidevs_lock() or d->pci_lock

Changes in v12.2:
- drop Roger's R-b
- drop both locks on error paths in vpci_msix_arch_print()
- add another ASSERT in vpci_msix_arch_print(), to enforce the expectation both locks are held before calling vpci_msix_arch_print()
- move pdev_done label in vpci_dump_msi()
- update comments in vpci_dump_msi() to say locks (plural)

Changes in v12.1:
- use read_trylock() in vpci_msix_arch_print()
- fixup in-code comments (revert double space, use DomXEN) in vpci_{read,write}()
- minor updates in commit message
- add Roger's R-b

Changes in v12:
- s/pci_rwlock/pci_lock/ in commit message
- expand comment about scope of pci_lock in sched.h
- in vpci_{read,write}, if hwdom is trying to access a device assigned to dom_xen, holding hwdom->pci_lock is sufficient (no need to hold dom_xen->pci_lock)
- reintroduce ASSERT in vmx_pi_update_irte()
- reintroduce ASSERT in __pci_enable_msi{x}()
- delete note 6. in commit message about removing ASSERTs since we have reintroduced them

Changes in v11:
- Fixed commit message regarding possible spinlocks
- Removed parameter from allocate_and_map_msi_pirq(), which was added in the prev version. Now we are taking pcidevs_lock in physdev_map_pirq()
- Returned ASSERT to pci_enable_msi
- Fixed case when we took read lock instead of write one
- Fixed label indentation

Changes in v10:
- Moved printk pas locked area
- Returned back ASSERTs
- Added new parameter to allocate_and_map_msi_pirq() so it knows if it should take the global pci lock
- Added comment about possible improvement in vpci_write
- Changed ASSERT(rw_is_locked()) to rw_is_write_locked() in appropriate places
- Renamed release_domain_locks() to release_domain_write_locks()
- moved domain_done label in vpci_dump_msi() to correct place
Changes in v9:
- extended locked region to protect vpci_remove_device and vpci_add_handlers() calls
- vpci_write() takes lock in the write mode to protect potential call to modify_bars()
- renamed lock releasing function
- removed ASSERT()s from msi code
- added trylock in vpci_dump_msi

Changes in v8:
- changed d->vpci_lock to d->pci_lock
- introducing d->pci_lock in a separate patch
- extended locked region in vpci_process_pending
- removed pcidevs_lockis vpci_dump_msi()
- removed some changes as they are not needed with the new locking scheme
- added handling for hwdom && dom_xen case

---
 xen/arch/x86/hvm/vmsi.c       | 36 ++++++++++++++++--------
 xen/arch/x86/hvm/vmx/vmx.c    |  2 +-
 xen/arch/x86/irq.c            |  8 +++---
 xen/arch/x86/msi.c            | 20 +++++++++-----
 xen/arch/x86/physdev.c        |  2 ++
 xen/drivers/passthrough/pci.c |  9 +++---
 xen/drivers/vpci/header.c     | 18 ++++++++++++
 xen/drivers/vpci/msi.c        | 30 +++++++++++++++++---
 xen/drivers/vpci/msix.c       | 52 ++++++++++++++++++++++++++++++-----
 xen/drivers/vpci/vpci.c       | 24 ++++++++++++++--
 xen/include/xen/pci.h         | 14 ++++++++++
 xen/include/xen/sched.h       |  3 +-
 12 files changed, 177 insertions(+), 41 deletions(-)
xen/arch/x86/hvm/vmsi.c +25 -11
index 128f23636279..19c334fb9c29 100644
@@ -468,7 +468,7 @@ int msixtbl_pt_register(struct domain *d, struct pirq *pirq, uint64_t gtable)
     struct msixtbl_entry *entry, *new_entry;
     int r = -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -538,7 +538,7 @@ void msixtbl_pt_unregister(struct domain *d, struct pirq *pirq)
     struct pci_dev *pdev;
     struct msixtbl_entry *entry;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -684,7 +684,7 @@ static int vpci_msi_update(const struct pci_dev *pdev, uint32_t data,
 {
     unsigned int i;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
 
     if ( (address & MSI_ADDR_BASE_MASK) != MSI_ADDR_HEADER )
     {
@@ -725,8 +725,8 @@ void vpci_msi_arch_update(struct vpci_msi *msi, const struct pci_dev *pdev)
     int rc;
 
     ASSERT(msi->arch.pirq != INVALID_PIRQ);
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
 
-    pcidevs_lock();
     for ( i = 0; i < msi->vectors && msi->arch.bound; i++ )
     {
         struct xen_domctl_bind_pt_irq unbind = {
@@ -745,7 +745,6 @@ void vpci_msi_arch_update(struct vpci_msi *msi, const struct pci_dev *pdev)
 
     msi->arch.bound = !vpci_msi_update(pdev, msi->data, msi->address,
                                        msi->vectors, msi->arch.pirq, msi->mask);
-    pcidevs_unlock();
 }
 
 static int vpci_msi_enable(const struct pci_dev *pdev, unsigned int nr,
@@ -778,15 +777,14 @@ int vpci_msi_arch_enable(struct vpci_msi *msi, const struct pci_dev *pdev,
     int rc;
 
     ASSERT(msi->arch.pirq == INVALID_PIRQ);
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
     rc = vpci_msi_enable(pdev, vectors, 0);
     if ( rc < 0 )
         return rc;
     msi->arch.pirq = rc;
 
-    pcidevs_lock();
     msi->arch.bound = !vpci_msi_update(pdev, msi->data, msi->address, vectors,
                                        msi->arch.pirq, msi->mask);
-    pcidevs_unlock();
 
     return 0;
 }
@@ -797,8 +795,8 @@ static void vpci_msi_disable(const struct pci_dev *pdev, int pirq,
     unsigned int i;
 
     ASSERT(pirq != INVALID_PIRQ);
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
 
-    pcidevs_lock();
     for ( i = 0; i < nr && bound; i++ )
     {
         struct xen_domctl_bind_pt_irq bind = {
@@ -814,7 +812,6 @@ static void vpci_msi_disable(const struct pci_dev *pdev, int pirq,
     write_lock(&pdev->domain->event_lock);
     unmap_domain_pirq(pdev->domain, pirq);
     write_unlock(&pdev->domain->event_lock);
-    pcidevs_unlock();
 }
 
 void vpci_msi_arch_disable(struct vpci_msi *msi, const struct pci_dev *pdev)
@@ -854,6 +851,7 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
     int rc;
 
     ASSERT(entry->arch.pirq == INVALID_PIRQ);
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
     rc = vpci_msi_enable(pdev, vmsix_entry_nr(pdev->vpci->msix, entry),
                          table_base);
     if ( rc < 0 )
@@ -861,7 +859,6 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
 
     entry->arch.pirq = rc;
 
-    pcidevs_lock();
     rc = vpci_msi_update(pdev, entry->data, entry->addr, 1, entry->arch.pirq,
                          entry->masked);
     if ( rc )
@@ -869,7 +866,6 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
         vpci_msi_disable(pdev, entry->arch.pirq, 1, false);
         entry->arch.pirq = INVALID_PIRQ;
     }
-    pcidevs_unlock();
 
     return rc;
 }
@@ -895,6 +891,14 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
+    /*
+     * Assert that d->pdev_list doesn't change. pdev_list_is_read_locked() is
+     * not suitable here because we may read_unlock(&pdev->domain->pci_lock)
+     * before returning.
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));
+
     for ( i = 0; i < msix->max_entries; i++ )
     {
         const struct vpci_msix_entry *entry = &msix->entries[i];
@@ -913,13 +917,23 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
             struct pci_dev *pdev = msix->pdev;
 
             spin_unlock(&msix->pdev->vpci->lock);
+            read_unlock(&pdev->domain->pci_lock);
             process_pending_softirqs();
+
+            if ( !read_trylock(&pdev->domain->pci_lock) )
+                return -EBUSY;
+
             /* NB: we assume that pdev cannot go away for an alive domain. */
             if ( !pdev->vpci || !spin_trylock(&pdev->vpci->lock) )
+            {
+                read_unlock(&pdev->domain->pci_lock);
                 return -EBUSY;
+            }
+
             if ( pdev->vpci->msix != msix )
             {
                 spin_unlock(&pdev->vpci->lock);
+                read_unlock(&pdev->domain->pci_lock);
                 return -EAGAIN;
             }
         }
xen/arch/x86/hvm/vmx/vmx.c +1 -1
index 48376cc32751..dd35091516b0 100644
@@ -413,7 +413,7 @@ static int cf_check vmx_pi_update_irte(const struct vcpu *v,
 
     spin_unlock_irq(&desc->lock);
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(msi_desc->dev->domain));
 
     return iommu_update_ire_from_msi(msi_desc, &msi_desc->msg);
 
xen/arch/x86/irq.c +4 -4
index bbae7751e494..e31144d82fd4 100644
@@ -2164,7 +2164,7 @@ int map_domain_pirq(
         struct pci_dev *pdev;
         unsigned int nr = 0;
 
-        ASSERT(pcidevs_locked());
+        ASSERT(pdev_list_is_read_locked(d));
 
         ret = -ENODEV;
         if ( !cpu_has_apic )
@@ -2321,7 +2321,7 @@ int unmap_domain_pirq(struct domain *d, int pirq)
     if ( (pirq < 0) || (pirq >= d->nr_pirqs) )
         return -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(d));
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     info = pirq_info(d, pirq);
@@ -2886,6 +2886,8 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 {
     int irq, pirq, ret;
 
+    ASSERT(pdev_list_is_read_locked(d));
+
     switch ( type )
     {
     case MAP_PIRQ_TYPE_MSI:
@@ -2915,7 +2917,6 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 
     msi->irq = irq;
 
-    pcidevs_lock();
     /* Verify or get pirq. */
     write_lock(&d->event_lock);
     pirq = allocate_pirq(d, index, *pirq_p, irq, type, &msi->entry_nr);
@@ -2931,7 +2932,6 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 
  done:
     write_unlock(&d->event_lock);
-    pcidevs_unlock();
     if ( ret )
     {
         switch ( type )
xen/arch/x86/msi.c +13 -7
index 335c0868a225..e008b6789a28 100644
@@ -602,7 +602,7 @@ static int msi_capability_init(struct pci_dev *dev,
     unsigned int i, mpos;
     uint16_t control;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(dev->domain));
     pos = pci_find_cap_offset(dev->sbdf, PCI_CAP_ID_MSI);
     if ( !pos )
         return -ENODEV;
@@ -771,7 +771,7 @@ static int msix_capability_init(struct pci_dev *dev,
     if ( !pos )
         return -ENODEV;
 
-    ASSERT(pcidevs_locked());
+    ASSERT(pdev_list_is_read_locked(dev->domain));
 
     control = pci_conf_read16(dev->sbdf, msix_control_reg(pos));
     /*
@@ -988,11 +988,11 @@ static int __pci_enable_msi(struct pci_dev *pdev, struct msi_info *msi,
 {
     struct msi_desc *old_desc;
 
-    ASSERT(pcidevs_locked());
-
     if ( !pdev )
         return -ENODEV;
 
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
+
     old_desc = find_msi_entry(pdev, msi->irq, PCI_CAP_ID_MSI);
     if ( old_desc )
     {
@@ -1043,9 +1043,12 @@ static int __pci_enable_msix(struct pci_dev *pdev, struct msi_info *msi,
 {
     struct msi_desc *old_desc;
 
-    ASSERT(pcidevs_locked());
+    if ( !pdev )
+        return -ENODEV;
+
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
 
-    if ( !pdev || !pdev->msix )
+    if ( !pdev->msix )
         return -ENODEV;
 
     if ( msi->entry_nr >= pdev->msix->nr_entries )
@@ -1154,7 +1157,10 @@ int pci_prepare_msix(u16 seg, u8 bus, u8 devfn, bool off)
 int pci_enable_msi(struct pci_dev *pdev, struct msi_info *msi,
                    struct msi_desc **desc)
 {
-    ASSERT(pcidevs_locked());
+    if ( !pdev )
+        return -ENODEV;
+
+    ASSERT(pdev_list_is_read_locked(pdev->domain));
 
     if ( !use_msi )
         return -EPERM;
xen/arch/x86/physdev.c +2 -0
index 47c4da0af7e1..7efa17cf4c1e 100644
@@ -123,7 +123,9 @@ int physdev_map_pirq(domid_t domid, int type, int *index, int *pirq_p,
 
     case MAP_PIRQ_TYPE_MSI:
     case MAP_PIRQ_TYPE_MULTI_MSI:
+        read_lock(&d->pci_lock);
         ret = allocate_and_map_msi_pirq(d, *index, pirq_p, type, msi);
+        read_unlock(&d->pci_lock);
         break;
 
     default:
xen/drivers/passthrough/pci.c +5 -4
index 47c0eee7bdcc..c97dd4504a7a 100644
@@ -750,7 +750,6 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
         pdev->domain = hardware_domain;
         write_lock(&hardware_domain->pci_lock);
         list_add(&pdev->domain_list, &hardware_domain->pdev_list);
-        write_unlock(&hardware_domain->pci_lock);
 
         /*
          * For devices not discovered by Xen during boot, add vPCI handlers
@@ -759,18 +758,18 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
         ret = vpci_add_handlers(pdev);
         if ( ret )
         {
-            printk(XENLOG_ERR "Setup of vPCI failed: %d\n", ret);
-            write_lock(&hardware_domain->pci_lock);
             list_del(&pdev->domain_list);
             write_unlock(&hardware_domain->pci_lock);
             pdev->domain = NULL;
+            printk(XENLOG_ERR "Setup of vPCI failed: %d\n", ret);
             goto out;
         }
+        write_unlock(&hardware_domain->pci_lock);
         ret = iommu_add_device(pdev);
         if ( ret )
         {
-            vpci_remove_device(pdev);
             write_lock(&hardware_domain->pci_lock);
+            vpci_remove_device(pdev);
             list_del(&pdev->domain_list);
             write_unlock(&hardware_domain->pci_lock);
             pdev->domain = NULL;
@@ -1146,7 +1145,9 @@ static void __hwdom_init setup_one_hwdom_device(const struct setup_hwdom *ctxt,
     } while ( devfn != pdev->devfn &&
               PCI_SLOT(devfn) == PCI_SLOT(pdev->devfn) );
 
+    write_lock(&ctxt->d->pci_lock);
     err = vpci_add_handlers(pdev);
+    write_unlock(&ctxt->d->pci_lock);
     if ( err )
         printk(XENLOG_ERR "setup of vPCI for d%d failed: %d\n",
                ctxt->d->domain_id, err);
xen/drivers/vpci/header.c +18 -0
index 58195549d50a..8f5850b8cf6d 100644
@@ -173,6 +173,7 @@ bool vpci_process_pending(struct vcpu *v)
         if ( rc == -ERESTART )
             return true;
 
+        write_lock(&v->domain->pci_lock);
         spin_lock(&v->vpci.pdev->vpci->lock);
         /* Disable memory decoding unconditionally on failure. */
         modify_decoding(v->vpci.pdev,
@@ -191,6 +192,7 @@ bool vpci_process_pending(struct vcpu *v)
              * failure.
              */
             vpci_remove_device(v->vpci.pdev);
+        write_unlock(&v->domain->pci_lock);
     }
 
     return false;
@@ -202,8 +204,20 @@ static int __init apply_map(struct domain *d, const struct pci_dev *pdev,
     struct map_data data = { .d = d, .map = true };
     int rc;
 
+    ASSERT(rw_is_write_locked(&d->pci_lock));
+
     while ( (rc = rangeset_consume_ranges(mem, map_range, &data)) == -ERESTART )
+    {
+        /*
+         * It's safe to drop and reacquire the lock in this context
+         * without risking pdev disappearing because devices cannot be
+         * removed until the initial domain has been started.
+         */
+        write_unlock(&d->pci_lock);
         process_pending_softirqs();
+        write_lock(&d->pci_lock);
+    }
+
     rangeset_destroy(mem);
     if ( !rc )
         modify_decoding(pdev, cmd, false);
@@ -244,6 +258,8 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
     unsigned int i;
     int rc;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !mem )
         return -ENOMEM;
 
@@ -524,6 +540,8 @@ static int cf_check init_header(struct pci_dev *pdev)
     int rc;
     bool mask_cap_list = false;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     switch ( pci_conf_read8(pdev->sbdf, PCI_HEADER_TYPE) & 0x7f )
     {
     case PCI_HEADER_TYPE_NORMAL:
xen/drivers/vpci/msi.c +26 -4
index a253ccbd7db7..dc71938e23f5 100644
@@ -263,7 +263,7 @@ REGISTER_VPCI_INIT(init_msi, VPCI_PRIORITY_LOW);
 
 void vpci_dump_msi(void)
 {
-    const struct domain *d;
+    struct domain *d;
 
     rcu_read_lock(&domlist_read_lock);
     for_each_domain ( d )
@@ -275,6 +275,9 @@ void vpci_dump_msi(void)
 
         printk("vPCI MSI/MSI-X d%d\n", d->domain_id);
 
+        if ( !read_trylock(&d->pci_lock) )
+            continue;
+
         for_each_pdev ( d, pdev )
         {
             const struct vpci_msi *msi;
@@ -313,17 +316,36 @@ void vpci_dump_msi(void)
                 {
                     /*
                      * On error vpci_msix_arch_print will always return without
-                     * holding the lock.
+                     * holding the locks.
                      */
                     printk("unable to print all MSI-X entries: %d\n", rc);
-                    process_pending_softirqs();
-                    continue;
+                    goto pdev_done;
                 }
             }
 
+            /*
+             * Unlock locks to process pending softirqs. This is
+             * potentially unsafe, as d->pdev_list can be changed in
+             * meantime.
+             */
             spin_unlock(&pdev->vpci->lock);
+            read_unlock(&d->pci_lock);
+        pdev_done:
             process_pending_softirqs();
+            if ( !read_trylock(&d->pci_lock) )
+            {
+                printk("unable to access other devices for the domain\n");
+                goto domain_done;
+            }
         }
+        read_unlock(&d->pci_lock);
+    domain_done:
+        /*
+         * We need this label at the end of the loop, but some
+         * compilers might not be happy about label at the end of the
+         * compound statement so we adding an empty statement here.
+         */
+        ;
     }
     rcu_read_unlock(&domlist_read_lock);
 }
xen/drivers/vpci/msix.c +45 -7

110 lines not on this page · raw message

xen/drivers/vpci/vpci.c +22 -2
index 72ef277c4f8e..475272b173f3 100644
@@ -42,6 +42,8 @@ extern vpci_register_init_t *const __end_vpci_array[];
 
 void vpci_remove_device(struct pci_dev *pdev)
 {
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !has_vpci(pdev->domain) || !pdev->vpci )
         return;
 
@@ -77,6 +79,8 @@ int vpci_add_handlers(struct pci_dev *pdev)
     const unsigned long *ro_map;
     int rc = 0;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !has_vpci(pdev->domain) )
         return 0;
 
@@ -361,7 +365,7 @@ static uint32_t merge_result(uint32_t data, uint32_t new, unsigned int size,
 
 uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
 {
-    const struct domain *d = current->domain;
+    struct domain *d = current->domain;
     const struct pci_dev *pdev;
     const struct vpci_register *r;
     unsigned int data_offset = 0;
@@ -376,12 +380,18 @@ uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
     /*
      * Find the PCI dev matching the address, which for hwdom also requires
      * consulting DomXEN.  Passthrough everything that's not trapped.
+     * If this is hwdom and the device is assigned to DomXEN, acquiring hwdom's
+     * pci_lock is sufficient.
      */
+    read_lock(&d->pci_lock);
     pdev = pci_get_pdev(d, sbdf);
     if ( !pdev && is_hardware_domain(d) )
         pdev = pci_get_pdev(dom_xen, sbdf);
     if ( !pdev || !pdev->vpci )
+    {
+        read_unlock(&d->pci_lock);
         return vpci_read_hw(sbdf, reg, size);
+    }
 
     spin_lock(&pdev->vpci->lock);
 
@@ -428,6 +438,7 @@ uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
         ASSERT(data_offset < size);
     }
     spin_unlock(&pdev->vpci->lock);
+    read_unlock(&d->pci_lock);
 
     if ( data_offset < size )
     {
@@ -470,7 +481,7 @@ static void vpci_write_helper(const struct pci_dev *pdev,
 void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
                 uint32_t data)
 {
-    const struct domain *d = current->domain;
+    struct domain *d = current->domain;
     const struct pci_dev *pdev;
     const struct vpci_register *r;
     unsigned int data_offset = 0;
@@ -484,7 +495,13 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
     /*
      * Find the PCI dev matching the address, which for hwdom also requires
      * consulting DomXEN.  Passthrough everything that's not trapped.
+     * If this is hwdom and the device is assigned to DomXEN, acquiring hwdom's
+     * pci_lock is sufficient.
+     *
+     * TODO: We need to take pci_locks in exclusive mode only if we
+     * are modifying BARs, so there is a room for improvement.
      */
+    write_lock(&d->pci_lock);
     pdev = pci_get_pdev(d, sbdf);
     if ( !pdev && is_hardware_domain(d) )
         pdev = pci_get_pdev(dom_xen, sbdf);
@@ -493,6 +510,8 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
         /* Ignore writes to read-only devices, which have no ->vpci. */
         const unsigned long *ro_map = pci_get_ro_map(sbdf.seg);
 
+        write_unlock(&d->pci_lock);
+
         if ( !ro_map || !test_bit(sbdf.bdf, ro_map) )
             vpci_write_hw(sbdf, reg, size, data);
         return;
@@ -534,6 +553,7 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
         ASSERT(data_offset < size);
     }
     spin_unlock(&pdev->vpci->lock);
+    write_unlock(&d->pci_lock);
 
     if ( data_offset < size )
         /* Tailing gap, write the remaining. */
xen/include/xen/pci.h +14 -0
index aabc5465a7d3..9f31cb84c9f3 100644
@@ -171,6 +171,20 @@ void pcidevs_lock(void);
 void pcidevs_unlock(void);
 bool __must_check pcidevs_locked(void);
 
+#ifndef NDEBUG
+/*
+ * Check for use in ASSERTs to ensure there will be no changes to the entries
+ * in d->pdev_list (but not the contents of each entry).
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                             \
+        /* NB: d may be evaluated multiple times, or not at all */ \
+        pcidevs_locked() || (d && rw_is_locked(&d->pci_lock));     \
+    })
+#else
+bool pdev_list_is_read_locked(const struct domain *d);
+#endif
+
 bool pci_known_segment(u16 seg);
 bool pci_device_detect(u16 seg, u8 bus, u8 dev, u8 func);
 int scan_pci_devices(void);
xen/include/xen/sched.h +2 -1
index 9da91e0e6244..37f5922f3206 100644
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,

base-commit: c4d6802d33f962a306405a20f4dccdc287990d07

Signature · 1 line
2.43.0
#13 lore raw

Re: [PATCH v13.1 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 65 lines · Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

8. When possible, the existing non-vPCI callers of these MSI-related functions haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs_lock(). This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time. One exception is where the pcidevs_lock() in allocate_and_map_msi_pirq() is moved to the caller, physdev_map_pirq(): this instance is switched to read_lock(&d->pci_lock) right away.

Quoted 5 lines

A couple of questions and the pdev_list_is_read_locked() needs a small adjustment.

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 897

Quoted 8 lines
xen/arch/x86/hvm/vmsi.c +4 -0
@@ -895,6 +891,14 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
+    /*
+     * Assert that d->pdev_list doesn't change. pdev_list_is_read_locked() is
+     * not suitable here because we may read_unlock(&pdev->domain->pci_lock)
+     * before returning.

I'm confused by this comment, as I don't see why it matters that the lock might be lock before returning. We need to ensure the lock is taken at the time of the assert, and hence pdev_list_is_read_locked() can be used.

Quoted 14 lines
xen/arch/x86/hvm/vmsi.c +4 -0
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));
+
     for ( i = 0; i < msix->max_entries; i++ )
     {
         const struct vpci_msix_entry *entry = &msix->entries[i];
xen/include/xen/pci.h +0 -0
index aabc5465a7d3..9f31cb84c9f3 100644
@@ -171,6 +171,20 @@ void pcidevs_lock(void);
 void pcidevs_unlock(void);
 bool __must_check pcidevs_locked(void);

xen/include/xen/pci.h void pcidevs_lock(void); · line 182

Quoted 10 lines
xen/include/xen/pci.h +9 -0
 
+#ifndef NDEBUG
+/*
+ * Check for use in ASSERTs to ensure there will be no changes to the entries
+ * in d->pdev_list (but not the contents of each entry).
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                             \
+        /* NB: d may be evaluated multiple times, or not at all */ \
+        pcidevs_locked() || (d && rw_is_locked(&d->pci_lock));     \

'd' is missing parentheses here, should be (d).

xen/include/xen/pci.h void pcidevs_lock(void); · line 186

Quoted 4 lines
xen/include/xen/pci.h +4 -0
+    })
+#else
+bool pdev_list_is_read_locked(const struct domain *d);
+#endif

FWIW, if this is only intended to be used with ASSERT, it might as well be an ASSERT itself:

ASSERT_PDEV_LIST_IS_READ_LOCKED(d) ...

Don't have a strong opinion, so I'm fine with how it's used, just noting it might be clearer if it was an ASSERT_ right away.

Thanks, Roger.

#14 lore raw

Re: [PATCH v13.1 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 79 lines · Roger Pau Monné
Quoted 65 lines · Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

8. When possible, the existing non-vPCI callers of these MSI-related functions haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs_lock(). This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time. One exception is where the pcidevs_lock() in allocate_and_map_msi_pirq() is moved to the caller, physdev_map_pirq(): this instance is switched to read_lock(&d->pci_lock) right away.

Quoted 5 lines

A couple of questions and the pdev_list_is_read_locked() needs a small adjustment.

Quoted 4 lines
xen/arch/x86/hvm/vmsi.c +0 -0
@@ -895,6 +891,14 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
Quoted 9 lines

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 897

Quoted 4 lines
xen/arch/x86/hvm/vmsi.c +4 -0
+    /*
+     * Assert that d->pdev_list doesn't change. pdev_list_is_read_locked() is
+     * not suitable here because we may read_unlock(&pdev->domain->pci_lock)
+     * before returning.

I'm confused by this comment, as I don't see why it matters that the lock might be lock before returning. We need to ensure the lock is taken at the time of the assert, and hence pdev_list_is_read_locked() can be used.

pdev_list_is_read_locked() currently would allow either pcidevs_lock() or d->pci_lock. If vpci_msix_arch_print() is entered with only pcidevs_lock() held, we may end up unlocking d->pci_lock when it is not locked, which would be wrong.

Perhaps the comment could be clarified as:

/*
* Assert that d->pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
* is not suitable here because it may allow either pcidevs_lock() or
* d->pci_lock to be held, but here we rely on d->pci_lock being held, not
* pcidevs_lock().
*/

Quoted 16 lines
Quoted 16 lines
xen/arch/x86/hvm/vmsi.c +4 -0
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));
+
     for ( i = 0; i < msix->max_entries; i++ )
     {
         const struct vpci_msix_entry *entry = &msix->entries[i];
xen/include/xen/pci.h +0 -0
index aabc5465a7d3..9f31cb84c9f3 100644
@@ -171,6 +171,20 @@ void pcidevs_lock(void);
 void pcidevs_unlock(void);
 bool __must_check pcidevs_locked(void);
 
Quoted 11 lines

xen/include/xen/pci.h void pcidevs_lock(void); · line 182

Quoted 9 lines
xen/include/xen/pci.h +9 -0
+#ifndef NDEBUG
+/*
+ * Check for use in ASSERTs to ensure there will be no changes to the entries
+ * in d->pdev_list (but not the contents of each entry).
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define pdev_list_is_read_locked(d) ({                             \
+        /* NB: d may be evaluated multiple times, or not at all */ \
+        pcidevs_locked() || (d && rw_is_locked(&d->pci_lock));     \

'd' is missing parentheses here, should be (d).

Thanks for spotting. I'll fix in v13.2.

Quoted 9 lines

xen/include/xen/pci.h void pcidevs_lock(void); · line 186

Quoted 5 lines
xen/include/xen/pci.h +4 -0
+    })
+#else
+bool pdev_list_is_read_locked(const struct domain *d);
+#endif

FWIW, if this is only intended to be used with ASSERT, it might as well be an ASSERT itself:

Quoted 4 lines

ASSERT_PDEV_LIST_IS_READ_LOCKED(d) ...

Don't have a strong opinion, so I'm fine with how it's used, just noting it might be clearer if it was an ASSERT_ right away.

This would also have the benefit of not relying on dead code elimination in the #else case. I'll be sending v13.2 anyway, I may as well make the change.

#15 lore raw

Re: [PATCH v13.1 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 95 lines · Stewart Hildebrand
Quoted 79 lines · Roger Pau Monné
Quoted 65 lines · Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

8. When possible, the existing non-vPCI callers of these MSI-related functions haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs_lock(). This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time. One exception is where the pcidevs_lock() in allocate_and_map_msi_pirq() is moved to the caller, physdev_map_pirq(): this instance is switched to read_lock(&d->pci_lock) right away.

Quoted 5 lines

A couple of questions and the pdev_list_is_read_locked() needs a small adjustment.

Quoted 4 lines
xen/arch/x86/hvm/vmsi.c +0 -0
@@ -895,6 +891,14 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
Quoted 9 lines

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 897

Quoted 4 lines
xen/arch/x86/hvm/vmsi.c +4 -0
+    /*
+     * Assert that d->pdev_list doesn't change. pdev_list_is_read_locked() is
+     * not suitable here because we may read_unlock(&pdev->domain->pci_lock)
+     * before returning.

I'm confused by this comment, as I don't see why it matters that the lock might be lock before returning. We need to ensure the lock is taken at the time of the assert, and hence pdev_list_is_read_locked() can be used.

pdev_list_is_read_locked() currently would allow either pcidevs_lock() or d->pci_lock. If vpci_msix_arch_print() is entered with only pcidevs_lock() held, we may end up unlocking d->pci_lock when it is not locked, which would be wrong.

Quoted 8 lines

Perhaps the comment could be clarified as:

/*
* Assert that d->pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
* is not suitable here because it may allow either pcidevs_lock() or
* d->pci_lock to be held, but here we rely on d->pci_lock being held, not
* pcidevs_lock().
*/

Yes, this is indeed better.

Thanks, Roger.

#16 lore raw

PATCH v13 1/14 vpci: use per-domain PCI lock to protect vpci structure

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

8. When possible, the existing non-vPCI callers of these MSI-related functions haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs_lock(). This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time. One exception is where the pcidevs_lock() in allocate_and_map_msi_pirq() is moved to the caller, physdev_map_pirq(): this instance is switched to read_lock(&d->pci_lock) right away.

---
Changes in v13.2:
- clarify comment in vpci_msix_arch_print()
- add parenthesis around arg in macro definition
- make the helper macro an ASSERT itself

Changes in v13.1:
- move pdev_list_is_read_locked() to pci.h
- use pdev_list_is_read_locked() in more places
- use d directly in pdev_list_is_read_locked()
- wrap pdev_list_is_read_locked() helper in #ifndef NDEBUG, and add declaration in the #else case with no implementation
- replace pcidevs_lock() with read_lock(&d->pci_lock) in physdev.c

Changes in v13:
- hold off adding Roger's R-b tag even though it was provided on v12.2
- use a wrapper construct to ease readability of odd-looking ASSERTs
- new placement of ASSERT in __pci_enable_msix(), __pci_enable_msi(), and pci_enable_msi(). Rearrange/add pdev NULL check.
- expand commit description with details about using either pcidevs_lock() or d->pci_lock

Changes in v12.2:
- drop Roger's R-b
- drop both locks on error paths in vpci_msix_arch_print()
- add another ASSERT in vpci_msix_arch_print(), to enforce the expectation both locks are held before calling vpci_msix_arch_print()
- move pdev_done label in vpci_dump_msi()
- update comments in vpci_dump_msi() to say locks (plural)

Changes in v12.1:
- use read_trylock() in vpci_msix_arch_print()
- fixup in-code comments (revert double space, use DomXEN) in vpci_{read,write}()
- minor updates in commit message
- add Roger's R-b

Changes in v12:
- s/pci_rwlock/pci_lock/ in commit message
- expand comment about scope of pci_lock in sched.h
- in vpci_{read,write}, if hwdom is trying to access a device assigned to dom_xen, holding hwdom->pci_lock is sufficient (no need to hold dom_xen->pci_lock)
- reintroduce ASSERT in vmx_pi_update_irte()
- reintroduce ASSERT in __pci_enable_msi{x}()
- delete note 6. in commit message about removing ASSERTs since we have reintroduced them

Changes in v11:
- Fixed commit message regarding possible spinlocks
- Removed parameter from allocate_and_map_msi_pirq(), which was added in the prev version. Now we are taking pcidevs_lock in physdev_map_pirq()
- Returned ASSERT to pci_enable_msi
- Fixed case when we took read lock instead of write one
- Fixed label indentation

Changes in v10:
- Moved printk pas locked area
- Returned back ASSERTs
- Added new parameter to allocate_and_map_msi_pirq() so it knows if it should take the global pci lock
- Added comment about possible improvement in vpci_write
- Changed ASSERT(rw_is_locked()) to rw_is_write_locked() in appropriate places
- Renamed release_domain_locks() to release_domain_write_locks()
- moved domain_done label in vpci_dump_msi() to correct place
Changes in v9:
- extended locked region to protect vpci_remove_device and vpci_add_handlers() calls
- vpci_write() takes lock in the write mode to protect potential call to modify_bars()
- renamed lock releasing function
- removed ASSERT()s from msi code
- added trylock in vpci_dump_msi

Changes in v8:
- changed d->vpci_lock to d->pci_lock
- introducing d->pci_lock in a separate patch
- extended locked region in vpci_process_pending
- removed pcidevs_lockis vpci_dump_msi()
- removed some changes as they are not needed with the new locking scheme
- added handling for hwdom && dom_xen case

---
 xen/arch/x86/hvm/vmsi.c       | 37 +++++++++++++++++--------
 xen/arch/x86/hvm/vmx/vmx.c    |  2 +-
 xen/arch/x86/irq.c            |  8 +++---
 xen/arch/x86/msi.c            | 20 +++++++++-----
 xen/arch/x86/physdev.c        |  2 ++
 xen/drivers/passthrough/pci.c |  9 +++---
 xen/drivers/vpci/header.c     | 18 ++++++++++++
 xen/drivers/vpci/msi.c        | 30 +++++++++++++++++---
 xen/drivers/vpci/msix.c       | 52 ++++++++++++++++++++++++++++++-----
 xen/drivers/vpci/vpci.c       | 24 ++++++++++++++--
 xen/include/xen/pci.h         | 13 +++++++++
 xen/include/xen/sched.h       |  3 +-
 12 files changed, 177 insertions(+), 41 deletions(-)
xen/arch/x86/hvm/vmsi.c +26 -11
index 128f23636279..bb1c60782419 100644
@@ -468,7 +468,7 @@ int msixtbl_pt_register(struct domain *d, struct pirq *pirq, uint64_t gtable)
     struct msixtbl_entry *entry, *new_entry;
     int r = -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -538,7 +538,7 @@ void msixtbl_pt_unregister(struct domain *d, struct pirq *pirq)
     struct pci_dev *pdev;
     struct msixtbl_entry *entry;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -684,7 +684,7 @@ static int vpci_msi_update(const struct pci_dev *pdev, uint32_t data,
 {
     unsigned int i;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
     if ( (address & MSI_ADDR_BASE_MASK) != MSI_ADDR_HEADER )
     {
@@ -725,8 +725,8 @@ void vpci_msi_arch_update(struct vpci_msi *msi, const struct pci_dev *pdev)
     int rc;
 
     ASSERT(msi->arch.pirq != INVALID_PIRQ);
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
-    pcidevs_lock();
     for ( i = 0; i < msi->vectors && msi->arch.bound; i++ )
     {
         struct xen_domctl_bind_pt_irq unbind = {
@@ -745,7 +745,6 @@ void vpci_msi_arch_update(struct vpci_msi *msi, const struct pci_dev *pdev)
 
     msi->arch.bound = !vpci_msi_update(pdev, msi->data, msi->address,
                                        msi->vectors, msi->arch.pirq, msi->mask);
-    pcidevs_unlock();
 }
 
 static int vpci_msi_enable(const struct pci_dev *pdev, unsigned int nr,
@@ -778,15 +777,14 @@ int vpci_msi_arch_enable(struct vpci_msi *msi, const struct pci_dev *pdev,
     int rc;
 
     ASSERT(msi->arch.pirq == INVALID_PIRQ);
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
     rc = vpci_msi_enable(pdev, vectors, 0);
     if ( rc < 0 )
         return rc;
     msi->arch.pirq = rc;
 
-    pcidevs_lock();
     msi->arch.bound = !vpci_msi_update(pdev, msi->data, msi->address, vectors,
                                        msi->arch.pirq, msi->mask);
-    pcidevs_unlock();
 
     return 0;
 }
@@ -797,8 +795,8 @@ static void vpci_msi_disable(const struct pci_dev *pdev, int pirq,
     unsigned int i;
 
     ASSERT(pirq != INVALID_PIRQ);
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
-    pcidevs_lock();
     for ( i = 0; i < nr && bound; i++ )
     {
         struct xen_domctl_bind_pt_irq bind = {
@@ -814,7 +812,6 @@ static void vpci_msi_disable(const struct pci_dev *pdev, int pirq,
     write_lock(&pdev->domain->event_lock);
     unmap_domain_pirq(pdev->domain, pirq);
     write_unlock(&pdev->domain->event_lock);
-    pcidevs_unlock();
 }
 
 void vpci_msi_arch_disable(struct vpci_msi *msi, const struct pci_dev *pdev)
@@ -854,6 +851,7 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
     int rc;
 
     ASSERT(entry->arch.pirq == INVALID_PIRQ);
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
     rc = vpci_msi_enable(pdev, vmsix_entry_nr(pdev->vpci->msix, entry),
                          table_base);
     if ( rc < 0 )
@@ -861,7 +859,6 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
 
     entry->arch.pirq = rc;
 
-    pcidevs_lock();
     rc = vpci_msi_update(pdev, entry->data, entry->addr, 1, entry->arch.pirq,
                          entry->masked);
     if ( rc )
@@ -869,7 +866,6 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
         vpci_msi_disable(pdev, entry->arch.pirq, 1, false);
         entry->arch.pirq = INVALID_PIRQ;
     }
-    pcidevs_unlock();
 
     return rc;
 }
@@ -895,6 +891,15 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
+    /*
+     * Assert that d->pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
+     * is not suitable here because it may allow either pcidevs_lock() or
+     * d->pci_lock to be held, but here we rely on d->pci_lock being held, not
+     * pcidevs_lock().
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));
+
     for ( i = 0; i < msix->max_entries; i++ )
     {
         const struct vpci_msix_entry *entry = &msix->entries[i];
@@ -913,13 +918,23 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
             struct pci_dev *pdev = msix->pdev;
 
             spin_unlock(&msix->pdev->vpci->lock);
+            read_unlock(&pdev->domain->pci_lock);
             process_pending_softirqs();
+
+            if ( !read_trylock(&pdev->domain->pci_lock) )
+                return -EBUSY;
+
             /* NB: we assume that pdev cannot go away for an alive domain. */
             if ( !pdev->vpci || !spin_trylock(&pdev->vpci->lock) )
+            {
+                read_unlock(&pdev->domain->pci_lock);
                 return -EBUSY;
+            }
+
             if ( pdev->vpci->msix != msix )
             {
                 spin_unlock(&pdev->vpci->lock);
+                read_unlock(&pdev->domain->pci_lock);
                 return -EAGAIN;
             }
         }
xen/arch/x86/hvm/vmx/vmx.c +1 -1
index 48376cc32751..80a20b17f8a9 100644
@@ -413,7 +413,7 @@ static int cf_check vmx_pi_update_irte(const struct vcpu *v,
 
     spin_unlock_irq(&desc->lock);
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(msi_desc->dev->domain);
 
     return iommu_update_ire_from_msi(msi_desc, &msi_desc->msg);
 
xen/arch/x86/irq.c +4 -4
index bbae7751e494..4beafa83f14b 100644
@@ -2164,7 +2164,7 @@ int map_domain_pirq(
         struct pci_dev *pdev;
         unsigned int nr = 0;
 
-        ASSERT(pcidevs_locked());
+        ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
 
         ret = -ENODEV;
         if ( !cpu_has_apic )
@@ -2321,7 +2321,7 @@ int unmap_domain_pirq(struct domain *d, int pirq)
     if ( (pirq < 0) || (pirq >= d->nr_pirqs) )
         return -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     info = pirq_info(d, pirq);
@@ -2886,6 +2886,8 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 {
     int irq, pirq, ret;
 
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
+
     switch ( type )
     {
     case MAP_PIRQ_TYPE_MSI:
@@ -2915,7 +2917,6 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 
     msi->irq = irq;
 
-    pcidevs_lock();
     /* Verify or get pirq. */
     write_lock(&d->event_lock);
     pirq = allocate_pirq(d, index, *pirq_p, irq, type, &msi->entry_nr);
@@ -2931,7 +2932,6 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 
  done:
     write_unlock(&d->event_lock);
-    pcidevs_unlock();
     if ( ret )
     {
         switch ( type )
xen/arch/x86/msi.c +13 -7
index 335c0868a225..e721aaf5c001 100644
@@ -602,7 +602,7 @@ static int msi_capability_init(struct pci_dev *dev,
     unsigned int i, mpos;
     uint16_t control;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(dev->domain);
     pos = pci_find_cap_offset(dev->sbdf, PCI_CAP_ID_MSI);
     if ( !pos )
         return -ENODEV;
@@ -771,7 +771,7 @@ static int msix_capability_init(struct pci_dev *dev,
     if ( !pos )
         return -ENODEV;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(dev->domain);
 
     control = pci_conf_read16(dev->sbdf, msix_control_reg(pos));
     /*
@@ -988,11 +988,11 @@ static int __pci_enable_msi(struct pci_dev *pdev, struct msi_info *msi,
 {
     struct msi_desc *old_desc;
 
-    ASSERT(pcidevs_locked());
-
     if ( !pdev )
         return -ENODEV;
 
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
+
     old_desc = find_msi_entry(pdev, msi->irq, PCI_CAP_ID_MSI);
     if ( old_desc )
     {
@@ -1043,9 +1043,12 @@ static int __pci_enable_msix(struct pci_dev *pdev, struct msi_info *msi,
 {
     struct msi_desc *old_desc;
 
-    ASSERT(pcidevs_locked());
+    if ( !pdev )
+        return -ENODEV;
+
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
-    if ( !pdev || !pdev->msix )
+    if ( !pdev->msix )
         return -ENODEV;
 
     if ( msi->entry_nr >= pdev->msix->nr_entries )
@@ -1154,7 +1157,10 @@ int pci_prepare_msix(u16 seg, u8 bus, u8 devfn, bool off)
 int pci_enable_msi(struct pci_dev *pdev, struct msi_info *msi,
                    struct msi_desc **desc)
 {
-    ASSERT(pcidevs_locked());
+    if ( !pdev )
+        return -ENODEV;
+
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
     if ( !use_msi )
         return -EPERM;
xen/arch/x86/physdev.c +2 -0
index 47c4da0af7e1..7efa17cf4c1e 100644
@@ -123,7 +123,9 @@ int physdev_map_pirq(domid_t domid, int type, int *index, int *pirq_p,
 
     case MAP_PIRQ_TYPE_MSI:
     case MAP_PIRQ_TYPE_MULTI_MSI:
+        read_lock(&d->pci_lock);
         ret = allocate_and_map_msi_pirq(d, *index, pirq_p, type, msi);
+        read_unlock(&d->pci_lock);
         break;
 
     default:
xen/drivers/passthrough/pci.c +5 -4
index 47c0eee7bdcc..c97dd4504a7a 100644
@@ -750,7 +750,6 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
         pdev->domain = hardware_domain;
         write_lock(&hardware_domain->pci_lock);
         list_add(&pdev->domain_list, &hardware_domain->pdev_list);
-        write_unlock(&hardware_domain->pci_lock);
 
         /*
          * For devices not discovered by Xen during boot, add vPCI handlers
@@ -759,18 +758,18 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
         ret = vpci_add_handlers(pdev);
         if ( ret )
         {
-            printk(XENLOG_ERR "Setup of vPCI failed: %d\n", ret);
-            write_lock(&hardware_domain->pci_lock);
             list_del(&pdev->domain_list);
             write_unlock(&hardware_domain->pci_lock);
             pdev->domain = NULL;
+            printk(XENLOG_ERR "Setup of vPCI failed: %d\n", ret);
             goto out;
         }
+        write_unlock(&hardware_domain->pci_lock);
         ret = iommu_add_device(pdev);
         if ( ret )
         {
-            vpci_remove_device(pdev);
             write_lock(&hardware_domain->pci_lock);
+            vpci_remove_device(pdev);
             list_del(&pdev->domain_list);
             write_unlock(&hardware_domain->pci_lock);
             pdev->domain = NULL;
@@ -1146,7 +1145,9 @@ static void __hwdom_init setup_one_hwdom_device(const struct setup_hwdom *ctxt,
     } while ( devfn != pdev->devfn &&
               PCI_SLOT(devfn) == PCI_SLOT(pdev->devfn) );
 
+    write_lock(&ctxt->d->pci_lock);
     err = vpci_add_handlers(pdev);
+    write_unlock(&ctxt->d->pci_lock);
     if ( err )
         printk(XENLOG_ERR "setup of vPCI for d%d failed: %d\n",
                ctxt->d->domain_id, err);
xen/drivers/vpci/header.c +18 -0
index 58195549d50a..8f5850b8cf6d 100644
@@ -173,6 +173,7 @@ bool vpci_process_pending(struct vcpu *v)
         if ( rc == -ERESTART )
             return true;
 
+        write_lock(&v->domain->pci_lock);
         spin_lock(&v->vpci.pdev->vpci->lock);
         /* Disable memory decoding unconditionally on failure. */
         modify_decoding(v->vpci.pdev,
@@ -191,6 +192,7 @@ bool vpci_process_pending(struct vcpu *v)
              * failure.
              */
             vpci_remove_device(v->vpci.pdev);
+        write_unlock(&v->domain->pci_lock);
     }
 
     return false;
@@ -202,8 +204,20 @@ static int __init apply_map(struct domain *d, const struct pci_dev *pdev,
     struct map_data data = { .d = d, .map = true };
     int rc;
 
+    ASSERT(rw_is_write_locked(&d->pci_lock));
+
     while ( (rc = rangeset_consume_ranges(mem, map_range, &data)) == -ERESTART )
+    {
+        /*
+         * It's safe to drop and reacquire the lock in this context
+         * without risking pdev disappearing because devices cannot be
+         * removed until the initial domain has been started.
+         */
+        write_unlock(&d->pci_lock);
         process_pending_softirqs();
+        write_lock(&d->pci_lock);
+    }
+
     rangeset_destroy(mem);
     if ( !rc )
         modify_decoding(pdev, cmd, false);
@@ -244,6 +258,8 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
     unsigned int i;
     int rc;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !mem )
         return -ENOMEM;
 
@@ -524,6 +540,8 @@ static int cf_check init_header(struct pci_dev *pdev)
     int rc;
     bool mask_cap_list = false;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     switch ( pci_conf_read8(pdev->sbdf, PCI_HEADER_TYPE) & 0x7f )
     {
     case PCI_HEADER_TYPE_NORMAL:
xen/drivers/vpci/msi.c +26 -4
index a253ccbd7db7..dc71938e23f5 100644
@@ -263,7 +263,7 @@ REGISTER_VPCI_INIT(init_msi, VPCI_PRIORITY_LOW);
 
 void vpci_dump_msi(void)
 {
-    const struct domain *d;
+    struct domain *d;
 
     rcu_read_lock(&domlist_read_lock);
     for_each_domain ( d )
@@ -275,6 +275,9 @@ void vpci_dump_msi(void)
 
         printk("vPCI MSI/MSI-X d%d\n", d->domain_id);
 
+        if ( !read_trylock(&d->pci_lock) )
+            continue;
+
         for_each_pdev ( d, pdev )
         {
             const struct vpci_msi *msi;
@@ -313,17 +316,36 @@ void vpci_dump_msi(void)
                 {
                     /*
                      * On error vpci_msix_arch_print will always return without
-                     * holding the lock.
+                     * holding the locks.
                      */
                     printk("unable to print all MSI-X entries: %d\n", rc);
-                    process_pending_softirqs();
-                    continue;
+                    goto pdev_done;
                 }
             }
 
+            /*
+             * Unlock locks to process pending softirqs. This is
+             * potentially unsafe, as d->pdev_list can be changed in
+             * meantime.
+             */
             spin_unlock(&pdev->vpci->lock);
+            read_unlock(&d->pci_lock);
+        pdev_done:
             process_pending_softirqs();
+            if ( !read_trylock(&d->pci_lock) )
+            {
+                printk("unable to access other devices for the domain\n");
+                goto domain_done;
+            }
         }
+        read_unlock(&d->pci_lock);
+    domain_done:
+        /*
+         * We need this label at the end of the loop, but some
+         * compilers might not be happy about label at the end of the
+         * compound statement so we adding an empty statement here.
+         */
+        ;
     }
     rcu_read_unlock(&domlist_read_lock);
 }
xen/drivers/vpci/msix.c +45 -7

110 lines not on this page · raw message

xen/drivers/vpci/vpci.c +22 -2
index 72ef277c4f8e..475272b173f3 100644
@@ -42,6 +42,8 @@ extern vpci_register_init_t *const __end_vpci_array[];
 
 void vpci_remove_device(struct pci_dev *pdev)
 {
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !has_vpci(pdev->domain) || !pdev->vpci )
         return;
 
@@ -77,6 +79,8 @@ int vpci_add_handlers(struct pci_dev *pdev)
     const unsigned long *ro_map;
     int rc = 0;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !has_vpci(pdev->domain) )
         return 0;
 
@@ -361,7 +365,7 @@ static uint32_t merge_result(uint32_t data, uint32_t new, unsigned int size,
 
 uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
 {
-    const struct domain *d = current->domain;
+    struct domain *d = current->domain;
     const struct pci_dev *pdev;
     const struct vpci_register *r;
     unsigned int data_offset = 0;
@@ -376,12 +380,18 @@ uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
     /*
      * Find the PCI dev matching the address, which for hwdom also requires
      * consulting DomXEN.  Passthrough everything that's not trapped.
+     * If this is hwdom and the device is assigned to DomXEN, acquiring hwdom's
+     * pci_lock is sufficient.
      */
+    read_lock(&d->pci_lock);
     pdev = pci_get_pdev(d, sbdf);
     if ( !pdev && is_hardware_domain(d) )
         pdev = pci_get_pdev(dom_xen, sbdf);
     if ( !pdev || !pdev->vpci )
+    {
+        read_unlock(&d->pci_lock);
         return vpci_read_hw(sbdf, reg, size);
+    }
 
     spin_lock(&pdev->vpci->lock);
 
@@ -428,6 +438,7 @@ uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
         ASSERT(data_offset < size);
     }
     spin_unlock(&pdev->vpci->lock);
+    read_unlock(&d->pci_lock);
 
     if ( data_offset < size )
     {
@@ -470,7 +481,7 @@ static void vpci_write_helper(const struct pci_dev *pdev,
 void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
                 uint32_t data)
 {
-    const struct domain *d = current->domain;
+    struct domain *d = current->domain;
     const struct pci_dev *pdev;
     const struct vpci_register *r;
     unsigned int data_offset = 0;
@@ -484,7 +495,13 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
     /*
      * Find the PCI dev matching the address, which for hwdom also requires
      * consulting DomXEN.  Passthrough everything that's not trapped.
+     * If this is hwdom and the device is assigned to DomXEN, acquiring hwdom's
+     * pci_lock is sufficient.
+     *
+     * TODO: We need to take pci_locks in exclusive mode only if we
+     * are modifying BARs, so there is a room for improvement.
      */
+    write_lock(&d->pci_lock);
     pdev = pci_get_pdev(d, sbdf);
     if ( !pdev && is_hardware_domain(d) )
         pdev = pci_get_pdev(dom_xen, sbdf);
@@ -493,6 +510,8 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
         /* Ignore writes to read-only devices, which have no ->vpci. */
         const unsigned long *ro_map = pci_get_ro_map(sbdf.seg);
 
+        write_unlock(&d->pci_lock);
+
         if ( !ro_map || !test_bit(sbdf.bdf, ro_map) )
             vpci_write_hw(sbdf, reg, size, data);
         return;
@@ -534,6 +553,7 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
         ASSERT(data_offset < size);
     }
     spin_unlock(&pdev->vpci->lock);
+    write_unlock(&d->pci_lock);
 
     if ( data_offset < size )
         /* Tailing gap, write the remaining. */
xen/include/xen/pci.h +13 -0
index aabc5465a7d3..f4577faf75fd 100644
@@ -171,6 +171,19 @@ void pcidevs_lock(void);
 void pcidevs_unlock(void);
 bool __must_check pcidevs_locked(void);
 
+#ifndef NDEBUG
+/*
+ * Check to ensure there will be no changes to the entries in d->pdev_list (but
+ * not the contents of each entry).
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d)                               \
+        /* NB: d may be evaluated multiple times, or not at all */       \
+        ASSERT(pcidevs_locked() || ((d) && rw_is_locked(&(d)->pci_lock)))
+#else
+#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d) ({ (void)(d); })
+#endif
+
 bool pci_known_segment(u16 seg);
 bool pci_device_detect(u16 seg, u8 bus, u8 dev, u8 func);
 int scan_pci_devices(void);
xen/include/xen/sched.h +2 -1
index 9da91e0e6244..37f5922f3206 100644
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,

base-commit: 78398afae10bfb4ab94e8af17b7ed58510a57d96

Signature · 1 line
2.43.2
#17 lore raw

Re: [PATCH v13.2 01/14] vpci: use per-domain PCI lock to protect vpci structure

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 901

Quoted 12 lines · Stewart Hildebrand
xen/arch/x86/hvm/vmsi.c +8 -0
@@ -895,6 +891,15 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
+    /*
+     * Assert that d->pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
+     * is not suitable here because it may allow either pcidevs_lock() or
+     * d->pci_lock to be held, but here we rely on d->pci_lock being held, not
+     * pcidevs_lock().
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));

There's no "d" in sight here, so it's a little odd that "d" is being talked about. But I guess people can infer what's meant without too much trouble.

Quoted 27 lines
xen/drivers/vpci/msi.c +13 -3
@@ -313,17 +316,36 @@ void vpci_dump_msi(void)
                 {
                     /*
                      * On error vpci_msix_arch_print will always return without
-                     * holding the lock.
+                     * holding the locks.
                      */
                     printk("unable to print all MSI-X entries: %d\n", rc);
-                    process_pending_softirqs();
-                    continue;
+                    goto pdev_done;
                 }
             }
 
+            /*
+             * Unlock locks to process pending softirqs. This is
+             * potentially unsafe, as d->pdev_list can be changed in
+             * meantime.
+             */
             spin_unlock(&pdev->vpci->lock);
+            read_unlock(&d->pci_lock);
+        pdev_done:
             process_pending_softirqs();
+            if ( !read_trylock(&d->pci_lock) )
+            {
+                printk("unable to access other devices for the domain\n");
+                goto domain_done;

xen/drivers/vpci/msi.c void vpci_dump_msi(void) · line 348

Quoted 10 lines
xen/drivers/vpci/msi.c +9 -0
+            }
         }
+        read_unlock(&d->pci_lock);
+    domain_done:
+        /*
+         * We need this label at the end of the loop, but some
+         * compilers might not be happy about label at the end of the
+         * compound statement so we adding an empty statement here.
+         */
+        ;

As to "some compilers": Are there any which accept a label not followed by a statement? Depending on the answer, this comment may be viewed as superfluous. Or else I'd ask about wording: Besides a grammar issue I also don't view it as appropriate that a comment talks about "adding" something when its adjacent code that is meant. That something is there when the comment is there, hence respective wording should imo be used.

Quoted 5 lines
xen/include/xen/pci.h +0 -0
@@ -171,6 +171,19 @@ void pcidevs_lock(void);
 void pcidevs_unlock(void);
 bool __must_check pcidevs_locked(void);

xen/include/xen/pci.h void pcidevs_lock(void); · line 182

Quoted 10 lines
xen/include/xen/pci.h +9 -0
 
+#ifndef NDEBUG
+/*
+ * Check to ensure there will be no changes to the entries in d->pdev_list (but
+ * not the contents of each entry).
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d)                               \
+        /* NB: d may be evaluated multiple times, or not at all */       \
+        ASSERT(pcidevs_locked() || ((d) && rw_is_locked(&(d)->pci_lock)))

Is there actually any case where d can be NULL here?

xen/include/xen/pci.h void pcidevs_lock(void); · line 184

Quoted 2 lines
xen/include/xen/pci.h +2 -0
+#else
+#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d) ({ (void)(d); })

Evaluating d here isn't very useful when the assertion expression doesn't guarantee single evaluation. Plus even if it needed evaluating, there would be no need to use a compiler extension here:

#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d) ((void)(d))

Jan

#18 lore raw

Re: [PATCH v13.2 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 5 lines · Jan Beulich
Quoted 4 lines · Stewart Hildebrand
xen/arch/x86/hvm/vmsi.c +0 -0
@@ -895,6 +891,15 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
Quoted 11 lines

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 901

Quoted 8 lines
xen/arch/x86/hvm/vmsi.c +8 -0
+    /*
+     * Assert that d->pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
+     * is not suitable here because it may allow either pcidevs_lock() or
+     * d->pci_lock to be held, but here we rely on d->pci_lock being held, not
+     * pcidevs_lock().
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));

There's no "d" in sight here, so it's a little odd that "d" is being talked about. But I guess people can infer what's meant without too much trouble.

I can s/d->pci_lock/msix->pdev->domain->pci_lock/ for the next rev.

Quoted 37 lines
Quoted 37 lines
xen/drivers/vpci/msi.c +21 -3
@@ -313,17 +316,36 @@ void vpci_dump_msi(void)
                 {
                     /*
                      * On error vpci_msix_arch_print will always return without
-                     * holding the lock.
+                     * holding the locks.
                      */
                     printk("unable to print all MSI-X entries: %d\n", rc);
-                    process_pending_softirqs();
-                    continue;
+                    goto pdev_done;
                 }
             }
 
+            /*
+             * Unlock locks to process pending softirqs. This is
+             * potentially unsafe, as d->pdev_list can be changed in
+             * meantime.
+             */
             spin_unlock(&pdev->vpci->lock);
+            read_unlock(&d->pci_lock);
+        pdev_done:
             process_pending_softirqs();
+            if ( !read_trylock(&d->pci_lock) )
+            {
+                printk("unable to access other devices for the domain\n");
+                goto domain_done;
+            }
         }
+        read_unlock(&d->pci_lock);
+    domain_done:
+        /*
+         * We need this label at the end of the loop, but some
+         * compilers might not be happy about label at the end of the
+         * compound statement so we adding an empty statement here.
+         */
Quoted 8 lines

xen/drivers/vpci/msi.c void vpci_dump_msi(void) · line 348

Quoted 1 line
xen/drivers/vpci/msi.c +1 -0
+        ;

As to "some compilers": Are there any which accept a label not followed by a statement? Depending on the answer, this comment may be viewed as superfluous. Or else I'd ask about wording: Besides a grammar issue I also don't view it as appropriate that a comment talks about "adding" something when its adjacent code that is meant. That something is there when the comment is there, hence respective wording should imo be used.

It seems like hit or miss whether gcc would accept it or not (prior discussion at [1]). I agree the comment is rather lengthy for what it's trying to convey. I'd be happy to either remove the comment or reduce it to:

domain_done:
; /* Empty statement to make some compilers happy */

[1] https://lore.kernel.org/xen-devel/[email protected]/

Quoted 7 lines
Quoted 7 lines
xen/include/xen/pci.h +0 -0
@@ -171,6 +171,19 @@ void pcidevs_lock(void);
 void pcidevs_unlock(void);
 bool __must_check pcidevs_locked(void);
 
Quoted 11 lines

xen/include/xen/pci.h void pcidevs_lock(void); · line 182

Quoted 9 lines
xen/include/xen/pci.h +9 -0
+#ifndef NDEBUG
+/*
+ * Check to ensure there will be no changes to the entries in d->pdev_list (but
+ * not the contents of each entry).
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d)                               \
+        /* NB: d may be evaluated multiple times, or not at all */       \
+        ASSERT(pcidevs_locked() || ((d) && rw_is_locked(&(d)->pci_lock)))

Is there actually any case where d can be NULL here?

Yes, when called from ns16550 driver, if the driver failed to make the device RO.

Quoted 9 lines

xen/include/xen/pci.h void pcidevs_lock(void); · line 184

Quoted 3 lines
xen/include/xen/pci.h +2 -0
+#else
+#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d) ({ (void)(d); })

Evaluating d here isn't very useful when the assertion expression doesn't guarantee single evaluation. Plus even if it needed evaluating, there would be no need to use a compiler extension here:

#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d) ((void)(d))

OK, I can make this change.

#19 lore raw

Re: [PATCH v13.2 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 18 lines · Stewart Hildebrand
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Stewart Hildebrand
xen/arch/x86/hvm/vmsi.c +0 -0
@@ -895,6 +891,15 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
Quoted 11 lines

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 901

Quoted 8 lines
xen/arch/x86/hvm/vmsi.c +8 -0
+    /*
+     * Assert that d->pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
+     * is not suitable here because it may allow either pcidevs_lock() or
+     * d->pci_lock to be held, but here we rely on d->pci_lock being held, not
+     * pcidevs_lock().
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));

There's no "d" in sight here, so it's a little odd that "d" is being talked about. But I guess people can infer what's meant without too much trouble.

Quoted 1 line

I can s/d->pci_lock/msix->pdev->domain->pci_lock/ for the next rev.

Or simply drop the d-s? That would be better for readability's sake, I think.

Quoted 50 lines
Quoted 36 lines
Quoted 36 lines
xen/drivers/vpci/msi.c +21 -3
@@ -313,17 +316,36 @@ void vpci_dump_msi(void)
                 {
                     /*
                      * On error vpci_msix_arch_print will always return without
-                     * holding the lock.
+                     * holding the locks.
                      */
                     printk("unable to print all MSI-X entries: %d\n", rc);
-                    process_pending_softirqs();
-                    continue;
+                    goto pdev_done;
                 }
             }
 
+            /*
+             * Unlock locks to process pending softirqs. This is
+             * potentially unsafe, as d->pdev_list can be changed in
+             * meantime.
+             */
             spin_unlock(&pdev->vpci->lock);
+            read_unlock(&d->pci_lock);
+        pdev_done:
             process_pending_softirqs();
+            if ( !read_trylock(&d->pci_lock) )
+            {
+                printk("unable to access other devices for the domain\n");
+                goto domain_done;
+            }
         }
+        read_unlock(&d->pci_lock);
+    domain_done:
+        /*
+         * We need this label at the end of the loop, but some
+         * compilers might not be happy about label at the end of the
+         * compound statement so we adding an empty statement here.
+         */
Quoted 8 lines

xen/drivers/vpci/msi.c void vpci_dump_msi(void) · line 348

Quoted 1 line
xen/drivers/vpci/msi.c +1 -0
+        ;

As to "some compilers": Are there any which accept a label not followed by a statement? Depending on the answer, this comment may be viewed as superfluous. Or else I'd ask about wording: Besides a grammar issue I also don't view it as appropriate that a comment talks about "adding" something when its adjacent code that is meant. That something is there when the comment is there, hence respective wording should imo be used.

It seems like hit or miss whether gcc would accept it or not (prior discussion at [1]). I agree the comment is rather lengthy for what it's trying to convey. I'd be happy to either remove the comment or reduce it to:

Quoted 4 lines

domain_done:
; /* Empty statement to make some compilers happy */

[1] https://lore.kernel.org/xen-devel/[email protected]/

This earlier discussion only proves that there is at least one compiler objecting. There's no proof there that any compiler exists which, as a language extension, actually permits such syntax. Yet if the comment was purely about normal language syntax, then imo it should be zapped altogether, not just be shrunk.

Jan

#20 lore raw

Re: [PATCH v13.2 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 19 lines · Jan Beulich
Quoted 18 lines · Stewart Hildebrand
Quoted 16 lines · Jan Beulich

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 901

Quoted 12 lines · Stewart Hildebrand
xen/arch/x86/hvm/vmsi.c +8 -0
@@ -895,6 +891,15 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
+    /*
+     * Assert that d->pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
+     * is not suitable here because it may allow either pcidevs_lock() or
+     * d->pci_lock to be held, but here we rely on d->pci_lock being held, not
+     * pcidevs_lock().
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));

There's no "d" in sight here, so it's a little odd that "d" is being talked about. But I guess people can infer what's meant without too much trouble.

Quoted 4 lines
Quoted 1 line

I can s/d->pci_lock/msix->pdev->domain->pci_lock/ for the next rev.

Or simply drop the d-s? That would be better for readability's sake, I think.

OK

Quoted 53 lines
Quoted 53 lines
Quoted 36 lines
Quoted 36 lines
xen/drivers/vpci/msi.c +21 -3
@@ -313,17 +316,36 @@ void vpci_dump_msi(void)
                 {
                     /*
                      * On error vpci_msix_arch_print will always return without
-                     * holding the lock.
+                     * holding the locks.
                      */
                     printk("unable to print all MSI-X entries: %d\n", rc);
-                    process_pending_softirqs();
-                    continue;
+                    goto pdev_done;
                 }
             }
 
+            /*
+             * Unlock locks to process pending softirqs. This is
+             * potentially unsafe, as d->pdev_list can be changed in
+             * meantime.
+             */
             spin_unlock(&pdev->vpci->lock);
+            read_unlock(&d->pci_lock);
+        pdev_done:
             process_pending_softirqs();
+            if ( !read_trylock(&d->pci_lock) )
+            {
+                printk("unable to access other devices for the domain\n");
+                goto domain_done;
+            }
         }
+        read_unlock(&d->pci_lock);
+    domain_done:
+        /*
+         * We need this label at the end of the loop, but some
+         * compilers might not be happy about label at the end of the
+         * compound statement so we adding an empty statement here.
+         */
Quoted 8 lines

xen/drivers/vpci/msi.c void vpci_dump_msi(void) · line 348

Quoted 1 line
xen/drivers/vpci/msi.c +1 -0
+        ;

As to "some compilers": Are there any which accept a label not followed by a statement? Depending on the answer, this comment may be viewed as superfluous. Or else I'd ask about wording: Besides a grammar issue I also don't view it as appropriate that a comment talks about "adding" something when its adjacent code that is meant. That something is there when the comment is there, hence respective wording should imo be used.

It seems like hit or miss whether gcc would accept it or not (prior discussion at [1]). I agree the comment is rather lengthy for what it's trying to convey. I'd be happy to either remove the comment or reduce it to:

domain_done:
; /* Empty statement to make some compilers happy */

Quoted 7 lines
Quoted 1 line

[1] https://lore.kernel.org/xen-devel/[email protected]/

This earlier discussion only proves that there is at least one compiler objecting. There's no proof there that any compiler exists which, as a language extension, actually permits such syntax. Yet if the comment was purely about normal language syntax, then imo it should be zapped altogether, not just be shrunk.

I'll zap it

#21 lore raw

PATCH v13 1/14 vpci: use per-domain PCI lock to protect vpci structure

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

8. When possible, the existing non-vPCI callers of these MSI-related functions haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs_lock(). This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time. One exception is where the pcidevs_lock() in allocate_and_map_msi_pirq() is moved to the caller, physdev_map_pirq(): this instance is switched to read_lock(&d->pci_lock) right away.

---
Changes in v13.3:
- remove d's in comment in vpci_msix_arch_print()
- remove comment after domain_done: label in vpci_dump_msi()
- slightly tweak ASSERT_PDEV_LIST_IS_READ_LOCKED() definition in the #else case

Changes in v13.2:
- clarify comment in vpci_msix_arch_print()
- add parenthesis around arg in macro definition
- make the helper macro an ASSERT itself

Changes in v13.1:
- move pdev_list_is_read_locked() to pci.h
- use pdev_list_is_read_locked() in more places
- use d directly in pdev_list_is_read_locked()
- wrap pdev_list_is_read_locked() helper in #ifndef NDEBUG, and add declaration in the #else case with no implementation
- replace pcidevs_lock() with read_lock(&d->pci_lock) in physdev.c

Changes in v13:
- hold off adding Roger's R-b tag even though it was provided on v12.2
- use a wrapper construct to ease readability of odd-looking ASSERTs
- new placement of ASSERT in __pci_enable_msix(), __pci_enable_msi(), and pci_enable_msi(). Rearrange/add pdev NULL check.
- expand commit description with details about using either pcidevs_lock() or d->pci_lock

Changes in v12.2:
- drop Roger's R-b
- drop both locks on error paths in vpci_msix_arch_print()
- add another ASSERT in vpci_msix_arch_print(), to enforce the expectation both locks are held before calling vpci_msix_arch_print()
- move pdev_done label in vpci_dump_msi()
- update comments in vpci_dump_msi() to say locks (plural)

Changes in v12.1:
- use read_trylock() in vpci_msix_arch_print()
- fixup in-code comments (revert double space, use DomXEN) in vpci_{read,write}()
- minor updates in commit message
- add Roger's R-b

Changes in v12:
- s/pci_rwlock/pci_lock/ in commit message
- expand comment about scope of pci_lock in sched.h
- in vpci_{read,write}, if hwdom is trying to access a device assigned to dom_xen, holding hwdom->pci_lock is sufficient (no need to hold dom_xen->pci_lock)
- reintroduce ASSERT in vmx_pi_update_irte()
- reintroduce ASSERT in __pci_enable_msi{x}()
- delete note 6. in commit message about removing ASSERTs since we have reintroduced them

Changes in v11:
- Fixed commit message regarding possible spinlocks
- Removed parameter from allocate_and_map_msi_pirq(), which was added in the prev version. Now we are taking pcidevs_lock in physdev_map_pirq()
- Returned ASSERT to pci_enable_msi
- Fixed case when we took read lock instead of write one
- Fixed label indentation

Changes in v10:
- Moved printk pas locked area
- Returned back ASSERTs
- Added new parameter to allocate_and_map_msi_pirq() so it knows if it should take the global pci lock
- Added comment about possible improvement in vpci_write
- Changed ASSERT(rw_is_locked()) to rw_is_write_locked() in appropriate places
- Renamed release_domain_locks() to release_domain_write_locks()
- moved domain_done label in vpci_dump_msi() to correct place
Changes in v9:
- extended locked region to protect vpci_remove_device and vpci_add_handlers() calls
- vpci_write() takes lock in the write mode to protect potential call to modify_bars()
- renamed lock releasing function
- removed ASSERT()s from msi code
- added trylock in vpci_dump_msi

Changes in v8:
- changed d->vpci_lock to d->pci_lock
- introducing d->pci_lock in a separate patch
- extended locked region in vpci_process_pending
- removed pcidevs_lockis vpci_dump_msi()
- removed some changes as they are not needed with the new locking scheme
- added handling for hwdom && dom_xen case

---
 xen/arch/x86/hvm/vmsi.c       | 37 +++++++++++++++++--------
 xen/arch/x86/hvm/vmx/vmx.c    |  2 +-
 xen/arch/x86/irq.c            |  8 +++---
 xen/arch/x86/msi.c            | 20 +++++++++-----
 xen/arch/x86/physdev.c        |  2 ++
 xen/drivers/passthrough/pci.c |  9 +++---
 xen/drivers/vpci/header.c     | 18 ++++++++++++
 xen/drivers/vpci/msi.c        | 25 ++++++++++++++---
 xen/drivers/vpci/msix.c       | 52 ++++++++++++++++++++++++++++++-----
 xen/drivers/vpci/vpci.c       | 24 ++++++++++++++--
 xen/include/xen/pci.h         | 13 +++++++++
 xen/include/xen/sched.h       |  3 +-
 12 files changed, 172 insertions(+), 41 deletions(-)
xen/arch/x86/hvm/vmsi.c +26 -11
index 128f23636279..211442eba704 100644
@@ -468,7 +468,7 @@ int msixtbl_pt_register(struct domain *d, struct pirq *pirq, uint64_t gtable)
     struct msixtbl_entry *entry, *new_entry;
     int r = -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -538,7 +538,7 @@ void msixtbl_pt_unregister(struct domain *d, struct pirq *pirq)
     struct pci_dev *pdev;
     struct msixtbl_entry *entry;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     if ( !msixtbl_initialised(d) )
@@ -684,7 +684,7 @@ static int vpci_msi_update(const struct pci_dev *pdev, uint32_t data,
 {
     unsigned int i;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
     if ( (address & MSI_ADDR_BASE_MASK) != MSI_ADDR_HEADER )
     {
@@ -725,8 +725,8 @@ void vpci_msi_arch_update(struct vpci_msi *msi, const struct pci_dev *pdev)
     int rc;
 
     ASSERT(msi->arch.pirq != INVALID_PIRQ);
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
-    pcidevs_lock();
     for ( i = 0; i < msi->vectors && msi->arch.bound; i++ )
     {
         struct xen_domctl_bind_pt_irq unbind = {
@@ -745,7 +745,6 @@ void vpci_msi_arch_update(struct vpci_msi *msi, const struct pci_dev *pdev)
 
     msi->arch.bound = !vpci_msi_update(pdev, msi->data, msi->address,
                                        msi->vectors, msi->arch.pirq, msi->mask);
-    pcidevs_unlock();
 }
 
 static int vpci_msi_enable(const struct pci_dev *pdev, unsigned int nr,
@@ -778,15 +777,14 @@ int vpci_msi_arch_enable(struct vpci_msi *msi, const struct pci_dev *pdev,
     int rc;
 
     ASSERT(msi->arch.pirq == INVALID_PIRQ);
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
     rc = vpci_msi_enable(pdev, vectors, 0);
     if ( rc < 0 )
         return rc;
     msi->arch.pirq = rc;
 
-    pcidevs_lock();
     msi->arch.bound = !vpci_msi_update(pdev, msi->data, msi->address, vectors,
                                        msi->arch.pirq, msi->mask);
-    pcidevs_unlock();
 
     return 0;
 }
@@ -797,8 +795,8 @@ static void vpci_msi_disable(const struct pci_dev *pdev, int pirq,
     unsigned int i;
 
     ASSERT(pirq != INVALID_PIRQ);
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
-    pcidevs_lock();
     for ( i = 0; i < nr && bound; i++ )
     {
         struct xen_domctl_bind_pt_irq bind = {
@@ -814,7 +812,6 @@ static void vpci_msi_disable(const struct pci_dev *pdev, int pirq,
     write_lock(&pdev->domain->event_lock);
     unmap_domain_pirq(pdev->domain, pirq);
     write_unlock(&pdev->domain->event_lock);
-    pcidevs_unlock();
 }
 
 void vpci_msi_arch_disable(struct vpci_msi *msi, const struct pci_dev *pdev)
@@ -854,6 +851,7 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
     int rc;
 
     ASSERT(entry->arch.pirq == INVALID_PIRQ);
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
     rc = vpci_msi_enable(pdev, vmsix_entry_nr(pdev->vpci->msix, entry),
                          table_base);
     if ( rc < 0 )
@@ -861,7 +859,6 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
 
     entry->arch.pirq = rc;
 
-    pcidevs_lock();
     rc = vpci_msi_update(pdev, entry->data, entry->addr, 1, entry->arch.pirq,
                          entry->masked);
     if ( rc )
@@ -869,7 +866,6 @@ int vpci_msix_arch_enable_entry(struct vpci_msix_entry *entry,
         vpci_msi_disable(pdev, entry->arch.pirq, 1, false);
         entry->arch.pirq = INVALID_PIRQ;
     }
-    pcidevs_unlock();
 
     return rc;
 }
@@ -895,6 +891,15 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
+    /*
+     * Assert that pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
+     * is not suitable here because it may allow either pcidevs_lock() or
+     * pci_lock to be held, but here we rely on pci_lock being held, not
+     * pcidevs_lock().
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));
+
     for ( i = 0; i < msix->max_entries; i++ )
     {
         const struct vpci_msix_entry *entry = &msix->entries[i];
@@ -913,13 +918,23 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
             struct pci_dev *pdev = msix->pdev;
 
             spin_unlock(&msix->pdev->vpci->lock);
+            read_unlock(&pdev->domain->pci_lock);
             process_pending_softirqs();
+
+            if ( !read_trylock(&pdev->domain->pci_lock) )
+                return -EBUSY;
+
             /* NB: we assume that pdev cannot go away for an alive domain. */
             if ( !pdev->vpci || !spin_trylock(&pdev->vpci->lock) )
+            {
+                read_unlock(&pdev->domain->pci_lock);
                 return -EBUSY;
+            }
+
             if ( pdev->vpci->msix != msix )
             {
                 spin_unlock(&pdev->vpci->lock);
+                read_unlock(&pdev->domain->pci_lock);
                 return -EAGAIN;
             }
         }
xen/arch/x86/hvm/vmx/vmx.c +1 -1
index 48376cc32751..80a20b17f8a9 100644
@@ -413,7 +413,7 @@ static int cf_check vmx_pi_update_irte(const struct vcpu *v,
 
     spin_unlock_irq(&desc->lock);
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(msi_desc->dev->domain);
 
     return iommu_update_ire_from_msi(msi_desc, &msi_desc->msg);
 
xen/arch/x86/irq.c +4 -4
index bbae7751e494..4beafa83f14b 100644
@@ -2164,7 +2164,7 @@ int map_domain_pirq(
         struct pci_dev *pdev;
         unsigned int nr = 0;
 
-        ASSERT(pcidevs_locked());
+        ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
 
         ret = -ENODEV;
         if ( !cpu_has_apic )
@@ -2321,7 +2321,7 @@ int unmap_domain_pirq(struct domain *d, int pirq)
     if ( (pirq < 0) || (pirq >= d->nr_pirqs) )
         return -EINVAL;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
     ASSERT(rw_is_write_locked(&d->event_lock));
 
     info = pirq_info(d, pirq);
@@ -2886,6 +2886,8 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 {
     int irq, pirq, ret;
 
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(d);
+
     switch ( type )
     {
     case MAP_PIRQ_TYPE_MSI:
@@ -2915,7 +2917,6 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 
     msi->irq = irq;
 
-    pcidevs_lock();
     /* Verify or get pirq. */
     write_lock(&d->event_lock);
     pirq = allocate_pirq(d, index, *pirq_p, irq, type, &msi->entry_nr);
@@ -2931,7 +2932,6 @@ int allocate_and_map_msi_pirq(struct domain *d, int index, int *pirq_p,
 
  done:
     write_unlock(&d->event_lock);
-    pcidevs_unlock();
     if ( ret )
     {
         switch ( type )
xen/arch/x86/msi.c +13 -7
index 335c0868a225..e721aaf5c001 100644
@@ -602,7 +602,7 @@ static int msi_capability_init(struct pci_dev *dev,
     unsigned int i, mpos;
     uint16_t control;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(dev->domain);
     pos = pci_find_cap_offset(dev->sbdf, PCI_CAP_ID_MSI);
     if ( !pos )
         return -ENODEV;
@@ -771,7 +771,7 @@ static int msix_capability_init(struct pci_dev *dev,
     if ( !pos )
         return -ENODEV;
 
-    ASSERT(pcidevs_locked());
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(dev->domain);
 
     control = pci_conf_read16(dev->sbdf, msix_control_reg(pos));
     /*
@@ -988,11 +988,11 @@ static int __pci_enable_msi(struct pci_dev *pdev, struct msi_info *msi,
 {
     struct msi_desc *old_desc;
 
-    ASSERT(pcidevs_locked());
-
     if ( !pdev )
         return -ENODEV;
 
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
+
     old_desc = find_msi_entry(pdev, msi->irq, PCI_CAP_ID_MSI);
     if ( old_desc )
     {
@@ -1043,9 +1043,12 @@ static int __pci_enable_msix(struct pci_dev *pdev, struct msi_info *msi,
 {
     struct msi_desc *old_desc;
 
-    ASSERT(pcidevs_locked());
+    if ( !pdev )
+        return -ENODEV;
+
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
-    if ( !pdev || !pdev->msix )
+    if ( !pdev->msix )
         return -ENODEV;
 
     if ( msi->entry_nr >= pdev->msix->nr_entries )
@@ -1154,7 +1157,10 @@ int pci_prepare_msix(u16 seg, u8 bus, u8 devfn, bool off)
 int pci_enable_msi(struct pci_dev *pdev, struct msi_info *msi,
                    struct msi_desc **desc)
 {
-    ASSERT(pcidevs_locked());
+    if ( !pdev )
+        return -ENODEV;
+
+    ASSERT_PDEV_LIST_IS_READ_LOCKED(pdev->domain);
 
     if ( !use_msi )
         return -EPERM;
xen/arch/x86/physdev.c +2 -0
index 47c4da0af7e1..7efa17cf4c1e 100644
@@ -123,7 +123,9 @@ int physdev_map_pirq(domid_t domid, int type, int *index, int *pirq_p,
 
     case MAP_PIRQ_TYPE_MSI:
     case MAP_PIRQ_TYPE_MULTI_MSI:
+        read_lock(&d->pci_lock);
         ret = allocate_and_map_msi_pirq(d, *index, pirq_p, type, msi);
+        read_unlock(&d->pci_lock);
         break;
 
     default:
xen/drivers/passthrough/pci.c +5 -4
index 47c0eee7bdcc..c97dd4504a7a 100644
@@ -750,7 +750,6 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
         pdev->domain = hardware_domain;
         write_lock(&hardware_domain->pci_lock);
         list_add(&pdev->domain_list, &hardware_domain->pdev_list);
-        write_unlock(&hardware_domain->pci_lock);
 
         /*
          * For devices not discovered by Xen during boot, add vPCI handlers
@@ -759,18 +758,18 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
         ret = vpci_add_handlers(pdev);
         if ( ret )
         {
-            printk(XENLOG_ERR "Setup of vPCI failed: %d\n", ret);
-            write_lock(&hardware_domain->pci_lock);
             list_del(&pdev->domain_list);
             write_unlock(&hardware_domain->pci_lock);
             pdev->domain = NULL;
+            printk(XENLOG_ERR "Setup of vPCI failed: %d\n", ret);
             goto out;
         }
+        write_unlock(&hardware_domain->pci_lock);
         ret = iommu_add_device(pdev);
         if ( ret )
         {
-            vpci_remove_device(pdev);
             write_lock(&hardware_domain->pci_lock);
+            vpci_remove_device(pdev);
             list_del(&pdev->domain_list);
             write_unlock(&hardware_domain->pci_lock);
             pdev->domain = NULL;
@@ -1146,7 +1145,9 @@ static void __hwdom_init setup_one_hwdom_device(const struct setup_hwdom *ctxt,
     } while ( devfn != pdev->devfn &&
               PCI_SLOT(devfn) == PCI_SLOT(pdev->devfn) );
 
+    write_lock(&ctxt->d->pci_lock);
     err = vpci_add_handlers(pdev);
+    write_unlock(&ctxt->d->pci_lock);
     if ( err )
         printk(XENLOG_ERR "setup of vPCI for d%d failed: %d\n",
                ctxt->d->domain_id, err);
xen/drivers/vpci/header.c +18 -0
index 58195549d50a..8f5850b8cf6d 100644
@@ -173,6 +173,7 @@ bool vpci_process_pending(struct vcpu *v)
         if ( rc == -ERESTART )
             return true;
 
+        write_lock(&v->domain->pci_lock);
         spin_lock(&v->vpci.pdev->vpci->lock);
         /* Disable memory decoding unconditionally on failure. */
         modify_decoding(v->vpci.pdev,
@@ -191,6 +192,7 @@ bool vpci_process_pending(struct vcpu *v)
              * failure.
              */
             vpci_remove_device(v->vpci.pdev);
+        write_unlock(&v->domain->pci_lock);
     }
 
     return false;
@@ -202,8 +204,20 @@ static int __init apply_map(struct domain *d, const struct pci_dev *pdev,
     struct map_data data = { .d = d, .map = true };
     int rc;
 
+    ASSERT(rw_is_write_locked(&d->pci_lock));
+
     while ( (rc = rangeset_consume_ranges(mem, map_range, &data)) == -ERESTART )
+    {
+        /*
+         * It's safe to drop and reacquire the lock in this context
+         * without risking pdev disappearing because devices cannot be
+         * removed until the initial domain has been started.
+         */
+        write_unlock(&d->pci_lock);
         process_pending_softirqs();
+        write_lock(&d->pci_lock);
+    }
+
     rangeset_destroy(mem);
     if ( !rc )
         modify_decoding(pdev, cmd, false);
@@ -244,6 +258,8 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
     unsigned int i;
     int rc;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !mem )
         return -ENOMEM;
 
@@ -524,6 +540,8 @@ static int cf_check init_header(struct pci_dev *pdev)
     int rc;
     bool mask_cap_list = false;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     switch ( pci_conf_read8(pdev->sbdf, PCI_HEADER_TYPE) & 0x7f )
     {
     case PCI_HEADER_TYPE_NORMAL:
xen/drivers/vpci/msi.c +21 -4
index a253ccbd7db7..2913adf4f64a 100644
@@ -263,7 +263,7 @@ REGISTER_VPCI_INIT(init_msi, VPCI_PRIORITY_LOW);
 
 void vpci_dump_msi(void)
 {
-    const struct domain *d;
+    struct domain *d;
 
     rcu_read_lock(&domlist_read_lock);
     for_each_domain ( d )
@@ -275,6 +275,9 @@ void vpci_dump_msi(void)
 
         printk("vPCI MSI/MSI-X d%d\n", d->domain_id);
 
+        if ( !read_trylock(&d->pci_lock) )
+            continue;
+
         for_each_pdev ( d, pdev )
         {
             const struct vpci_msi *msi;
@@ -313,17 +316,31 @@ void vpci_dump_msi(void)
                 {
                     /*
                      * On error vpci_msix_arch_print will always return without
-                     * holding the lock.
+                     * holding the locks.
                      */
                     printk("unable to print all MSI-X entries: %d\n", rc);
-                    process_pending_softirqs();
-                    continue;
+                    goto pdev_done;
                 }
             }
 
+            /*
+             * Unlock locks to process pending softirqs. This is
+             * potentially unsafe, as d->pdev_list can be changed in
+             * meantime.
+             */
             spin_unlock(&pdev->vpci->lock);
+            read_unlock(&d->pci_lock);
+        pdev_done:
             process_pending_softirqs();
+            if ( !read_trylock(&d->pci_lock) )
+            {
+                printk("unable to access other devices for the domain\n");
+                goto domain_done;
+            }
         }
+        read_unlock(&d->pci_lock);
+    domain_done:
+        ;
     }
     rcu_read_unlock(&domlist_read_lock);
 }
xen/drivers/vpci/msix.c +45 -7

110 lines not on this page · raw message

xen/drivers/vpci/vpci.c +22 -2
index 72ef277c4f8e..475272b173f3 100644
@@ -42,6 +42,8 @@ extern vpci_register_init_t *const __end_vpci_array[];
 
 void vpci_remove_device(struct pci_dev *pdev)
 {
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !has_vpci(pdev->domain) || !pdev->vpci )
         return;
 
@@ -77,6 +79,8 @@ int vpci_add_handlers(struct pci_dev *pdev)
     const unsigned long *ro_map;
     int rc = 0;
 
+    ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
+
     if ( !has_vpci(pdev->domain) )
         return 0;
 
@@ -361,7 +365,7 @@ static uint32_t merge_result(uint32_t data, uint32_t new, unsigned int size,
 
 uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
 {
-    const struct domain *d = current->domain;
+    struct domain *d = current->domain;
     const struct pci_dev *pdev;
     const struct vpci_register *r;
     unsigned int data_offset = 0;
@@ -376,12 +380,18 @@ uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
     /*
      * Find the PCI dev matching the address, which for hwdom also requires
      * consulting DomXEN.  Passthrough everything that's not trapped.
+     * If this is hwdom and the device is assigned to DomXEN, acquiring hwdom's
+     * pci_lock is sufficient.
      */
+    read_lock(&d->pci_lock);
     pdev = pci_get_pdev(d, sbdf);
     if ( !pdev && is_hardware_domain(d) )
         pdev = pci_get_pdev(dom_xen, sbdf);
     if ( !pdev || !pdev->vpci )
+    {
+        read_unlock(&d->pci_lock);
         return vpci_read_hw(sbdf, reg, size);
+    }
 
     spin_lock(&pdev->vpci->lock);
 
@@ -428,6 +438,7 @@ uint32_t vpci_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int size)
         ASSERT(data_offset < size);
     }
     spin_unlock(&pdev->vpci->lock);
+    read_unlock(&d->pci_lock);
 
     if ( data_offset < size )
     {
@@ -470,7 +481,7 @@ static void vpci_write_helper(const struct pci_dev *pdev,
 void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
                 uint32_t data)
 {
-    const struct domain *d = current->domain;
+    struct domain *d = current->domain;
     const struct pci_dev *pdev;
     const struct vpci_register *r;
     unsigned int data_offset = 0;
@@ -484,7 +495,13 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
     /*
      * Find the PCI dev matching the address, which for hwdom also requires
      * consulting DomXEN.  Passthrough everything that's not trapped.
+     * If this is hwdom and the device is assigned to DomXEN, acquiring hwdom's
+     * pci_lock is sufficient.
+     *
+     * TODO: We need to take pci_locks in exclusive mode only if we
+     * are modifying BARs, so there is a room for improvement.
      */
+    write_lock(&d->pci_lock);
     pdev = pci_get_pdev(d, sbdf);
     if ( !pdev && is_hardware_domain(d) )
         pdev = pci_get_pdev(dom_xen, sbdf);
@@ -493,6 +510,8 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
         /* Ignore writes to read-only devices, which have no ->vpci. */
         const unsigned long *ro_map = pci_get_ro_map(sbdf.seg);
 
+        write_unlock(&d->pci_lock);
+
         if ( !ro_map || !test_bit(sbdf.bdf, ro_map) )
             vpci_write_hw(sbdf, reg, size, data);
         return;
@@ -534,6 +553,7 @@ void vpci_write(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
         ASSERT(data_offset < size);
     }
     spin_unlock(&pdev->vpci->lock);
+    write_unlock(&d->pci_lock);
 
     if ( data_offset < size )
         /* Tailing gap, write the remaining. */
xen/include/xen/pci.h +13 -0
index aabc5465a7d3..1df1863b1331 100644
@@ -171,6 +171,19 @@ void pcidevs_lock(void);
 void pcidevs_unlock(void);
 bool __must_check pcidevs_locked(void);
 
+#ifndef NDEBUG
+/*
+ * Check to ensure there will be no changes to the entries in d->pdev_list (but
+ * not the contents of each entry).
+ * This check is not suitable for protecting other state or critical regions.
+ */
+#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d)                               \
+        /* NB: d may be evaluated multiple times, or not at all */       \
+        ASSERT(pcidevs_locked() || ((d) && rw_is_locked(&(d)->pci_lock)))
+#else
+#define ASSERT_PDEV_LIST_IS_READ_LOCKED(d) ((void)(d))
+#endif
+
 bool pci_known_segment(u16 seg);
 bool pci_device_detect(u16 seg, u8 bus, u8 dev, u8 func);
 int scan_pci_devices(void);
xen/include/xen/sched.h +2 -1
index 9da91e0e6244..37f5922f3206 100644
@@ -462,7 +462,8 @@ struct domain
 #ifdef CONFIG_HAS_PCI
     struct list_head pdev_list;
     /*
-     * pci_lock protects access to pdev_list.
+     * pci_lock protects access to pdev_list. pci_lock also protects pdev->vpci
+     * structure from being removed.
      *
      * Any user *reading* from pdev_list, or from devices stored in pdev_list,
      * should hold either pcidevs_lock() or pci_lock in read mode. Optionally,

base-commit: f8791d0fd3adbda3701e7eb9db63a9351b478365

Signature · 1 line
2.43.2
Acked-by on v13 1/14
#22 lore raw

Re: [PATCH v13.3 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 65 lines · Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

8. When possible, the existing non-vPCI callers of these MSI-related functions haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs_lock(). This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time. One exception is where the pcidevs_lock() in allocate_and_map_msi_pirq() is moved to the caller, physdev_map_pirq(): this instance is switched to read_lock(&d->pci_lock) right away.

Quoted 5 lines

with two small remaining remarks (below) and on the assumption that an R-b from Roger in particular for the vPCI code is going to turn up eventually.

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 901

Quoted 12 lines
xen/arch/x86/hvm/vmsi.c +8 -0
@@ -895,6 +891,15 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
+    /*
+     * Assert that pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
+     * is not suitable here because it may allow either pcidevs_lock() or
+     * pci_lock to be held, but here we rely on pci_lock being held, not
+     * pcidevs_lock().
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));

As to the comment, I think it's not really "may". I also think referral to
...

Quoted 14 lines
xen/arch/x86/hvm/vmsi.c +7 -0
@@ -913,13 +918,23 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
             struct pci_dev *pdev = msix->pdev;
 
             spin_unlock(&msix->pdev->vpci->lock);
+            read_unlock(&pdev->domain->pci_lock);
             process_pending_softirqs();
+
+            if ( !read_trylock(&pdev->domain->pci_lock) )
+                return -EBUSY;
+
             /* NB: we assume that pdev cannot go away for an alive domain. */
             if ( !pdev->vpci || !spin_trylock(&pdev->vpci->lock) )
+            {
+                read_unlock(&pdev->domain->pci_lock);

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 940

Quoted 10 lines
xen/arch/x86/hvm/vmsi.c +3 -0
                 return -EBUSY;
+            }
+
             if ( pdev->vpci->msix != msix )
             {
                 spin_unlock(&pdev->vpci->lock);
+                read_unlock(&pdev->domain->pci_lock);
                 return -EAGAIN;
             }
         }

... this machinery would be quite helpful (and iirc you even had such in an earlier version).

Quoted 22 lines
xen/drivers/vpci/msi.c +9 -3
@@ -313,17 +316,31 @@ void vpci_dump_msi(void)
                 {
                     /*
                      * On error vpci_msix_arch_print will always return without
-                     * holding the lock.
+                     * holding the locks.
                      */
                     printk("unable to print all MSI-X entries: %d\n", rc);
-                    process_pending_softirqs();
-                    continue;
+                    goto pdev_done;
                 }
             }
 
+            /*
+             * Unlock locks to process pending softirqs. This is
+             * potentially unsafe, as d->pdev_list can be changed in
+             * meantime.
+             */
             spin_unlock(&pdev->vpci->lock);
+            read_unlock(&d->pci_lock);
+        pdev_done:

xen/drivers/vpci/msi.c void vpci_dump_msi(void) · line 343

Quoted 10 lines
xen/drivers/vpci/msi.c +8 -0
             process_pending_softirqs();
+            if ( !read_trylock(&d->pci_lock) )
+            {
+                printk("unable to access other devices for the domain\n");
+                goto domain_done;
+            }
         }
+        read_unlock(&d->pci_lock);
+    domain_done:
+        ;

I think a blank line ahead of this label and perhaps also ahead of "pdev_done" would be quite nice.

I guess respective adjustments could be done while committing, provided there's not going to be any other reason for yet another revision.

Jan

#23 lore raw

Re: [PATCH v13.3 01/14] vpci: use per-domain PCI lock to protect vpci structure

Quoted 81 lines · Jan Beulich
Quoted 65 lines · Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

8. When possible, the existing non-vPCI callers of these MSI-related functions haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs_lock(). This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time. One exception is where the pcidevs_lock() in allocate_and_map_msi_pirq() is moved to the caller, physdev_map_pirq(): this instance is switched to read_lock(&d->pci_lock) right away.

Quoted 5 lines

with two small remaining remarks (below) and on the assumption that an R-b from Roger in particular for the vPCI code is going to turn up eventually.

Quoted 4 lines
xen/arch/x86/hvm/vmsi.c +0 -0
@@ -895,6 +891,15 @@ int vpci_msix_arch_print(const struct vpci_msix *msix)
 {
     unsigned int i;
 
Quoted 11 lines

xen/arch/x86/hvm/vmsi.c int vpci_msix_arch_print(const struct vpci_msix *msix) · line 901

Quoted 8 lines
xen/arch/x86/hvm/vmsi.c +8 -0
+    /*
+     * Assert that pdev_list doesn't change. ASSERT_PDEV_LIST_IS_READ_LOCKED
+     * is not suitable here because it may allow either pcidevs_lock() or
+     * pci_lock to be held, but here we rely on pci_lock being held, not
+     * pcidevs_lock().
+     */
+    ASSERT(rw_is_locked(&msix->pdev->domain->pci_lock));
+    ASSERT(spin_is_locked(&msix->pdev->vpci->lock));

As to the comment, I think it's not really "may". I also think referral to
...

+1 to dropping 'may'.

Thanks, Roger.

Reviewed-by on v13 1/14
#24 lore raw

Re: [PATCH v13.3 01/14] vpci: use per-domain PCI lock to protect vpci structure

In reply to Stewart Hildebrand
Quoted 65 lines · Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Use the per-domain PCI read/write lock to protect the presence of the pci device vpci field. This lock can be used (and in a few cases is used right away) so that vpci removal can be performed while holding the lock in write mode. Previously such removal could race with vpci_read for example.

When taking both d->pci_lock and pdev->vpci->lock, they should be taken in this exact order: d->pci_lock then pdev->vpci->lock to avoid possible deadlock situations.

1. Per-domain's pci_lock is used to protect pdev->vpci structure from being removed.

2. Writing the command register and ROM BAR register may trigger modify_bars to run, which in turn may access multiple pdevs while checking for the existing BAR's overlap. The overlapping check, if done under the read lock, requires vpci->lock to be acquired on both devices being compared, which may produce a deadlock. It is not possible to upgrade read lock to write lock in such a case. So, in order to prevent the deadlock, use d->pci_lock in write mode instead.

All other code, which doesn't lead to pdev->vpci destruction and does not access multiple pdevs at the same time, can still use a combination of the read lock and pdev->vpci->lock.

3. Drop const qualifier where the new rwlock is used and this is appropriate.

4. Do not call process_pending_softirqs with any locks held. For that unlock prior the call and re-acquire the locks after. After re-acquiring the lock there is no need to check if pdev->vpci exists:
- in apply_map because of the context it is called (no race condition possible)
- for MSI/MSI-X debug code because it is called at the end of pdev->vpci access and no further access to pdev->vpci is made

5. Use d->pci_lock around for_each_pdev and pci_get_pdev() while accessing pdevs in vpci code.

6. Switch vPCI functions to use per-domain pci_lock for ensuring pdevs do not go away. The vPCI functions call several MSI-related functions which already have existing non-vPCI callers. Change those MSI-related functions to allow using either pcidevs_lock() or d->pci_lock for ensuring pdevs do not go away. Holding d->pci_lock in read mode is sufficient. Note that this pdev protection mechanism does not protect other state or critical sections. These MSI-related functions already have other race condition and state protection mechanims (e.g. d->event_lock and msixtbl RCU), so we deduce that the use of the global pcidevs_lock() is to ensure that pdevs do not go away.

7. Introduce wrapper construct, pdev_list_is_read_locked(), for checking that pdevs do not go away. The purpose of this wrapper is to aid readability and document the intent of the pdev protection mechanism.

8. When possible, the existing non-vPCI callers of these MSI-related functions haven't been switched to use the newly introduced per-domain pci_lock, and will continue to use the global pcidevs_lock(). This is done to reduce the risk of the new locking scheme introducing regressions. Those users will be adjusted in due time. One exception is where the pcidevs_lock() in allocate_and_map_msi_pirq() is moved to the caller, physdev_map_pirq(): this instance is switched to read_lock(&d->pci_lock) right away.

Quoted 5 lines

Thanks, Roger.

#25 lore raw

PATCH v13 2/14 vpci: restrict unhandled read/write operations for guests

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

A guest would be able to read and write those registers which are not emulated and have no respective vPCI handlers, so it will be possible for it to access the hardware directly.
In order to prevent a guest from reads and writes from/to the unhandled registers make sure only hardware domain can access the hardware directly and restrict guests from doing so.

---
Since v9:
- removed stray formatting change
- added Roger's R-b tag
Since v6:
- do not use is_hwdom parameter for vpci_{read|write}_hw and use current->domain internally
- update commit message
New in v6

---
 xen/drivers/vpci/vpci.c | 8 ++++++++
 1 file changed, 8 insertions(+)
xen/drivers/vpci/vpci.c +8 -0
index 475272b173f3..d545dc633c40 100644
@@ -268,6 +268,10 @@ static uint32_t vpci_read_hw(pci_sbdf_t sbdf, unsigned int reg,
 {
     uint32_t data;
 
+    /* Guest domains are not allowed to read real hardware. */
+    if ( !is_hardware_domain(current->domain) )
+        return ~(uint32_t)0;
+
     switch ( size )
     {
     case 4:
@@ -311,6 +315,10 @@ static uint32_t vpci_read_hw(pci_sbdf_t sbdf, unsigned int reg,
 static void vpci_write_hw(pci_sbdf_t sbdf, unsigned int reg, unsigned int size,
                           uint32_t data)
 {
+    /* Guest domains are not allowed to write real hardware. */
+    if ( !is_hardware_domain(current->domain) )
+        return;
+
     switch ( size )
     {
     case 4:
Signature · 1 line
2.43.0
#26 lore raw

PATCH v13 3/14 vpci: add hooks for PCI device assign/de-assign

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

When a PCI device gets assigned/de-assigned we need to initialize/de-initialize vPCI state for the device.

Also, rename vpci_add_handlers() to vpci_assign_device() and vpci_remove_device() to vpci_deassign_device() to better reflect role of the functions.

---
In v13:
- Add Jan's A-b
- Rebase on
cb4ecb3cc17b ("pci: fail device assignment if phantom functions cannot be assigned") and add if ( rc ) goto done; in assign_device()
In v12:
- Add Roger's R-b
- Clean up comment in xen/include/xen/vpci.h
- Add comment in xen/drivers/passthrough/pci.c:deassign_device() to clarify vpci_assign_device() call
In v11:
- Call vpci_assign_device() in "deassign_device" if IOMMU call "reassign_device" was successful.
In v10:
- removed HAS_VPCI_GUEST_SUPPORT checks
- HAS_VPCI_GUEST_SUPPORT config option (in Kconfig) as it is not used anywhere
In v9:
- removed previous vpci_[de]assign_device function and renamed
existing handlers
- dropped attempts to handle errors in assign_device() function
- do not call vpci_assign_device for dom_io
- use d instead of pdev->domain
- use IS_ENABLED macro
In v8:
- removed vpci_deassign_device
In v6:
- do not pass struct domain to vpci_{assign|deassign}_device as pdev->domain can be used
- do not leave the device assigned (pdev->domain == new domain) in case vpci_assign_device fails: try to de-assign and if this also fails, then crash the domain
In v5:
- do not split code into run_vpci_init
- do not check for is_system_domain in vpci_{de}assign_device
- do not use vpci_remove_device_handlers_locked and re-allocate pdev->vpci completely
- make vpci_deassign_device void
In v4:
- de-assign vPCI from the previous domain on device assignment
- do not remove handlers in vpci_assign_device as those must not
exist at that point
In v3:
- remove toolstack roll-back description from the commit message
as error are to be handled with proper cleanup in Xen itself
- remove __must_check
- remove redundant rc check while assigning devices
- fix redundant CONFIG_HAS_VPCI check for CONFIG_HAS_VPCI_GUEST_SUPPORT
- use REGISTER_VPCI_INIT machinery to run required steps on device init/assign: add run_vpci_init helper
In v2:
- define CONFIG_HAS_VPCI_GUEST_SUPPORT so dead code is not compiled
for x86
In v1:
- constify struct pci_dev where possible
- do not open code is_system_domain()
- extended the commit message

---
 xen/drivers/passthrough/pci.c | 28 ++++++++++++++++++++++++----
 xen/drivers/vpci/header.c     |  2 +-
 xen/drivers/vpci/vpci.c       |  6 +++---
 xen/include/xen/vpci.h        | 10 +++++-----
 4 files changed, 33 insertions(+), 13 deletions(-)
xen/drivers/passthrough/pci.c +24 -4
index c97dd4504a7a..4c0a836486ec 100644
@@ -755,7 +755,7 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
          * For devices not discovered by Xen during boot, add vPCI handlers
          * when Dom0 first informs Xen about such devices.
          */
-        ret = vpci_add_handlers(pdev);
+        ret = vpci_assign_device(pdev);
         if ( ret )
         {
             list_del(&pdev->domain_list);
@@ -769,7 +769,7 @@ int pci_add_device(u16 seg, u8 bus, u8 devfn,
         if ( ret )
         {
             write_lock(&hardware_domain->pci_lock);
-            vpci_remove_device(pdev);
+            vpci_deassign_device(pdev);
             list_del(&pdev->domain_list);
             write_unlock(&hardware_domain->pci_lock);
             pdev->domain = NULL;
@@ -817,7 +817,7 @@ int pci_remove_device(u16 seg, u8 bus, u8 devfn)
     list_for_each_entry ( pdev, &pseg->alldevs_list, alldevs_list )
         if ( pdev->bus == bus && pdev->devfn == devfn )
         {
-            vpci_remove_device(pdev);
+            vpci_deassign_device(pdev);
             pci_cleanup_msi(pdev);
             ret = iommu_remove_device(pdev);
             if ( pdev->domain )
@@ -875,6 +875,10 @@ static int deassign_device(struct domain *d, uint16_t seg, uint8_t bus,
             goto out;
     }
 
+    write_lock(&d->pci_lock);
+    vpci_deassign_device(pdev);
+    write_unlock(&d->pci_lock);
+
     devfn = pdev->devfn;
     ret = iommu_call(hd->platform_ops, reassign_device, d, target, devfn,
                      pci_to_dev(pdev));
@@ -886,6 +890,11 @@ static int deassign_device(struct domain *d, uint16_t seg, uint8_t bus,
 
     pdev->fault.count = 0;
 
+    write_lock(&target->pci_lock);
+    /* Re-assign back to hardware_domain */
+    ret = vpci_assign_device(pdev);
+    write_unlock(&target->pci_lock);
+
  out:
     if ( ret )
         printk(XENLOG_G_ERR "%pd: deassign (%pp) failed (%d)\n",
@@ -1146,7 +1155,7 @@ static void __hwdom_init setup_one_hwdom_device(const struct setup_hwdom *ctxt,
               PCI_SLOT(devfn) == PCI_SLOT(pdev->devfn) );
 
     write_lock(&ctxt->d->pci_lock);
-    err = vpci_add_handlers(pdev);
+    err = vpci_assign_device(pdev);
     write_unlock(&ctxt->d->pci_lock);
     if ( err )
         printk(XENLOG_ERR "setup of vPCI for d%d failed: %d\n",
@@ -1476,6 +1485,10 @@ static int assign_device(struct domain *d, u16 seg, u8 bus, u8 devfn, u32 flag)
     if ( pdev->broken && d != hardware_domain && d != dom_io )
         goto done;
 
+    write_lock(&pdev->domain->pci_lock);
+    vpci_deassign_device(pdev);
+    write_unlock(&pdev->domain->pci_lock);
+
     rc = pdev_msix_assign(d, pdev);
     if ( rc )
         goto done;
@@ -1501,6 +1514,13 @@ static int assign_device(struct domain *d, u16 seg, u8 bus, u8 devfn, u32 flag)
                         pci_to_dev(pdev), flag);
     }
 
+    if ( rc )
+        goto done;
+
+    write_lock(&d->pci_lock);
+    rc = vpci_assign_device(pdev);
+    write_unlock(&d->pci_lock);
+
  done:
     if ( rc )
     {
xen/drivers/vpci/header.c +1 -1
index 8f5850b8cf6d..2f2d98ada012 100644
@@ -191,7 +191,7 @@ bool vpci_process_pending(struct vcpu *v)
              * killed in order to avoid leaking stale p2m mappings on
              * failure.
              */
-            vpci_remove_device(v->vpci.pdev);
+            vpci_deassign_device(v->vpci.pdev);
         write_unlock(&v->domain->pci_lock);
     }
 
xen/drivers/vpci/vpci.c +3 -3
index d545dc633c40..ff4837391786 100644
@@ -40,7 +40,7 @@ extern vpci_register_init_t *const __start_vpci_array[];
 extern vpci_register_init_t *const __end_vpci_array[];
 #define NUM_VPCI_INIT (__end_vpci_array - __start_vpci_array)
 
-void vpci_remove_device(struct pci_dev *pdev)
+void vpci_deassign_device(struct pci_dev *pdev)
 {
     ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
 
@@ -73,7 +73,7 @@ void vpci_remove_device(struct pci_dev *pdev)
     pdev->vpci = NULL;
 }
 
-int vpci_add_handlers(struct pci_dev *pdev)
+int vpci_assign_device(struct pci_dev *pdev)
 {
     unsigned int i;
     const unsigned long *ro_map;
@@ -107,7 +107,7 @@ int vpci_add_handlers(struct pci_dev *pdev)
     }
 
     if ( rc )
-        vpci_remove_device(pdev);
+        vpci_deassign_device(pdev);
 
     return rc;
 }
xen/include/xen/vpci.h +5 -5
index d20c301a3db3..99fe76f08ace 100644
@@ -25,11 +25,11 @@ typedef int vpci_register_init_t(struct pci_dev *dev);
   static vpci_register_init_t *const x##_entry  \
                __used_section(".data.vpci." p) = x
 
-/* Add vPCI handlers to device. */
-int __must_check vpci_add_handlers(struct pci_dev *pdev);
+/* Assign vPCI to device by adding handlers. */
+int __must_check vpci_assign_device(struct pci_dev *pdev);
 
 /* Remove all handlers and free vpci related structures. */
-void vpci_remove_device(struct pci_dev *pdev);
+void vpci_deassign_device(struct pci_dev *pdev);
 
 /* Add/remove a register handler. */
 int __must_check vpci_add_register_mask(struct vpci *vpci,
@@ -255,12 +255,12 @@ bool vpci_ecam_read(pci_sbdf_t sbdf, unsigned int reg, unsigned int len,
 #else /* !CONFIG_HAS_VPCI */
 struct vpci_vcpu {};
 
-static inline int vpci_add_handlers(struct pci_dev *pdev)
+static inline int vpci_assign_device(struct pci_dev *pdev)
 {
     return 0;
 }
 
-static inline void vpci_remove_device(struct pci_dev *pdev) { }
+static inline void vpci_deassign_device(struct pci_dev *pdev) { }
 
 static inline void vpci_dump_msi(void) { }
 
Signature · 1 line
2.43.0
#27 lore raw

PATCH v13 4/14 vpci/header: rework exit path in init_header()

In reply to Stewart Hildebrand

From: Volodymyr Babchuk <[email protected]>

Introduce "fail" label in init_header() function to have the centralized error return path. This is the pre-requirement for the future changes in this function.

This patch does not introduce functional changes.

---
In v12:
- s/init_bars/init_header/
- Re-order tags
- Fixup scissors line
In v11:
- Do not remove empty line between "goto fail;" and "continue;" In v10:
- Added Roger's A-b tag.
In v9:
- New in v9

---
 xen/drivers/vpci/header.c | 19 +++++++------------
 1 file changed, 7 insertions(+), 12 deletions(-)
xen/drivers/vpci/header.c +7 -12
index 2f2d98ada012..803fe4bb99a6 100644
@@ -656,10 +656,7 @@ static int cf_check init_header(struct pci_dev *pdev)
             rc = vpci_add_register(pdev->vpci, vpci_hw_read32, bar_write, reg,
                                    4, &bars[i]);
             if ( rc )
-            {
-                pci_conf_write16(pdev->sbdf, PCI_COMMAND, cmd);
-                return rc;
-            }
+                goto fail;
 
             continue;
         }
@@ -679,10 +676,7 @@ static int cf_check init_header(struct pci_dev *pdev)
         rc = pci_size_mem_bar(pdev->sbdf, reg, &addr, &size,
                               (i == num_bars - 1) ? PCI_BAR_LAST : 0);
         if ( rc < 0 )
-        {
-            pci_conf_write16(pdev->sbdf, PCI_COMMAND, cmd);
-            return rc;
-        }
+            goto fail;
 
         if ( size == 0 )
         {
@@ -697,10 +691,7 @@ static int cf_check init_header(struct pci_dev *pdev)
         rc = vpci_add_register(pdev->vpci, vpci_hw_read32, bar_write, reg, 4,
                                &bars[i]);
         if ( rc )
-        {
-            pci_conf_write16(pdev->sbdf, PCI_COMMAND, cmd);
-            return rc;
-        }
+            goto fail;
     }
 
     /* Check expansion ROM. */
@@ -722,6 +713,10 @@ static int cf_check init_header(struct pci_dev *pdev)
     }
 
     return (cmd & PCI_COMMAND_MEMORY) ? modify_bars(pdev, cmd, false) : 0;
+
+ fail:
+    pci_conf_write16(pdev->sbdf, PCI_COMMAND, cmd);
+    return rc;
 }
 REGISTER_VPCI_INIT(init_header, VPCI_PRIORITY_MIDDLE);
 
Signature · 1 line
2.43.0
#28 lore raw

PATCH v13 5/14 vpci/header: implement guest BAR register handlers

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Add relevant vpci register handlers when assigning PCI device to a domain and remove those when de-assigning. This allows having different handlers for different domains, e.g. hwdom and other guests.

Emulate guest BAR register values: this allows creating a guest view of the registers and emulates size and properties probe as it is done during PCI device enumeration by the guest.

All empty, IO and ROM BARs for guests are emulated by returning 0 on reads and ignoring writes: this BARs are special with this respect as their lower bits have special meaning, so returning default ~0 on read may confuse guest OS.

Introduce is_hwdom convenience variable and convert an existing is_hardware_domain() check.

---
In v12:
- Add Roger's R-b
- Get rid of empty_bar_read, use vpci_read_val instead
- Convert an existing is_hardware_domain() check to is_hwdom
- Re-indent usage of ternary operator
- Use ternary operator to avoid re-indenting expansion ROM block In v11:
- Access guest_addr after adjusting for MEM64_HI bar in guest_bar_write()
- guest bar handlers renamed and now _mem_ part to denote that they are handling only memory BARs
- refuse to update guest BAR address if BAR is enabled
In v10:
- ull -> ULL to be MISRA-compatbile
- Use PAGE_OFFSET() instead of combining with ~PAGE_MASK
- Set type of empty bars to VPCI_BAR_EMPTY
In v9:
- factored-out "fail" label introduction in init_bars()
- replaced #ifdef CONFIG_X86 with IS_ENABLED()
- do not pass bars[i] to empty_bar_read() handler
- store guest's BAR address instead of guests BAR register view Since v6:
- unify the writing of the PCI_COMMAND register on the
error path into a label
- do not introduce bar_ignore_access helper and open code
- s/guest_bar_ignore_read/empty_bar_read
- update error message in guest_bar_write
- only setup empty_bar_read for IO if !x86
Since v5:
- make sure that the guest set address has the same page offset as the physical address on the host
- remove guest_rom_{read|write} as those just implement the default behaviour of the registers not being handled
- adjusted comment for struct vpci.addr field
- add guest handlers for BARs which are not handled and will otherwise return ~0 on read and ignore writes. The BARs are special with this respect as their lower bits have special meaning, so returning ~0 doesn't seem to be right
Since v4:
- updated commit message
- s/guest_addr/guest_reg
Since v3:
- squashed two patches: dynamic add/remove handlers and guest BAR handler implementation
- fix guest BAR read of the high part of a 64bit BAR (Roger)
- add error handling to vpci_assign_device
- s/dom%pd/%pd
- blank line before return
Since v2:
- remove unneeded ifdefs for CONFIG_HAS_VPCI_GUEST_SUPPORT as more code has been eliminated from being built on x86
Since v1:
- constify struct pci_dev where possible
- do not open code is_system_domain()
- simplify some code3. simplify
- use gdprintk + error code instead of gprintk
- gate vpci_bar_{add|remove}_handlers with CONFIG_HAS_VPCI_GUEST_SUPPORT, so these do not get compiled for x86
- removed unneeded is_system_domain check
- re-work guest read/write to be much simpler and do more work on write than read which is expected to be called more frequently
- removed one too obvious comment

---
 xen/drivers/vpci/header.c | 109 +++++++++++++++++++++++++++++++++++---
 xen/include/xen/vpci.h    |   3 ++
 2 files changed, 106 insertions(+), 6 deletions(-)
xen/drivers/vpci/header.c +103 -6
index 803fe4bb99a6..39e11e141b38 100644
@@ -478,6 +478,69 @@ static void cf_check bar_write(
     pci_conf_write32(pdev->sbdf, reg, val);
 }
 
+static void cf_check guest_mem_bar_write(const struct pci_dev *pdev,
+                                         unsigned int reg, uint32_t val,
+                                         void *data)
+{
+    struct vpci_bar *bar = data;
+    bool hi = false;
+    uint64_t guest_addr;
+
+    if ( bar->type == VPCI_BAR_MEM64_HI )
+    {
+        ASSERT(reg > PCI_BASE_ADDRESS_0);
+        bar--;
+        hi = true;
+    }
+    else
+    {
+        val &= PCI_BASE_ADDRESS_MEM_MASK;
+    }
+
+    guest_addr = bar->guest_addr;
+    guest_addr &= ~(0xffffffffULL << (hi ? 32 : 0));
+    guest_addr |= (uint64_t)val << (hi ? 32 : 0);
+
+    /* Allow guest to size BAR correctly */
+    guest_addr &= ~(bar->size - 1);
+
+    /*
+     * Xen only cares whether the BAR is mapped into the p2m, so allow BAR
+     * writes as long as the BAR is not mapped into the p2m.
+     */
+    if ( bar->enabled )
+    {
+        /* If the value written is the current one avoid printing a warning. */
+        if ( guest_addr != bar->guest_addr )
+            gprintk(XENLOG_WARNING,
+                    "%pp: ignored guest BAR %zu write while mapped\n",
+                    &pdev->sbdf, bar - pdev->vpci->header.bars + hi);
+        return;
+    }
+    bar->guest_addr = guest_addr;
+}
+
+static uint32_t cf_check guest_mem_bar_read(const struct pci_dev *pdev,
+                                            unsigned int reg, void *data)
+{
+    const struct vpci_bar *bar = data;
+    uint32_t reg_val;
+
+    if ( bar->type == VPCI_BAR_MEM64_HI )
+    {
+        ASSERT(reg > PCI_BASE_ADDRESS_0);
+        bar--;
+        return bar->guest_addr >> 32;
+    }
+
+    reg_val = bar->guest_addr;
+    reg_val |= bar->type == VPCI_BAR_MEM32 ? PCI_BASE_ADDRESS_MEM_TYPE_32 :
+                                             PCI_BASE_ADDRESS_MEM_TYPE_64;
+    reg_val |= bar->prefetchable ? PCI_BASE_ADDRESS_MEM_PREFETCH : 0;
+
+    return reg_val;
+}
+
 static void cf_check rom_write(
     const struct pci_dev *pdev, unsigned int reg, uint32_t val, void *data)
 {
@@ -539,6 +602,7 @@ static int cf_check init_header(struct pci_dev *pdev)
     struct vpci_bar *bars = header->bars;
     int rc;
     bool mask_cap_list = false;
+    bool is_hwdom = is_hardware_domain(pdev->domain);
 
     ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
 
@@ -564,7 +628,7 @@ static int cf_check init_header(struct pci_dev *pdev)
     if ( rc )
         return rc;
 
-    if ( !is_hardware_domain(pdev->domain) )
+    if ( !is_hwdom )
     {
         if ( pci_conf_read16(pdev->sbdf, PCI_STATUS) & PCI_STATUS_CAP_LIST )
         {
@@ -653,8 +717,11 @@ static int cf_check init_header(struct pci_dev *pdev)
         if ( i && bars[i - 1].type == VPCI_BAR_MEM64_LO )
         {
             bars[i].type = VPCI_BAR_MEM64_HI;
-            rc = vpci_add_register(pdev->vpci, vpci_hw_read32, bar_write, reg,
-                                   4, &bars[i]);
+            rc = vpci_add_register(pdev->vpci,
+                                   is_hwdom ? vpci_hw_read32
+                                            : guest_mem_bar_read,
+                                   is_hwdom ? bar_write : guest_mem_bar_write,
+                                   reg, 4, &bars[i]);
             if ( rc )
                 goto fail;
 
@@ -665,6 +732,14 @@ static int cf_check init_header(struct pci_dev *pdev)
         if ( (val & PCI_BASE_ADDRESS_SPACE) == PCI_BASE_ADDRESS_SPACE_IO )
         {
             bars[i].type = VPCI_BAR_IO;
+            if ( !IS_ENABLED(CONFIG_X86) && !is_hwdom )
+            {
+                rc = vpci_add_register(pdev->vpci, vpci_read_val, NULL,
+                                       reg, 4, (void *)0);
+                if ( rc )
+                    goto fail;
+            }
+
             continue;
         }
         if ( (val & PCI_BASE_ADDRESS_MEM_TYPE_MASK) ==
@@ -681,6 +756,15 @@ static int cf_check init_header(struct pci_dev *pdev)
         if ( size == 0 )
         {
             bars[i].type = VPCI_BAR_EMPTY;
+
+            if ( !is_hwdom )
+            {
+                rc = vpci_add_register(pdev->vpci, vpci_read_val, NULL,
+                                       reg, 4, (void *)0);
+                if ( rc )
+                    goto fail;
+            }
+
             continue;
         }
 
@@ -688,14 +772,18 @@ static int cf_check init_header(struct pci_dev *pdev)
         bars[i].size = size;
         bars[i].prefetchable = val & PCI_BASE_ADDRESS_MEM_PREFETCH;
 
-        rc = vpci_add_register(pdev->vpci, vpci_hw_read32, bar_write, reg, 4,
-                               &bars[i]);
+        rc = vpci_add_register(pdev->vpci,
+                               is_hwdom ? vpci_hw_read32 : guest_mem_bar_read,
+                               is_hwdom ? bar_write : guest_mem_bar_write,
+                               reg, 4, &bars[i]);
         if ( rc )
             goto fail;
     }
 
     /* Check expansion ROM. */
-    rc = pci_size_mem_bar(pdev->sbdf, rom_reg, &addr, &size, PCI_BAR_ROM);
+    rc = is_hwdom ? pci_size_mem_bar(pdev->sbdf, rom_reg, &addr, &size,
+                                     PCI_BAR_ROM)
+                  : 0;
     if ( rc > 0 && size )
     {
         struct vpci_bar *rom = &header->bars[num_bars];
@@ -711,6 +799,15 @@ static int cf_check init_header(struct pci_dev *pdev)
         if ( rc )
             rom->type = VPCI_BAR_EMPTY;
     }
+    else if ( !is_hwdom )
+    {
+        /* TODO: Check expansion ROM, we do not handle ROM for guests for now */
+        header->bars[num_bars].type = VPCI_BAR_EMPTY;
+        rc = vpci_add_register(pdev->vpci, vpci_read_val, NULL,
+                               rom_reg, 4, (void *)0);
+        if ( rc )
+            goto fail;
+    }
 
     return (cmd & PCI_COMMAND_MEMORY) ? modify_bars(pdev, cmd, false) : 0;
 
xen/include/xen/vpci.h +3 -0
index 99fe76f08ace..b0e38a5a1acb 100644
@@ -87,7 +87,10 @@ struct vpci {
     struct vpci_header {
         /* Information about the PCI BARs of this device. */
         struct vpci_bar {
+            /* Physical (host) address. */
             uint64_t addr;
+            /* Guest address. */
+            uint64_t guest_addr;
             uint64_t size;
             enum {
                 VPCI_BAR_EMPTY,
Signature · 1 line
2.43.0
#29 lore raw

PATCH v13 6/14 rangeset: add RANGESETF_no_print flag

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

There are range sets which should not be printed, so introduce a flag which allows marking those as such. Implement relevant logic to skip such entries while printing.

While at it also simplify the definition of the flags by directly defining those without helpers.

---
Since v5:
- comment indentation (Jan)
Since v1:
- update BUG_ON with new flag
- simplify the definition of the flags

---
 xen/common/rangeset.c      | 5 ++++-
 xen/include/xen/rangeset.h | 5 +++--
 2 files changed, 7 insertions(+), 3 deletions(-)
xen/common/rangeset.c +4 -1
index 16a4c3b842e6..0ccd53caac52 100644
@@ -433,7 +433,7 @@ struct rangeset *rangeset_new(
     INIT_LIST_HEAD(&r->range_list);
     r->nr_ranges = -1;
 
-    BUG_ON(flags & ~RANGESETF_prettyprint_hex);
+    BUG_ON(flags & ~(RANGESETF_prettyprint_hex | RANGESETF_no_print));
     r->flags = flags;
 
     safe_strcpy(r->name, name ?: "(no name)");
@@ -575,6 +575,9 @@ void rangeset_domain_printk(
 
     list_for_each_entry ( r, &d->rangesets, rangeset_list )
     {
+        if ( r->flags & RANGESETF_no_print )
+            continue;
+
         printk("    ");
         rangeset_printk(r);
         printk("\n");
xen/include/xen/rangeset.h +3 -2
index 8be0722787ed..87bd956962b5 100644
@@ -49,8 +49,9 @@ void rangeset_limit(
 
 /* Flags for passing to rangeset_new(). */
  /* Pretty-print range limits in hexadecimal. */
-#define _RANGESETF_prettyprint_hex 0
-#define RANGESETF_prettyprint_hex  (1U << _RANGESETF_prettyprint_hex)
+#define RANGESETF_prettyprint_hex   (1U << 0)
+ /* Do not print entries marked with this flag. */
+#define RANGESETF_no_print          (1U << 1)
 
 bool __must_check rangeset_is_empty(
     const struct rangeset *r);
Signature · 1 line
2.43.0
#30 lore raw

PATCH v13 7/14 rangeset: add rangeset_purge() function

In reply to Stewart Hildebrand

From: Volodymyr Babchuk <[email protected]>

This function can be used when user wants to remove all rangeset entries but do not want to destroy rangeset itself.

---
Changes in v13:
- Added Jan's A-b
Changes in v12:
- s/rangeset_empty/rangeset_purge/
Changes in v11:
- Now the function only empties rangeset, without removing it from domain's list

Changes in v10:
- New in v10. The function is used in "vpci/header: handle p2m range sets per BAR"

---
 xen/common/rangeset.c      | 16 ++++++++++++----
 xen/include/xen/rangeset.h |  3 ++-
 2 files changed, 14 insertions(+), 5 deletions(-)
xen/common/rangeset.c +12 -4
index 0ccd53caac52..b75590f90744 100644
@@ -448,11 +448,20 @@ struct rangeset *rangeset_new(
     return r;
 }
 
-void rangeset_destroy(
-    struct rangeset *r)
+void rangeset_purge(struct rangeset *r)
 {
     struct range *x;
 
+    if ( r == NULL )
+        return;
+
+    while ( (x = first_range(r)) != NULL )
+        destroy_range(r, x);
+}
+
+void rangeset_destroy(
+    struct rangeset *r)
+{
     if ( r == NULL )
         return;
 
@@ -463,8 +472,7 @@ void rangeset_destroy(
         spin_unlock(&r->domain->rangesets_lock);
     }
 
-    while ( (x = first_range(r)) != NULL )
-        destroy_range(r, x);
+    rangeset_purge(r);
 
     xfree(r);
 }
xen/include/xen/rangeset.h +2 -1
index 87bd956962b5..96c918082501 100644
@@ -56,7 +56,7 @@ void rangeset_limit(
 bool __must_check rangeset_is_empty(
     const struct rangeset *r);
 
-/* Add/claim/remove/query a numeric range. */
+/* Add/claim/remove/query/purge a numeric range. */
 int __must_check rangeset_add_range(
     struct rangeset *r, unsigned long s, unsigned long e);
 int __must_check rangeset_claim_range(struct rangeset *r, unsigned long size,
@@ -70,6 +70,7 @@ bool __must_check rangeset_overlaps_range(
 int rangeset_report_ranges(
     struct rangeset *r, unsigned long s, unsigned long e,
     int (*cb)(unsigned long s, unsigned long e, void *data), void *ctxt);
+void rangeset_purge(struct rangeset *r);
 
 /*
  * Note that the consume function can return an error value apart from
Signature · 1 line
2.43.0
#31 lore raw

PATCH v13 8/14 vpci/header: handle p2m range sets per BAR

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Instead of handling a single range set, that contains all the memory regions of all the BARs and ROM, have them per BAR.
As the range sets are now created when a PCI device is added and destroyed when it is removed so make them named and accounted.

Note that rangesets were chosen here despite there being only up to 3 separate ranges in each set (typically just 1). But rangeset per BAR was chosen for the ease of implementation and existing code re-usability.

Also note that error handling of vpci_process_pending() is slightly modified, and that vPCI handlers are no longer removed if the creation of the mappings in vpci_process_pending() fails, as that's unlikely to lead to a functional device in any case.

This is in preparation of making non-identity mappings in p2m for the MMIOs.

---
In v12:
- s/rangeset_empty/rangeset_purge/
- change i to num_bars for expansion ROM (purely cosmetic change) In v11:
- Modified commit message to note changes in error handling in vpci_process_pending()
- Removed redundant ASSERT() in defer_map. There is no reason to introduce it in this patch and there is no other patch where introducing that ASSERT() was appropriate.
- Fixed formatting
- vpci_process_pending() clears v->vpci.pdev if it failed checks at the beginning
- Added Roger's R-B tag
In v10:
- Added additional checks to vpci_process_pending()
- vpci_process_pending() now clears rangeset in case of failure
- Fixed locks in vpci_process_pending()
- Fixed coding style issues
- Fixed error handling in init_bars
In v9:
- removed d->vpci.map_pending in favor of checking v->vpci.pdev != NULL
- printk -> gprintk
- renamed bar variable to fix shadowing
- fixed bug with iterating on remote device's BARs
- relaxed lock in vpci_process_pending
- removed stale comment
Since v6:
- update according to the new locking scheme
- remove odd fail label in modify_bars
Since v5:
- fix comments
- move rangeset allocation to init_bars and only allocate for MAPPABLE BARs
- check for overlap with the already setup BAR ranges Since v4:
- use named range sets for BARs (Jan)
- changes required by the new locking scheme
- updated commit message (Jan)
Since v3:
- re-work vpci_cancel_pending accordingly to the per-BAR handling
- s/num_mem_ranges/map_pending and s/uint8_t/bool
- ASSERT(bar->mem) in modify_bars
- create and destroy the rangesets on add/remove

---
 xen/drivers/vpci/header.c | 257 ++++++++++++++++++++++++++------------
 xen/drivers/vpci/vpci.c   |   6 +
 xen/include/xen/vpci.h    |   2 +-
 3 files changed, 185 insertions(+), 80 deletions(-)
xen/drivers/vpci/header.c +178 -79
index 39e11e141b38..feccd070ddd0 100644
@@ -162,63 +162,107 @@ static void modify_decoding(const struct pci_dev *pdev, uint16_t cmd,
 
 bool vpci_process_pending(struct vcpu *v)
 {
-    if ( v->vpci.mem )
+    struct pci_dev *pdev = v->vpci.pdev;
+    struct map_data data = {
+        .d = v->domain,
+        .map = v->vpci.cmd & PCI_COMMAND_MEMORY,
+    };
+    struct vpci_header *header = NULL;
+    unsigned int i;
+
+    if ( !pdev )
+        return false;
+
+    read_lock(&v->domain->pci_lock);
+
+    if ( !pdev->vpci || (v->domain != pdev->domain) )
     {
-        struct map_data data = {
-            .d = v->domain,
-            .map = v->vpci.cmd & PCI_COMMAND_MEMORY,
-        };
-        int rc = rangeset_consume_ranges(v->vpci.mem, map_range, &data);
+        v->vpci.pdev = NULL;
+        read_unlock(&v->domain->pci_lock);
+        return false;
+    }
+
+    header = &pdev->vpci->header;
+    for ( i = 0; i < ARRAY_SIZE(header->bars); i++ )
+    {
+        struct vpci_bar *bar = &header->bars[i];
+        int rc;
+
+        if ( rangeset_is_empty(bar->mem) )
+            continue;
+
+        rc = rangeset_consume_ranges(bar->mem, map_range, &data);
 
         if ( rc == -ERESTART )
+        {
+            read_unlock(&v->domain->pci_lock);
             return true;
+        }
 
-        write_lock(&v->domain->pci_lock);
-        spin_lock(&v->vpci.pdev->vpci->lock);
-        /* Disable memory decoding unconditionally on failure. */
-        modify_decoding(v->vpci.pdev,
-                        rc ? v->vpci.cmd & ~PCI_COMMAND_MEMORY : v->vpci.cmd,
-                        !rc && v->vpci.rom_only);
-        spin_unlock(&v->vpci.pdev->vpci->lock);
-
-        rangeset_destroy(v->vpci.mem);
-        v->vpci.mem = NULL;
         if ( rc )
-            /*
-             * FIXME: in case of failure remove the device from the domain.
-             * Note that there might still be leftover mappings. While this is
-             * safe for Dom0, for DomUs the domain will likely need to be
-             * killed in order to avoid leaking stale p2m mappings on
-             * failure.
-             */
-            vpci_deassign_device(v->vpci.pdev);
-        write_unlock(&v->domain->pci_lock);
+        {
+            spin_lock(&pdev->vpci->lock);
+            /* Disable memory decoding unconditionally on failure. */
+            modify_decoding(pdev, v->vpci.cmd & ~PCI_COMMAND_MEMORY,
+                            false);
+            spin_unlock(&pdev->vpci->lock);
+
+            /* Clean all the rangesets */
+            for ( i = 0; i < ARRAY_SIZE(header->bars); i++ )
+                if ( !rangeset_is_empty(header->bars[i].mem) )
+                     rangeset_purge(header->bars[i].mem);
+
+            v->vpci.pdev = NULL;
+
+            read_unlock(&v->domain->pci_lock);
+
+            if ( !is_hardware_domain(v->domain) )
+                domain_crash(v->domain);
+
+            return false;
+        }
     }
+    v->vpci.pdev = NULL;
+
+    spin_lock(&pdev->vpci->lock);
+    modify_decoding(pdev, v->vpci.cmd, v->vpci.rom_only);
+    spin_unlock(&pdev->vpci->lock);
+
+    read_unlock(&v->domain->pci_lock);
 
     return false;
 }
 
 static int __init apply_map(struct domain *d, const struct pci_dev *pdev,
-                            struct rangeset *mem, uint16_t cmd)
+                            uint16_t cmd)
 {
     struct map_data data = { .d = d, .map = true };
-    int rc;
+    struct vpci_header *header = &pdev->vpci->header;
+    int rc = 0;
+    unsigned int i;
 
     ASSERT(rw_is_write_locked(&d->pci_lock));
 
-    while ( (rc = rangeset_consume_ranges(mem, map_range, &data)) == -ERESTART )
+    for ( i = 0; i < ARRAY_SIZE(header->bars); i++ )
     {
-        /*
-         * It's safe to drop and reacquire the lock in this context
-         * without risking pdev disappearing because devices cannot be
-         * removed until the initial domain has been started.
-         */
-        write_unlock(&d->pci_lock);
-        process_pending_softirqs();
-        write_lock(&d->pci_lock);
-    }
+        struct vpci_bar *bar = &header->bars[i];
 
-    rangeset_destroy(mem);
+        if ( rangeset_is_empty(bar->mem) )
+            continue;
+
+        while ( (rc = rangeset_consume_ranges(bar->mem, map_range,
+                                              &data)) == -ERESTART )
+        {
+            /*
+             * It's safe to drop and reacquire the lock in this context
+             * without risking pdev disappearing because devices cannot be
+             * removed until the initial domain has been started.
+             */
+            write_unlock(&d->pci_lock);
+            process_pending_softirqs();
+            write_lock(&d->pci_lock);
+        }
+    }
     if ( !rc )
         modify_decoding(pdev, cmd, false);
 
@@ -226,7 +270,7 @@ static int __init apply_map(struct domain *d, const struct pci_dev *pdev,
 }
 
 static void defer_map(struct domain *d, struct pci_dev *pdev,
-                      struct rangeset *mem, uint16_t cmd, bool rom_only)
+                      uint16_t cmd, bool rom_only)
 {
     struct vcpu *curr = current;
 
@@ -237,7 +281,6 @@ static void defer_map(struct domain *d, struct pci_dev *pdev,
      * started for the same device if the domain is not well-behaved.
      */
     curr->vpci.pdev = pdev;
-    curr->vpci.mem = mem;
     curr->vpci.cmd = cmd;
     curr->vpci.rom_only = rom_only;
     /*
@@ -251,33 +294,33 @@ static void defer_map(struct domain *d, struct pci_dev *pdev,
 static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
 {
     struct vpci_header *header = &pdev->vpci->header;
-    struct rangeset *mem = rangeset_new(NULL, NULL, 0);
     struct pci_dev *tmp, *dev = NULL;
     const struct domain *d;
     const struct vpci_msix *msix = pdev->vpci->msix;
-    unsigned int i;
+    unsigned int i, j;
     int rc;
 
     ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
 
-    if ( !mem )
-        return -ENOMEM;
-
     /*
-     * Create a rangeset that represents the current device BARs memory region
-     * and compare it against all the currently active BAR memory regions. If
-     * an overlap is found, subtract it from the region to be mapped/unmapped.
+     * Create a rangeset per BAR that represents the current device memory
+     * region and compare it against all the currently active BAR memory
+     * regions. If an overlap is found, subtract it from the region to be
+     * mapped/unmapped.
      *
-     * First fill the rangeset with all the BARs of this device or with the ROM
+     * First fill the rangesets with the BAR of this device or with the ROM
      * BAR only, depending on whether the guest is toggling the memory decode
      * bit of the command register, or the enable bit of the ROM BAR register.
      */
     for ( i = 0; i < ARRAY_SIZE(header->bars); i++ )
     {
-        const struct vpci_bar *bar = &header->bars[i];
+        struct vpci_bar *bar = &header->bars[i];
         unsigned long start = PFN_DOWN(bar->addr);
         unsigned long end = PFN_DOWN(bar->addr + bar->size - 1);
 
+        if ( !bar->mem )
+            continue;
+
         if ( !MAPPABLE_BAR(bar) ||
              (rom_only ? bar->type != VPCI_BAR_ROM
                        : (bar->type == VPCI_BAR_ROM && !header->rom_enabled)) ||
@@ -293,14 +336,31 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
             continue;
         }
 
-        rc = rangeset_add_range(mem, start, end);
+        rc = rangeset_add_range(bar->mem, start, end);
         if ( rc )
         {
             printk(XENLOG_G_WARNING "Failed to add [%lx, %lx]: %d\n",
                    start, end, rc);
-            rangeset_destroy(mem);
             return rc;
         }
+
+        /* Check for overlap with the already setup BAR ranges. */
+        for ( j = 0; j < i; j++ )
+        {
+            struct vpci_bar *prev_bar = &header->bars[j];
+
+            if ( rangeset_is_empty(prev_bar->mem) )
+                continue;
+
+            rc = rangeset_remove_range(prev_bar->mem, start, end);
+            if ( rc )
+            {
+                gprintk(XENLOG_WARNING,
+                       "%pp: failed to remove overlapping range [%lx, %lx]: %d\n",
+                        &pdev->sbdf, start, end, rc);
+                return rc;
+            }
+        }
     }
 
     /* Remove any MSIX regions if present. */
@@ -310,14 +370,21 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
         unsigned long end = PFN_DOWN(vmsix_table_addr(pdev->vpci, i) +
                                      vmsix_table_size(pdev->vpci, i) - 1);
 
-        rc = rangeset_remove_range(mem, start, end);
-        if ( rc )
+        for ( j = 0; j < ARRAY_SIZE(header->bars); j++ )
         {
-            printk(XENLOG_G_WARNING
-                   "Failed to remove MSIX table [%lx, %lx]: %d\n",
-                   start, end, rc);
-            rangeset_destroy(mem);
-            return rc;
+            const struct vpci_bar *bar = &header->bars[j];
+
+            if ( rangeset_is_empty(bar->mem) )
+                continue;
+
+            rc = rangeset_remove_range(bar->mem, start, end);
+            if ( rc )
+            {
+                gprintk(XENLOG_WARNING,
+                       "%pp: failed to remove MSIX table [%lx, %lx]: %d\n",
+                        &pdev->sbdf, start, end, rc);
+                return rc;
+            }
         }
     }
 
@@ -357,27 +424,37 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
 
             for ( i = 0; i < ARRAY_SIZE(tmp->vpci->header.bars); i++ )
             {
-                const struct vpci_bar *bar = &tmp->vpci->header.bars[i];
-                unsigned long start = PFN_DOWN(bar->addr);
-                unsigned long end = PFN_DOWN(bar->addr + bar->size - 1);
-
-                if ( !bar->enabled ||
-                     !rangeset_overlaps_range(mem, start, end) ||
-                     /*
-                      * If only the ROM enable bit is toggled check against
-                      * other BARs in the same device for overlaps, but not
-                      * against the same ROM BAR.
-                      */
-                     (rom_only && tmp == pdev && bar->type == VPCI_BAR_ROM) )
+                const struct vpci_bar *remote_bar = &tmp->vpci->header.bars[i];
+                unsigned long start = PFN_DOWN(remote_bar->addr);
+                unsigned long end = PFN_DOWN(remote_bar->addr +
+                                             remote_bar->size - 1);
+
+                if ( !remote_bar->enabled )
                     continue;
 
-                rc = rangeset_remove_range(mem, start, end);
-                if ( rc )
+                for ( j = 0; j < ARRAY_SIZE(header->bars); j++)
                 {
-                    printk(XENLOG_G_WARNING "Failed to remove [%lx, %lx]: %d\n",
-                           start, end, rc);
-                    rangeset_destroy(mem);
-                    return rc;
+                    const struct vpci_bar *bar = &header->bars[j];
+
+                    if ( !rangeset_overlaps_range(bar->mem, start, end) ||
+                         /*
+                          * If only the ROM enable bit is toggled check against
+                          * other BARs in the same device for overlaps, but not
+                          * against the same ROM BAR.
+                          */
+                         (rom_only &&
+                          tmp == pdev &&
+                          bar->type == VPCI_BAR_ROM) )
+                        continue;
+
+                    rc = rangeset_remove_range(bar->mem, start, end);
+                    if ( rc )
+                    {
+                        gprintk(XENLOG_WARNING,
+                                "%pp: failed to remove [%lx, %lx]: %d\n",
+                                &pdev->sbdf, start, end, rc);
+                        return rc;
+                    }
                 }
             }
         }
@@ -401,10 +478,10 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
          * will always be to establish mappings and process all the BARs.
          */
         ASSERT((cmd & PCI_COMMAND_MEMORY) && !rom_only);
-        return apply_map(pdev->domain, pdev, mem, cmd);
+        return apply_map(pdev->domain, pdev, cmd);
     }
 
-    defer_map(dev->domain, dev, mem, cmd, rom_only);
+    defer_map(dev->domain, dev, cmd, rom_only);
 
     return 0;
 }
@@ -593,6 +670,18 @@ static void cf_check rom_write(
         rom->addr = val & PCI_ROM_ADDRESS_MASK;
 }
 
+static int bar_add_rangeset(const struct pci_dev *pdev, struct vpci_bar *bar,
+                            unsigned int i)
+{
+    char str[32];
+
+    snprintf(str, sizeof(str), "%pp:BAR%u", &pdev->sbdf, i);
+
+    bar->mem = rangeset_new(pdev->domain, str, RANGESETF_no_print);
+
+    return !bar->mem ? -ENOMEM : 0;
+}
+
 static int cf_check init_header(struct pci_dev *pdev)
 {
     uint16_t cmd;
@@ -748,6 +837,10 @@ static int cf_check init_header(struct pci_dev *pdev)
         else
             bars[i].type = VPCI_BAR_MEM32;
 
+        rc = bar_add_rangeset(pdev, &bars[i], i);
+        if ( rc )
+            goto fail;
+
         rc = pci_size_mem_bar(pdev->sbdf, reg, &addr, &size,
                               (i == num_bars - 1) ? PCI_BAR_LAST : 0);
         if ( rc < 0 )
@@ -798,6 +891,12 @@ static int cf_check init_header(struct pci_dev *pdev)
                                4, rom);
         if ( rc )
             rom->type = VPCI_BAR_EMPTY;
+        else
+        {
+            rc = bar_add_rangeset(pdev, rom, num_bars);
+            if ( rc )
+                goto fail;
+        }
     }
     else if ( !is_hwdom )
     {
xen/drivers/vpci/vpci.c +6 -0
index ff4837391786..260b72875ee1 100644
@@ -42,6 +42,8 @@ extern vpci_register_init_t *const __end_vpci_array[];
 
 void vpci_deassign_device(struct pci_dev *pdev)
 {
+    unsigned int i;
+
     ASSERT(rw_is_write_locked(&pdev->domain->pci_lock));
 
     if ( !has_vpci(pdev->domain) || !pdev->vpci )
@@ -67,6 +69,10 @@ void vpci_deassign_device(struct pci_dev *pdev)
             if ( pdev->vpci->msix->table[i] )
                 iounmap(pdev->vpci->msix->table[i]);
     }
+
+    for ( i = 0; i < ARRAY_SIZE(pdev->vpci->header.bars); i++ )
+        rangeset_destroy(pdev->vpci->header.bars[i].mem);
+
     xfree(pdev->vpci->msix);
     xfree(pdev->vpci->msi);
     xfree(pdev->vpci);
xen/include/xen/vpci.h +1 -1
index b0e38a5a1acb..817ee9ee7300 100644
@@ -92,6 +92,7 @@ struct vpci {
             /* Guest address. */
             uint64_t guest_addr;
             uint64_t size;
+            struct rangeset *mem;
             enum {
                 VPCI_BAR_EMPTY,
                 VPCI_BAR_IO,
@@ -176,7 +177,6 @@ struct vpci {
 
 struct vpci_vcpu {
     /* Per-vcpu structure to store state while {un}mapping of PCI BARs. */
-    struct rangeset *mem;
     struct pci_dev *pdev;
     uint16_t cmd;
     bool rom_only : 1;
Signature · 1 line
2.43.0
#32 lore raw

PATCH v13 9/14 vpci/header: program p2m with guest BAR view

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Take into account guest's BAR view and program its p2m accordingly:
gfn is guest's view of the BAR and mfn is the physical BAR value. This way hardware domain sees physical BAR values and guest sees emulated ones.

Hardware domain continues getting the BARs identity mapped, while for domUs the BARs are mapped at the requested guest address without modifying the BAR address in the device PCI config space.

---
In v12.3:
- Update arguments passed to permission error prints in map_range() In v12.2:
- Slightly tweak print format in modify_bars()
In v12.1:
- ASSERT(rangeset_is_empty()) in modify_bars()
- Fixup print format in modify_bars()
- Make comment single line in bar_write()
- Add Roger's R-b
In v12:
- Update guest_addr in rom_write()
- Use unsigned long for start_mfn and map_mfn to reduce mfn_x() calls
- Use existing vmsix_table_*() functions
- Change vmsix_table_base() to use .guest_addr
In v11:
- Add vmsix_guest_table_addr() and vmsix_guest_table_base() functions to access guest's view of the VMSIx tables.
- Use MFN (not GFN) to check access permissions
- Move page offset check to this patch
- Call rangeset_remove_range() with correct parameters
In v10:
- Moved GFN variable definition outside the loop in map_range()
- Updated printk error message in map_range()
- Now BAR address is always stored in bar->guest_addr, even for HW dom, this removes bunch of ugly is_hwdom() checks in modify_bars()
- vmsix_table_base() now uses .guest_addr instead of .addr
In v9:
- Extended the commit message
- Use bar->guest_addr in modify_bars
- Extended printk error message in map_range
- Moved map_data initialization so .bar can be initialized during declaration Since v5:
- remove debug print in map_range callback
- remove "identity" from the debug print
Since v4:
- moved start_{gfn|mfn} calculation into map_range
- pass vpci_bar in the map_data instead of start_{gfn|mfn}
- s/guest_addr/guest_reg
Since v3:
- updated comment (Roger)
- removed gfn_add(map->start_gfn, rc); which is wrong
- use v->domain instead of v->vpci.pdev->domain
- removed odd e.g. in comment
- s/d%d/%pd in altered code
- use gdprintk for map/unmap logs
Since v2:
- improve readability for data.start_gfn and restructure ?: construct Since v1:
- s/MSI/MSI-X in comments

---
 xen/drivers/vpci/header.c | 83 ++++++++++++++++++++++++++++++---------
 xen/include/xen/vpci.h    |  3 +-
 2 files changed, 66 insertions(+), 20 deletions(-)
xen/drivers/vpci/header.c +64 -19
index feccd070ddd0..47648c395132 100644
@@ -34,6 +34,7 @@
 
 struct map_data {
     struct domain *d;
+    const struct vpci_bar *bar;
     bool map;
 };
 
@@ -41,26 +42,37 @@ static int cf_check map_range(
     unsigned long s, unsigned long e, void *data, unsigned long *c)
 {
     const struct map_data *map = data;
+    /* Start address of the BAR as seen by the guest. */
+    unsigned long start_gfn = PFN_DOWN(map->bar->guest_addr);
+    /* Physical start address of the BAR. */
+    unsigned long start_mfn = PFN_DOWN(map->bar->addr);
     int rc;
 
     for ( ; ; )
     {
         unsigned long size = e - s + 1;
+        /*
+         * Ranges to be mapped don't always start at the BAR start address, as
+         * there can be holes or partially consumed ranges. Account for the
+         * offset of the current address from the BAR start.
+         */
+        unsigned long map_mfn = start_mfn + s - start_gfn;
+        unsigned long m_end = map_mfn + size - 1;
 
-        if ( !iomem_access_permitted(map->d, s, e) )
+        if ( !iomem_access_permitted(map->d, map_mfn, m_end) )
         {
             printk(XENLOG_G_WARNING
                    "%pd denied access to MMIO range [%#lx, %#lx]\n",
-                   map->d, s, e);
+                   map->d, map_mfn, m_end);
             return -EPERM;
         }
 
-        rc = xsm_iomem_mapping(XSM_HOOK, map->d, s, e, map->map);
+        rc = xsm_iomem_mapping(XSM_HOOK, map->d, map_mfn, m_end, map->map);
         if ( rc )
         {
             printk(XENLOG_G_WARNING
                    "%pd XSM denied access to MMIO range [%#lx, %#lx]: %d\n",
-                   map->d, s, e, rc);
+                   map->d, map_mfn, m_end, rc);
             return rc;
         }
 
@@ -73,8 +85,8 @@ static int cf_check map_range(
          * - {un}map_mmio_regions doesn't support preemption.
          */
 
-        rc = map->map ? map_mmio_regions(map->d, _gfn(s), size, _mfn(s))
-                      : unmap_mmio_regions(map->d, _gfn(s), size, _mfn(s));
+        rc = map->map ? map_mmio_regions(map->d, _gfn(s), size, _mfn(map_mfn))
+                      : unmap_mmio_regions(map->d, _gfn(s), size, _mfn(map_mfn));
         if ( rc == 0 )
         {
             *c += size;
@@ -83,8 +95,9 @@ static int cf_check map_range(
         if ( rc < 0 )
         {
             printk(XENLOG_G_WARNING
-                   "Failed to identity %smap [%lx, %lx] for d%d: %d\n",
-                   map->map ? "" : "un", s, e, map->d->domain_id, rc);
+                   "Failed to %smap [%lx %lx] -> [%lx %lx] for %pd: %d\n",
+                   map->map ? "" : "un", s, e, map_mfn,
+                   map_mfn + size, map->d, rc);
             break;
         }
         ASSERT(rc < size);
@@ -163,10 +176,6 @@ static void modify_decoding(const struct pci_dev *pdev, uint16_t cmd,
 bool vpci_process_pending(struct vcpu *v)
 {
     struct pci_dev *pdev = v->vpci.pdev;
-    struct map_data data = {
-        .d = v->domain,
-        .map = v->vpci.cmd & PCI_COMMAND_MEMORY,
-    };
     struct vpci_header *header = NULL;
     unsigned int i;
 
@@ -186,6 +195,11 @@ bool vpci_process_pending(struct vcpu *v)
     for ( i = 0; i < ARRAY_SIZE(header->bars); i++ )
     {
         struct vpci_bar *bar = &header->bars[i];
+        struct map_data data = {
+            .d = v->domain,
+            .map = v->vpci.cmd & PCI_COMMAND_MEMORY,
+            .bar = bar,
+        };
         int rc;
 
         if ( rangeset_is_empty(bar->mem) )
@@ -236,7 +250,6 @@ bool vpci_process_pending(struct vcpu *v)
 static int __init apply_map(struct domain *d, const struct pci_dev *pdev,
                             uint16_t cmd)
 {
-    struct map_data data = { .d = d, .map = true };
     struct vpci_header *header = &pdev->vpci->header;
     int rc = 0;
     unsigned int i;
@@ -246,6 +259,7 @@ static int __init apply_map(struct domain *d, const struct pci_dev *pdev,
     for ( i = 0; i < ARRAY_SIZE(header->bars); i++ )
     {
         struct vpci_bar *bar = &header->bars[i];
+        struct map_data data = { .d = d, .map = true, .bar = bar };
 
         if ( rangeset_is_empty(bar->mem) )
             continue;
@@ -311,12 +325,16 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
      * First fill the rangesets with the BAR of this device or with the ROM
      * BAR only, depending on whether the guest is toggling the memory decode
      * bit of the command register, or the enable bit of the ROM BAR register.
+     *
+     * For non-hardware domain we use guest physical addresses.
      */
     for ( i = 0; i < ARRAY_SIZE(header->bars); i++ )
     {
         struct vpci_bar *bar = &header->bars[i];
         unsigned long start = PFN_DOWN(bar->addr);
         unsigned long end = PFN_DOWN(bar->addr + bar->size - 1);
+        unsigned long start_guest = PFN_DOWN(bar->guest_addr);
+        unsigned long end_guest = PFN_DOWN(bar->guest_addr + bar->size - 1);
 
         if ( !bar->mem )
             continue;
@@ -336,11 +354,26 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
             continue;
         }
 
-        rc = rangeset_add_range(bar->mem, start, end);
+        ASSERT(rangeset_is_empty(bar->mem));
+
+        /*
+         * Make sure that the guest set address has the same page offset
+         * as the physical address on the host or otherwise things won't work as
+         * expected.
+         */
+        if ( PAGE_OFFSET(bar->guest_addr) != PAGE_OFFSET(bar->addr) )
+        {
+            gprintk(XENLOG_G_WARNING,
+                    "%pp: can't map BAR%u - offset mismatch: %#lx vs %#lx\n",
+                    &pdev->sbdf, i, bar->guest_addr, bar->addr);
+            return -EINVAL;
+        }
+
+        rc = rangeset_add_range(bar->mem, start_guest, end_guest);
         if ( rc )
         {
             printk(XENLOG_G_WARNING "Failed to add [%lx, %lx]: %d\n",
-                   start, end, rc);
+                   start_guest, end_guest, rc);
             return rc;
         }
 
@@ -352,12 +385,12 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
             if ( rangeset_is_empty(prev_bar->mem) )
                 continue;
 
-            rc = rangeset_remove_range(prev_bar->mem, start, end);
+            rc = rangeset_remove_range(prev_bar->mem, start_guest, end_guest);
             if ( rc )
             {
                 gprintk(XENLOG_WARNING,
                        "%pp: failed to remove overlapping range [%lx, %lx]: %d\n",
-                        &pdev->sbdf, start, end, rc);
+                        &pdev->sbdf, start_guest, end_guest, rc);
                 return rc;
             }
         }
@@ -425,8 +458,8 @@ static int modify_bars(const struct pci_dev *pdev, uint16_t cmd, bool rom_only)
             for ( i = 0; i < ARRAY_SIZE(tmp->vpci->header.bars); i++ )
             {
                 const struct vpci_bar *remote_bar = &tmp->vpci->header.bars[i];
-                unsigned long start = PFN_DOWN(remote_bar->addr);
-                unsigned long end = PFN_DOWN(remote_bar->addr +
+                unsigned long start = PFN_DOWN(remote_bar->guest_addr);
+                unsigned long end = PFN_DOWN(remote_bar->guest_addr +
                                              remote_bar->size - 1);
 
                 if ( !remote_bar->enabled )
@@ -513,6 +546,8 @@ static void cf_check bar_write(
     struct vpci_bar *bar = data;
     bool hi = false;
 
+    ASSERT(is_hardware_domain(pdev->domain));
+
     if ( bar->type == VPCI_BAR_MEM64_HI )
     {
         ASSERT(reg > PCI_BASE_ADDRESS_0);
@@ -543,6 +578,8 @@ static void cf_check bar_write(
      */
     bar->addr &= ~(0xffffffffULL << (hi ? 32 : 0));
     bar->addr |= (uint64_t)val << (hi ? 32 : 0);
+    /* Update guest address, so hardware domain BAR is identity mapped. */
+    bar->guest_addr = bar->addr;
 
     /* Make sure Xen writes back the same value for the BAR RO bits. */
     if ( !hi )
@@ -639,11 +676,14 @@ static void cf_check rom_write(
     }
 
     if ( !rom->enabled )
+    {
         /*
          * If the ROM BAR is not mapped update the address field so the
          * correct address is mapped into the p2m.
          */
         rom->addr = val & PCI_ROM_ADDRESS_MASK;
+        rom->guest_addr = rom->addr;
+    }
 
     if ( !header->bars_mapped || rom->enabled == new_enabled )
     {
@@ -667,7 +707,10 @@ static void cf_check rom_write(
         return;
 
     if ( !new_enabled )
+    {
         rom->addr = val & PCI_ROM_ADDRESS_MASK;
+        rom->guest_addr = rom->addr;
+    }
 }
 
 static int bar_add_rangeset(const struct pci_dev *pdev, struct vpci_bar *bar,
@@ -862,6 +905,7 @@ static int cf_check init_header(struct pci_dev *pdev)
         }
 
         bars[i].addr = addr;
+        bars[i].guest_addr = addr;
         bars[i].size = size;
         bars[i].prefetchable = val & PCI_BASE_ADDRESS_MEM_PREFETCH;
 
@@ -884,6 +928,7 @@ static int cf_check init_header(struct pci_dev *pdev)
         rom->type = VPCI_BAR_ROM;
         rom->size = size;
         rom->addr = addr;
+        rom->guest_addr = addr;
         header->rom_enabled = pci_conf_read32(pdev->sbdf, rom_reg) &
                               PCI_ROM_ADDRESS_ENABLE;
 
xen/include/xen/vpci.h +2 -1
index 817ee9ee7300..e89c571890b2 100644
@@ -216,7 +216,8 @@ int vpci_msix_arch_print(const struct vpci_msix *msix);
  */
 static inline paddr_t vmsix_table_base(const struct vpci *vpci, unsigned int nr)
 {
-    return vpci->header.bars[vpci->msix->tables[nr] & PCI_MSIX_BIRMASK].addr;
+    return vpci->header.bars[vpci->msix->tables[nr] &
+                             PCI_MSIX_BIRMASK].guest_addr;
 }
 
 static inline paddr_t vmsix_table_addr(const struct vpci *vpci, unsigned int nr)
Signature · 1 line
2.43.0
#33 lore raw

PATCH v13 10/14 vpci/header: emulate PCI_COMMAND register for guests

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Xen and/or Dom0 may have put values in PCI_COMMAND which they expect to remain unaltered. PCI_COMMAND_SERR bit is a good example: while the guest's (domU) view of this will want to be zero (for now), the host having set it to 1 should be preserved, or else we'd effectively be giving the domU control of the bit. Thus, PCI_COMMAND register needs proper emulation in order to honor host's settings.

According to "PCI LOCAL BUS SPECIFICATION, REV. 3.0", section "6.2.2 Device Control" the reset state of the command register is typically 0, so when assigning a PCI device use 0 as the initial state for the guest's (domU) view of the command register.

Here is the full list of command register bits with notes about PCI/PCIe specification, and how Xen handles the bit. QEMU's behavior is also documented here since that is our current reference implementation for PCI passthrough.

PCI_COMMAND_IO (bit 0)
PCIe 6.1: RW
PCI LB 3.0: RW
QEMU: (emu_mask) QEMU provides an emulated view of this bit. Guest
writes do not propagate to hardware. QEMU sets this bit to 1 in hardware if an I/O BAR is exposed to the guest.
Xen domU: (rsvdp_mask) We treat this bit as RsvdP for now since we
don't yet support I/O BARs for domUs.
Xen dom0: We allow dom0 to control this bit freely.

PCI_COMMAND_MEMORY (bit 1)
PCIe 6.1: RW
PCI LB 3.0: RW
QEMU: (emu_mask) QEMU provides an emulated view of this bit. Guest
writes do not propagate to hardware. QEMU sets this bit to 1 in hardware if a Memory BAR is exposed to the guest.
Xen domU/dom0: We handle writes to this bit by mapping/unmapping BAR
regions.
Xen domU: For devices assigned to DomUs, memory decoding will be
disabled at the time of initialization.

PCI_COMMAND_MASTER (bit 2)
PCIe 6.1: RW
PCI LB 3.0: RW
QEMU: Pass through writes to hardware.
Xen domU/dom0: Pass through writes to hardware.

PCI_COMMAND_SPECIAL (bit 3)
PCIe 6.1: RO, hardwire to 0
PCI LB 3.0: RW
QEMU: Pass through writes to hardware.
Xen domU/dom0: Pass through writes to hardware.

PCI_COMMAND_INVALIDATE (bit 4)
PCIe 6.1: RO, hardwire to 0
PCI LB 3.0: RW
QEMU: Pass through writes to hardware.
Xen domU/dom0: Pass through writes to hardware.

PCI_COMMAND_VGA_PALETTE (bit 5)
PCIe 6.1: RO, hardwire to 0
PCI LB 3.0: RW
QEMU: Pass through writes to hardware.
Xen domU/dom0: Pass through writes to hardware.

PCI_COMMAND_PARITY (bit 6)
PCIe 6.1: RW
PCI LB 3.0: RW
QEMU: (emu_mask) QEMU provides an emulated view of this bit. Guest
writes do not propagate to hardware.
Xen domU: (rsvdp_mask) We treat this bit as RsvdP.
Xen dom0: We allow dom0 to control this bit freely.

PCI_COMMAND_WAIT (bit 7)
PCIe 6.1: RO, hardwire to 0
PCI LB 3.0: hardwire to 0
QEMU: res_mask
Xen domU: (rsvdp_mask) We treat this bit as RsvdP. Xen dom0: We allow dom0 to control this bit freely.

PCI_COMMAND_SERR (bit 8)
PCIe 6.1: RW
PCI LB 3.0: RW
QEMU: (emu_mask) QEMU provides an emulated view of this bit. Guest
writes do not propagate to hardware.
Xen domU: (rsvdp_mask) We treat this bit as RsvdP.
Xen dom0: We allow dom0 to control this bit freely.

PCI_COMMAND_FAST_BACK (bit 9)
PCIe 6.1: RO, hardwire to 0
PCI LB 3.0: RW
QEMU: (emu_mask) QEMU provides an emulated view of this bit. Guest
writes do not propagate to hardware.
Xen domU: (rsvdp_mask) We treat this bit as RsvdP.
Xen dom0: We allow dom0 to control this bit freely.

PCI_COMMAND_INTX_DISABLE (bit 10)
PCIe 6.1: RW
PCI LB 3.0: RW
QEMU: (emu_mask) QEMU provides an emulated view of this bit. Guest
writes do not propagate to hardware. QEMU checks if INTx was mapped for a device. If it is not, then guest can't control PCI_COMMAND_INTX_DISABLE bit.
Xen domU: We prohibit a guest from enabling INTx if MSI(X) is enabled. Xen dom0: We allow dom0 to control this bit freely.

Bits 11-15
PCIe 6.1: RsvdP
PCI LB 3.0: Reserved
QEMU: res_mask
Xen domU/dom0: rsvdp_mask

---
RFC: There is an unaddressed question for Roger: should we update the
guest view of the PCI_COMMAND_INTX_DISABLE bit in msi.c/msix.c:control_write()? See prior discussion at [1].

[1] https://lore.kernel.org/xen-devel/[email protected]/

In v13:
- Update right away (don't defer) PCI_COMMAND_MEMORY bit in guest_cmd variable in cmd_write()
- Make comment single line in xen/drivers/vpci/msi.c:control_write()
- Rearrange memory decoding disabling snippet in init_header()

In v12:
- Rework patch using vpci_add_register_mask()
- Add bitmask #define in pci_regs.h according to PCIe 6.1 spec, except don't add the RO bits because they were RW in PCI LB 3.0 spec.
- Move and expand TODO comment about properly emulating bits
- Update guest_cmd in msi.c/msix.c:control_write()
- Simplify cmd_write(), thanks to rsvdp_mask
- Update commit description

In v11:
- Fix copy-paste mistake: vpci->msi should be vpci->msix
- Handle PCI_COMMAND_IO
- Fix condition for disabling INTx in the MSI-X code
- Show domU changes to only allowed bits
- Show PCI_COMMAND_MEMORY write only after P2M was altered
- Update comments in the code
In v10:
- Added cf_check attribute to guest_cmd_read
- Removed warning about non-zero cmd
- Updated comment MSI code regarding disabling INTX
- Used ternary operator in vpci_add_register() call
- Disable memory decoding for DomUs in init_bars()
In v9:
- Reworked guest_cmd_read
- Added handling for more bits
Since v6:
- fold guest's logic into cmd_write
- implement cmd_read, so we can report emulated INTx state to guests
- introduce header->guest_cmd to hold the emulated state of the PCI_COMMAND register for guests
Since v5:
- add additional check for MSI-X enabled while altering INTX bit
- make sure INTx disabled while guests enable MSI/MSI-X Since v3:
- gate more code on CONFIG_HAS_MSI
- removed logic for the case when MSI/MSI-X not enabled

---
 xen/drivers/vpci/header.c  | 57 ++++++++++++++++++++++++++++++++++----
 xen/drivers/vpci/msi.c     |  7 +++++
 xen/drivers/vpci/msix.c    |  7 +++++
 xen/include/xen/pci_regs.h |  1 +
 xen/include/xen/vpci.h     |  3 ++
 5 files changed, 69 insertions(+), 6 deletions(-)
xen/drivers/vpci/header.c +51 -6
index 47648c395132..5d13ea975cc2 100644
@@ -524,9 +524,21 @@ static void cf_check cmd_write(
 {
     struct vpci_header *header = data;
 
+    if ( !is_hardware_domain(pdev->domain) )
+    {
+        const struct vpci *vpci = pdev->vpci;
+
+        if ( (vpci->msi && vpci->msi->enabled) ||
+             (vpci->msix && vpci->msix->enabled) )
+            cmd |= PCI_COMMAND_INTX_DISABLE;
+
+        header->guest_cmd = cmd;
+    }
+
     /*
      * Let Dom0 play with all the bits directly except for the memory
-     * decoding one.
+     * decoding one. Bits that are not allowed for DomU are already
+     * handled above and by the rsvdp_mask.
      */
     if ( header->bars_mapped != !!(cmd & PCI_COMMAND_MEMORY) )
         /*
@@ -540,6 +552,14 @@ static void cf_check cmd_write(
         pci_conf_write16(pdev->sbdf, reg, cmd);
 }
 
+static uint32_t cf_check guest_cmd_read(
+    const struct pci_dev *pdev, unsigned int reg, void *data)
+{
+    const struct vpci_header *header = data;
+
+    return header->guest_cmd;
+}
+
 static void cf_check bar_write(
     const struct pci_dev *pdev, unsigned int reg, uint32_t val, void *data)
 {
@@ -754,9 +774,23 @@ static int cf_check init_header(struct pci_dev *pdev)
         return -EOPNOTSUPP;
     }
 
-    /* Setup a handler for the command register. */
-    rc = vpci_add_register(pdev->vpci, vpci_hw_read16, cmd_write, PCI_COMMAND,
-                           2, header);
+    /*
+     * Setup a handler for the command register.
+     *
+     * TODO: If support for emulated bits is added, re-visit how to handle
+     * PCI_COMMAND_PARITY, PCI_COMMAND_SERR, and PCI_COMMAND_FAST_BACK.
+     */
+    rc = vpci_add_register_mask(pdev->vpci,
+                                is_hwdom ? vpci_hw_read16 : guest_cmd_read,
+                                cmd_write, PCI_COMMAND, 2, header, 0, 0,
+                                PCI_COMMAND_RSVDP_MASK |
+                                    (is_hwdom ? 0
+                                              : PCI_COMMAND_IO |
+                                                PCI_COMMAND_PARITY |
+                                                PCI_COMMAND_WAIT |
+                                                PCI_COMMAND_SERR |
+                                                PCI_COMMAND_FAST_BACK),
+                                0);
     if ( rc )
         return rc;
 
@@ -836,9 +870,20 @@ static int cf_check init_header(struct pci_dev *pdev)
     if ( pdev->ignore_bars )
         return 0;
 
-    /* Disable memory decoding before sizing. */
     cmd = pci_conf_read16(pdev->sbdf, PCI_COMMAND);
-    if ( cmd & PCI_COMMAND_MEMORY )
+
+    /*
+     * Clear PCI_COMMAND_MEMORY and PCI_COMMAND_IO for DomUs, so they will
+     * always start with memory decoding disabled and to ensure that we will not
+     * call modify_bars() at the end of this function.
+     */
+    if ( !is_hwdom )
+        cmd &= ~(PCI_COMMAND_MEMORY | PCI_COMMAND_IO);
+
+    header->guest_cmd = cmd;
+
+    /* Disable memory decoding before sizing. */
+    if ( !is_hwdom || (cmd & PCI_COMMAND_MEMORY) )
         pci_conf_write16(pdev->sbdf, PCI_COMMAND, cmd & ~PCI_COMMAND_MEMORY);
 
     for ( i = 0; i < num_bars; i++ )
xen/drivers/vpci/msi.c +7 -0
index dc71938e23f5..1e747ad9bba8 100644
@@ -70,6 +70,13 @@ static void cf_check control_write(
 
         if ( vpci_msi_arch_enable(msi, pdev, vectors) )
             return;
+
+        /* Make sure domU doesn't enable INTx while enabling MSI. */
+        if ( !is_hardware_domain(pdev->domain) )
+        {
+            pci_intx(pdev, false);
+            pdev->vpci->header.guest_cmd |= PCI_COMMAND_INTX_DISABLE;
+        }
     }
     else
         vpci_msi_arch_disable(msi, pdev);
xen/drivers/vpci/msix.c +7 -0
index b6abab47efdd..d4f756ce287a 100644
@@ -135,6 +135,13 @@ static void cf_check control_write(
         }
     }
 
+    /* Make sure domU doesn't enable INTx while enabling MSI-X. */
+    if ( new_enabled && !msix->enabled && !is_hardware_domain(pdev->domain) )
+    {
+        pci_intx(pdev, false);
+        pdev->vpci->header.guest_cmd |= PCI_COMMAND_INTX_DISABLE;
+    }
+
     msix->masked = new_masked;
     msix->enabled = new_enabled;
 
xen/include/xen/pci_regs.h +1 -0
index 9909b27425a5..b2f2e43e864d 100644
@@ -48,6 +48,7 @@
 #define  PCI_COMMAND_SERR	0x100	/* Enable SERR */
 #define  PCI_COMMAND_FAST_BACK	0x200	/* Enable back-to-back writes */
 #define  PCI_COMMAND_INTX_DISABLE 0x400 /* INTx Emulation Disable */
+#define  PCI_COMMAND_RSVDP_MASK	0xf800
 
 #define PCI_STATUS		0x06	/* 16 bits */
 #define  PCI_STATUS_IMM_READY	0x01	/* Immediate Readiness */
xen/include/xen/vpci.h +3 -0
index e89c571890b2..77320a667e55 100644
@@ -107,6 +107,9 @@ struct vpci {
         } bars[PCI_HEADER_NORMAL_NR_BARS + 1];
         /* At most 6 BARS + 1 expansion ROM BAR. */
 
+        /* Guest (domU only) view of the PCI_COMMAND register. */
+        uint16_t guest_cmd;
+
         /*
          * Store whether the ROM enable bit is set (doesn't imply ROM BAR
          * is mapped into guest p2m) if there's a ROM BAR on the device.
Signature · 1 line
2.43.0
#34 lore raw

Re: [PATCH v13 10/14] vpci/header: emulate PCI_COMMAND register for guests

xen/drivers/vpci/header.c static int cf_check init_header(struct pci_dev *pdev) · line 878

Quoted 12 lines · Stewart Hildebrand
xen/drivers/vpci/header.c +5 -2
@@ -836,9 +870,20 @@ static int cf_check init_header(struct pci_dev *pdev)
     if ( pdev->ignore_bars )
         return 0;
 
-    /* Disable memory decoding before sizing. */
     cmd = pci_conf_read16(pdev->sbdf, PCI_COMMAND);
-    if ( cmd & PCI_COMMAND_MEMORY )
+
+    /*
+     * Clear PCI_COMMAND_MEMORY and PCI_COMMAND_IO for DomUs, so they will
+     * always start with memory decoding disabled and to ensure that we will not
+     * call modify_bars() at the end of this function.

To achieve this, fiddling with PCI_COMMAND_IO isn't necessary. Which isn't to say its clearing should go away; quite the other way around: Why would we leave e.g. PCI_COMMAND_MASTER enabled? In fact wasn't it in an earlier version of the series that the guest view simply started out as zero? The patch description still says so.

xen/drivers/vpci/msi.c static void cf_check control_write( · line 79

Quoted 13 lines
xen/drivers/vpci/msi.c +7 -0
@@ -70,6 +70,13 @@ static void cf_check control_write(
 
         if ( vpci_msi_arch_enable(msi, pdev, vectors) )
             return;
+
+        /* Make sure domU doesn't enable INTx while enabling MSI. */
+        if ( !is_hardware_domain(pdev->domain) )
+        {
+            pci_intx(pdev, false);
+            pdev->vpci->header.guest_cmd |= PCI_COMMAND_INTX_DISABLE;
+        }

While here we're inside "if ( new_enabled )", ...

xen/drivers/vpci/msix.c static void cf_check control_write( · line 143

Quoted 12 lines
xen/drivers/vpci/msix.c +6 -0
@@ -135,6 +135,13 @@ static void cf_check control_write(
         }
     }
 
+    /* Make sure domU doesn't enable INTx while enabling MSI-X. */
+    if ( new_enabled && !msix->enabled && !is_hardware_domain(pdev->domain) )
+    {
+        pci_intx(pdev, false);
+        pdev->vpci->header.guest_cmd |= PCI_COMMAND_INTX_DISABLE;
+    }

.. here you further check that it's actually a 0->1 transition? Why not alike for MSI?

Jan

#35 lore raw

Re: [PATCH v13 10/14] vpci/header: emulate PCI_COMMAND register for guests

Quoted 5 lines · Jan Beulich
Quoted 4 lines · Stewart Hildebrand
xen/drivers/vpci/header.c +0 -0
@@ -836,9 +870,20 @@ static int cf_check init_header(struct pci_dev *pdev)
     if ( pdev->ignore_bars )
         return 0;
 
Quoted 14 lines

xen/drivers/vpci/header.c static int cf_check init_header(struct pci_dev *pdev) · line 878

Quoted 8 lines
xen/drivers/vpci/header.c +5 -2
-    /* Disable memory decoding before sizing. */
     cmd = pci_conf_read16(pdev->sbdf, PCI_COMMAND);
-    if ( cmd & PCI_COMMAND_MEMORY )
+
+    /*
+     * Clear PCI_COMMAND_MEMORY and PCI_COMMAND_IO for DomUs, so they will
+     * always start with memory decoding disabled and to ensure that we will not
+     * call modify_bars() at the end of this function.

To achieve this, fiddling with PCI_COMMAND_IO isn't necessary. Which isn't to say its clearing should go away; quite the other way around: Why would we leave e.g. PCI_COMMAND_MASTER enabled? In fact wasn't it in an earlier version of the series that the guest view simply started out as zero? The patch description still says so.

Yep, clearing PCI_COMMAND_MASTER too for domUs makes sense to me, I'll make this change in v14. I'll also try to improve the comment.

Roger suggested at [1] that we should reflect the state of the hardware in the command register. I'll update the patch description accordingly.

Archaeology/notes/references follow, primarily for my own reference:

Note that the rsvdp_mask will be applied to the guest_cmd value before being returned to the guest, so no need to apply masks here.

Clearing both PCI_COMMAND_MEMORY and PCI_COMMAND_IO for domUs was suggested by Roger at [2] and [3]. It is currently problematic for devices assigned to domUs to have memory decoding enabled at this stage because we don't yet have a good/generic way to initialize bar.guest_addr taking the domU memory layout into account.

Reminder that we want to leave the PCI_COMMAND_{MASTER,MEMORY,IO} bits unchanged for devices assigned to dom0. A description of why can be found in the commit message of:

53d9133638c3 ("pci: do not disable memory decoding for devices").

[1] https://lore.kernel.org/xen-devel/[email protected]/
[2] https://lore.kernel.org/xen-devel/ZRquRcRz-K43WeMc@MacBookPdeRoger/
[3] https://lore.kernel.org/xen-devel/[email protected]/

Quoted 22 lines

xen/drivers/vpci/msi.c static void cf_check control_write( · line 79

Quoted 13 lines
xen/drivers/vpci/msi.c +7 -0
@@ -70,6 +70,13 @@ static void cf_check control_write(
 
         if ( vpci_msi_arch_enable(msi, pdev, vectors) )
             return;
+
+        /* Make sure domU doesn't enable INTx while enabling MSI. */
+        if ( !is_hardware_domain(pdev->domain) )
+        {
+            pci_intx(pdev, false);
+            pdev->vpci->header.guest_cmd |= PCI_COMMAND_INTX_DISABLE;
+        }

While here we're inside "if ( new_enabled )", ...

Quoted 6 lines
xen/drivers/vpci/msix.c +0 -0
@@ -135,6 +135,13 @@ static void cf_check control_write(
         }
     }
 
Quoted 9 lines

xen/drivers/vpci/msix.c static void cf_check control_write( · line 143

Quoted 6 lines
xen/drivers/vpci/msix.c +6 -0
+    /* Make sure domU doesn't enable INTx while enabling MSI-X. */
+    if ( new_enabled && !msix->enabled && !is_hardware_domain(pdev->domain) )
+    {
+        pci_intx(pdev, false);
+        pdev->vpci->header.guest_cmd |= PCI_COMMAND_INTX_DISABLE;
+    }

.. here you further check that it's actually a 0->1 transition? Why not alike for MSI?

Good catch, we should similarly check for a 0->1 transition for MSI. I'll fix it.

#36 lore raw

Re: [PATCH v13 10/14] vpci/header: emulate PCI_COMMAND register for guests

Quoted 21 lines · Stewart Hildebrand
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Stewart Hildebrand
xen/drivers/vpci/header.c +0 -0
@@ -836,9 +870,20 @@ static int cf_check init_header(struct pci_dev *pdev)
     if ( pdev->ignore_bars )
         return 0;
 
Quoted 14 lines

xen/drivers/vpci/header.c static int cf_check init_header(struct pci_dev *pdev) · line 878

Quoted 8 lines
xen/drivers/vpci/header.c +5 -2
-    /* Disable memory decoding before sizing. */
     cmd = pci_conf_read16(pdev->sbdf, PCI_COMMAND);
-    if ( cmd & PCI_COMMAND_MEMORY )
+
+    /*
+     * Clear PCI_COMMAND_MEMORY and PCI_COMMAND_IO for DomUs, so they will
+     * always start with memory decoding disabled and to ensure that we will not
+     * call modify_bars() at the end of this function.

To achieve this, fiddling with PCI_COMMAND_IO isn't necessary. Which isn't to say its clearing should go away; quite the other way around: Why would we leave e.g. PCI_COMMAND_MASTER enabled? In fact wasn't it in an earlier version of the series that the guest view simply started out as zero? The patch description still says so.

Quoted 5 lines

Yep, clearing PCI_COMMAND_MASTER too for domUs makes sense to me, I'll make this change in v14. I'll also try to improve the comment.

Roger suggested at [1] that we should reflect the state of the hardware in the command register. I'll update the patch description accordingly.

Roger's request can be carried out in several ways. But first of all state reflected should be that of whatever is consistent in the virtualized view. Any bits the guest may control ought to start out as zero, imo (which may mean bringing hardware in sync with the guest view, not necessarily the other way around). For bits the guest cannot control what the guest ought to see depends.

Jan

#37 lore raw

PATCH v13 11/14 vpci: add initial support for virtual PCI bus topology

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

Assign SBDF to the PCI devices being passed through with bus 0. The resulting topology is where PCIe devices reside on the bus 0 of the root complex itself (embedded endpoints).
This implementation is limited to 32 devices which are allowed on a single PCI bus.

Please note, that at the moment only function 0 of a multifunction device can be passed through.

---
In v13:
- s/depends on/select/ in Kconfig
- check pdev->sbdf.fn instead of two booleans in add_virtual_device()
- comment #endifs in sched.h
- clarify comment about limits in vpci.h with seg/bus limit
In v11:
- Fixed code formatting
- Removed bogus write_unlock() call
- Fixed type for new_dev_number
In v10:
- Removed ASSERT(pcidevs_locked())
- Removed redundant code (local sbdf variable, clearing sbdf during device removal, etc)
- Added __maybe_unused attribute to "out:" label
- Introduced HAS_VPCI_GUEST_SUPPORT Kconfig option, as this is the first patch where it is used (previously was in "vpci: add hooks for PCI device assign/de-assign")
In v9:
- Lock in add_virtual_device() replaced with ASSERT (thanks, Stewart) In v8:
- Added write lock in add_virtual_device
Since v6:
- re-work wrt new locking scheme
- OT: add ASSERT(pcidevs_write_locked()); to add_virtual_device() Since v5:
- s/vpci_add_virtual_device/add_virtual_device and make it static
- call add_virtual_device from vpci_assign_device and do not use REGISTER_VPCI_INIT machinery
- add pcidevs_locked ASSERT
- use DECLARE_BITMAP for vpci_dev_assigned_map
Since v4:
- moved and re-worked guest sbdf initializers
- s/set_bit/__set_bit
- s/clear_bit/__clear_bit
- minor comment fix s/Virtual/Guest/
- added VPCI_MAX_VIRT_DEV constant (PCI_SLOT(~0) + 1) which will be used later for counting the number of MMIO handlers required for a guest (Julien)
Since v3:
- make use of VPCI_INIT
- moved all new code to vpci.c which belongs to it
- changed open-coded 31 to PCI_SLOT(~0)
- added comments and code to reject multifunction devices with functions other than 0
- updated comment about vpci_dev_next and made it unsigned int
- implement roll back in case of error while assigning/deassigning devices
- s/dom%pd/%pd
Since v2:
- remove casts that are (a) malformed and (b) unnecessary
- add new line for better readability
- remove CONFIG_HAS_VPCI_GUEST_SUPPORT ifdef's as the relevant vPCI functions are now completely gated with this config
- gate common code with CONFIG_HAS_VPCI_GUEST_SUPPORT
New in v2

---
 xen/drivers/Kconfig     |  4 +++
 xen/drivers/vpci/vpci.c | 57 +++++++++++++++++++++++++++++++++++++++++
 xen/include/xen/sched.h | 10 +++++++-
 xen/include/xen/vpci.h  | 12 +++++++++
 4 files changed, 82 insertions(+), 1 deletion(-)
xen/drivers/Kconfig +4 -0
index db94393f47a6..20050e9bb8b3 100644
@@ -15,4 +15,8 @@ source "drivers/video/Kconfig"
 config HAS_VPCI
 	bool
 
+config HAS_VPCI_GUEST_SUPPORT
+	bool
+	select HAS_VPCI
+
 endmenu
xen/drivers/vpci/vpci.c +57 -0

81 lines not on this page · raw message

xen/include/xen/sched.h +9 -1
index c3adec1aca3c..daa3c1743047 100644
@@ -484,7 +484,15 @@ struct domain
      * 2. pdev->vpci->lock
      */
     rwlock_t pci_lock;
-#endif
+#ifdef CONFIG_HAS_VPCI_GUEST_SUPPORT
+    /*
+     * The bitmap which shows which device numbers are already used by the
+     * virtual PCI bus topology and is used to assign a unique SBDF to the
+     * next passed through virtual PCI device.
+     */
+    DECLARE_BITMAP(vpci_dev_assigned_map, VPCI_MAX_VIRT_DEV);
+#endif /* CONFIG_HAS_VPCI_GUEST_SUPPORT */
+#endif /* CONFIG_HAS_PCI */
 
 #ifdef CONFIG_HAS_PASSTHROUGH
     struct domain_iommu iommu;
xen/include/xen/vpci.h +12 -0
index 77320a667e55..a69c640d065a 100644
@@ -21,6 +21,14 @@ typedef int vpci_register_init_t(struct pci_dev *dev);
 
 #define VPCI_ECAM_BDF(addr)     (((addr) & 0x0ffff000) >> 12)
 
+/*
+ * Maximum number of devices supported by the virtual bus topology:
+ * each PCI bus supports 32 devices/slots at max or up to 256 when
+ * there are multi-function ones which are not yet supported.
+ * This limit implies only segment 0, bus 0 is supported.
+ */
+#define VPCI_MAX_VIRT_DEV       (PCI_SLOT(~0) + 1)
+
 #define REGISTER_VPCI_INIT(x, p)                \
   static vpci_register_init_t *const x##_entry  \
                __used_section(".data.vpci." p) = x
@@ -175,6 +183,10 @@ struct vpci {
             struct vpci_arch_msix_entry arch;
         } entries[];
     } *msix;
+#ifdef CONFIG_HAS_VPCI_GUEST_SUPPORT
+    /* Guest SBDF of the device. */
+    pci_sbdf_t guest_sbdf;
+#endif
 #endif
 };
 
Signature · 1 line
2.43.0
#38 lore raw

PATCH v13 12/14 xen/arm: translate virtual PCI bus topology for guests

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

There are three originators for the PCI configuration space access:
1. The domain that owns physical host bridge: MMIO handlers are there so we can update vPCI register handlers with the values written by the hardware domain, e.g. physical view of the registers vs guest's view on the configuration space.
2. Guest access to the passed through PCI devices: we need to properly map virtual bus topology to the physical one, e.g. pass the configuration space access to the corresponding physical devices.
3. Emulated host PCI bridge access. It doesn't exist in the physical topology, e.g. it can't be mapped to some physical host bridge. So, all access to the host bridge itself needs to be trapped and emulated.

---
In v11:
- Fixed format issues
- Added ASSERT_UNREACHABLE() to the dummy implementation of vpci_translate_virtual_device()
- Moved variable in vpci_sbdf_from_gpa(), now it is easier to follow the logic in the function
Since v9:
- Commend about required lock replaced with ASSERT()
- Style fixes
- call to vpci_translate_virtual_device folded into vpci_sbdf_from_gpa Since v8:
- locks moved out of vpci_translate_virtual_device()
Since v6:
- add pcidevs locking to vpci_translate_virtual_device
- update wrt to the new locking scheme
Since v5:
- add vpci_translate_virtual_device for #ifndef CONFIG_HAS_VPCI_GUEST_SUPPORT case to simplify ifdefery
- add ASSERT(!is_hardware_domain(d)); to vpci_translate_virtual_device
- reset output register on failed virtual SBDF translation
Since v4:
- indentation fixes
- constify struct domain
- updated commit message
- updates to the new locking scheme (pdev->vpci_lock)
Since v3:
- revisit locking
- move code to vpci.c
Since v2:
- pass struct domain instead of struct vcpu
- constify arguments where possible
- gate relevant code with CONFIG_HAS_VPCI_GUEST_SUPPORT
New in v2

---
 xen/arch/arm/vpci.c     | 47 +++++++++++++++++++++++++++++++----------
 xen/drivers/vpci/vpci.c | 24 +++++++++++++++++++++
 xen/include/xen/vpci.h  | 12 +++++++++++
 3 files changed, 72 insertions(+), 11 deletions(-)
xen/arch/arm/vpci.c +36 -11
index 3bc4bb55082a..7a6a0017d132 100644
@@ -7,31 +7,51 @@
 
 #include <asm/mmio.h>
 
-static pci_sbdf_t vpci_sbdf_from_gpa(const struct pci_host_bridge *bridge,
-                                     paddr_t gpa)
+static bool vpci_sbdf_from_gpa(struct domain *d,
+                               const struct pci_host_bridge *bridge,
+                               paddr_t gpa, pci_sbdf_t *sbdf)
 {
-    pci_sbdf_t sbdf;
+    bool translated = true;
+
+    ASSERT(sbdf);
 
     if ( bridge )
     {
-        sbdf.sbdf = VPCI_ECAM_BDF(gpa - bridge->cfg->phys_addr);
-        sbdf.seg = bridge->segment;
-        sbdf.bus += bridge->cfg->busn_start;
+        sbdf->sbdf = VPCI_ECAM_BDF(gpa - bridge->cfg->phys_addr);
+        sbdf->seg = bridge->segment;
+        sbdf->bus += bridge->cfg->busn_start;
     }
     else
-        sbdf.sbdf = VPCI_ECAM_BDF(gpa - GUEST_VPCI_ECAM_BASE);
+    {
+        /*
+         * For the passed through devices we need to map their virtual SBDF
+         * to the physical PCI device being passed through.
+         */
+        sbdf->sbdf = VPCI_ECAM_BDF(gpa - GUEST_VPCI_ECAM_BASE);
+        read_lock(&d->pci_lock);
+        translated = vpci_translate_virtual_device(d, sbdf);
+        read_unlock(&d->pci_lock);
+    }
 
-    return sbdf;
+    return translated;
 }
 
 static int vpci_mmio_read(struct vcpu *v, mmio_info_t *info,
                           register_t *r, void *p)
 {
     struct pci_host_bridge *bridge = p;
-    pci_sbdf_t sbdf = vpci_sbdf_from_gpa(bridge, info->gpa);
+    pci_sbdf_t sbdf;
     /* data is needed to prevent a pointer cast on 32bit */
     unsigned long data;
 
+    ASSERT(!bridge == !is_hardware_domain(v->domain));
+
+    if ( !vpci_sbdf_from_gpa(v->domain, bridge, info->gpa, &sbdf) )
+    {
+        *r = ~0UL;
+        return 1;
+    }
+
     if ( vpci_ecam_read(sbdf, ECAM_REG_OFFSET(info->gpa),
                         1U << info->dabt.size, &data) )
     {
@@ -39,7 +59,7 @@ static int vpci_mmio_read(struct vcpu *v, mmio_info_t *info,
         return 1;
     }
 
-    *r = ~0ul;
+    *r = ~0UL;
 
     return 0;
 }
@@ -48,7 +68,12 @@ static int vpci_mmio_write(struct vcpu *v, mmio_info_t *info,
                            register_t r, void *p)
 {
     struct pci_host_bridge *bridge = p;
-    pci_sbdf_t sbdf = vpci_sbdf_from_gpa(bridge, info->gpa);
+    pci_sbdf_t sbdf;
+
+    ASSERT(!bridge == !is_hardware_domain(v->domain));
+
+    if ( !vpci_sbdf_from_gpa(v->domain, bridge, info->gpa, &sbdf) )
+        return 1;
 
     return vpci_ecam_write(sbdf, ECAM_REG_OFFSET(info->gpa),
                            1U << info->dabt.size, r);
xen/drivers/vpci/vpci.c +24 -0
index 3cd142068f4e..6b732bb2358e 100644
@@ -81,6 +81,30 @@ static int add_virtual_device(struct pci_dev *pdev)
     return 0;
 }
 
+/*
+ * Find the physical device which is mapped to the virtual device
+ * and translate virtual SBDF to the physical one.
+ */
+bool vpci_translate_virtual_device(const struct domain *d, pci_sbdf_t *sbdf)
+{
+    const struct pci_dev *pdev;
+
+    ASSERT(!is_hardware_domain(d));
+    ASSERT(rw_is_locked(&d->pci_lock));
+
+    for_each_pdev ( d, pdev )
+    {
+        if ( pdev->vpci && (pdev->vpci->guest_sbdf.sbdf == sbdf->sbdf) )
+        {
+            /* Replace guest SBDF with the physical one. */
+            *sbdf = pdev->sbdf;
+            return true;
+        }
+    }
+
+    return false;
+}
+
 #endif /* CONFIG_HAS_VPCI_GUEST_SUPPORT */
 
 void vpci_deassign_device(struct pci_dev *pdev)
xen/include/xen/vpci.h +12 -0
index a69c640d065a..a23320562ed7 100644
@@ -303,6 +303,18 @@ static inline bool __must_check vpci_process_pending(struct vcpu *v)
 }
 #endif
 
+#ifdef CONFIG_HAS_VPCI_GUEST_SUPPORT
+bool vpci_translate_virtual_device(const struct domain *d, pci_sbdf_t *sbdf);
+#else
+static inline bool vpci_translate_virtual_device(const struct domain *d,
+                                                 pci_sbdf_t *sbdf)
+{
+    ASSERT_UNREACHABLE();
+
+    return false;
+}
+#endif
+
 #endif
 
 /*
Signature · 1 line
2.43.0
#39 lore raw

PATCH v13 13/14 xen/arm: account IO handlers for emulated PCI MSI-X

In reply to Stewart Hildebrand

From: Oleksandr Andrushchenko <[email protected]>

At the moment, we always allocate an extra 16 slots for IO handlers (see MAX_IO_HANDLER). So while adding IO trap handlers for the emulated MSI-X registers we need to explicitly tell that we have additional IO handlers, so those are accounted.

---
This actually moved here from the part 2 of the prep work for PCI passthrough on Arm as it seems to be the proper place for it.

Since v5:
- optimize with IS_ENABLED(CONFIG_HAS_PCI_MSI) since VPCI_MAX_VIRT_DEV is defined unconditionally
New in v5

---
 xen/arch/arm/vpci.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
xen/arch/arm/vpci.c +13 -1
index 7a6a0017d132..348ba0fbc860 100644
@@ -130,6 +130,8 @@ static int vpci_get_num_handlers_cb(struct domain *d,
 
 unsigned int domain_vpci_get_num_mmio_handlers(struct domain *d)
 {
+    unsigned int count;
+
     if ( !has_vpci(d) )
         return 0;
 
@@ -150,7 +152,17 @@ unsigned int domain_vpci_get_num_mmio_handlers(struct domain *d)
      * For guests each host bridge requires one region to cover the
      * configuration space. At the moment, we only expose a single host bridge.
      */
-    return 1;
+    count = 1;
+
+    /*
+     * There's a single MSI-X MMIO handler that deals with both PBA
+     * and MSI-X tables per each PCI device being passed through.
+     * Maximum number of emulated virtual devices is VPCI_MAX_VIRT_DEV.
+     */
+    if ( IS_ENABLED(CONFIG_HAS_PCI_MSI) )
+        count += VPCI_MAX_VIRT_DEV;
+
+    return count;
 }
 
 /*
Signature · 1 line
2.43.0
#40 lore raw

PATCH v13 14/14 arm/vpci: honor access size when returning an error

In reply to Stewart Hildebrand

From: Volodymyr Babchuk <[email protected]>

Guest can try to read config space using different access sizes: 8, 16, 32, 64 bits. We need to take this into account when we are returning an error back to MMIO handler, otherwise it is possible to provide more data than requested: i.e. guest issues LDRB instruction to read one byte, but we are writing 0xFFFFFFFFFFFFFFFF in the target register.

---
v9->10:
* New patch in v10.

---
 xen/arch/arm/vpci.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
xen/arch/arm/vpci.c +4 -2
index 348ba0fbc860..aaf9d9120c3d 100644
@@ -41,6 +41,8 @@ static int vpci_mmio_read(struct vcpu *v, mmio_info_t *info,
 {
     struct pci_host_bridge *bridge = p;
     pci_sbdf_t sbdf;
+    const uint8_t access_size = (1 << info->dabt.size) * 8;
+    const uint64_t access_mask = GENMASK_ULL(access_size - 1, 0);
     /* data is needed to prevent a pointer cast on 32bit */
     unsigned long data;
 
@@ -48,7 +50,7 @@ static int vpci_mmio_read(struct vcpu *v, mmio_info_t *info,
 
     if ( !vpci_sbdf_from_gpa(v->domain, bridge, info->gpa, &sbdf) )
     {
-        *r = ~0UL;
+        *r = access_mask;
         return 1;
     }
 
@@ -59,7 +61,7 @@ static int vpci_mmio_read(struct vcpu *v, mmio_info_t *info,
         return 1;
     }
 
-    *r = ~0UL;
+    *r = access_mask;
 
     return 0;
 }
Signature · 1 line
2.43.0