Linux IOMMU Development
 help / color / mirror / Atom feed
* [PATCH] iommu/vt-d: debugfs: Increment the reference count of page table page
@ 2023-06-25  2:28 Jingqi Liu
  2023-07-03  7:00 ` Tian, Kevin
  0 siblings, 1 reply; 4+ messages in thread
From: Jingqi Liu @ 2023-06-25  2:28 UTC (permalink / raw)
  To: iommu, Lu Baolu, Tian, Kevin, David Woodhouse, Joerg Roedel,
	Will Deacon, Robin Murphy
  Cc: linux-kernel, Jingqi Liu

There may be a race with iommu_unmap() interface when traversing a page
table.

When debugfs traverses an IOMMU page table, iommu_unmap() may clear
entries and free the page table pages pointed to by the entries.
So debugfs may read invalid or freed pages.

To avoid this, increment the refcount of a page table page before
traversing the page, and decrement its refcount after traversing it.

Signed-off-by: Jingqi Liu <Jingqi.liu@intel.com>
---
 drivers/iommu/intel/debugfs.c | 36 +++++++++++++++++++++++++++++++++--
 1 file changed, 34 insertions(+), 2 deletions(-)

diff --git a/drivers/iommu/intel/debugfs.c b/drivers/iommu/intel/debugfs.c
index 1f925285104e..d228e1580aec 100644
--- a/drivers/iommu/intel/debugfs.c
+++ b/drivers/iommu/intel/debugfs.c
@@ -333,9 +333,41 @@ static void pgtable_walk_level(struct seq_file *m, struct dma_pte *pde,
 		path[level] = pde->val;
 		if (dma_pte_superpage(pde) || level == 1)
 			dump_page_info(m, start, path);
-		else
-			pgtable_walk_level(m, phys_to_virt(dma_pte_addr(pde)),
+		else {
+			struct page *pg;
+			u64 pte_addr;
+
+			/*
+			 * The entry references a Page-Directory Table
+			 * or a Page Table.
+			 */
+retry:
+			pte_addr = dma_pte_addr(pde);
+			pg = pfn_to_page(pte_addr >> PAGE_SHIFT);
+			if (!get_page_unless_zero(pg))
+				/*
+				 * If this page has a refcount of zero,
+				 * it has been freed, or will be freed.
+				 */
+				continue;
+
+			/* Check if the value of the entry is changed. */
+			if (pde->val != path[level]) {
+				put_page(pg);
+
+				if (!dma_pte_present(pde))
+					/* The entry is invalid. Skip it. */
+					continue;
+
+				/* The entry has been updated. */
+				path[level] = pde->val;
+				goto retry;
+			}
+
+			pgtable_walk_level(m, phys_to_virt(pte_addr),
 					   level - 1, start, path);
+			put_page(pg);
+		}
 		path[level] = 0;
 	}
 }
-- 
2.21.3


^ permalink raw reply related	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2023-08-03 11:21 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2023-06-25  2:28 [PATCH] iommu/vt-d: debugfs: Increment the reference count of page table page Jingqi Liu
2023-07-03  7:00 ` Tian, Kevin
2023-07-03 14:48   ` Liu, Jingqi
2023-08-03 11:21     ` Liu, Jingqi

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox