Re: [PATCH] PCI/PTM: Keep ptm_enable_cnt balanced when pci_enable_ptm() fails
From: Mika Westerberg
Date: Mon Nov 09 2026 - 05:03:58 EST
On Wed, Nov 04, 2026 at 08:14:57PM +0800, Li Yifan wrote:
> Since commit e1092d5e15e6 ("PCI/PTM: Do not enable PTM automatically
> for Root and Switch Upstream Ports"), pci_enable_ptm() takes a
> reference on the device and on each port of the upstream path, and
> pci_disable_ptm() releases them. If pci_enable_ptm() fails, the counts
> can become incorrect in two ways:
>
> 1. pci_disable_ptm() decrements dev->ptm_enable_cnt without a check.
> Many drivers ignore the return value of pci_enable_ptm() and call
> pci_disable_ptm() unconditionally, for example mlx5 and bnxt. If
> pci_enable_ptm() failed, for example because the upstream port does
> not support PTM, the count becomes -1 and stays negative after the
> driver unbinds. Then pcie_ptm_enabled() returns true, and
> pci_resume_ptm() can enable PTM on the device after a resume,
> although the upstream path does not support PTM. Before
> e1092d5e15e6, pci_disable_ptm() did nothing if PTM was not enabled.
>
> 2. If __pci_enable_ptm() fails for the device after the upstream path
> is enabled, pci_enable_ptm() drops the reference on the device, but
> it keeps the references on the upstream ports. For example, this
> occurs if the device has no PTM Capability and its upstream port
> has one. Callers that check pcie_ptm_enabled() before
> pci_disable_ptm() never release these references, so the upstream
> ports keep PTM enabled with no user. Callers that call
> pci_disable_ptm() unconditionally release them only through the
> underflow in 1.
>
> Fix both problems in one change, because a fix for only one of them
> makes the other one worse. Release the upstream references when
> __pci_enable_ptm() fails. Make pci_disable_ptm() do nothing if PTM is
> not enabled for the device, and use atomic_dec_if_positive() so that
> the check and the decrement are one atomic operation.
>
> The fix for 2 is based on a patch from Wentao Liang [1].
>
> Fixes: e1092d5e15e6 ("PCI/PTM: Do not enable PTM automatically for Root and Switch Upstream Ports")
> Cc: stable@xxxxxxxxxxxxxxx
> Suggested-by: Bjorn Helgaas <bhelgaas@xxxxxxxxxx>
> Link: https://lore.kernel.org/r/20261102222817.GA983941@bhelgaas
> Link: https://lore.kernel.org/r/20260616141733.1688264-1-vulab@xxxxxxxxxxx # [1]
> Signed-off-by: Li Yifan <yifan2.li@xxxxxxxxx>
Reviewed-by: Mika Westerberg <mika.westerberg@xxxxxxxxxxxxxxx>