Skip to contentSkip to conversation

DMA_PMD: PMD_SIZE-backed IO buffer pools

RFC Superseded Luigi Rizzo 19 participants 162 messages Oct 3 – Nov 27 Page 2 of 2

Subsystems (37)
lore
Share & tools
lore
#90 lore raw

Re: [RFC PATCH v3 17/25] net: Allocate small skb heads from PISA

In reply to Luigi Rizzo
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] net: __GFP_PISA leaks to frag pages in sock_alloc_send_pskb() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] net: __GFP_PISA leaks to frag pages in sock_alloc_send_pskb() --

commit fb32b2e4054bdacb45b319dad44d287251d24e33
Author: Luigi Rizzo <[email protected]>

net: Allocate small skb heads from PISA

This commit adds a parallel skbuff_small_head_pisa slab cache backed by read-only PISA folios and updates TX skb allocation paths to allocate small skb heads from it when per-device pisa_tx_skb_heads is enabled.

Quoted 34 lines
net/core/sock.c +8 -4
index 56dea49baaec2..0599c7d1aa6d0 100644
@@ -3062,9 +3062,10 @@ static long sock_wait_for_wmem(struct sock *sk, long timeo)
  *	Generic send/receive buffer handlers
  */
 
-struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
-				     unsigned long data_len, int noblock,
-				     int *errcode, int max_page_order)
+struct sk_buff *__sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
+				       unsigned long data_len, int noblock,
+				       int *errcode, int max_page_order,
+				       gfp_t gfp)
 {
 	struct sk_buff *skb;
 	long timeo;
@@ -3093,7 +3094,8 @@ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
 		timeo = sock_wait_for_wmem(sk, timeo);
 	}
 	skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
-				   errcode, sk->sk_allocation);
+				   errcode,
+				   sk->sk_allocation | gfp);
 	if (skb)
 		skb_set_owner_w(skb, sk);
 	return skb;
@@ -3104,6 +3106,17 @@ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
 	*errcode = err;
 	return NULL;
 }
+EXPORT_SYMBOL(__sock_alloc_send_pskb);
+

net/core/sock.c struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, · line 3120

Quoted 10 lines
net/core/sock.c +9 -0
+struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
+				     unsigned long data_len, int noblock,
+				     int *errcode, int max_page_order)
+{
+	/* Callers with data_len != 0 (unix, packet, tun/tap) have no sk_dst_cache, so gfp is 0. */
+	return __sock_alloc_send_pskb(sk, header_len, data_len, noblock,
+				      errcode, max_page_order,
+				      pisa_tx_head_sk_gfp(sk));
+}
 EXPORT_SYMBOL(sock_alloc_send_pskb);

[Severity: Medium]
Does passing pisa_tx_head_sk_gfp(sk) unconditionally to __sock_alloc_send_pskb() cause alloc_skb_with_frags() to allocate nonlinear payload fragment pages from PISA memory even when pisa_tx_bufs is disabled?

ovpn_tcp_sendmsg() calls sock_alloc_send_pskb() on an established TCP socket (which has sk->sk_dst_cache populated) with non-zero data_len whenever the packet exceeds PAGE_SIZE:

drivers/net/ovpn/tcp.c:ovpn_tcp_sendmsg() {
	...
	skb = sock_alloc_send_pskb(sk, linear, size - linear,
				   msg->msg_flags & MSG_DONTWAIT, &ret, 0);
	...
}

When pisa_tx_skb_heads is enabled on the egress device while pisa_tx_bufs is disabled, pisa_tx_head_sk_gfp(sk) returns __GFP_PISA, and alloc_skb_with_frags() reuses gfp_mask without stripping __GFP_PISA when calling alloc_pages() and alloc_page() for the nonlinear fragments.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
#91 lore raw

RFC PATCH v3 18/25 net: Migrate user pages into PISA for MSG_ZEROCOPY

In reply to Luigi Rizzo

Perform best-effort migration of user pages into PISA memory on MSG_ZEROCOPY sends in zerocopy_fill_skb_from_iter() when the egress device has the per-device attribute pisa_tx_zerocopy enabled. For TCP over a device that also has pisa_tx_bufs enabled, pages that cannot be migrated fall back to the regular copy path into PISA TX page_frags without reporting SO_EE_CODE_ZEROCOPY_COPIED.

---
 include/linux/pisa.h |  3 ++
 include/net/pisa.h   | 32 +++++++++++++--
 mm/pisa-user.c       |  8 ++++
 net/core/datagram.c  | 17 ++++++--
 net/core/pisa-net.c  | 95 ++++++++++++++++++++++++++++++++++++++++++--
 net/core/skbuff.c    |  3 +-
 net/ipv4/tcp.c       | 12 +++++-
 7 files changed, 158 insertions(+), 12 deletions(-)
include/linux/pisa.h +3 -0
index 84692852299f1..11e3ea9eb263d 100644
@@ -95,6 +95,7 @@ bool __pisa_page_can_recycle(const struct page *page);
 bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,
 			     size_t size, size_t offset,
 			     enum dma_data_direction dir, bool pinned);
+bool pisa_page_tx_ok(const struct page *page);
 
 static inline bool pisa_enabled(void)
 {
@@ -264,6 +265,8 @@ static inline bool pisa_upgrade_user_pages(struct iov_iter *iter,
 	return false;
 }
 
+static inline bool pisa_page_tx_ok(const struct page *page) { return false; }
+
 #endif /* CONFIG_PISA */
 
 #if defined(CONFIG_PISA) && defined(CONFIG_IOMMU_DMA)
include/net/pisa.h +29 -3
index 7fe2e7d5aa97e..c95e4ab1f344f 100644
@@ -13,9 +13,9 @@ struct sk_buff *__sock_alloc_send_pskb(struct sock *sk, unsigned long header_len
 				       gfp_t gfp);
 
 /*
- * struct net_device caches the PISA enable flags for tx_bufs and tx_heads used
- * by the leaf device, refreshed every 256 jiffies. The helpers below decide
- * whether to use PISA memory for a given dst, sk, skb.
+ * struct net_device caches the PISA enable flags for tx_bufs, tx_heads and
+ * tx_zerocopy used by the leaf device, refreshed every 256 jiffies. The helpers
+ * below decide whether to use PISA memory for a given dst, sk, skb.
  */
 #ifdef CONFIG_PISA
 
@@ -23,6 +23,7 @@ enum pisa_tx_flags {
 	PISA_TX_FLAG_BUFS	= BIT(0),
 	PISA_TX_FLAG_HEADS	= BIT(1),
 	PISA_TX_XFRM_OK		= BIT(2),
+	PISA_TX_FLAG_ZC		= BIT(3),
 	PISA_TX_TSTAMP_MASK	= ~0xffU,
 };
 
@@ -36,6 +37,10 @@ DECLARE_STATIC_KEY_FALSE(net_pisa_tx_skb_heads_key);
 
 u32 pisa_tx_flags_refresh(struct net_device *dev, u32 now);
 void *__pisa_skb_head_alloc_node(gfp_t flags, int node);
+bool __pisa_zc_iter_stop(struct sk_buff *skb, struct iov_iter *from,
+			 size_t *length, const struct sock *sk,
+			 struct page **pages, int max_pages,
+			 unsigned int orig_len, size_t *start, ssize_t *copied);
 
 /*
  * May TX data routed through @dst use PISA pages? Those pages stay readable by
@@ -144,6 +149,18 @@ static inline struct page_frag *sk_page_frag_dst(struct sock *sk,
 	       sk->sk_use_task_frag ? task_page_frag(dst) : sk_page_frag(sk);
 }
 
+/* Hook for __zerocopy_fill_skb_from_iter() MSG_ZEROCOPY upgrade (@pisa_user_key). */
+static inline bool pisa_zc_iter_stop(struct sk_buff *skb, struct iov_iter *from,
+				     size_t *length, const struct sock *sk,
+				     struct page **pages, int max_pages,
+				     unsigned int orig_len, size_t *start,
+				     ssize_t *copied)
+{
+	return pisa_user_enabled() &&
+	       __pisa_zc_iter_stop(skb, from, length, sk, pages, max_pages,
+				   orig_len, start, copied);
+}
+
 #else /* !CONFIG_PISA */
 
 static inline void *pisa_skb_head_alloc_node(gfp_t flags, int node) { return NULL; }
@@ -174,5 +191,14 @@ static inline struct page_frag *sk_page_frag_dst(struct sock *sk,
 	return sk_page_frag(sk);
 }
 
+static inline bool pisa_zc_iter_stop(struct sk_buff *skb, struct iov_iter *from,
+				     size_t *length, const struct sock *sk,
+				     struct page **pages, int max_pages,
+				     unsigned int orig_len, size_t *start,
+				     ssize_t *copied)
+{
+	return false;
+}
+
 #endif /* CONFIG_PISA */
 #endif /* _NET_PISA_H */
mm/pisa-user.c +8 -0
index 5fb1ec7c45204..e4a4e1a606b24 100644
@@ -439,6 +439,14 @@ bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,
 	return true;
 }
 
+/* Is @page, referenced by the caller, PISA memory that devices can read (usable for TX)? */
+bool pisa_page_tx_ok(const struct page *page)
+{
+	unsigned long pfn = page_to_pfn(page);
+
+	return is_pisa_pfn(pfn) && (READ_ONCE(pisa_meta_of_pfn(pfn)->prot) & IOMMU_READ);
+}
+
 /* Migrate the single-page segments already added to @bio; the caller then extracts them again. */
 bool __pisa_bio_migrate_pages(struct bio *bio, struct iov_iter *iter,
 			      enum dma_data_direction dir)
net/core/datagram.c +14 -3
index ecc30a6f83023..c589a543c3166 100644
@@ -62,6 +62,7 @@
 #include <net/tcp_states.h>
 #include <trace/events/skb.h>
 #include <net/busy_poll.h>
+#include <net/pisa.h>
 
 #include "devmem.h"
 
@@ -632,10 +633,11 @@ int skb_copy_datagram_from_iter_full(struct sk_buff *skb, int offset,
 }
 EXPORT_SYMBOL(skb_copy_datagram_from_iter_full);
 
-int zerocopy_fill_skb_from_iter(struct sk_buff *skb,
-				struct iov_iter *from, size_t length)
+static int __zerocopy_fill_skb_from_iter(struct sk_buff *skb, struct iov_iter *from,
+					 size_t length, const struct sock *sk)
 {
 	int frag = skb_shinfo(skb)->nr_frags;
+	unsigned int orig_len = skb->len;
 
 	if (!skb_frags_readable(skb))
 		return -EFAULT;
@@ -654,6 +656,9 @@ int zerocopy_fill_skb_from_iter(struct sk_buff *skb,
 					    MAX_SKB_FRAGS - frag, &start);
 		if (copied < 0)
 			return -EFAULT;
+		if (pisa_zc_iter_stop(skb, from, &length, sk, pages,
+				      MAX_SKB_FRAGS - frag, orig_len, &start, &copied))
+			return copied;
 
 		length -= copied;
 
@@ -703,6 +708,12 @@ int zerocopy_fill_skb_from_iter(struct sk_buff *skb,
 	return 0;
 }
 
+int zerocopy_fill_skb_from_iter(struct sk_buff *skb,
+				struct iov_iter *from, size_t length)
+{
+	return __zerocopy_fill_skb_from_iter(skb, from, length, NULL);
+}
+
 static int
 zerocopy_fill_skb_from_devmem(struct sk_buff *skb, struct iov_iter *from,
 			      int length,
@@ -760,7 +771,7 @@ int __zerocopy_sg_from_iter(struct msghdr *msg, struct sock *sk,
 	else if (binding)
 		ret = zerocopy_fill_skb_from_devmem(skb, from, length, binding);
 	else
-		ret = zerocopy_fill_skb_from_iter(skb, from, length);
+		ret = __zerocopy_fill_skb_from_iter(skb, from, length, sk);
 
 	truesize = skb->truesize - orig_size;
 	if (sk && sk->sk_type == SOCK_STREAM) {
net/core/pisa-net.c +91 -4

128 lines not on this page · raw message

net/core/skbuff.c +2 -1
index 4f487e0450d4b..be6b6f42ee77e 100644
@@ -1942,7 +1942,8 @@ int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
 
 	err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len,
 				      binding);
-	if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
+	if (err == -EFAULT ||
+	    ((err == -EMSGSIZE || err == -EXDEV) && skb->len == orig_len)) {
 		u32 delta_truesize = skb->truesize - orig_truesize;
 		struct sock *save_sk = skb->sk;
 
net/ipv4/tcp.c +11 -1
index 83f8ed2aa9a7e..411714edb90bd 100644
@@ -1132,6 +1132,7 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 	int process_backlog = 0;
 	int sockc_err = 0;
 	int zc = 0;
+	bool must_copy = false;	/* copy the next chunk of a MSG_ZEROCOPY send */
 	long timeo;
 
 	flags = msg->msg_flags;
@@ -1293,7 +1294,7 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 		if (copy > msg_data_left(msg))
 			copy = msg_data_left(msg);
 
-		if (zc == 0) {
+		if (zc == 0 || unlikely(must_copy)) {
 			bool merge = true;
 			int i = skb_shinfo(skb)->nr_frags;
 			struct page_frag *pfrag = sk_page_frag_dst(sk, __sk_dst_get(sk));
@@ -1338,6 +1339,7 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 				page_ref_inc(pfrag->page);
 			}
 			pfrag->offset += copy;
+			must_copy = false;
 		} else if (zc == MSG_ZEROCOPY)  {
 			/* First append to a fragless skb builds initial
 			 * pure zerocopy skb
@@ -1357,6 +1359,14 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 				tcp_mark_push(tp, skb);
 				goto new_segment;
 			}
+			/*
+			 * The next user page is not in PISA memory: copy this
+			 * chunk, without reporting SO_EE_CODE_ZEROCOPY_COPIED.
+			 */
+			if (unlikely(err == -EXDEV)) {
+				must_copy = true;
+				continue;
+			}
 			if (err < 0)
 				goto do_error;
 			copy = err;
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#92 lore raw

RFC PATCH v3 19/25 mm, iommu/dma: Support decrypted PISA pages

In reply to Luigi Rizzo

In Confidential Computing (CoCo) guests (AMD SEV-SNP, Intel TDX, ARM CCA), guest memory is private/encrypted by default, and DMA buffers must be converted to shared/decrypted in the host page tables before a device can access them.

Doing that hypercall per-packet on 4KB pages is prohibitively expensive, so guests normally bounce DMA through swiotlb. With PISA, 2MB pages are decrypted once upfront when allocated and re-encrypted only when retired back to the buddy allocator, avoiding both per-packet hypercalls and bounce-buffer copies.

Add the pisa_decrypt_key static key (enabled at boot in CoCo guests, which report CC_ATTR_GUEST_MEM_ENCRYPT) and the PISA_DECRYPTED flag to manage 2MB page decryption/re-encryption and bypass swiotlb bouncing for decrypted PISA pages.

PISA refuses to initialize when memory is encrypted but the platform is neither such a guest nor a bare-metal SME host, rather than hand a device memory that it cannot access. That covers arm64 Realms until the next commit.

Pages are decrypted in sleepable context, so atomic callers are only served from the per-node reservoirs: in a CoCo guest pisa.reservoir_max cannot be set to 0, and the reservoirs are filled when PISA is first enabled.

User PTEs that map a decrypted PISA page are built with pisa_pgprot_decrypted(), which applies pgprot_decrypted().

---
 drivers/iommu/dma-iommu.c  |   4 +
 drivers/iommu/pisa-map.c   |   8 +-
 include/linux/pisa-iommu.h |   6 ++
 include/linux/pisa-mm.h    |  20 +++++
 include/linux/pisa.h       |  21 +++++
 kernel/dma/direct.c        |   4 +
 mm/ksm.c                   |   3 +-
 mm/memory.c                |   8 +-
 mm/migrate.c               |   3 +-
 mm/pisa-alloc.c            |   9 ++-
 mm/pisa-kunit.c            |  13 ++-
 mm/pisa-meta.c             |  17 ++++
 mm/pisa-node.c             | 159 ++++++++++++++++++++++++++++++++-----
 mm/pisa-priv.h             |   8 +-
 mm/swapfile.c              |   3 +-
 mm/userfaultfd.c           |   7 +-
 16 files changed, 260 insertions(+), 33 deletions(-)
drivers/iommu/dma-iommu.c +4 -0
index 45e9432d2a020..5e4d9803645b4 100644
@@ -37,6 +37,7 @@
 
 #include "dma-iommu.h"
 #include <linux/pisa.h>
+#include <linux/pisa-mm.h>
 #include "iommu-pages.h"
 #include "iommu-priv.h"
 
@@ -1780,6 +1781,9 @@ int iommu_dma_mmap(struct device *dev, struct vm_area_struct *vma,
 		pfn = vmalloc_to_pfn(cpu_addr);
 	} else {
 		pfn = page_to_pfn(virt_to_page(cpu_addr));
+		/* A decrypted PISA page (CoCo guest) needs a decrypted user mapping too. */
+		vma->vm_page_prot = pisa_pgprot_decrypted(virt_to_page(cpu_addr),
+							  vma->vm_page_prot);
 	}
 
 	return remap_pfn_range(vma, vma->vm_start, pfn + off,
drivers/iommu/pisa-map.c +6 -2
index bbf330877f824..08ac91fafcf20 100644
@@ -7,6 +7,7 @@
 #include <linux/atomic.h>
 #include <linux/bitops.h>
 #include <linux/cache.h>
+#include <linux/dma-direct.h>
 #include <linux/dma-map-ops.h>
 #include <linux/dma-mapping.h>
 #include <linux/iommu.h>
@@ -354,7 +355,10 @@ bool __pisa_map_phys(dma_addr_t *iova, struct device *dev,
 
 	/* Every mapping of the page carries IOMMU_CACHE | @meta->prot. */
 	block_prot = IOMMU_CACHE | meta->prot;
-	if (unlikely(prot & ~block_prot))
+	/* In a CoCo guest @dev can only reach decrypted pages; an SME host needs no check. */
+	if (unlikely((prot & ~block_prot) ||
+		     (pisa_decrypt_enabled() && force_dma_unencrypted(dev) &&
+		      !(meta->flags & PISA_DECRYPTED))))
 		return false;
 
 	/* Acquire pairs with the .base release in pisa_domain_init(). */
@@ -388,7 +392,7 @@ bool __pisa_map_phys(dma_addr_t *iova, struct device *dev,
 		phys_addr_t pisa_phys = phys & PISA_MASK;
 
 		ret = iommu_map(domain, pisa_phys_to_iova(pi, meta, pisa_phys),
-				pisa_phys, PISA_SIZE, block_prot, GFP_ATOMIC);
+				pisa_pte_phys(meta, pisa_phys), PISA_SIZE, block_prot, GFP_ATOMIC);
 		if (unlikely(ret))
 			return false;
 		/* Ensure the mapping is visible before setting the domain bit. */
include/linux/pisa-iommu.h +6 -0
index 7dd91ff47288a..fed44c2050f9a 100644
@@ -81,6 +81,12 @@ struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn);
 bool pisa_quarantine_page(struct pisa_meta *meta);
 void pisa_schedule_reclaim(void);
 
+/* Physical address for IOMMU PTE of @meta at @phys (shared alias if decrypted). */
+static inline phys_addr_t pisa_pte_phys(const struct pisa_meta *meta, phys_addr_t phys)
+{
+	return (meta->flags & PISA_DECRYPTED) ? dma_addr_unencrypted(phys) : phys;
+}
+
 /* IOVA of @phys inside active RAM page @meta in @pi. */
 static inline dma_addr_t pisa_phys_to_iova(const struct pisa_iova *pi,
 					   const struct pisa_meta *meta, phys_addr_t phys)
include/linux/pisa-mm.h +20 -0
index fd5e7234e9423..8034850d2c87b 100644
@@ -121,6 +121,21 @@ static inline bool pisa_writeback_upgrade(const struct address_space *mapping,
 	       __pisa_writeback_upgrade(mapping, folio, index, fbatch);
 }
 
+/*
+ * Hook for the paths that build a user PTE for a page that may be a decrypted
+ * PISA page (CoCo guests, @pisa_decrypt_key). Not tied to @pisa_user_key: RX
+ * buffers and coherent memory are mapped to user space too, and decrypted user
+ * pages outlive pisa.user_max_pages=0.
+ */
+static inline pgprot_t pisa_pgprot_decrypted(const struct page *page, pgprot_t prot)
+{
+	if (pisa_decrypt_enabled() &&
+	    (pisa_pfn_flags(page_to_pfn(page)) & (PISA_ACTIVE | PISA_DECRYPTED)) ==
+	    (PISA_ACTIVE | PISA_DECRYPTED))
+		return pgprot_decrypted(prot);
+	return prot;
+}
+
 #else /* !CONFIG_PISA */
 
 static inline unsigned long
@@ -175,6 +190,11 @@ static inline bool pisa_writeback_upgrade(const struct address_space *mapping,
 	return false;
 }
 
+static inline pgprot_t pisa_pgprot_decrypted(const struct page *page, pgprot_t prot)
+{
+	return prot;
+}
+
 static inline int pisa_madvise(struct vm_area_struct *vma, unsigned long start,
 			       unsigned long end, bool to_pisa)
 {
include/linux/pisa.h +21 -0
index 11e3ea9eb263d..92a4c529d1605 100644
@@ -62,20 +62,24 @@ static inline struct pisa_iova *pisa_dma_iova(struct iommu_domain *domain) { ret
 enum {
 	_PISA_ACTIVE,
 	_PISA_QUARANTINED,
+	_PISA_DECRYPTED,
 };
 
 #define PISA_ACTIVE		BIT(_PISA_ACTIVE)	/* set up as a PISA page, not retired yet */
 #define PISA_QUARANTINED	BIT(_PISA_QUARANTINED)	/* IOMMU unmap failed: never reuse */
+#define PISA_DECRYPTED		BIT(_PISA_DECRYPTED)	/* page was set_memory_decrypted() */
 
 /*
  * Static keys guarding all kernel hooks:
  * - @pisa_key: enabled on first device opt-in (pisa_meta_init()).
  * - @pisa_recycle_check_key: enabled when pisa.compact or pisa.target_usage_percent > 0.
  * - @pisa_user_key: enabled when pisa.user_max_pages > 0.
+ * - @pisa_decrypt_key: enabled at boot in CoCo guests, where PISA pages are decrypted.
  */
 DECLARE_STATIC_KEY_FALSE(pisa_key);
 DECLARE_STATIC_KEY_FALSE(pisa_recycle_check_key);
 DECLARE_STATIC_KEY_FALSE(pisa_user_key);
+DECLARE_STATIC_KEY_FALSE(pisa_decrypt_key);
 
 extern u32 *pisa_pfn2slot;
 extern unsigned int pisa_nr_slots;
@@ -92,6 +96,7 @@ void *__pisa_alloc_map_coherent_dev(struct device *dev, size_t size,
 				    unsigned long attrs);
 bool __pisa_has_free_blocks_rx(unsigned int order, int nid);
 bool __pisa_page_can_recycle(const struct page *page);
+bool __is_pisa_direct(phys_addr_t phys, size_t size);
 bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,
 			     size_t size, size_t offset,
 			     enum dma_data_direction dir, bool pinned);
@@ -107,6 +112,11 @@ static inline bool pisa_user_enabled(void)
 	return static_branch_unlikely(&pisa_user_key);
 }
 
+static inline bool pisa_decrypt_enabled(void)
+{
+	return static_branch_unlikely(&pisa_decrypt_key);
+}
+
 static inline u32 pisa_pfn_flags(unsigned long pfn)
 {
 	unsigned long frame = pfn >> PISA_ORDER;
@@ -181,6 +191,12 @@ static inline bool pisa_free_coherent(const void *cpu_addr, size_t size)
 	return true;
 }
 
+/* Hook for dma_direct_map_phys() CoCo swiotlb bypass (guarded by @pisa_key). */
+static inline bool is_pisa_direct(phys_addr_t phys, size_t size)
+{
+	return pisa_enabled() && __is_pisa_direct(phys, size);
+}
+
 /* Hook for __page_pool_alloc_netmems_slow() (guarded by @pisa_key). */
 static inline gfp_t pisa_rx_gfp(const struct device *dev)
 {
@@ -237,6 +253,11 @@ static inline bool pisa_free_coherent(const void *cpu_addr, size_t size)
 	return false;
 }
 
+static inline bool is_pisa_direct(phys_addr_t phys, size_t size)
+{
+	return false;
+}
+
 static inline gfp_t pisa_rx_gfp(const struct device *dev)
 {
 	return 0;
kernel/dma/direct.c +4 -0
index 9ac4912e4a0a1..545f2fdb6088d 100644
@@ -709,6 +709,10 @@ dma_addr_t dma_direct_map_phys(struct device *dev, phys_addr_t phys,
 		return swiotlb_map(dev, phys, size, dir, attrs);
 	}
 
+	if (force_dma_unencrypted(dev) && !is_swiotlb_for_alloc(dev) &&
+	    is_pisa_direct(phys, size))
+		attrs |= DMA_ATTR_CC_SHARED;
+
 	if (attrs & DMA_ATTR_CC_SHARED)
 		dma_addr = phys_to_dma_unencrypted(dev, phys);
 	else
mm/ksm.c +2 -1
index d24b129932bf7..f5763b0bdb4fb 100644
@@ -23,6 +23,7 @@
 #include <linux/sched/cputime.h>
 #include <linux/rwsem.h>
 #include <linux/pagemap.h>
+#include <linux/pisa-mm.h>
 #include <linux/rmap.h>
 #include <linux/spinlock.h>
 #include <linux/xxhash.h>
@@ -1447,7 +1448,7 @@ static int replace_page(struct vm_area_struct *vma, struct page *page,
 	if (!is_zero_pfn(page_to_pfn(kpage))) {
 		folio_get(kfolio);
 		folio_add_anon_rmap_pte(kfolio, kpage, vma, addr, RMAP_NONE);
-		newpte = mk_pte(kpage, vma->vm_page_prot);
+		newpte = mk_pte(kpage, pisa_pgprot_decrypted(kpage, vma->vm_page_prot));
 	} else {
 		/*
 		 * Use pte_mkdirty to mark the zero page mapped by KSM, and then
mm/memory.c +5 -3
index 7f019afc35ca0..90aad56b97b6d 100644
@@ -50,6 +50,7 @@
 #include <linux/swap.h>
 #include <linux/highmem.h>
 #include <linux/pagemap.h>
+#include <linux/pisa-mm.h>
 #include <linux/memremap.h>
 #include <linux/kmsan.h>
 #include <linux/ksm.h>
@@ -915,7 +916,7 @@ static void restore_exclusive_pte(struct vm_area_struct *vma,
 
 	VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
 
-	pte = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot)));
+	pte = pte_mkold(mk_pte(page, pisa_pgprot_decrypted(page, READ_ONCE(vma->vm_page_prot))));
 	if (pte_swp_soft_dirty(orig_pte))
 		pte = pte_mksoft_dirty(pte);
 
@@ -2487,6 +2488,7 @@ static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte,
 	}
 
 	/* Ok, finally just insert the thing.. */
+	prot = pisa_pgprot_decrypted(page, prot);
 	pteval = mk_pte(page, prot);
 	if (unlikely(is_zero_folio(folio))) {
 		pteval = pte_mkspecial(pteval);
@@ -5285,7 +5287,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 
 	add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr_pages);
 	add_mm_counter(vma->vm_mm, MM_SWAPENTS, -nr_pages);
-	pte = mk_pte(page, vma->vm_page_prot);
+	pte = mk_pte(page, pisa_pgprot_decrypted(page, vma->vm_page_prot));
 	if (pte_swp_soft_dirty(vmf->orig_pte))
 		pte = pte_mksoft_dirty(pte);
 	if (pte_swp_uffd(vmf->orig_pte))
@@ -5836,7 +5838,7 @@ void set_pte_range(struct vm_fault *vmf, struct folio *folio,
 	pte_t entry;
 
 	flush_icache_pages(vma, page, nr);
-	entry = mk_pte(page, vma->vm_page_prot);
+	entry = mk_pte(page, pisa_pgprot_decrypted(page, vma->vm_page_prot));
 
 	if (prefault && arch_wants_old_prefaulted_pte())
 		entry = pte_mkold(entry);
mm/migrate.c +2 -1
index e6cd83cf32aa1..9b1d40710ff0f 100644
@@ -37,6 +37,7 @@
 #include <linux/gfp.h>
 #include <linux/page_idle.h>
 #include <linux/page_owner.h>
+#include <linux/pisa-mm.h>
 #include <linux/sched/mm.h>
 #include <linux/ptrace.h>
 #include <linux/memory.h>
@@ -398,7 +399,7 @@ static bool remove_migration_pte(struct folio *folio,
 
 		folio_get(folio);
 		new = folio_page(folio, idx);
-		pte = mk_pte(new, READ_ONCE(vma->vm_page_prot));
+		pte = mk_pte(new, pisa_pgprot_decrypted(new, READ_ONCE(vma->vm_page_prot)));
 		if (!softleaf_is_migration_young(entry))
 			pte = pte_mkold(pte);
 		if (folio_test_dirty(folio) && softleaf_is_migration_dirty(entry))
mm/pisa-alloc.c +6 -3
index 4fc3b4d29de67..edfa7cf424451 100644
@@ -9,6 +9,7 @@
 #include <linux/bitmap.h>
 #include <linux/bitops.h>
 #include <linux/cache.h>
+#include <linux/cc_platform.h>
 #include <linux/cpuhotplug.h>
 #include <linux/device.h>
 #include <linux/dma-direct.h>
@@ -178,7 +179,7 @@ static void pisa_reclaim_work_fn(struct work_struct *work)
 
 	node = llist_del_all(&pisa_free_list);
 	llist_for_each_entry_safe(meta, tmp, node, llnode)
-		pisa_release_page(meta);
+		__pisa_release_page(meta);
 
 	if (next_delay != MAX_JIFFY_OFFSET)
 		queue_delayed_work(pisa_wq ?: system_wq, &pisa_reclaim_work, next_delay);
@@ -833,7 +834,7 @@ static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, in
 	int err;
 
 	/* __GFP_DMA/__GFP_DMA32 were already declined by pisa_alloc_bulk(). */
-	meta = pisa_reservoir_pop(nid, gfp & ~__GFP_ZERO, &clean);
+	meta = pisa_reservoir_pop(nid, gfp & ~__GFP_ZERO, pisa_want_decrypt(), &clean);
 	if (IS_ERR(meta))
 		return meta;
 
@@ -1268,7 +1269,7 @@ __pisa_alloc_map_coherent(struct device *dev, struct iommu_domain *domain,
 		    !pisa_coherent_dev_fits(dev, pi))
 			return NULL;
 	} else if (is_swiotlb_for_alloc(dev) ||
-		   force_dma_unencrypted(dev) ||
+		   (force_dma_unencrypted(dev) && !pisa_want_decrypt()) ||
 		   !dma_coherent_ok(dev, PFN_PHYS(max_pfn) - 1, 1)) {
 		return NULL;
 	}
@@ -1331,6 +1332,8 @@ __pisa_alloc_map_coherent(struct device *dev, struct iommu_domain *domain,
 			pisa_free_coherent(page_address(page), size);
 			return NULL;
 		}
+	} else if (force_dma_unencrypted(dev)) {
+		*dma_handle = phys_to_dma_unencrypted(dev, page_to_phys(page));
 	} else {
 		*dma_handle = phys_to_dma(dev, page_to_phys(page));
 	}
mm/pisa-kunit.c +12 -1
index 0dbc3ecf44465..c195fdfdbd9fa 100644
@@ -66,7 +66,7 @@ static void pisa_meta_set_active(struct pisa_meta *meta, bool active)
 	if (active)
 		pisa_meta_set_flags(meta, PISA_ACTIVE);
 	else
-		pisa_meta_clear_flags(meta, PISA_ACTIVE);
+		pisa_meta_clear_flags(meta, PISA_ACTIVE | PISA_DECRYPTED);
 }
 
 static void test_meta_active_toggle(struct kunit *test)
@@ -74,6 +74,7 @@ static void test_meta_active_toggle(struct kunit *test)
 	unsigned long pfn, base_pfn;
 	struct pisa_meta *meta;
 	struct page *page;
+	phys_addr_t pa;
 
 	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
 
@@ -91,16 +92,26 @@ static void test_meta_active_toggle(struct kunit *test)
 	}
 	KUNIT_EXPECT_EQ(test, pisa_meta_ensure_pfn(pfn, false), 0);
 	meta = pisa_meta_of_pfn(pfn);
+	pa = page_to_phys(page);
 
 	KUNIT_EXPECT_FALSE(test, is_pisa_pfn(pfn));
+	KUNIT_EXPECT_FALSE(test, is_pisa_direct(pa, PAGE_SIZE));
 
 	pisa_meta_set_active(meta, true);
 	KUNIT_EXPECT_TRUE(test, is_pisa_pfn(base_pfn));
 	KUNIT_EXPECT_TRUE(test, is_pisa_pfn(pfn));
 	KUNIT_EXPECT_TRUE(test, is_pisa_pfn(base_pfn + (1UL << PISA_ORDER) - 1));
+	KUNIT_EXPECT_FALSE(test, is_pisa_direct(pa, PAGE_SIZE));
+	KUNIT_EXPECT_EQ(test, pisa_pte_phys(meta, pa), pa);
+
+	pisa_meta_set_flags(meta, PISA_ACTIVE | PISA_DECRYPTED);
+	KUNIT_EXPECT_TRUE(test, is_pisa_direct(pa, PAGE_SIZE));
+	KUNIT_EXPECT_FALSE(test, is_pisa_direct(pa, PISA_SIZE + PAGE_SIZE));
+	KUNIT_EXPECT_EQ(test, pisa_pte_phys(meta, pa), dma_addr_unencrypted(pa));
 
 	pisa_meta_set_active(meta, false);
 	KUNIT_EXPECT_FALSE(test, is_pisa_pfn(pfn));
+	KUNIT_EXPECT_FALSE(test, is_pisa_direct(pa, PAGE_SIZE));
 
 	pisa_slot_free(meta);
 	__free_pages(page, PISA_ORDER);
mm/pisa-meta.c +17 -0
index 25d3add7a4891..99c5bc42eed10 100644
@@ -176,6 +176,19 @@ struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn)
 	return &pisa_meta_array[slot - 1];
 }
 
+bool __is_pisa_direct(phys_addr_t phys, size_t size)
+{
+	u32 flags = pisa_pfn_flags(PHYS_PFN(phys));
+
+	/*
+	 * Only decrypted active pages can bypass swiotlb bouncing, and the
+	 * transfer must not straddle the end of the PISA frame.
+	 */
+	return (flags & (PISA_ACTIVE | PISA_DECRYPTED)) ==
+	       (PISA_ACTIVE | PISA_DECRYPTED) &&
+	       (phys & (PISA_SIZE - 1)) + size <= PISA_SIZE;
+}
+
 /*
  * Update @meta's position on @pa's lists under @pa->lock. When all blocks
  * become available (avail == bpp), either queues @meta to @pisa_free_list (and
@@ -716,6 +729,9 @@ int pisa_meta_init(void)
 
 	if (pisa_enabled())
 		return 0;
+	/* Never hand a device memory that it cannot access. */
+	if (pisa_cc_unsupported())
+		return -EOPNOTSUPP;
 
 	mutex_lock(&pisa_meta_mutex);
 	if (pisa_init_err) {
@@ -790,6 +806,7 @@ int pisa_meta_init(void)
 	mutex_unlock(&pisa_meta_mutex);
 out_enable:
 	static_branch_enable(&pisa_key);
+	pisa_reservoir_prime();
 	pisa_schedule_reservoir();
 	return 0;
 
mm/pisa-node.c +141 -18

296 lines not on this page · raw message

mm/pisa-priv.h +7 -1
index 08bf1b64bcf2c..865f3d779b84d 100644
@@ -10,6 +10,7 @@
 #undef MODULE_PARAM_PREFIX
 #define MODULE_PARAM_PREFIX "pisa."
 #include <linux/jiffies.h>
+#include <linux/mem_encrypt.h>
 #include <linux/nodemask.h>
 #include <linux/spinlock.h>
 #include <linux/topology.h>
@@ -204,6 +205,9 @@ static inline void pisa_alloc_backoff(struct pisa_node *node, bool can_block)
 		WRITE_ONCE(node->next_alloc, jiffies + DIV_ROUND_UP(HZ, 100));
 }
 
+bool pisa_want_decrypt(void);
+bool pisa_cc_unsupported(void);
+
 /* pisa-alloc.c, also used by the per-node code in pisa-node.c */
 struct pisa_alloc *pisa_alloc_create(int nid, unsigned int order, enum dma_data_direction dir);
 __printf(2, 3)
@@ -220,6 +224,7 @@ bool pisa_place_meta(struct pisa_meta *meta);
 extern struct llist_head pisa_free_list;
 extern unsigned int pisa_idle_ms;
 void pisa_release_page(struct pisa_meta *meta);
+void __pisa_release_page(struct pisa_meta *meta);
 unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
 			      unsigned long nr_pages, struct page **page_array, bool frozen);
 
@@ -249,9 +254,10 @@ bool pisa_user_scrub_node(int nid);
 extern unsigned int pisa_reservoir_max;
 void pisa_node_init(void);
 void pisa_schedule_reservoir(void);
+void pisa_reservoir_prime(void);
 void pisa_schedule_scrub(int nid);
 void pisa_schedule_scrub_all(void);
-struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean);
+struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool decrypt, bool *clean);
 unsigned long pisa_reservoir_count(void);
 unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan);
 void pisa_user_boot_enable(void);
mm/swapfile.c +2 -1
index 2d2df53fc51a9..c8952ac306d74 100644
@@ -17,6 +17,7 @@
 #include <linux/swap.h>
 #include <linux/vmalloc.h>
 #include <linux/pagemap.h>
+#include <linux/pisa-mm.h>
 #include <linux/namei.h>
 #include <linux/shmem_fs.h>
 #include <linux/blk-cgroup.h>
@@ -2587,7 +2588,7 @@ static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
 		folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
 		folio_add_lru_vma(folio, vma);
 	}
-	new_pte = pte_mkold(mk_pte(page, vma->vm_page_prot));
+	new_pte = pte_mkold(mk_pte(page, pisa_pgprot_decrypted(page, vma->vm_page_prot)));
 	if (pte_swp_soft_dirty(old_pte))
 		new_pte = pte_mksoft_dirty(new_pte);
 	if (pte_swp_uffd(old_pte))
mm/userfaultfd.c +5 -2
index 14fdbf217f00e..200f56bcba069 100644
@@ -13,6 +13,7 @@
 #include <linux/mm.h>
 #include <linux/sched/signal.h>
 #include <linux/pagemap.h>
+#include <linux/pisa-mm.h>
 #include <linux/rmap.h>
 #include <linux/swap.h>
 #include <linux/leafops.h>
@@ -341,7 +342,7 @@ static int mfill_atomic_install_pte(pmd_t *dst_pmd,
 	bool page_in_cache = folio_mapping(folio);
 	pte_t dst_ptep;
 
-	_dst_pte = mk_pte(page, dst_vma->vm_page_prot);
+	_dst_pte = mk_pte(page, pisa_pgprot_decrypted(page, dst_vma->vm_page_prot));
 	_dst_pte = pte_mkdirty(_dst_pte);
 	if (page_in_cache && !vm_shared)
 		writable = false;
@@ -1303,7 +1304,9 @@ static long move_present_ptes(struct mm_struct *mm,
 		folio_move_anon_rmap(src_folio, dst_vma);
 		src_folio->index = linear_anon_page_index(dst_vma, dst_addr);
 
-		orig_dst_pte = folio_mk_pte(src_folio, dst_vma->vm_page_prot);
+		orig_dst_pte = folio_mk_pte(src_folio,
+					    pisa_pgprot_decrypted(folio_page(src_folio, 0),
+								  dst_vma->vm_page_prot));
 		/* Set soft dirty bit so userspace can notice the pte was moved */
 		if (pgtable_supports_soft_dirty())
 			orig_dst_pte = pte_mksoft_dirty(orig_dst_pte);
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#93 lore raw

Re: [RFC PATCH v3 19/25] mm, iommu/dma: Support decrypted PISA pages

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] iommu/dma: iommu_dma_alloc() rejects CoCo allocations before PISA hook --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] iommu/dma: iommu_dma_alloc() rejects CoCo allocations before PISA hook
--

commit 9188f1b04aac4884c0b7b2222a205db844b8ac89
Author: Luigi Rizzo <[email protected]>

mm, iommu/dma: Support decrypted PISA pages

This commit adds support for decrypting and re-encrypting 2MB PISA pages in Confidential Computing (CoCo) guests so that DMA mappings can bypass swiotlb bouncing and user mappings use decrypted PTE protections.

Quoted 4 lines
drivers/iommu/dma-iommu.c +0 -0
index 45e9432d2a020..5e4d9803645b4 100644

[ ... ]

drivers/iommu/dma-iommu.c int iommu_dma_mmap(struct device *dev, struct vm_area_struct *vma, · line 1789

Quoted 10 lines
drivers/iommu/dma-iommu.c +3 -0
@@ -1780,6 +1781,9 @@ int iommu_dma_mmap(struct device *dev, struct vm_area_struct *vma,
 		pfn = vmalloc_to_pfn(cpu_addr);
 	} else {
 		pfn = page_to_pfn(virt_to_page(cpu_addr));
+		/* A decrypted PISA page (CoCo guest) needs a decrypted user mapping too. */
+		vma->vm_page_prot = pisa_pgprot_decrypted(virt_to_page(cpu_addr),
+							  vma->vm_page_prot);
 	}
 
 	return remap_pfn_range(vma, vma->vm_start, pfn + off,

[Severity: Medium]
Can iommu_dma_alloc() ever allocate a decrypted PISA page in a CoCo guest?

When force_dma_unencrypted(dev) is true, dma_alloc_attrs() sets __DMA_ATTR_ALLOC_CC_SHARED in attrs before calling iommu_dma_alloc(), and __pisa_alloc_map_coherent() accepts that attribute. However, iommu_dma_alloc() still bails out on is_alloc_cc_shared before calling pisa_alloc_map_coherent():

drivers/iommu/dma-iommu.c:iommu_dma_alloc() {
	...
	/* Not yet supported */
	if (is_alloc_cc_shared)
		return NULL;

	gfp |= __GFP_ZERO;

	cpu_addr = pisa_alloc_map_coherent(dev, size, handle, gfp, attrs);
	if (cpu_addr)
		return cpu_addr;
	...
}

As a result, coherent allocations for IOMMU-backed devices in CoCo guests always fail with NULL before reaching PISA, and this new pisa_pgprot_decrypted() path in iommu_dma_mmap() is unreachable for them. Moving the pisa_alloc_map_coherent() call ahead of the is_alloc_cc_shared check would allow PISA to serve those allocations.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
#94 lore raw

RFC PATCH v3 20/25 arm64/mm, mm: Support decrypted PISA pages in Realms

In reply to Luigi Rizzo

An arm64 Realm (ARM CCA guest) only reports CC_ATTR_MEM_ENCRYPT, so PISA did not treat it as a CoCo guest and refused to initialize there.

Treat a Realm as a CoCo guest: PISA pages are decrypted (shared with the host) when they are allocated, as on SEV-SNP and TDX.

A decrypted page is mapped with PROT_NS_SHARED, the top IPA bit, set in the address field of its PTEs. PISA maps such pages into user space with ordinary PTEs (page cache, migrated user pages, zerocopy receive), and for those pte_pfn() must be the PFN of the page, or vm_normal_page() and GUP see a PFN that has no struct page.

Make __pte_to_phys() strip the bit when what is left is a decrypted PISA page. The check is behind pisa_decrypt_key, so outside CoCo guests it costs one static branch, and every other shared mapping (ioremap() of emulated MMIO, swiotlb, DMA mmap) keeps the address it has today.

pisa_decrypt_key and the lookup are exported because pte_pfn() is used by modules.

---
 arch/arm64/include/asm/pgtable.h | 28 ++++++++++++++++++++++++++--
 mm/pisa-meta.c                   |  9 +++++++++
 mm/pisa-node.c                   |  9 +++++++--
 3 files changed, 42 insertions(+), 4 deletions(-)
arch/arm64/include/asm/pgtable.h +26 -2
index a474c9fb485ad..86c60b8f43ae0 100644
@@ -108,7 +108,7 @@ static inline void arch_leave_lazy_mmu_mode(void)
 			  TLBF_NOBROADCAST | TLBF_NONOTIFY | TLBF_NOWALKCACHE)
 
 #ifdef CONFIG_ARM64_PA_BITS_52
-static inline phys_addr_t __pte_to_phys(pte_t pte)
+static inline phys_addr_t __pte_to_phys_raw(pte_t pte)
 {
 	pte_val(pte) &= ~PTE_MAYBE_SHARED;
 	return (pte_val(pte) & PTE_ADDR_LOW) |
@@ -119,7 +119,7 @@ static inline pteval_t __phys_to_pte_val(phys_addr_t phys)
 	return (phys | (phys >> PTE_ADDR_HIGH_SHIFT)) & PHYS_TO_PTE_ADDR_MASK;
 }
 #else
-static inline phys_addr_t __pte_to_phys(pte_t pte)
+static inline phys_addr_t __pte_to_phys_raw(pte_t pte)
 {
 	return pte_val(pte) & PTE_ADDR_LOW;
 }
@@ -130,6 +130,30 @@ static inline pteval_t __phys_to_pte_val(phys_addr_t phys)
 }
 #endif
 
+#if defined(CONFIG_PISA) && !defined(__DISABLE_EXPORTS)
+DECLARE_STATIC_KEY_FALSE(pisa_decrypt_key);
+bool __pisa_phys_decrypted(phys_addr_t phys);
+#endif
+
+static inline phys_addr_t __pte_to_phys(pte_t pte)
+{
+#if defined(CONFIG_PISA) && !defined(__DISABLE_EXPORTS)
+	/*
+	 * In a Realm, PISA maps its decrypted pages into user space with ordinary
+	 * PTEs. Those have PROT_NS_SHARED, the top IPA bit, set in their address
+	 * field, but pte_pfn() must be the PFN of the page: strip the bit when
+	 * what is left is a decrypted PISA page. Other shared mappings keep it.
+	 */
+	if (static_branch_unlikely(&pisa_decrypt_key) && (pte_val(pte) & PROT_NS_SHARED)) {
+		phys_addr_t phys = __pte_to_phys_raw(__pte(pte_val(pte) & ~PROT_NS_SHARED));
+
+		if (__pisa_phys_decrypted(phys))
+			return phys;
+	}
+#endif
+	return __pte_to_phys_raw(pte);
+}
+
 #define pte_pfn(pte)		(__pte_to_phys(pte) >> PAGE_SHIFT)
 #define pfn_pte(pfn,prot)	\
 	__pte(__phys_to_pte_val((phys_addr_t)(pfn) << PAGE_SHIFT) | pgprot_val(prot))
mm/pisa-meta.c +9 -0
index 99c5bc42eed10..b608ef71152af 100644
@@ -189,6 +189,15 @@ bool __is_pisa_direct(phys_addr_t phys, size_t size)
 	       (phys & (PISA_SIZE - 1)) + size <= PISA_SIZE;
 }
 
+#ifdef CONFIG_ARM64
+/* For __pte_to_phys(): true if @phys is in a decrypted PISA page. */
+bool __pisa_phys_decrypted(phys_addr_t phys)
+{
+	return pisa_pfn_flags(PHYS_PFN(phys)) & PISA_DECRYPTED;
+}
+EXPORT_SYMBOL(__pisa_phys_decrypted);
+#endif
+
 /*
  * Update @meta's position on @pa's lists under @pa->lock. When all blocks
  * become available (avail == bpp), either queues @meta to @pisa_free_list (and
mm/pisa-node.c +7 -2
index 12fbb617c342b..aa4f8759ae5e8 100644
@@ -36,11 +36,16 @@ unsigned int pisa_reservoir_max __read_mostly = 16;
 
 /* Enabled in CoCo guests by pisa_node_init(): new PISA pages are decrypted for DMA. */
 DEFINE_STATIC_KEY_FALSE(pisa_decrypt_key);
+EXPORT_SYMBOL(pisa_decrypt_key);
 
-/* A confidential guest: PISA pages are decrypted for DMA. A bare-metal SME host is not one. */
+/*
+ * A confidential guest: PISA pages are decrypted for DMA. A bare-metal SME host
+ * is not one. An arm64 Realm only reports CC_ATTR_MEM_ENCRYPT.
+ */
 static bool pisa_coco_guest(void)
 {
-	return cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT);
+	return cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) ||
+	       (IS_ENABLED(CONFIG_ARM64) && cc_platform_has(CC_ATTR_MEM_ENCRYPT));
 }
 
 /* Memory encryption that PISA cannot handle: neither an SME host nor a guest it decrypts for. */
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#95 lore raw

Re: [RFC PATCH v3 20/25] arm64/mm, mm: Support decrypted PISA pages in Realms

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] mm/pisa: redundant arm64 CC_ATTR_MEM_ENCRYPT check in pisa_coco_guest() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] mm/pisa: redundant arm64 CC_ATTR_MEM_ENCRYPT check in pisa_coco_guest()
--

commit 4bc8313e88b22932cffa12afb0c2ba3b273c8641
Author: Luigi Rizzo <[email protected]>

arm64/mm, mm: Support decrypted PISA pages in Realms

This commit enables decrypted PISA pages in arm64 Realms and strips PROT_NS_SHARED in __pte_to_phys() when translating PTEs for decrypted PISA pages.

Quoted 11 lines
mm/pisa-node.c +1 -1
index 12fbb617c342b..aa4f8759ae5e8 100644
@@ -36,11 +36,16 @@ unsigned int pisa_reservoir_max __read_mostly = 16;
 
 /* Enabled in CoCo guests by pisa_node_init(): new PISA pages are decrypted for DMA. */
 DEFINE_STATIC_KEY_FALSE(pisa_decrypt_key);
+EXPORT_SYMBOL(pisa_decrypt_key);
 
-/* A confidential guest: PISA pages are decrypted for DMA. A bare-metal SME host is not one. */

mm/pisa-node.c unsigned int pisa_reservoir_max __read_mostly = 16; · line 49

Quoted 10 lines
mm/pisa-node.c +6 -1
+/*
+ * A confidential guest: PISA pages are decrypted for DMA. A bare-metal SME host
+ * is not one. An arm64 Realm only reports CC_ATTR_MEM_ENCRYPT.
+ */
 static bool pisa_coco_guest(void)
 {
-	return cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT);
+	return cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) ||
+	       (IS_ENABLED(CONFIG_ARM64) && cc_platform_has(CC_ATTR_MEM_ENCRYPT));
 }

[Severity: Low]
Is the CC_ATTR_MEM_ENCRYPT fallback in pisa_coco_guest() needed?

On arm64, cc_platform_has() handles CC_ATTR_GUEST_MEM_ENCRYPT in the same case as CC_ATTR_MEM_ENCRYPT:

arch/arm64/mm/init.c:cc_platform_has() {
	switch (attr) {
	case CC_ATTR_MEM_ENCRYPT:
	case CC_ATTR_GUEST_MEM_ENCRYPT:
		return is_realm_world() || is_protected_kvm_guest();
	...
}

Because cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) already returns true in an arm64 Realm, the extra arm64 check is unreachable today and would misclassify an arm64 host as a CoCo guest if host memory encryption is added later.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=20
#96 lore raw

RFC PATCH v3 21/25 mm: Add PISA statistics and debugfs

In reply to Luigi Rizzo

PISA allocation and mapping failures silently fall back to standard page allocation and per-buffer DMA mappings, making performance regressions hard to diagnose without observability.

Add per-allocator, per-node reservoir, user-page migration, and global shrinker/reclaim counters, and expose them via /sys/kernel/debug/pisa/allocs. Also emit a one-shot dmesg warning on the first 2MB buddy allocation failure.

---
 drivers/iommu/pisa-map.c   |  91 ++++++++++++-
 include/linux/pisa-iommu.h |  20 +++
 include/linux/pisa.h       |   2 +
 mm/pisa-alloc.c            | 270 +++++++++++++++++++++++++++++++++----
 mm/pisa-kunit.c            |   6 +-
 mm/pisa-node.c             |  40 ++++++
 mm/pisa-priv.h             |  57 +++++++-
 mm/pisa-user.c             |  71 +++++++++-
 net/core/pisa-net.c        |   2 +
 9 files changed, 521 insertions(+), 38 deletions(-)
drivers/iommu/pisa-map.c +87 -4
index 08ac91fafcf20..fc6fa3682f045 100644
@@ -17,11 +17,21 @@
 #include <linux/mm.h>
 #include <linux/pci.h>
 #include <linux/pisa-iommu.h>
+#include <linux/seq_file.h>
 #include <linux/spinlock.h>
 #include <linux/srcu.h>
 
 #include "iommu-priv.h"
 
+static struct {
+	atomic64_t page_map;
+	atomic64_t unmap_fail;
+	atomic64_t fallback_nowindow;
+	atomic64_t fallback_noidx;
+	atomic64_t fallback_nohuge;
+	atomic64_t fallback_maperr;
+	atomic64_t fallback_prot;
+} pisa_map_stats;
 
 /*
  * Registry of PISA IOMMU domains. Each slot is FREE (!domain && !base),
@@ -32,6 +42,8 @@ static struct {
 	struct iommu_domain *domain;
 	dma_addr_t base;
 	spinlock_t map_lock;	/* serialises iommu_map() in __pisa_map_phys() */
+	atomic_t slots;
+	char name[32];
 } pisa_domains[PISA_MAX_DOMAINS] __read_mostly;
 static DEFINE_SPINLOCK(pisa_domains_lock);
 
@@ -41,12 +53,61 @@ DEFINE_STATIC_SRCU(pisa_srcu);
 /* Bumped under pisa_domains_lock whenever a domain index is released. */
 unsigned int pisa_domains_generation __read_mostly;
 
+void pisa_domains_show(struct seq_file *s)
+{
+	unsigned int active = 0, draining = 0;
+	char bmap[PISA_MAX_DOMAINS];
+
+	for (int idx = 0; idx < PISA_MAX_DOMAINS; idx++) {
+		if (READ_ONCE(pisa_domains[idx].domain)) {
+			active++;
+			bmap[idx] = 'A';
+		} else if (READ_ONCE(pisa_domains[idx].base)) {
+			draining++;
+			bmap[idx] = 'd';
+		} else {
+			bmap[idx] = '.';
+		}
+	}
+
+	pisa_seq_kv(s, "domains", { "active", active }, { "draining", draining },
+		    { "max", PISA_MAX_DOMAINS },
+		    { "mapped", atomic64_read(&pisa_map_stats.page_map) },
+		    { "unmap_fail", atomic64_read(&pisa_map_stats.unmap_fail) });
+	pisa_seq_kv(s, "map_fail",
+		    { "no_window", atomic64_read(&pisa_map_stats.fallback_nowindow) },
+		    { "no_idx", atomic64_read(&pisa_map_stats.fallback_noidx) },
+		    { "no_huge", atomic64_read(&pisa_map_stats.fallback_nohuge) },
+		    { "map_err", atomic64_read(&pisa_map_stats.fallback_maperr) },
+		    { "prot", atomic64_read(&pisa_map_stats.fallback_prot) });
+	for (int idx = 0; idx < PISA_MAX_DOMAINS; idx++) {
+		if ((idx & 63) == 0)
+			seq_printf(s, "  %-12s", idx ? "" : "domains_map");
+		if ((idx & 7) == 0)
+			seq_putc(s, ' ');
+		seq_putc(s, bmap[idx]);
+		if ((idx & 63) == 63 || idx == PISA_MAX_DOMAINS - 1)
+			seq_putc(s, '\n');
+	}
+
+	for (int idx = 0; idx < PISA_MAX_DOMAINS; idx++) {
+		dma_addr_t base = READ_ONCE(pisa_domains[idx].base);
+
+		if (!READ_ONCE(pisa_domains[idx].domain))
+			continue;
+		seq_printf(s, "  domain_%-5d base %pad size %lluM slots %d name %s\n",
+			   idx, &base, pisa_iova_size() >> 20,
+			   atomic_read(&pisa_domains[idx].slots), pisa_domains[idx].name);
+	}
+}
+
 /* Report a short IOMMU unmap and mark @meta quarantined so it is never reused. */
 static bool pisa_quarantine_meta(struct pisa_meta *meta, struct iommu_domain *domain,
 				 int idx, dma_addr_t iova, size_t unmapped)
 {
 	pr_err_ratelimited("pisa: unmap of IOVA %pad in domain %p (index %d) returned %zu, quarantining PISA page\n",
 			   &iova, domain, idx, unmapped);
+	atomic64_inc(&pisa_map_stats.unmap_fail);
 	return pisa_quarantine_page(meta);
 }
 
@@ -71,6 +132,7 @@ void pisa_unmap_all_domains(struct pisa_meta *meta)
 
 		if (!test_and_clear_bit(idx, meta->domains_mapped))
 			continue;
+		atomic_dec(&pisa_domains[idx].slots);
 
 		spin_lock_irqsave(&pisa_domains_lock, flags);
 		domain = pisa_domains[idx].domain;
@@ -138,6 +200,8 @@ void __pisa_domain_release(struct iommu_domain *domain)
 	spin_lock_irqsave(&pisa_domains_lock, flags);
 	/* Mark slot FREE and bump @pisa_domains_generation so NOIDX domains retry. */
 	pisa_domains[idx].base = 0;
+	atomic_set(&pisa_domains[idx].slots, 0);
+	pisa_domains[idx].name[0] = '\0';
 	WRITE_ONCE(pisa_domains_generation, pisa_domains_generation + 1);
 	spin_unlock_irqrestore(&pisa_domains_lock, flags);
 
@@ -176,6 +240,7 @@ void __pisa_domain_quiesce(struct iommu_domain *domain)
 		if (!test_bit(idx, meta->domains_mapped) ||
 		    !test_and_clear_bit(idx, meta->domains_mapped))
 			continue;
+		atomic_dec(&pisa_domains[idx].slots);
 
 		/* Unmap the page, batching the IOTLB flush into @gather. */
 		iova = base + pisa_meta2iova_offset(meta);
@@ -314,6 +379,9 @@ static int pisa_domain_init(struct device *dev, struct iommu_domain *domain,
 	pisa_domains[idx].domain = domain;
 	pisa_domains[idx].base = base;
 	spin_lock_init(&pisa_domains[idx].map_lock);
+	atomic_set(&pisa_domains[idx].slots, 0);
+	strscpy(pisa_domains[idx].name, dev_name(dev),
+		sizeof(pisa_domains[idx].name));
 	WRITE_ONCE(pi->domain_idx, idx + PISA_IDX_FIRST);
 	/* Publish .domain_idx before .base (paired with is_pisa_iova()). */
 	smp_store_release(&pi->base, base);
@@ -358,8 +426,10 @@ bool __pisa_map_phys(dma_addr_t *iova, struct device *dev,
 	/* In a CoCo guest @dev can only reach decrypted pages; an SME host needs no check. */
 	if (unlikely((prot & ~block_prot) ||
 		     (pisa_decrypt_enabled() && force_dma_unencrypted(dev) &&
-		      !(meta->flags & PISA_DECRYPTED))))
+		      !(meta->flags & PISA_DECRYPTED)))) {
+		atomic64_inc(&pisa_map_stats.fallback_prot);
 		return false;
+	}
 
 	/* Acquire pairs with the .base release in pisa_domain_init(). */
 	if (unlikely(!smp_load_acquire(&pi->base))) {
@@ -368,8 +438,15 @@ bool __pisa_map_phys(dma_addr_t *iova, struct device *dev,
 		if (likely(!ret))
 			ret = pisa_domain_init(dev, domain, pi);
 
-		if (ret)
+		if (ret) {
+			if (ret == -EOPNOTSUPP)
+				atomic64_inc(&pisa_map_stats.fallback_nohuge);
+			else if (ret == -EBUSY)
+				atomic64_inc(&pisa_map_stats.fallback_noidx);
+			else
+				atomic64_inc(&pisa_map_stats.fallback_nowindow);
 			return false;
+		}
 	}
 
 	addr = pisa_phys_to_iova(pi, meta, phys);
@@ -377,8 +454,10 @@ bool __pisa_map_phys(dma_addr_t *iova, struct device *dev,
 	/* Check @dev's own DMA mask and bus limit against the window IOVA. */
 	limit = min_not_zero(dma_get_mask(dev), dev->bus_dma_limit);
 	limit = min_not_zero(limit, dev->coherent_dma_mask);
-	if (unlikely(addr + size - 1 > limit))
+	if (unlikely(addr + size - 1 > limit)) {
+		atomic64_inc(&pisa_map_stats.fallback_nowindow);
 		return false;
+	}
 
 	domain_idx = pi->domain_idx - PISA_IDX_FIRST;
 	if (likely(test_bit(domain_idx, meta->domains_mapped))) {
@@ -393,11 +472,15 @@ bool __pisa_map_phys(dma_addr_t *iova, struct device *dev,
 
 		ret = iommu_map(domain, pisa_phys_to_iova(pi, meta, pisa_phys),
 				pisa_pte_phys(meta, pisa_phys), PISA_SIZE, block_prot, GFP_ATOMIC);
-		if (unlikely(ret))
+		if (unlikely(ret)) {
+			atomic64_inc(&pisa_map_stats.fallback_maperr);
 			return false;
+		}
 		/* Ensure the mapping is visible before setting the domain bit. */
 		smp_mb__before_atomic();
 		set_bit(domain_idx, meta->domains_mapped);
+		atomic_inc(&pisa_domains[domain_idx].slots);
+		atomic64_inc(&pisa_map_stats.page_map);
 	}
 
 	*iova = addr;
include/linux/pisa-iommu.h +20 -0
index fed44c2050f9a..aa91d3cbaa75c 100644
@@ -11,6 +11,7 @@
 #include <linux/pisa.h>
 
 struct pisa_alloc;
+struct seq_file;
 
 #ifdef CONFIG_PISA
 
@@ -95,6 +96,23 @@ static inline dma_addr_t pisa_phys_to_iova(const struct pisa_iova *pi,
 	       (phys & (PISA_SIZE - 1));
 }
 
+/* One name/value pair of a debugfs statistics line. */
+struct pisa_kv {
+	const char *name;
+	s64 val;
+};
+
+void __pisa_seq_kv(struct seq_file *s, const char *title,
+		   const struct pisa_kv *st, unsigned int n);
+
+/* Print @title and fixed-width name/value pairs to debugfs seq_file @s. */
+#define pisa_seq_kv(s, title, ...)					\
+do {									\
+	const struct pisa_kv __st[] = { __VA_ARGS__ };			\
+									\
+	__pisa_seq_kv(s, title, __st, ARRAY_SIZE(__st));		\
+} while (0)
+
 #endif /* CONFIG_PISA */
 
 #if defined(CONFIG_PISA) && defined(CONFIG_IOMMU_DMA)
@@ -104,11 +122,13 @@ extern unsigned int pisa_domains_generation;
 
 void pisa_unmap_all_domains(struct pisa_meta *meta);
 int pisa_dev_dma_domain(struct device *dev, struct iommu_domain **domain);
+void pisa_domains_show(struct seq_file *s);
 int pisa_iova_declined(const struct pisa_iova *pi);
 
 #else /* !CONFIG_PISA || !CONFIG_IOMMU_DMA */
 
 static inline void pisa_unmap_all_domains(struct pisa_meta *meta) {}
+static inline void pisa_domains_show(struct seq_file *s) {}
 static inline int pisa_iova_declined(const struct pisa_iova *pi) { return -EOPNOTSUPP; }
 
 static inline int pisa_dev_dma_domain(struct device *dev, struct iommu_domain **domain)
include/linux/pisa.h +2 -0
index 92a4c529d1605..8ca1a459a2279 100644
@@ -101,6 +101,7 @@ bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,
 			     size_t size, size_t offset,
 			     enum dma_data_direction dir, bool pinned);
 bool pisa_page_tx_ok(const struct page *page);
+void pisa_stats_inc_user_copy(void);
 
 static inline bool pisa_enabled(void)
 {
@@ -287,6 +288,7 @@ static inline bool pisa_upgrade_user_pages(struct iov_iter *iter,
 }
 
 static inline bool pisa_page_tx_ok(const struct page *page) { return false; }
+static inline void pisa_stats_inc_user_copy(void) {}
 
 #endif /* CONFIG_PISA */
 
mm/pisa-alloc.c +245 -25

510 lines not on this page · raw message

mm/pisa-kunit.c +3 -3
index c195fdfdbd9fa..98f06a7f2db7f 100644
@@ -389,9 +389,9 @@ static int fake_domain_setup(struct kunit *test)
 
 static void test_map_and_domain_lifecycle(struct kunit *test)
 {
+	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	struct device dev = { .init_name = "pisa_map_kunit", .numa_node = NUMA_NO_NODE,
 			      .coherent_dma_mask = DMA_BIT_MASK(64) };
-	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	struct pisa_iova *pi;
 	struct pisa_meta *meta;
 	struct pisa_alloc *pa;
@@ -676,9 +676,9 @@ static void test_gfp_pisa(struct kunit *test)
 
 static void test_reservoir_and_scrubber(struct kunit *test)
 {
+	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	unsigned int old_res = READ_ONCE(pisa_reservoir_max);
 	unsigned int old_scrub = READ_ONCE(pisa_scrub_max);
-	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	struct pisa_meta *meta;
 	struct pisa_alloc *pa;
 	struct page *p;
@@ -711,9 +711,9 @@ static void test_reservoir_and_scrubber(struct kunit *test)
 			WRITE_ONCE(pisa_scrub_max, 512);
 			pisa_scrub_node(pa->nid);
 			KUNIT_EXPECT_EQ(test, meta->nr_dirty, 0U);
+			KUNIT_EXPECT_GE(test, pa->stats.block_scrub, 1ULL);
 		}
 	}
-	pisa_shrink_scan(NULL, &sc);
 
 	/* Trim reservoirs back to 0. */
 	for_each_node_state(nid, N_MEMORY)
mm/pisa-node.c +40 -0
index aa4f8759ae5e8..e1ae834d0f9b6 100644
@@ -19,6 +19,7 @@
 #include <linux/rcupdate.h>
 #include <linux/sched.h>
 #include <linux/sched/mm.h>
+#include <linux/seq_file.h>
 #include <linux/set_memory.h>
 #include <linux/spinlock.h>
 #include <linux/topology.h>
@@ -228,6 +229,7 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 	/* Still shared with the host, or possibly still mapped by a device. */
 	if (flags & (PISA_DECRYPTED | PISA_QUARANTINED))
 		return;
+
 	atomic_long_dec(&pisa_nr_pages);
 	for (unsigned int i = 0; i < PISA_BLOCKS(order); i++) {
 		struct page *block = page + (i << order);
@@ -296,6 +298,7 @@ static void pisa_reservoir_refill_node(struct pisa_node *node, int nid)
 		meta = __pisa_page_alloc(GFP_KERNEL | __GFP_THISNODE, nid, true,
 					 pisa_want_decrypt(), &clean);
 		if (IS_ERR(meta)) {
+			pisa_stat_inc(node->stats.refill_err);
 			pisa_alloc_backoff(node, false);
 			break;
 		}
@@ -310,6 +313,7 @@ static void pisa_reservoir_refill_node(struct pisa_node *node, int nid)
 		if (added) {
 			list_add(&meta->list, &node->pages);
 			WRITE_ONCE(node->nr_pages, node->nr_pages + 1);
+			pisa_stat_inc(node->stats.refill);
 		}
 		spin_unlock_irqrestore(&node->lock, flags);
 		if (!added) {
@@ -334,6 +338,7 @@ static void pisa_reservoir_trim_node(struct pisa_node *node, unsigned int max)
 		if (meta) {
 			list_del_init(&meta->list);
 			WRITE_ONCE(node->nr_pages, node->nr_pages - 1);
+			pisa_stat_inc(node->stats.trim);
 		}
 		spin_unlock_irqrestore(&node->lock, flags);
 		if (!meta)
@@ -434,6 +439,7 @@ static struct pisa_meta *pisa_reservoir_pop_node(int nid, unsigned int max, bool
 	if (meta && !!(meta->flags & PISA_DECRYPTED) == decrypt) {
 		list_del_init(&meta->list);
 		WRITE_ONCE(node->nr_pages, node->nr_pages - 1);
+		pisa_stat_inc(node->stats.hit);
 		refill = node->nr_pages <= max / 2;
 	} else {
 		meta = NULL;
@@ -462,6 +468,7 @@ struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool decrypt, bool *cle
 			*clean = true;
 			return meta;
 		}
+		pisa_stat_atomic_inc(pisa_nodes[nid].stats.miss);
 	}
 
 	/* Back off briefly on GFP_ATOMIC if previous allocation on @nid failed. */
@@ -525,3 +532,36 @@ void __init pisa_node_init(void)
 		INIT_WORK(&pisa_nodes[nid].work, pisa_node_work_fn);
 	}
 }
+
+/* Print the reservoir of each node that has seen any activity. */
+void pisa_reservoir_show(struct seq_file *s)
+{
+	bool header = false;
+	char pages[16];
+	int nid;
+
+	for_each_node_state(nid, N_MEMORY) {
+		struct pisa_node *node = &pisa_nodes[nid];
+		unsigned int nr = READ_ONCE(node->nr_pages);
+		s64 refill = pisa_stat_read(node->stats.refill);
+		s64 refill_err = pisa_stat_read(node->stats.refill_err);
+		s64 miss = pisa_stat_atomic_read(node->stats.miss);
+		char title[16];
+
+		/* Pages served or trimmed were refilled first. */
+		if (!nr && !refill && !refill_err && !miss)
+			continue;
+		if (!header) {
+			snprintf(pages, sizeof(pages), "pages_%luM", PISA_SIZE >> 20);
+			seq_puts(s, "reservoir\n");
+			header = true;
+		}
+		snprintf(title, sizeof(title), "node_%d", nid);
+		pisa_seq_kv(s, title, { pages, nr },
+			    { "hit", pisa_stat_read(node->stats.hit) },
+			    { "miss", miss });
+		pisa_seq_kv(s, title, { "refill", refill },
+			    { "refill_err", refill_err },
+			    { "trim", pisa_stat_read(node->stats.trim) });
+	}
+}
mm/pisa-priv.h +55 -2

79 lines not on this page · raw message

mm/pisa-user.c +67 -4

135 lines not on this page · raw message

net/core/pisa-net.c +2 -0
index 6422c472029a1..2ff90511cb7ae 100644
@@ -256,6 +256,8 @@ bool __pisa_zc_iter_stop(struct sk_buff *skb, struct iov_iter *from,
 		return false;
 	}
 
+	if (skb->len == orig_len)
+		pisa_stats_inc_user_copy();
 	/* -EXDEV tells tcp_sendmsg_locked() to copy this chunk instead of zerocopy. */
 	*copied = (skb->len != orig_len) ? 0 : -EXDEV;
 	return true;
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#97 lore raw

Re: [RFC PATCH v3 21/25] mm: Add PISA statistics and debugfs

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm: test_reservoir_and_scrubber() drains all blocks before scrubbing --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm: test_reservoir_and_scrubber() drains all blocks before scrubbing
--

commit ccfc0b438a0acbf15484d4c2bbaaca5a2185d2d6
Author: Luigi Rizzo <[email protected]>

mm: Add PISA statistics and debugfs

This commit adds per-allocator, per-node reservoir, user-page migration, IOMMU domain, and reclaim statistics for PISA, and exposes them via /sys/kernel/debug/pisa/allocs.

Quoted 4 lines
mm/pisa-kunit.c +0 -0
index c195fdfdbd9fa..98f06a7f2db7f 100644

[ ... ]

mm/pisa-kunit.c static void test_reservoir_and_scrubber(struct kunit *test) · line 716

Quoted 7 lines
mm/pisa-kunit.c +1 -0
@@ -711,9 +711,9 @@ static void test_reservoir_and_scrubber(struct kunit *test)
 			WRITE_ONCE(pisa_scrub_max, 512);
 			pisa_scrub_node(pa->nid);
 			KUNIT_EXPECT_EQ(test, meta->nr_dirty, 0U);
+			KUNIT_EXPECT_GE(test, pa->stats.block_scrub, 1ULL);
 		}
 	}

[Severity: Medium]
Will pisa_scrub_node() always skip meta in test_reservoir_and_scrubber() when init_on_free is disabled?

The test allocates a single block p, frees it, and drains pa->pcp before calling pisa_scrub_node(). Because every block of meta is now free, pisa_place_meta() moves meta onto pa->idle. However, pisa_alloc_scrub_blocks() -> pisa_pick_dirty_meta() only searches pa->partial_dirty and pa->partial, leaving pa->idle untouched:

mm/pisa-alloc.c:pisa_pick_dirty_meta() {
	meta = list_first_entry_or_null(&pa->partial_dirty, struct pisa_meta, list);
	if (meta)
		return meta;

	list_for_each_entry(meta, &pa->partial, list) {
		if (meta->nr_dirty)
			return meta;
	}

	/* Idle pages are left alone: scrubbing one would restart its idle clock. */
	return NULL;
}

As a result, pisa_alloc_scrub_blocks() clears pa->scrub_demand and returns without scrubbing meta, causing both KUNIT_EXPECT_EQ(test, meta->nr_dirty, 0U) and KUNIT_EXPECT_GE(test, pa->stats.block_scrub, 1ULL) to fail. Keeping a second block allocated from meta until after pisa_scrub_node() runs would keep meta on pa->partial so the scrubber processes it.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
#98 lore raw

RFC PATCH v3 22/25 net/libeth: Use GFP_KERNEL when pre-filling RX rings

In reply to Luigi Rizzo

libeth_rx_alloc() is called both when pre-filling RX fill queues in process context (for indices 0 .. fq->count - 2, when buf->truesize is still 0) and when refilling RX buffers from NAPI softirq.

Use GFP_KERNEL during the initial process-context ring fill so page_pool and PISA page allocations (including set_memory_decrypted() under CoCo) are not forced into GFP_ATOMIC context.

---
 include/net/libeth/rx.h | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
include/net/libeth/rx.h +9 -2
index 0e736846c5e8a..4361dbcf03cb1 100644
@@ -106,10 +106,17 @@ void libeth_rx_fq_destroy(struct libeth_fq *fq);
 static inline dma_addr_t libeth_rx_alloc(const struct libeth_fq_fp *fq, u32 i)
 {
 	struct libeth_fqe *buf = &fq->fqes[i];
+	/* fq->fqes is zero-allocated and pre-filled in process context for
+	 * indices [0 .. fq->count - 2]; slot fq->count - 1 is first allocated
+	 * in NAPI. Use GFP_KERNEL for initial pre-fill and GFP_ATOMIC after.
+	 */
+	gfp_t gfp = (buf->truesize || i == fq->count - 1 || in_softirq()) ?
+		    GFP_ATOMIC : GFP_KERNEL;
 
 	buf->truesize = fq->truesize;
-	buf->netmem = page_pool_dev_alloc_netmem(fq->pp, &buf->offset,
-						 &buf->truesize);
+	buf->netmem = page_pool_alloc_netmem(fq->pp, &buf->offset,
+					     &buf->truesize,
+					     gfp | __GFP_NOWARN);
 	if (unlikely(!buf->netmem))
 		return DMA_MAPPING_ERROR;
 
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#99 lore raw

RFC PATCH v3 23/25 net/gve: Use GFP_KERNEL when pre-filling RX rings

In reply to Luigi Rizzo

When pre-filling DQO and GQI RX rings in process context before NAPI is enabled (e.g. gve_open), use GFP_KERNEL instead of GFP_ATOMIC so page allocation (and CoCo page decryption) can sleep instead of dipping into atomic reserves.

---
 drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c |  8 +++++++-
 drivers/net/ethernet/google/gve/gve_rx.c              | 10 +++++-----
 2 files changed, 12 insertions(+), 6 deletions(-)
drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c +7 -1
index 6880d1531ba5e..a3fe684ca087a 100644
@@ -223,13 +223,19 @@ void gve_free_to_page_pool(struct gve_rx_ring *rx,
 static int gve_alloc_from_page_pool(struct gve_rx_ring *rx,
 				    struct gve_rx_buf_state_dqo *buf_state)
 {
+	/*
+	 * Use GFP_KERNEL when pre-filling RX rings in process context (e.g.
+	 * gve_open) so PISA metadata init and CoCo page decryption can sleep.
+	 */
+	gfp_t gfp = (gve_get_napi_enabled(rx->gve) || in_softirq()) ?
+		    GFP_ATOMIC : GFP_KERNEL;
 	netmem_ref netmem;
 
 	buf_state->page_info.buf_size = rx->packet_buffer_truesize;
 	netmem = page_pool_alloc_netmem(rx->dqo.page_pool,
 					&buf_state->page_info.page_offset,
 					&buf_state->page_info.buf_size,
-					GFP_ATOMIC);
+					gfp);
 
 	if (!netmem)
 		return -ENOMEM;
drivers/net/ethernet/google/gve/gve_rx.c +5 -5
index 81ea800e66e94..7c201fd513ee3 100644
@@ -159,14 +159,13 @@ static void gve_setup_rx_buffer(struct gve_rx_ring *rx,
 static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev,
 			       struct gve_rx_slot_page_info *page_info,
 			       union gve_rx_data_slot *data_slot,
-			       struct gve_rx_ring *rx)
+			       struct gve_rx_ring *rx, gfp_t gfp)
 {
 	struct page *page;
 	dma_addr_t dma;
 	int err;
 
-	err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE,
-			     GFP_ATOMIC);
+	err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE, gfp);
 	if (err) {
 		u64_stats_update_begin(&rx->statss);
 		rx->rx_buf_alloc_fail++;
@@ -209,7 +208,7 @@ static int gve_rx_prefill_pages(struct gve_rx_ring *rx,
 		}
 		err = gve_rx_alloc_buffer(priv, &priv->pdev->dev,
 					  &rx->data.page_info[i],
-					  &rx->data.data_ring[i], rx);
+					  &rx->data.data_ring[i], rx, GFP_KERNEL);
 		if (err)
 			goto alloc_err_rda;
 	}
@@ -986,7 +985,8 @@ static bool gve_rx_refill_buffers(struct gve_priv *priv, struct gve_rx_ring *rx)
 				gve_rx_free_buffer(dev, page_info, data_slot);
 				page_info->page = NULL;
 				if (gve_rx_alloc_buffer(priv, dev, page_info,
-							data_slot, rx)) {
+							data_slot, rx,
+							GFP_ATOMIC)) {
 					break;
 				}
 			}
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#100 lore raw

RFC PATCH v3 24/25 net/gve: Use PISA memory for RX buffers

In reply to Luigi Rizzo

When dev->pisa_rx_bufs is enabled, allocate GQI-RDA RX packet buffers with pisa_rx_gfp(dev) so they come from the per-node PISA allocator, and evict plain pages when a free PISA RX block is available; DQO-RDA uses page_pool, which checks dev->pisa_rx_bufs directly.

---
 drivers/net/ethernet/google/gve/gve_rx.c | 34 ++++++++++++++++--------
 1 file changed, 23 insertions(+), 11 deletions(-)
drivers/net/ethernet/google/gve/gve_rx.c +23 -11
index 7c201fd513ee3..562c11f5bdd24 100644
@@ -4,6 +4,7 @@
  * Copyright (C) 2015-2021 Google, Inc.
  */
 
+#include <linux/pisa.h>
 #include "gve.h"
 #include "gve_adminq.h"
 #include "gve_utils.h"
@@ -165,6 +166,8 @@ static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev,
 	dma_addr_t dma;
 	int err;
 
+	if (rx->data.raw_addressing)
+		gfp |= pisa_rx_gfp(dev);
 	err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE, gfp);
 	if (err) {
 		u64_stats_update_begin(&rx->statss);
@@ -494,13 +497,19 @@ static void gve_rx_flip_buff(struct gve_rx_slot_page_info *page_info, __be64 *sl
 	*(slot_addr) ^= offset;
 }
 
-static int gve_rx_can_recycle_buffer(struct gve_rx_slot_page_info *page_info)
+static int gve_rx_can_recycle_buffer(struct gve_rx_ring *rx,
+				     struct gve_rx_slot_page_info *page_info)
 {
 	int pagecount = page_count(page_info->page);
 
 	/* This page is not being used by any SKBs - reuse */
-	if (pagecount == page_info->pagecnt_bias)
+	if (pagecount == page_info->pagecnt_bias) {
+		if (rx && rx->data.raw_addressing &&
+		    !is_pisa_page(page_info->page) &&
+		    pisa_has_free_blocks_rx(&rx->gve->pdev->dev, 0, rx->gve->numa_node))
+			return 0;
 		return 1;
+	}
 	/* This page is still being used by an SKB - we can't reuse */
 	else if (pagecount > page_info->pagecnt_bias)
 		return 0;
@@ -544,7 +553,7 @@ static struct sk_buff *gve_rx_copy_to_pool(struct gve_rx_ring *rx,
 
 	copy_page_info = &rx->qpl_copy_pool[pool_idx];
 	if (!copy_page_info->can_flip) {
-		int recycle = gve_rx_can_recycle_buffer(copy_page_info);
+		int recycle = gve_rx_can_recycle_buffer(NULL, copy_page_info);
 
 		if (unlikely(recycle < 0)) {
 			gve_schedule_reset(rx->gve);
@@ -664,7 +673,7 @@ static struct sk_buff *gve_rx_skb(struct gve_priv *priv, struct gve_rx_ring *rx,
 			u64_stats_update_end(&rx->statss);
 		}
 	} else {
-		int recycle = gve_rx_can_recycle_buffer(page_info);
+		int recycle = gve_rx_can_recycle_buffer(rx, page_info);
 
 		if (unlikely(recycle < 0)) {
 			gve_schedule_reset(priv);
@@ -970,7 +979,7 @@ static bool gve_rx_refill_buffers(struct gve_priv *priv, struct gve_rx_ring *rx)
 			 * owns half the page it is impossible to tell which half. Either
 			 * the whole page is free or it needs to be replaced.
 			 */
-			int recycle = gve_rx_can_recycle_buffer(page_info);
+			int recycle = gve_rx_can_recycle_buffer(rx, page_info);
 
 			if (recycle < 0) {
 				if (!rx->data.raw_addressing)
@@ -982,13 +991,16 @@ static bool gve_rx_refill_buffers(struct gve_priv *priv, struct gve_rx_ring *rx)
 				union gve_rx_data_slot *data_slot =
 						&rx->data.data_ring[idx];
 				struct device *dev = &priv->pdev->dev;
-				gve_rx_free_buffer(dev, page_info, data_slot);
-				page_info->page = NULL;
-				if (gve_rx_alloc_buffer(priv, dev, page_info,
-							data_slot, rx,
-							GFP_ATOMIC)) {
+				struct gve_rx_slot_page_info new_info = {};
+				union gve_rx_data_slot new_slot;
+
+				if (gve_rx_alloc_buffer(priv, dev, &new_info,
+							&new_slot, rx,
+							GFP_ATOMIC))
 					break;
-				}
+				gve_rx_free_buffer(dev, page_info, data_slot);
+				*page_info = new_info;
+				*data_slot = new_slot;
 			}
 		}
 		fill_cnt++;
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#101 lore raw

RFC PATCH v3 25/25 Documentation: Add PISA architecture documentation

In reply to Luigi Rizzo

Document the PISA IOMMU 2MB-hugepage-backed DMA memory subsystem in Documentation/core-api/pisa.rst.

---
 .../admin-guide/kernel-parameters.txt         |   7 +
 Documentation/core-api/index.rst              |   1 +
 Documentation/core-api/pisa.rst               | 485 ++++++++++++++++++
 3 files changed, 493 insertions(+)
 create mode 100644 Documentation/core-api/pisa.rst
Documentation/admin-guide/kernel-parameters.txt +7 -0
index 176648941aec2..cce75a9abddad 100644
@@ -5345,6 +5345,13 @@ Kernel parameters
 	pirq=		[SMP,APIC] Manual mp-table setup
 			See Documentation/arch/x86/i386/IO-APIC.rst.
 
+	pisa.*=		[ARM64,X86-64] Pre-mapped IOVA Superpage Allocator (PISA)
+			tuning parameters (max_pages, max_idle, idle_ms,
+			reservoir_max, scrub_max, compact,
+			target_usage_percent, old_ms, pcp_batch, user_max_pages,
+			scrub_migrate).
+			See Documentation/core-api/pisa.rst.
+
 	plip=		[PPT,NET] Parallel port network link
 			Format: { parport<nr> | timid | 0 }
 			See also Documentation/admin-guide/parport.rst.
Documentation/core-api/index.rst +1 -0
index 92f91c6a0d79d..4955f477ed797 100644
@@ -113,6 +113,7 @@ more memory-management documentation in Documentation/mm/index.rst.
    dma-attributes
    dma-isa-lpc
    swiotlb
+   pisa
    mm-api
    cgroup
    genalloc
Documentation/core-api/pisa.rst new file +485 -0

485 lines not on this page · raw message

Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#102 lore raw

Re: [RFC PATCH v3 25/25] Documentation: Add PISA architecture documentation

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] docs: pisa.rst claims CoCo disables pisa_tx_skb_heads but code does not --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] docs: pisa.rst claims CoCo disables pisa_tx_skb_heads but code does not
--

commit 6f86ffee9c2de79fdda7c37ed8b420a9db3ff92f
Author: Luigi Rizzo <[email protected]>

Documentation: Add PISA architecture documentation

This commit adds core API documentation and a kernel-parameters.txt entry for the Pre-mapped IOVA Superpage Allocator (PISA).

Quoted 5 lines
Documentation/core-api/pisa.rst new file +0 -0
new file mode 100644
index 0000000000000..f9690b4a9c96a

[ ... ]

Documentation/core-api/pisa.rst line 395

Quoted 9 lines

+- **Small skb heads**

Documentation/core-api/pisa.rst new file +8 -0
+
+  - PISA is enabled per device via ``pisa_tx_skb_heads``,
+    which allows small skb heads to come from an ``skbuff_small_head_pisa`` slab cache,
+    backed by PISA memory mapped ``DMA_TO_DEVICE``.
+    PISA memory is only used in the cases listed earlier.
+
+    One exception, PISA memory is never used for skb small heads in Confidential
+    Computing because it would expose kernel pointers and callback structures.

[Severity: Medium]
Does the implementation enforce this Confidential Computing restriction for pisa_tx_skb_heads?

Neither net_pisa_tx_skb_heads_set() nor pisa_tx_flags() in net/core/pisa-net.c checks pisa_decrypt_enabled() or force_dma_unencrypted(), and __pisa_alloc_folio() in mm/pisa-alloc.c allocates SLAB_CACHE_PISA_RO folios from PISA pages that are decrypted in Confidential Computing guests. If pisa_tx_skb_heads is enabled on a device in a Confidential Computing guest, small skb heads (including skb_shared_info pointers and callback structures) are allocated from decrypted host-shared PISA pages rather than falling back to swiotlb.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25
#103 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

In reply to Luigi Rizzo
Quoted 3 lines · Luigi Rizzo

This is v3 of the RFC previously posted as DMA_PMD [0], now renamed PISA ("Pre-mapped IOVA Superpage Allocator"). The text below follows Documentation/core-api/pisa.rst (patch 25/25), which has the details.

I thought the conclusion was to just do this stuff in netdev pagepool, now you come with an enormous AI series spread across the entire kernel?

Quoted 2 lines

- Needs bounce buffers: in Confidential Computing VMs, PISA allocators pre-decrypt 2MB pages in place, avoiding swiotlb bounce-buffer copies.

It seems this was ignored too. We want the bounce buffers in CC. They serve a security purpose. You cannot loose control of the shared memory buffers have have them leak into SKBs, user mappings and so on. It is not secure.

I don't see how any of this is valuable or necessary for CC, especially when we really don't even expect to have an vIOMMU for CC very often..

Jason

#104 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

Quoted 8 lines · Jason Gunthorpe
Quoted 3 lines · Luigi Rizzo

This is v3 of the RFC previously posted as DMA_PMD [0], now renamed PISA ("Pre-mapped IOVA Superpage Allocator"). The text below follows Documentation/core-api/pisa.rst (patch 25/25), which has the details.

I thought the conclusion was to just do this stuff in netdev pagepool, now you come with an enormous AI series spread across the entire kernel?

Welcome to 2026 :) It's so exhausting.

Quoted 9 lines
Quoted 3 lines

- Needs bounce buffers: in Confidential Computing VMs, PISA allocators pre-decrypt 2MB pages in place, avoiding swiotlb bounce-buffer copies.

It seems this was ignored too. We want the bounce buffers in CC. They serve a security purpose. You cannot loose control of the shared memory buffers have have them leak into SKBs, user mappings and so on. It is not secure.

Quoted 5 lines

I don't see how any of this is valuable or necessary for CC, especially when we really don't even expect to have an vIOMMU for CC very often..

Jason

Agreed, this whole thing needs to be rethought.

Will reply separately to the cover I think :)

--
Cheers, Lorenzo

#105 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

In reply to Jason Gunthorpe
Quoted 9 lines · Jason Gunthorpe
Quoted 3 lines · Luigi Rizzo

This is v3 of the RFC previously posted as DMA_PMD [0], now renamed PISA ("Pre-mapped IOVA Superpage Allocator"). The text below follows Documentation/core-api/pisa.rst (patch 25/25), which has the details.

I thought the conclusion was to just do this stuff in netdev pagepool, now you come with an enormous AI series spread across the entire kernel?

There were surely comments claiming nothing outside net/ cares or needs this.

I respectfully disagree, witness is the fact that e.g. there was already an io_uring proposal which is smaller, but does not address applications that want to use the standard disk I/O paths (libaio, buffer cache etc)

Nothing has changed from the initial series in terms of size, use cases or subsystems involved. Large files are placed where they should, the series covers the same three use cases (disk, network, CoCo), and touches three parts which it has to touch: mm (most of it; it is a memory allocator
extension after all), dma (it hooks into map and unmap, not a large change) and net (the pagepool change is a couple of lines; the tx path needs to touch more places because the current stack assumes all paths have the same I/O requirements).

For CoCo, there are very fine grained controls so the bounce buffers can be enabled only when they don't pose a risk, which in turn depends on the threat model.

Specifically, for network tx buffers or disk writes, the user-to-kernel copy is basically a bounce buffer provided it is used correctly and not leaked elsewhere (which is the design; of course the implementation needs to be verified and possibly fixed so that it matches the design).

cheers
luigi

Quoted 13 lines
Quoted 2 lines

- Needs bounce buffers: in Confidential Computing VMs, PISA allocators pre-decrypt 2MB pages in place, avoiding swiotlb bounce-buffer copies.

It seems this was ignored too. We want the bounce buffers in CC. They serve a security purpose. You cannot loose control of the shared memory buffers have have them leak into SKBs, user mappings and so on. It is not secure.

I don't see how any of this is valuable or necessary for CC, especially when we really don't even expect to have an vIOMMU for CC very often..

Jason

maintainer NAK
#106 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

Quoted 31 lines · Luigi Rizzo
Quoted 9 lines · Jason Gunthorpe
Quoted 3 lines · Luigi Rizzo

This is v3 of the RFC previously posted as DMA_PMD [0], now renamed PISA ("Pre-mapped IOVA Superpage Allocator"). The text below follows Documentation/core-api/pisa.rst (patch 25/25), which has the details.

I thought the conclusion was to just do this stuff in netdev pagepool, now you come with an enormous AI series spread across the entire kernel?

There were surely comments claiming nothing outside net/ cares or needs this.

I respectfully disagree, witness is the fact that e.g. there was already an io_uring proposal which is smaller, but does not address applications that want to use the standard disk I/O paths (libaio, buffer cache etc)

Nothing has changed from the initial series in terms of size, use cases or subsystems involved. Large files are placed where they should, the series covers the same three use cases (disk, network, CoCo), and touches three parts which it has to touch: mm (most of it; it is a memory allocator
extension after all), dma (it hooks into map and unmap, not a large change) and net (the pagepool change is a couple of lines; the tx path needs to touch more places because the current stack assumes all paths have the same I/O requirements).

For CoCo, there are very fine grained controls so the bounce buffers can be enabled only when they don't pose a risk, which in turn depends on the threat model.

Quoted 7 lines

Specifically, for network tx buffers or disk writes, the user-to-kernel copy is basically a bounce buffer provided it is used correctly and not leaked elsewhere (which is the design; of course the implementation needs to be verified and possibly fixed so that it matches the design).

cheers
luigi

NAK.

Cheers, Lorenzo

--
Cheers, Lorenzo

#107 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

In reply to Luigi Rizzo
Quoted 31 lines · Luigi Rizzo
Quoted 9 lines · Jason Gunthorpe
Quoted 3 lines · Luigi Rizzo

This is v3 of the RFC previously posted as DMA_PMD [0], now renamed PISA ("Pre-mapped IOVA Superpage Allocator"). The text below follows Documentation/core-api/pisa.rst (patch 25/25), which has the details.

I thought the conclusion was to just do this stuff in netdev pagepool, now you come with an enormous AI series spread across the entire kernel?

There were surely comments claiming nothing outside net/ cares or needs this.

I respectfully disagree, witness is the fact that e.g. there was already an io_uring proposal which is smaller, but does not address applications that want to use the standard disk I/O paths (libaio, buffer cache etc)

Nothing has changed from the initial series in terms of size, use cases or subsystems involved. Large files are placed where they should, the series covers the same three use cases (disk, network, CoCo), and touches three parts which it has to touch: mm (most of it; it is a memory allocator
extension after all), dma (it hooks into map and unmap, not a large change) and net (the pagepool change is a couple of lines; the tx path needs to touch more places because the current stack assumes all paths have the same I/O requirements).

For CoCo, there are very fine grained controls so the bounce buffers can be enabled only when they don't pose a risk, which in turn depends on the threat model.

Quoted 7 lines

Specifically, for network tx buffers or disk writes, the user-to-kernel copy is basically a bounce buffer provided it is used correctly and not leaked elsewhere (which is the design; of course the implementation needs to be verified and possibly fixed so that it matches the design).

cheers
luigi

Hi Luigi, Hi Jason,

I've been lurking but following this series since the start. I am torn. On s390 where the IOMMU is always enabled on our closest equivalent to bare metal (non paging LPAR hypervisor), and where we also default to an emulated IOMMU in KVM guests, the underlying problem is a real pain. We're also in the process of enabling large IOMMU mappings via the generic_pt API which are 1M and 2G on s390. So, the idea of making better use of larger mappings is very attractive to us and I applaud you for trying to tackle this very real issue.

That said I do have to agree with the critique. This series is too invasive, too unclear in its layering, and most importantly it feels like you're trying to do everything in a big swoop ignoring advice from the maintainers just because it would limit the scope of a first step.

I also don't think Jason's point is that nothing outside net/ cares, I think, it's rather that the IOMMU and DMA layers already offer the tools and each subsystem needs to use the right combination for its specific requirements. And if a tool is missing this needs to be stated very precisely including how the addition keeps layering intact.

I don't claim to have a simple solution to offer, if I did I would have sent patches already, but let me state my thoughts. First I think this really needs an iterative approach with much smaller self contained steps and focus on specific issues. With that, I think this should focus on the network stack, while the io_uring specific proposal can go after the block layer. Also in my experience networking is where this hurts most.

Now, I wonder if we can't start with something simple. What if the page pool could start by allocating in batches of PMD sized and aligned folios of contiguous pages that can share a single large IOMMU translation. The page pool can then still hand out pages from that batch without having to do sub-page allocation but would already use much fewer IOTLB entries and the locality might even help non IOMMU workloads. So, I'd even hope this could be enabled by default and this is actually something I don't like about this series, I really don't like having a tunable when we know that larger IOMMU mappings are strictly better when you have an IOMMU that supports them.

I think that approach would also align with Jason's idea to keep things within the network stack and to work with the tools we have until their limits become very clear.

Thanks,
Niklas

Quoted 1 line
Quoted 1 line
#108 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

Quoted 82 lines · Niklas Schnelle
Quoted 31 lines · Luigi Rizzo
Quoted 9 lines · Jason Gunthorpe
Quoted 3 lines · Luigi Rizzo

This is v3 of the RFC previously posted as DMA_PMD [0], now renamed PISA ("Pre-mapped IOVA Superpage Allocator"). The text below follows Documentation/core-api/pisa.rst (patch 25/25), which has the details.

I thought the conclusion was to just do this stuff in netdev pagepool, now you come with an enormous AI series spread across the entire kernel?

There were surely comments claiming nothing outside net/ cares or needs this.

I respectfully disagree, witness is the fact that e.g. there was already an io_uring proposal which is smaller, but does not address applications that want to use the standard disk I/O paths (libaio, buffer cache etc)

Nothing has changed from the initial series in terms of size, use cases or subsystems involved. Large files are placed where they should, the series covers the same three use cases (disk, network, CoCo), and touches three parts which it has to touch: mm (most of it; it is a memory allocator
extension after all), dma (it hooks into map and unmap, not a large change) and net (the pagepool change is a couple of lines; the tx path needs to touch more places because the current stack assumes all paths have the same I/O requirements).

For CoCo, there are very fine grained controls so the bounce buffers can be enabled only when they don't pose a risk, which in turn depends on the threat model.

Quoted 7 lines

Specifically, for network tx buffers or disk writes, the user-to-kernel copy is basically a bounce buffer provided it is used correctly and not leaked elsewhere (which is the design; of course the implementation needs to be verified and possibly fixed so that it matches the design).

cheers
luigi

Hi Luigi, Hi Jason,

I've been lurking but following this series since the start. I am torn. On s390 where the IOMMU is always enabled on our closest equivalent to bare metal (non paging LPAR hypervisor), and where we also default to an emulated IOMMU in KVM guests, the underlying problem is a real pain. We're also in the process of enabling large IOMMU mappings via the generic_pt API which are 1M and 2G on s390. So, the idea of making better use of larger mappings is very attractive to us and I applaud you for trying to tackle this very real issue.

That said I do have to agree with the critique. This series is too invasive, too unclear in its layering, and most importantly it feels like you're trying to do everything in a big swoop ignoring advice from the maintainers just because it would limit the scope of a first step.

I also don't think Jason's point is that nothing outside net/ cares, I think, it's rather that the IOMMU and DMA layers already offer the tools and each subsystem needs to use the right combination for its specific requirements. And if a tool is missing this needs to be stated very precisely including how the addition keeps layering intact.

I don't claim to have a simple solution to offer, if I did I would have sent patches already, but let me state my thoughts. First I think this really needs an iterative approach with much smaller self contained steps and focus on specific issues. With that, I think this should focus on the network stack, while the io_uring specific proposal can go after the block layer. Also in my experience networking is where this hurts most.

Now, I wonder if we can't start with something simple. What if the page pool could start by allocating in batches of PMD sized and aligned folios of contiguous pages that can share a single large IOMMU translation. The page pool can then still hand out pages from that batch without having to do sub-page allocation but would already use much fewer IOTLB entries and the locality might even help non IOMMU workloads. So, I'd even hope this could be enabled by default and this is actually something I don't like about this series, I really don't like having a tunable when we know that larger IOMMU mappings are strictly better when you have an IOMMU that supports them.

Quoted 3 lines

I think that approach would also align with Jason's idea to keep things within the network stack and to work with the tools we have until their limits become very clear.

Hi Niklas,

I have been working on this idea exactly - extending the network page-pool with a memory provider that allocates large pages, splitting them into N smaller pages that all share a single IOMMU entry. I breifly shared my approach in the v1 PMD series [1]. I'm readying a short RFC to share shortly, would appreciate your feedback.

[1] https://lore.kernel.org/netdev/CAMP57yWvHO0pWCR3-9q1gtwVe8WV4Y6i69trmw+BJRVYf3JB1g@mail.gmail.com/

Quoted 4 lines

Thanks,
Niklas

Quoted 1 line
Quoted 1 line
#109 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

Quoted 6 lines · Naman Gulati
Quoted 5 lines · Niklas Schnelle
Quoted 3 lines · Luigi Rizzo
Quoted 2 lines · Jason Gunthorpe

On Fri, Nov 20, 2026 at 01:06:30AM +0000, Luigi Rizzo wrote:

Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
Quoted 7 lines
Quoted 3 lines

This is v3 of the RFC previously posted as DMA_PMD [0], now renamed PISA ("Pre-mapped IOVA Superpage Allocator"). The text below follows Documentation/core-api/pisa.rst (patch 25/25), which has the details.

I thought the conclusion was to just do this stuff in netdev pagepool, now you come with an enormous AI series spread across the entire kernel?

--- snip ---

Quoted 17 lines
Quoted 11 lines

Now, I wonder if we can't start with something simple. What if the page pool could start by allocating in batches of PMD sized and aligned folios of contiguous pages that can share a single large IOMMU translation. The page pool can then still hand out pages from that batch without having to do sub-page allocation but would already use much fewer IOTLB entries and the locality might even help non IOMMU workloads. So, I'd even hope this could be enabled by default and this is actually something I don't like about this series, I really don't like having a tunable when we know that larger IOMMU mappings are strictly better when you have an IOMMU that supports them.

Quoted 3 lines

I think that approach would also align with Jason's idea to keep things within the network stack and to work with the tools we have until their limits become very clear.

Hi Niklas,

Quoted 9 lines

I have been working on this idea exactly - extending the network page-pool with a memory provider that allocates large pages, splitting them into N smaller pages that all share a single IOMMU entry. I breifly shared my approach in the v1 PMD series [1]. I'm readying a short RFC to share shortly, would appreciate your feedback.

[1] https://lore.kernel.org/netdev/CAMP57yWvHO0pWCR3-9q1gtwVe8WV4Y6i69trmw+BJRVYf3JB1g@mail.gmail.com/

Hi Naman,

This does look more contained, but I'd say you should still go simpler and fewer steps per series. Some thoughts:

- Drop the CoCo aspect for now. The shadowing / virtio-iommu and IOTLB performance aspects stand on their own in my opinion and the focus makes it easier to review too. As Jason said it's then really just normal memory that was pre-mapped for DMA.
- I'm not a network stack expert but I think using the page pool for TX warrants its own series. Maybe just start with RX, this is also where we see the biggest performance issues and it would hopefully make the patches at least a bit more manageable.
- This is still a LOT of churn, my gut says much of the benefit should be possible with much less churn. It's really too much to follow but a cursory look makes me feel like there is duplication between rx and tx, which is weird since for the pre-mapping they should be quite similar. There also seems to be very little integration with the existing page pool, rather it seems to set up a parallel mechanism for the pre-mapped buffers. Really in a first step I think we "just" want to use a more efficient DMA mapping and contiguous memory chunks for the page pool and also keep the page pool API unchanged as much as possible.

These are only guesses from looking at the GitHub branch a bit, I did not dive super deep.

Thanks,
Niklas

Quoted 1 line
#110 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

Catching up on a few comments:

Quoted 3 lines · Niklas Schnelle
Quoted 1 line · Naman Gulati

On Mon, Nov 23, 2026 at 2:10 AM Niklas Schnelle <[email protected]> wrote:

...

Quoted 20 lines
Quoted 6 lines
Quoted 3 lines

I think that approach would also align with Jason's idea to keep things within the network stack and to work with the tools we have until their limits become very clear.

Hi Niklas,

Quoted 9 lines

I have been working on this idea exactly - extending the network page-pool with a memory provider that allocates large pages, splitting them into N smaller pages that all share a single IOMMU entry. I breifly shared my approach in the v1 PMD series [1]. I'm readying a short RFC to share shortly, would appreciate your feedback.

[1] https://lore.kernel.org/netdev/CAMP57yWvHO0pWCR3-9q1gtwVe8WV4Y6i69trmw+BJRVYf3JB1g@mail.gmail.com/

Hi Naman,

This does look more contained, but I'd say you should still go simpler and fewer steps per series. Some thoughts:

...

Quoted 9 lines

- This is still a LOT of churn, my gut says much of the benefit should be possible with much less churn. It's really too much to follow but a cursory look makes me feel like there is duplication between rx and tx, which is weird since for the pre-mapping they should be quite similar. There also seems to be very little integration with the existing page pool, rather it seems to set up a parallel mechanism for the pre-mapped buffers. Really in a first step I think we "just" want to use a more efficient DMA mapping and contiguous memory chunks for the page pool and also keep the page pool API unchanged as much as possible.

The implementations seem large because they expose limitations in the current kernel code (or our understanding of it; but the proof is in the pudding). Networking for one, since you mention it: the tx path allocates memory in many places without any hint on how the memory will be used (loopback or device with IOMMU ? cleartext or encrypted?).

If we limit to the easy parts (e.g. just network RX) we may avoid some churn but we will not resolve the problems arising
from reasonably strict IOMMU deployments on large systems:
- IOTLB thrashing (network traffic uses separate PTEs for
rx buffers, rx headers, tx_buffers, tx headers). Rx buffers
are only 25..50% of the total. See [1] for some data.
- per-buffer VM exits on overcommitted VMs (same problem as above)
- IOMMU unmap serialization (with strict DMA, I measured over 10us under load)
- swiotlb copy cost (on tx and a backlogged queue, most of the copies happen on the TX softirq handler).

Also we will not be able to see what is lacking in the current kernel code to address all the above.

What I wanted to do with my series (Request-For-Comment, for a reason) was to identify the components we presumably need (meaning: implement, or figure out where they already exist and actually do what we need) and get an idea of how intrusive the changes would be.

Then it is completely fair to say that the goal is not worth the effort and should not be pursued, or to take the low-hanging fruits out of it.

cheers
luigi

[1] Here is an experiment with a system using bidirectional TCP traffic on multiple NICs, where IOTLB thrashing becomes a bottleneck. Below is how total throughput (TCP payload TX+RX across all NICs) changes using 2MB mappings for different regions.
We really need to cover them all to recover the performance of identity mode

Use of 2MB mappings total TCP throughput Gbps
-----------------------------------------------------

none                                  440
rings                                 572
rx_buf rings                          577
rx_buf tx_hdr                         572
rx_buf tx_buf                         649
rx_buf rx_hdr                         674
rx_buf rx_hdr tx_buf                  716
rx_buf tx_buf tx_hdr                  734
rx_buf rx_hdr tx_buf tx_hdr rings     744
identity mode                         744

------------------------------------------------------

#111 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

In reply to Luigi Rizzo

TL;DR: NAK. All of it. (And yeah, I'm steeling myself for the inevitable 'oh Lorenzo' :)

Sigh. You know, it's hard being a maintainer, and it's twice as hard lately, given the endless surge of AI-generated stuff we see every day.

But I am especially frustrated that I have to ask people to do the _absolute basics_. And from people who are not helping with any of that. Quite the opposite.

So the basics - you haven't cc'd the right people here and you're sending a massive new series in-reply-to another. See below for some automatically generated feedback on that.

In any case, the courteous thing to do would be to familiarise yourself with how series are sent in mm. And that goes so much more for a series that is so invasive. And seemingly, AI generated...

And you're sending it when
https://lore.kernel.org/linux-mm/[email protected]/
is in effect.

Anyway, to the series itself....

This is ludicrous:

Quoted 58 lines
 .../admin-guide/kernel-parameters.txt         |    7 +
 Documentation/core-api/index.rst              |    1 +
 Documentation/core-api/pisa.rst               |  485 +++++
 arch/arm64/include/asm/pgtable.h              |   28 +-
 block/bio.c                                   |    9 +
 drivers/base/core.c                           |   78 +
 drivers/iommu/Makefile                        |    3 +
 drivers/iommu/dma-iommu.c                     |   49 +-
 drivers/iommu/iommu.c                         |    7 +-
 drivers/iommu/pisa-map.c                      |  488 +++++
 .../ethernet/google/gve/gve_buffer_mgmt_dqo.c |    8 +-
 drivers/net/ethernet/google/gve/gve_rx.c      |   40 +-
 include/linux/device.h                        |   32 +
 include/linux/gfp_types.h                     |   14 +-
 include/linux/huge_mm.h                       |    7 +
 include/linux/netdevice.h                     |    4 +
 include/linux/pisa-iommu.h                    |  141 ++
 include/linux/pisa-mm.h                       |  205 ++
 include/linux/pisa.h                          |  356 ++++
 include/linux/sched.h                         |    4 +
 include/linux/slab.h                          |   10 +
 include/linux/swap.h                          |    1 +
 include/net/libeth/rx.h                       |   11 +-
 include/net/pisa.h                            |  204 ++
 include/trace/events/mmflags.h                |   11 +-
 include/uapi/asm-generic/mman-common.h        |    2 +
 kernel/dma/direct.c                           |   11 +
 kernel/exit.c                                 |    2 +
 kernel/fork.c                                 |    2 +
 mm/Kconfig                                    |   35 +
 mm/Makefile                                   |    3 +
 mm/filemap.c                                  |   12 +-
 mm/huge_memory.c                              |   36 +-
 mm/ksm.c                                      |    3 +-
 mm/madvise.c                                  |   19 +
 mm/memory.c                                   |    8 +-
 mm/migrate.c                                  |    3 +-
 mm/page-writeback.c                           |    9 +
 mm/page_alloc.c                               |   10 +
 mm/pisa-alloc.c                               | 1758 +++++++++++++++++
 mm/pisa-kunit.c                               |  778 ++++++++
 mm/pisa-meta.c                                |  834 ++++++++
 mm/pisa-node.c                                |  567 ++++++
 mm/pisa-priv.h                                |  319 +++
 mm/pisa-user.c                                |  898 +++++++++
 mm/readahead.c                                |    3 +-
 mm/slab.h                                     |    3 +-
 mm/slab_common.c                              |    2 +-
 mm/slub.c                                     |   23 +-
 mm/swapfile.c                                 |    3 +-
 mm/userfaultfd.c                              |    7 +-
 net/core/Makefile                             |    1 +
 net/core/datagram.c                           |   17 +-
 net/core/page_pool.c                          |    3 +
 net/core/pisa-net.c                           |  264 +++
 net/core/skbuff.c                             |   33 +-
 net/core/sock.c                               |   31 +-
 net/ipv4/esp4.c                               |    7 +-
Quoted 8 lines
 net/ipv4/ip_output.c                          |   20 +-
 net/ipv4/raw.c                                |    6 +-
 net/ipv4/tcp.c                                |   17 +-
 net/ipv4/tcp_output.c                         |   14 +-
 net/ipv6/esp6.c                               |    7 +-
 net/ipv6/ip6_output.c                         |   20 +-
 net/ipv6/raw.c                                |    6 +-
 65 files changed, 7907 insertions(+), 92 deletions(-)

I mean ~ +8ksloc. 65 files. These should be clues for you.

Quoted 4 lines
 create mode 100644 Documentation/core-api/pisa.rst
 create mode 100644 drivers/iommu/pisa-map.c
 create mode 100644 include/linux/pisa-iommu.h
 create mode 100644 include/linux/pisa-mm.h
Quoted 8 lines
 create mode 100644 include/linux/pisa.h
 create mode 100644 include/net/pisa.h
 create mode 100644 mm/pisa-alloc.c
 create mode 100644 mm/pisa-kunit.c
 create mode 100644 mm/pisa-meta.c
 create mode 100644 mm/pisa-node.c
 create mode 100644 mm/pisa-priv.h
 create mode 100644 mm/pisa-user.c

And here is a perfect clue. 'pisa-mm.h'. 'pisa-alloc.c'. You are creating parallel implementations of core mm mechanics _just for your feature_.

And you didn't even update MAINTAINERS :) though, moving implementation to your own files and adding hooks elsewhere is its own kind of anti-pattern.

Quoted 1 line
 create mode 100644 net/core/pisa-net.c

What I'm trying to say, constructively, is that you have gone down the wrong road here. And it's one we've seen many times before.

You have decided that this feature is exciting and important and really special and unlike anything else, so it must be implemented through hooks into other stuff, new special GFP flags, an madvise() hook which amounts to 'I can do what I want here', your own allocator, your own node code, your own everything.

And I'm sorry but we've seen this before, and it's been a disaster. Hugetlb and uffd are examples of code like this.

Every feature of this nature imposes a tax. It means that you 'just have to remember' to consider and deal with feature X when you write code touching Y because feature X sits outside of the core mm code.

So my constructive suggestion to you (and this is an RFC, so you're asking for this kind of feedback right? :) is as follows:

Firstly - please rethink using AI to generate massive series like this. You are not going to get anything like that merged, and it disinclines maintainers from even looking at your code.

Secondly - think about the problem at an architectural level. Listen to people like Jason and David who are giving you highly valuable feedback, seriously you are lucky to get it.

Thirdly - rework it so it _fits in with the existing core mm architecture_.

Finally, please don't send it as an +8 ksloc 65 file monster. Nobody is going to take a series like that frankly, especially not from a newcomer to the subsystem who may or may not stick around to maintain it.

IOW - try to find ways to implement it incrementally.

Thanks!

~~

FYI: Issues my scripts picked up:

1. New revisions sent in-reply-to mail

Please always send new revisions of series individually, not in-reply-to any other email.

The easiest way of accomplishing this is to use b4 [0] (the recommended way of sending patches to mm), otherwise format patches like this:

For a patch series, e.g. at v2:

$ git format-patch -v2 --cover-letter --thread ...

For an individual patch, e.g. at v2:

$ git format-patch -v2 HEAD~1

[0]: https://b4.docs.kernel.org/en/latest/contributor/send.html

2. Missing cc's

You are missing cc's. Fixing this is easy with b4 [0] (the recommended way of sending patches to mm):

$ b4 prep --auto-to-cc

Alternatively, you can use scripts/get_maintainer.pl:

$ scripts/get_maintainer.pl --nogit-fallback <files-or-patches>

[0]: https://b4.docs.kernel.org/en/latest/contributor/send.html

Specifically, the following appear to be missing:

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

--
Cheers, Lorenzo

#112 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

Quoted 2 lines · Lorenzo Stoakes (ARM)

TL;DR: NAK. All of it. (And yeah, I'm steeling myself for the inevitable 'oh Lorenzo' :)

Oh Lorenzo ... you are absolutely right.

Signature · 3 lines
Cheers,

David
#113 lore raw

Re: [RFC PATCH v3 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

Quoted 5 lines · David Hildenbrand (Arm)
Quoted 2 lines · Lorenzo Stoakes (ARM)

TL;DR: NAK. All of it. (And yeah, I'm steeling myself for the inevitable 'oh Lorenzo' :)

Oh Lorenzo ... you are absolutely right.

:)))

--
Cheers, Lorenzo

syzbot Tested-by [email protected] on the v3 series
#114 lore raw

[syzbot ci] Re: PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

In reply to Luigi Rizzo
syzbot ci has tested the following series

syzbot ci has tested the following series

[v3] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo
https://lore.kernel.org/all/[email protected]
* [RFC PATCH v3 01/25] mm: Introduce CONFIG_PISA and metadata table
* [RFC PATCH v3 02/25] mm: Add PISA allocator lifecycle and page recycle hook
* [RFC PATCH v3 03/25] mm: Add per-NUMA-node PISA page reservoir
* [RFC PATCH v3 04/25] mm/page_alloc: Extend alloc_pages() to __GFP_PISA and PISA block allocation
* [RFC PATCH v3 05/25] mm: Add global cap and shrinker for PISA pages
* [RFC PATCH v3 06/25] iommu/dma: Map PISA memory in a per-domain IOVA window
* [RFC PATCH v3 07/25] driver core: Add per-device pisa_* sysfs attributes for PISA optin
* [RFC PATCH v3 08/25] iommu/dma: Use PISA for coherent DMA allocations
* [RFC PATCH v3 09/25] mm: Add per-CPU block caches to PISA allocators
* [RFC PATCH v3 10/25] mm: Add background page scrubber for PISA allocators
* [RFC PATCH v3 11/25] mm: Migrate user pages into PISA
* [RFC PATCH v3 12/25] block, mm: Support PISA for disk I/O and scrub migration
* [RFC PATCH v3 13/25] net: Cache leaf PISA TX flags on struct net_device
* [RFC PATCH v3 14/25] net: Use per-node PISA allocators for skb_page_frag_refill()
* [RFC PATCH v3 15/25] net: Use PISA for page_pool memory
* [RFC PATCH v3 16/25] mm/slub: Add SLAB_CACHE_PISA_RO for PISA-backed slab caches
* [RFC PATCH v3 17/25] net: Allocate small skb heads from PISA
* [RFC PATCH v3 18/25] net: Migrate user pages into PISA for MSG_ZEROCOPY
* [RFC PATCH v3 19/25] mm, iommu/dma: Support decrypted PISA pages
* [RFC PATCH v3 20/25] arm64/mm, mm: Support decrypted PISA pages in Realms
* [RFC PATCH v3 21/25] mm: Add PISA statistics and debugfs
* [RFC PATCH v3 22/25] net/libeth: Use GFP_KERNEL when pre-filling RX rings
* [RFC PATCH v3 23/25] net/gve: Use GFP_KERNEL when pre-filling RX rings
* [RFC PATCH v3 24/25] net/gve: Use PISA memory for RX buffers
* [RFC PATCH v3 25/25] Documentation: Add PISA architecture documentation

and found the following issue:
WARNING in __alloc_workqueue

Full report is available here:
https://ci.syzbot.org/series/80fa818b-452d-4361-bfc6-33c65f928f71

***

WARNING in __alloc_workqueue

tree:      axboe
URL:       https://kernel.googlesource.com/pub/scm/linux/kernel/git/axboe/linux.git
base:      20eef29b7c8465ac98d7dd6d6f2ac07a8d8056ca
arch:      amd64
compiler:  Debian clang version 22.1.8 (1~deb13u4), Debian LLD 22.1.8
config:    https://ci.syzbot.org/builds/1b1679cb-3959-4df9-8546-bc04ba6e5cd3/config

smpboot: CPU0: Intel QEMU Virtual CPU version 2.5+ (family: 0xf, model: 0x6b, stepping: 0x1)
Performance Events: unsupported Netburst CPU model 107 no PMU driver, software events only.
signal: max sigframe size: 1440
rcu: Hierarchical SRCU implementation.
rcu: Max phase no-delay instances is 1000.
Timer migration: 1 hierarchy levels; 8 children per group; 0 crossnode level
NMI watchdog: Perf NMI watchdog permanently disabled
smp: Bringing up secondary CPUs ...
smpboot: x86: Booting SMP configuration:
.... node #1, CPUs: #1
smp: Brought up 2 nodes, 2 CPUs
smpboot: Total of 2 processors activated (11200.80 BogoMIPS)
Memory: 5553400K/7339508K available (181131K kernel code, 30788K rwdata, 59468K rodata, 27564K init, 120564K bss, 1621204K reserved, 0K cma-reserved)
devtmpfs: initialized
x86/mm: Memory block size: 128MB
Running RCU synchronous self tests
Running RCU synchronous self tests
Running RCU Tasks wait API self tests
Running RCU Tasks Trace wait API self tests
posixtimers hash table entries: 1024 (order: 5, 73728 bytes, vmalloc)
futex hash table entries: 256 (32768 bytes on 2 NUMA nodes, total 64 KiB, linear).
PM: RTC time: 20:32:46, date: 2026-11-24
NET: Registered PF_NETLINK/PF_ROUTE protocol family
audit: initializing netlink subsys (disabled)
thermal_sys: Registered thermal governor 'step_wise'
cpuidle: using governor menu
NET: Registered PF_QIPCRTR protocol family
dca service started, version 1.12.1
PCI: ECAM [mem 0xb0000000-0xbfffffff] (base 0xb0000000) for domain 0000 [bus 00-ff]
PCI: ECAM [mem 0xb0000000-0xbfffffff] reserved as E820 entry
PCI: Using configuration type 1 for base access
HugeTLB: registered 2.00 MiB page size, pre-allocated 0 pages
HugeTLB: 28 KiB vmemmap can be freed for a 2.00 MiB page

------------[ cut here ]------------
workqueue: pisa is using neither WQ_PERCPU or WQ_UNBOUND. Setting WQ_PERCPU.
WARNING: kernel/workqueue.c:6151 at __alloc_workqueue+0x1e4b/0x21d0, CPU#1: swapper/0/1
Modules linked in:
CPU: 1 UID: 0 PID: 1 Comm: swapper/0 Not tainted syzkaller #0 PREEMPT(full) 
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014
RIP: 0010:__alloc_workqueue+0x1e4e/0x21d0
Code: 18 89 39 00 90 0f 0b 90 e9 87 fd ff ff e8 0a 89 39 00 90 0f 0b 90 e9 79 fd ff ff e8 fc 88 39 00 48 8d 3d 65 52 32 10 4c 89 f6 <67> 48 0f b9 3a 8b 5c 24 20 81 cb 00 01 00 00 e9 99 e4 ff ff e8 d9
RSP: 0000:ffffc90000067750 EFLAGS: 00010293
RAX: ffffffff818fa174 RBX: 0000000000000000 RCX: ffff888102aa5ac0
RDX: 0000000000000000 RSI: ffff888162ab5d78 RDI: ffffffff91c1f3e0
RBP: ffffc900000678a0 R08: ffff888102aa5ac0 R09: 0000000000000002
R10: 0000000000000102 R11: 0000000000000000 R12: dffffc0000000000
R13: ffff888162ab5c00 R14: ffff888162ab5d78 R15: ffff888162ab5d18
FS:  0000000000000000(0000) GS:ffff8882a77e4000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000000000000000 CR3: 000000000ff48000 CR4: 00000000000006f0
Call Trace:
 <TASK>
 alloc_workqueue_noprof+0xe3/0x210
 pisa_init+0x127/0x260
 do_one_initcall+0x250/0x870
 do_initcall_level+0x10a/0x1a0
 do_initcalls+0x59/0xa0
 kernel_init_freeable+0x29d/0x3e0
 kernel_init+0x22/0x1d0
 ret_from_fork+0x514/0xb70
 ret_from_fork_asm+0x1a/0x30
 </TASK>

***

If these findings have caused you to resend the series or submit a separate fix, please add the following tag to your commit message:

---
This report is generated by a bot. It may contain errors. syzbot ci engineers can be reached at [email protected].

maintainer
#115 lore raw

Re: [RFC PATCH v2 00/25] PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

In reply to Luigi Rizzo
Quoted 2 lines · Luigi Rizzo

PISA stands for "Pre-mapped IOVA Superpage Allocator" and as the name says, it is a specialized memory allocator. Invoked via __GFP_PISA* flag

No.

#116 lore raw

RFC PATCH v2 1/25 iommu/dma: Introduce CONFIG_PISA and metadata table

In reply to Luigi Rizzo

PISA ("Pre-mapped IOVA Superpage Allocator") is a memory allocator that provides devices which opt in with DMA-able memory backed by large physically contiguous pages (typically 2MB, but fully configurable), and mapped by IOMMU leaves of the same size.

PISA has the following features:
- greatly reduces IOTLB pressure by using fewer, much larger IOMMU entries.

- greatly reduces DMA map/unmap cost. Mapping only happens when the first block from a 2MB page is used. Unmapping is a no-op for the caller, and happens in a separate task when no blocks from the 2MB page are in use and the page should be returned to the buddy allocator.

- much better security than DMA-FQ, because buffers are not returned to the buddy allocator until the mappings have been removed and the IOTLB flushed.

- removes the cost of copying into bounce buffers, e.g. for overcommitted or Confidential Computing VMs.

- fine-grained opt-in selection (each device can opt in selectively for descriptors, transmit and/or receive data buffers and headers) permits choosing the correct security and performance tradeoffs.

- default is to use the base IOMMU mode (DMA or DMA-FQ) of the device.

PISA is integrated with the main IO APIs (dma_alloc_attrs, dma_map/unmap, page_pool, TX socket buffers and disk IO buffers) so that no device driver modifications should be necessary.

Add a CONFIG_PISA option, enabled only on supported kernels (64bit, !PREEMPT_RT) and introduce a sparse metadata table to hold per-2MB buffer state (similar to pageblock_flags).
The metadata table is initialized on first use, consumes 4KB of RAM and 2MB of virtual address space for each 16GB of physical RAM.

Also add a built-in KUnit test suite (CONFIG_PISA_META_KUNIT_TEST) exercising initialization idempotency, PFN/physical round-trip lookups, out-of-bounds physical address handling, and PISA membership toggling.

---
 drivers/iommu/Kconfig      |  33 +++++
 drivers/iommu/Makefile     |   2 +
 drivers/iommu/pisa-kunit.c | 102 +++++++++++++
 drivers/iommu/pisa-meta.c  | 286 +++++++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-priv.h  |  31 ++++
 include/linux/pisa.h       |  79 ++++++++++
 6 files changed, 533 insertions(+)
 create mode 100644 drivers/iommu/pisa-kunit.c
 create mode 100644 drivers/iommu/pisa-meta.c
 create mode 100644 drivers/iommu/pisa-priv.h
 create mode 100644 include/linux/pisa.h
drivers/iommu/Kconfig +33 -0
index 85a8d7fdfa30b..15e06eaed0924 100644
@@ -423,4 +423,37 @@ config IOMMU_DEBUG_PAGEALLOC
 	  If unsure, say N.
 endif # IOMMU_SUPPORT
 
+# Pre-mapped IOVA Superpage Allocator
+config PISA
+	bool "Pre-mapped IOVA Superpage Allocator"
+	depends on X86_64 || ARM64
+	depends on !PREEMPT_RT
+	default y
+	help
+	  PISA is a specialized memory allocator with an API similar to
+	  alloc_pages(). For devices that opt-in, it provides DMA-able
+	  pages backed by 2MB physically contiguous pages, and mapped in
+	  the IOMMU maps with a single leaf PTE of the same size. Mapping,
+	  unmapping and IOTLB flushing are done lazily to reduce CPU overhead.
+	  The large mappings greatly reduce IOTLB usage. As in strict iommu
+	  mode, pages are returned to the buddy allocator only when any existing
+	  mappings have been removed and IOTLB flushed.
+	  Uses 4KB of metadata for each 32MB of PISA buffers, allocated on demand.
+
+	  The config option enforces requirements (2MB large pages and !PREEMPT_RT) at compile
+	  time. Other constraints (e.g. dma-coherent devices) are verified at runtime.
+
+	  If unsure, say Y.
+
+config PISA_META_KUNIT_TEST
+	bool "KUnit test for PISA metadata table (built-in)" if !KUNIT_ALL_TESTS
+	depends on PISA && KUNIT=y
+	default KUNIT_ALL_TESTS
+	help
+	  Builds KUnit unit tests for the sparse, per-PISA-frame metadata table,
+	  and PISA page allocators in drivers/iommu/pisa-*.c, verifying metadata
+	  lookup, allocator recycling, and coherent block allocation.
+
+	  If unsure, say N.
+
 source "drivers/iommu/generic_pt/Kconfig"
drivers/iommu/Makefile +2 -0
index 29a26d2a3af12..b5d3be1df3eda 100644
@@ -11,6 +11,8 @@ obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
+obj-$(CONFIG_PISA) += pisa-meta.o
+obj-$(CONFIG_PISA_META_KUNIT_TEST) += pisa-kunit.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE) += io-pgtable.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_ARMV7S) += io-pgtable-arm-v7s.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_LPAE) += io-pgtable-arm.o
drivers/iommu/pisa-kunit.c new file +102 -0

102 lines not on this page · raw message

drivers/iommu/pisa-meta.c new file +286 -0

286 lines not on this page · raw message

drivers/iommu/pisa-priv.h new file +31 -0
new file mode 100644
index 0000000000000..c873970f6a670
@@ -0,0 +1,31 @@
+/* SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause */
+#ifndef _DRIVERS_IOMMU_PISA_PRIV_H
+#define _DRIVERS_IOMMU_PISA_PRIV_H
+
+#include <linux/pisa.h>
+#include <linux/spinlock.h>
+#include <linux/types.h>
+
+#ifdef CONFIG_PISA
+
+#define PISA_MAX_BLOCKS		512U
+
+#define PISA_BLOCKS(order)	(1U << (PISA_ORDER - (order)))
+
+/**
+ * struct pisa_meta - Metadata for a single PISA page in @pisa_meta_array
+ * @flags:	PISA_ACTIVE while this page is owned by a pisa_alloc
+ */
+struct pisa_meta {
+	u8 flags;
+} __aligned(PISA_META_SIZE);
+
+static_assert(offsetof(struct pisa_meta, flags) == 0);
+static_assert(sizeof(struct pisa_meta) == PISA_META_SIZE);
+
+int pisa_meta_ensure_pfn(unsigned long pfn, bool can_block);
+struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn);
+unsigned long pisa_meta_to_pfn(const struct pisa_meta *meta);
+
+#endif /* CONFIG_PISA */
+#endif /* _DRIVERS_IOMMU_PISA_PRIV_H */
include/linux/pisa.h new file +79 -0

79 lines not on this page · raw message

Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#117 lore raw

Re: [RFC PATCH v2 01/25] iommu/dma: Introduce CONFIG_PISA and metadata table

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] iommu/dma: CONFIG_PISA breaks builds on 64-bit UML and !SPARSEMEM - [Medium] iommu/dma…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] iommu/dma: CONFIG_PISA breaks builds on 64-bit UML and !SPARSEMEM
- [Medium] iommu/dma: pisa_meta_memory_cb() ignores pisa_meta_prealloc() error
--

commit 4571e9a5a4e068f2cb559f5c16306bf2b33d6515
Author: Luigi Rizzo <[email protected]>

iommu/dma: Introduce CONFIG_PISA and metadata table

This commit introduces the CONFIG_PISA build option, a sparse per-2MB-frame metadata table in drivers/iommu/pisa-meta.c, and KUnit tests for metadata table operations.

Quoted 5 lines
drivers/iommu/Kconfig +0 -0
index 85a8d7fdfa30b..15e06eaed0924 100644

drivers/iommu/Kconfig config IOMMU_DEBUG_PAGEALLOC · line 431

Quoted 9 lines
drivers/iommu/Kconfig +6 -0
@@ -423,4 +423,37 @@ config IOMMU_DEBUG_PAGEALLOC
 	  If unsure, say N.
 endif # IOMMU_SUPPORT
 
+# Pre-mapped IOVA Superpage Allocator
+config PISA
+	bool "Pre-mapped IOVA Superpage Allocator"
+	depends on X86_64 || ARM64
+	depends on !PREEMPT_RT
+	default y

[Severity: Medium]
Can enabling CONFIG_PISA by default break builds on 64-bit UML (ARCH=um on x86_64) or configurations without CONFIG_SPARSEMEM?

PISA is placed outside the IOMMU_SUPPORT block, and drivers/Makefile enters drivers/iommu/ unconditionally. In drivers/iommu/pisa-meta.c, static_assert(PISA_SHIFT <= SUBSECTION_SHIFT) and pisa_meta_init()'s use of MAX_PHYSMEM_BITS both rely on symbols that are only defined when CONFIG_SPARSEMEM is enabled, whereas 64-bit UML sets CONFIG_X86_64=y with CONFIG_FLATMEM=y.

Quoted 5 lines
drivers/iommu/pisa-meta.c new file +0 -0
new file mode 100644
index 0000000000000..5ceea91e4d5e8

[ ... ]

Quoted 5 lines
drivers/iommu/pisa-meta.c new file +5 -0
+/* Page tables for memory about to go online; failure keeps it out of the allocators. */
+static int pisa_meta_memory_cb(struct notifier_block *nb, unsigned long action, void *arg)
+{
+	struct memory_notify *mn = arg;
+

drivers/iommu/pisa-meta.c line 190

Quoted 10 lines
drivers/iommu/pisa-meta.c new file +10 -0
+	if (action != MEM_GOING_ONLINE)
+		return NOTIFY_OK;
+
+	mutex_lock(&pisa_meta_mutex);
+	if (pisa_meta_array)
+		pisa_meta_prealloc(pisa_meta_array, pisa_meta_nframes, mn->start_pfn,
+				   mn->start_pfn + mn->nr_pages);
+	mutex_unlock(&pisa_meta_mutex);
+	return NOTIFY_OK;
+}

[Severity: Medium]
Should pisa_meta_memory_cb() propagate errors from pisa_meta_prealloc() via notifier_from_errno()?

Returning NOTIFY_OK unconditionally allows online_pages() to bring hotplugged memory online even when page-table preallocation fails. Any subsequent non-blocking pisa_meta_ensure_pfn(pfn, false) call on a page from that range cannot allocate the missing page table and fails with -EINVAL in pisa_meta_back().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#118 lore raw

RFC PATCH v2 2/25 iommu/dma: Add PISA allocator lifecycle and page recycle hook

In reply to Luigi Rizzo

PISA allocators use 2MB physically contiguous memory pages from which IO buffers are allocated. Recycling memory to the PISA allocator amortizes the cost of mapping, unmapping and IOTLB flush. Memory is returned to the buddy allocator only when all active IOMMU/IOTLB mappings have been flushed, so sensitive data or code will not ever be accessible to IO devices.

Add the allocator creation (struct pisa_alloc, pisa_create()) and the page release side, hooking into __free_pages_prepare() so that PISA pages are returned to the allocator.

Also implement asynchronous PISA page retirement and release to the buddy allocator via a WQ_MEM_RECLAIM worker. Retirement removes PISA pages from allocators and destroys the mappings flushing the IOTLB, but defers the buddy release by an RCU grace period.

---
 drivers/iommu/Makefile     |   2 +-
 drivers/iommu/pisa-alloc.c | 369 +++++++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-kunit.c |  10 +-
 drivers/iommu/pisa-priv.h  |  85 +++++++++
 include/linux/pisa.h       |  28 ++-
 mm/page_alloc.c            |  21 +++
 6 files changed, 512 insertions(+), 3 deletions(-)
 create mode 100644 drivers/iommu/pisa-alloc.c
drivers/iommu/Makefile +1 -1
index b5d3be1df3eda..bda0b102dd3ba 100644
@@ -11,7 +11,7 @@ obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
-obj-$(CONFIG_PISA) += pisa-meta.o
+obj-$(CONFIG_PISA) += pisa-meta.o pisa-alloc.o
 obj-$(CONFIG_PISA_META_KUNIT_TEST) += pisa-kunit.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE) += io-pgtable.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_ARMV7S) += io-pgtable-arm-v7s.o
drivers/iommu/pisa-alloc.c new file +369 -0

369 lines not on this page · raw message

drivers/iommu/pisa-kunit.c +9 -1
index 0633f3238e012..12edc73abc9c6 100644
@@ -85,10 +85,18 @@ static void test_meta_active_toggle(struct kunit *test)
 	__free_pages(page, PISA_ORDER);
 }
 
+static void test_alloc_and_recycle(struct kunit *test)
+{
+	KUNIT_EXPECT_NULL(test, pisa_create(NUMA_NO_NODE, 0, DMA_NONE));
+	KUNIT_EXPECT_NULL(test, pisa_create(NUMA_NO_NODE, PISA_ORDER + 1, DMA_BIDIRECTIONAL));
+	pisa_set_name(NULL, "ignored");
+}
+
 static struct kunit_case pisa_meta_test_cases[] = {
 	KUNIT_CASE(test_meta_init_and_roundtrip),
 	KUNIT_CASE(test_meta_invalid_phys),
 	KUNIT_CASE(test_meta_active_toggle),
+	KUNIT_CASE(test_alloc_and_recycle),
 	{}
 };
 
@@ -98,5 +106,5 @@ static struct kunit_suite pisa_meta_test_suite = {
 };
 
 kunit_test_suite(pisa_meta_test_suite);
-MODULE_DESCRIPTION("KUnit tests for struct pisa_meta table");
+MODULE_DESCRIPTION("KUnit tests for struct pisa_meta table and PISA allocator");
 MODULE_LICENSE("Dual BSD/GPL");
drivers/iommu/pisa-priv.h +85 -0

113 lines not on this page · raw message

include/linux/pisa.h +27 -1
index acf92ced245d8..dddcedb8c93f6 100644
@@ -3,10 +3,11 @@
 #ifndef _LINUX_PISA_H
 #define _LINUX_PISA_H
 
+#include <linux/types.h>
 #include <linux/bitops.h>
 #include <linux/jump_label.h>
 #include <linux/mm.h>
-#include <linux/types.h>
+#include <linux/rcupdate.h>
 
 #ifdef CONFIG_PISA
 
@@ -53,6 +54,24 @@ static inline bool is_pisa_pfn(unsigned long pfn)
 	return READ_ONCE(*flags) & PISA_ACTIVE;
 }
 
+static inline bool is_pisa_page(const struct page *page);
+
+bool __pisa_free_page(struct page *page);
+bool free_page_prepare_pisa(struct page *page, unsigned int order);
+
+static inline bool pisa_free_page(struct page *page)
+{
+	bool ret;
+
+	if (!static_branch_unlikely(&pisa_key))
+		return false;
+	rcu_read_lock();
+	ret = is_pisa_page(page) && __pisa_free_page(page);
+	rcu_read_unlock();
+
+	return ret;
+}
+
 #else /* !CONFIG_PISA */
 
 static inline int pisa_meta_init(void)
@@ -60,11 +79,18 @@ static inline int pisa_meta_init(void)
 	return -EOPNOTSUPP;
 }
 
+bool free_page_prepare_pisa(struct page *page, unsigned int order);
+
 static inline bool is_pisa_pfn(unsigned long pfn)
 {
 	return false;
 }
 
+static inline bool pisa_free_page(struct page *page)
+{
+	return false;
+}
+
 #endif /* CONFIG_PISA */
 
 static inline bool is_pisa_phys(phys_addr_t phys)
mm/page_alloc.c +21 -0
index eb4f02617f53c..48df87a19d312 100644
@@ -17,6 +17,7 @@
 #include <linux/stddef.h>
 #include <linux/mm.h>
 #include <linux/highmem.h>
+#include <linux/pisa.h>
 #include <linux/interrupt.h>
 #include <linux/jiffies.h>
 #include <linux/compiler.h>
@@ -1298,6 +1299,23 @@ static inline void pgalloc_tag_sub_pages(struct alloc_tag *tag, unsigned int nr)
 
 #endif /* CONFIG_MEM_ALLOC_PROFILING */
 
+/*
+ * pisa_free_page() in __free_pages_prepare() recycles a PISA block into
+ * its allocator before the rest of that function runs. __pisa_free_page() calls
+ * this to apply the buddy allocator's checks.
+ *
+ * Return: false if the block is in a bad state (already reported): leak it.
+ */
+bool free_page_prepare_pisa(struct page *page, unsigned int order)
+{
+	if (!IS_ENABLED(CONFIG_PISA))
+		return true;
+	if (is_check_pages_enabled() && free_page_is_bad(page))
+		return false;
+	page_table_check_free(page, order);
+	return true;
+}
+
 static __always_inline bool __free_pages_prepare(struct page *page,
 		unsigned int order, fpi_t fpi_flags)
 {
@@ -1312,6 +1330,9 @@ static __always_inline bool __free_pages_prepare(struct page *page,
 
 	VM_BUG_ON_PAGE(PageTail(page), page);
 
+	if (unlikely(pisa_free_page(page)))
+		return false;
+
 	trace_mm_page_free(page, order);
 	kmsan_free_page(page, order);
 
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#119 lore raw

RFC PATCH v2 3/25 iommu/dma: Add per-NUMA-node PISA page reservoir

In reply to Luigi Rizzo

Allocating a large page may involve compacting and blocking, so it cannot be issued in GFP_ATOMIC context.

Add a per-NUMA-node reservoir of pre-allocated and set up PISA pages, that can serve allocations without blocking. The reservoir is refilled in process context by a per-node work item, queued with queue_work_node() on system_dfl_wq so each node is refilled from its own CPUs, not bound to the CPU that caused the miss.

pisa.reservoir_max, writable at runtime, sets the number of PISA pages per node (default 16 = 32 MB per node; 0 = disabled).

---
 drivers/iommu/Makefile     |   2 +-
 drivers/iommu/pisa-alloc.c |  17 ++-
 drivers/iommu/pisa-kunit.c |   7 +
 drivers/iommu/pisa-meta.c  |   1 +
 drivers/iommu/pisa-node.c  | 268 +++++++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-priv.h  |  30 +++++
 6 files changed, 323 insertions(+), 2 deletions(-)
 create mode 100644 drivers/iommu/pisa-node.c
drivers/iommu/Makefile +1 -1
index bda0b102dd3ba..bc58166f9303a 100644
@@ -11,7 +11,7 @@ obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
-obj-$(CONFIG_PISA) += pisa-meta.o pisa-alloc.o
+obj-$(CONFIG_PISA) += pisa-meta.o pisa-alloc.o pisa-node.o
 obj-$(CONFIG_PISA_META_KUNIT_TEST) += pisa-kunit.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE) += io-pgtable.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_ARMV7S) += io-pgtable-arm-v7s.o
drivers/iommu/pisa-alloc.c +16 -1
index 68f5d333ae15c..cf559ee86d6f9 100644
@@ -46,6 +46,14 @@ module_param_named(idle_ms, pisa_idle_ms, uint, 0644);
 static LIST_HEAD(pisa_allocs);
 static DEFINE_RWLOCK(pisa_allocs_lock);
 
+/* Per-NUMA-node PISA state (ring/TX/user allocators, reservoir). */
+struct pisa_node pisa_nodes[MAX_NUMNODES] = {
+	[0 ... MAX_NUMNODES - 1] = {
+		.next_alloc = INITIAL_JIFFIES,
+		.lock = __SPIN_LOCK_UNLOCKED(pisa_nodes.lock),
+	},
+};
+
 static void pisa_schedule_reclaim(void);
 
 /*
@@ -75,8 +83,13 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 }
 
 /* Unmap a retired PISA page, clear PISA_ACTIVE, and queue RCU release. */
-static void pisa_release_page(struct pisa_meta *meta)
+void pisa_release_page(struct pisa_meta *meta)
 {
+	if (!meta->pa) {
+		__free_pages(pfn_to_page(pisa_meta_to_pfn(meta)), PISA_ORDER);
+		return;
+	}
+
 	/* pisa_unmap_all(meta) will be called here once IOMMU mappings are added. */
 
 	/* Clear PISA_ACTIVE before the RCU grace period so new readers stop entering. */
@@ -359,6 +372,8 @@ bool __pisa_free_page(struct page *page)
 
 static int __init pisa_init(void)
 {
+	pisa_node_init();
+
 	/* Dedicated WQ_MEM_RECLAIM workqueue so reclaim never blocks behind system_wq. */
 	pisa_wq = alloc_workqueue("pisa", WQ_MEM_RECLAIM, 0);
 	if (!pisa_wq)
drivers/iommu/pisa-kunit.c +7 -0
index 12edc73abc9c6..079f6220e742a 100644
@@ -92,11 +92,18 @@ static void test_alloc_and_recycle(struct kunit *test)
 	pisa_set_name(NULL, "ignored");
 }
 
+static void test_reservoir_and_scrubber(struct kunit *test)
+{
+	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
+	KUNIT_EXPECT_EQ(test, READ_ONCE(pisa_reservoir_max), 16U);
+}
+
 static struct kunit_case pisa_meta_test_cases[] = {
 	KUNIT_CASE(test_meta_init_and_roundtrip),
 	KUNIT_CASE(test_meta_invalid_phys),
 	KUNIT_CASE(test_meta_active_toggle),
 	KUNIT_CASE(test_alloc_and_recycle),
+	KUNIT_CASE(test_reservoir_and_scrubber),
 	{}
 };
 
drivers/iommu/pisa-meta.c +1 -0
index 5ceea91e4d5e8..00939c366ba6d 100644
@@ -272,6 +272,7 @@ int pisa_meta_init(void)
 
 	/* Register outside pisa_meta_mutex (taken by the notifier under chain lock). */
 	register_memory_notifier(&pisa_meta_memory_nb);
+	pisa_schedule_reservoir();
 	return 0;
 
 out_free_vm:
drivers/iommu/pisa-node.c new file +268 -0

268 lines not on this page · raw message

drivers/iommu/pisa-priv.h +30 -0
index 769b0ef071705..0d097c665c790 100644
@@ -4,12 +4,14 @@
 
 #include <linux/dma-direction.h>
 #include <linux/pisa.h>
+#include <linux/jiffies.h>
 #include <linux/list.h>
 #include <linux/llist.h>
 #include <linux/nodemask.h>
 #include <linux/spinlock.h>
 #include <linux/topology.h>
 #include <linux/types.h>
+#include <linux/workqueue.h>
 
 #ifdef CONFIG_PISA
 
@@ -95,6 +97,19 @@ struct pisa_alloc {
 	char			name[48];
 } ____cacheline_aligned;
 
+/* Per-NUMA-node PISA state. */
+struct pisa_node {
+	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
+
+	spinlock_t		lock;		/* protects @pages and @nr_pages */
+	struct list_head	pages;		/* reservoir */
+	unsigned int		nr_pages;
+	struct work_struct	work;		/* refill/trim, on this node */
+} ____cacheline_aligned_in_smp;
+
+/* Per-NUMA-node PISA state (ring/TX/user allocators, reservoir). */
+extern struct pisa_node pisa_nodes[MAX_NUMNODES];
+
 int pisa_meta_ensure_pfn(unsigned long pfn, bool can_block);
 struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn);
 unsigned long pisa_meta_to_pfn(const struct pisa_meta *meta);
@@ -102,6 +117,7 @@ unsigned long pisa_meta_to_pfn(const struct pisa_meta *meta);
 struct pisa_alloc *pisa_create(int nid, unsigned int order, enum dma_data_direction dir);
 __printf(2, 3)
 void pisa_set_name(struct pisa_alloc *pa, const char *fmt, ...);
+void pisa_release_page(struct pisa_meta *meta);
 
 static inline int pisa_sanitize_nid(int nid)
 {
@@ -112,5 +128,19 @@ static inline int pisa_sanitize_nid(int nid)
 	return nid;
 }
 
+static inline void pisa_alloc_backoff(int nid, bool can_block)
+{
+	nid = pisa_sanitize_nid(nid);
+	if (!can_block)
+		WRITE_ONCE(pisa_nodes[nid].next_alloc, jiffies + DIV_ROUND_UP(HZ, 100));
+}
+
+/* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
+extern unsigned int pisa_reservoir_max;
+void pisa_node_init(void);
+void pisa_schedule_reservoir(void);
+struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean);
+unsigned long pisa_reservoir_count(void);
+
 #endif /* CONFIG_PISA */
 #endif /* _DRIVERS_IOMMU_PISA_PRIV_H */
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#120 lore raw

Re: [RFC PATCH v2 03/25] iommu/dma: Add per-NUMA-node PISA page reservoir

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] iommu/dma: pisa_reservoir_pop() schedules refill worker before backoff check - [Medium] iommu/dma…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] iommu/dma: pisa_reservoir_pop() schedules refill worker before backoff check
- [Medium] iommu/dma: fs_reclaim lock inversion on pisa_meta_mutex in __pisa_page_alloc()
--

commit 6907cf09179e9a96def9072a9cbbe4eddf0cc46c
Author: Luigi Rizzo <[email protected]>

iommu/dma: Add per-NUMA-node PISA page reservoir

This commit adds a per-NUMA-node reservoir of pre-allocated PISA pages to serve non-blocking allocations, refilled and trimmed asynchronously by per-node work items.

Quoted 5 lines
drivers/iommu/pisa-node.c new file +0 -0
new file mode 100644
index 0000000000000..524f0d4457ad7

[ ... ]

Quoted 22 lines
drivers/iommu/pisa-node.c new file +22 -0
+/* Allocate a PISA page from the buddy allocator and initialize its metadata. */
+static struct pisa_meta *__pisa_page_alloc(gfp_t gfp, int nid, bool can_block,
+					   bool *clean)
+{
+	struct pisa_meta *meta;
+	unsigned int memflags;
+	struct page *page;
+
+	if (unlikely(!static_branch_unlikely(&pisa_key))) {
+		if (!can_block || (gfp & (__GFP_FS | __GFP_IO)) != (__GFP_FS | __GFP_IO) ||
+		    pisa_meta_init())
+			return ERR_PTR(-EAGAIN);
+	}
+
+	/*
+	 * Long-lived active pages must be unmovable, lowmem, non-compound, and
+	 * must not dip into emergency reserves or trigger OOM/warnings.
+	 */
+	gfp &= ~(__GFP_COMP | __GFP_HIGHMEM | __GFP_MOVABLE);
+	gfp |= __GFP_NOWARN | __GFP_NOMEMALLOC | (can_block ? __GFP_RETRY_MAYFAIL : __GFP_NORETRY);
+
+	if (can_block)

drivers/iommu/pisa-node.c line 94

Quoted 10 lines
drivers/iommu/pisa-node.c new file +10 -0
+		memflags = pisa_memalloc_save(gfp);
+	page = alloc_pages_node(nid, gfp, PISA_ORDER);
+	if (!page) {
+		if (can_block)
+			memalloc_flags_restore(memflags);
+		return ERR_PTR(-ENOMEM);
+	}
+
+	/* Ensure the metadata chunk for this PFN is populated. */
+	if (unlikely(pisa_meta_ensure_pfn(page_to_pfn(page), can_block))) {

[Severity: Medium]
Can this invert the lock order between pisa_meta_mutex and fs_reclaim when called under GFP_NOFS, GFP_NOIO, or a memalloc_nofs_save() / memalloc_noio_save() scope?

pisa_meta_init(), pisa_meta_memory_cb(), and GFP_KERNEL calls to pisa_meta_ensure_pfn() perform GFP_KERNEL allocations while holding pisa_meta_mutex, establishing pisa_meta_mutex -> fs_reclaim.

Here, can_block is gfpflags_allow_blocking(gfp), which is true for GFP_NOFS and GFP_NOIO. Although pisa_memalloc_save(gfp) sets PF_MEMALLOC_NOFS or PF_MEMALLOC_NOIO, __pisa_page_alloc() still passes can_block = true to pisa_meta_ensure_pfn(), which acquires pisa_meta_mutex when the metadata page table is not yet populated:

drivers/iommu/pisa-meta.c:pisa_meta_ensure_pfn() {
    ...
	if (can_block && !pisa_meta_pte((unsigned long)pisa_meta_array + (idx << PAGE_SHIFT))) {
		int err;

		mutex_lock(&pisa_meta_mutex);
		err = pisa_meta_prealloc(pisa_meta_array, pisa_meta_nframes, pfn, pfn + 1);
		mutex_unlock(&pisa_meta_mutex);
    ...
}

In addition, the pisa_meta_init() check above tests raw gfp rather than current_gfp_context(gfp), so a caller inside a memalloc_nofs_save() or memalloc_noio_save() scope passing GFP_KERNEL will also take pisa_meta_mutex:

CPU0 CPU1
---- ----
lock(fs_reclaim)
mutex_lock(&pisa_meta_mutex)
mutex_lock(&pisa_meta_mutex)
lock(fs_reclaim)

*** DEADLOCK ***

CPU0: fs/io path (holding lock waited on by reclaim) -> pisa_reservoir_pop()

      -> __pisa_page_alloc() -> pisa_meta_ensure_pfn() / pisa_meta_init()

CPU1: pisa_node_work_fn() -> pisa_meta_init() -> kvcalloc(..., GFP_KERNEL)

Passing current_gfp_context(gfp) into gfp at entry and only allowing the mutex-taking paths when (gfp & (__GFP_FS | __GFP_IO)) == (__GFP_FS | __GFP_IO) would avoid this lock inversion.

[ ... ]

Quoted 13 lines
drivers/iommu/pisa-node.c new file +13 -0
+/* Refill node @nid's reservoir up to pisa_reservoir_max pre-zeroed PISA pages. */
+static void pisa_reservoir_refill_node(int nid)
+{
+	struct pisa_node *res = &pisa_nodes[nid];
+
+	while (res->nr_pages < READ_ONCE(pisa_reservoir_max)) {
+		struct pisa_meta *meta;
+		unsigned long flags;
+		bool clean;
+
+		meta = __pisa_page_alloc(GFP_KERNEL | __GFP_THISNODE, nid, true, &clean);
+		if (IS_ERR(meta))
+			break;

[ ... ]

Quoted 10 lines
drivers/iommu/pisa-node.c new file +10 -0
+struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean)
+{
+	bool can_block = gfpflags_allow_blocking(gfp);
+	unsigned int max = READ_ONCE(pisa_reservoir_max);
+	struct pisa_meta *meta;
+
+	nid = pisa_sanitize_nid(nid);
+	if (max) {
+		meta = pisa_reservoir_pop_node(nid, max);
+		if (meta) {

drivers/iommu/pisa-node.c line 240

Quoted 10 lines
drivers/iommu/pisa-node.c new file +10 -0
+			*clean = true;
+			return meta;
+		}
+		/* Empty: pop_node() only schedules after a successful pop. */
+		pisa_schedule_reservoir_node(nid);
+	}
+
+	/* Back off briefly on GFP_ATOMIC if previous allocation on @nid failed. */
+	if (!can_block && time_before(jiffies, READ_ONCE(pisa_nodes[nid].next_alloc)))
+		return ERR_PTR(-EAGAIN);

[Severity: Medium]
Does calling pisa_schedule_reservoir_node(nid) before checking pisa_nodes[nid].next_alloc defeat the backoff for the refill work item when the reservoir is empty?

When order-9 allocations on nid are failing under memory pressure or fragmentation, a GFP_ATOMIC miss sets pisa_nodes[nid].next_alloc to back off for 10ms. However, every subsequent GFP_ATOMIC call to pisa_reservoir_pop() during that backoff window still queues pisa_nodes[nid].work before hitting the next_alloc check, and pisa_reservoir_refill_node() immediately breaks out on __pisa_page_alloc() failure, allowing softirq callers to continuously re-queue the worker and trigger repeated GFP_KERNEL | __GFP_RETRY_MAYFAIL compaction attempts.

Checking next_alloc before pisa_schedule_reservoir_node(nid) (or having refill failure also update next_alloc) would keep the worker from thrashing during backoff.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#121 lore raw

RFC PATCH v2 4/25 iommu/dma: Add PISA block allocation

In reply to Luigi Rizzo

Add block allocation (pisa_alloc_bulk(), pisa_alloc())
and split_page_compound(), which splits a newly acquired 2MB PISA page into blocks of the allocator's order, frozen at refcount 0.

Introduce __GFP_PISA_RO and __GFP_PISA_RW GFP flags and hook __alloc_frozen_pages_noprof() and alloc_pages_bulk_noprof() so callers can allocate from per-node PISA allocators (pisa_nodes[nid].pa[ro][order]) using standard page allocation APIs.

---
 drivers/iommu/pisa-alloc.c     | 345 +++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-kunit.c     |  78 +++++++-
 drivers/iommu/pisa-priv.h      |  24 ++-
 include/linux/gfp_types.h      |  17 +-
 include/linux/pisa.h           |  25 +++
 include/trace/events/mmflags.h |  11 +-
 mm/page_alloc.c                |  40 +++-
 7 files changed, 527 insertions(+), 13 deletions(-)
drivers/iommu/pisa-alloc.c +345 -0
index cf559ee86d6f9..1f1b99023094c 100644
@@ -14,13 +14,19 @@
 #include <linux/gfp.h>
 #include <linux/list.h>
 #include <linux/llist.h>
+#include <linux/memcontrol.h>
 #include <linux/mm.h>
 #include <linux/moduleparam.h>
 #include <linux/mutex.h>
+#include <linux/page_owner.h>
+#include <linux/pgalloc_tag.h>
 #include <linux/rcupdate.h>
+#include <linux/sched/mm.h>
+#include <linux/skbuff.h>
 #include <linux/slab.h>
 #include <linux/spinlock.h>
 #include <linux/workqueue.h>
+#include <net/sock.h>
 
 #include "pisa-priv.h"
 
@@ -328,6 +334,318 @@ static void pisa_return_block_locked(struct pisa_alloc *pa, struct page *block,
 	*release |= pisa_place_meta(meta);
 }
 
+/*
+ * Return the predefined per-node allocator for (@nid, @order, @ro), or NULL.
+ */
+struct pisa_alloc *pisa_node_pa(int nid, unsigned int order, bool ro)
+{
+	if (order > PISA_ORDER)
+		return NULL;
+	nid = pisa_sanitize_nid(nid);
+
+	return pisa_nodes[nid].pa[ro][order];
+}
+
+/**
+ * pisa_alloc_pages_bulk - Allocate pages from a per-node __GFP_PISA_* allocator
+ * @gfp: GFP flags (must have __GFP_PISA_RW or __GFP_PISA_RO set)
+ * @order: Page order
+ * @preferred_nid: Preferred NUMA node (or NUMA_NO_NODE)
+ * @nodemask: Allowed NUMA nodemask (declined if non-NULL)
+ * @nr_pages: Total entries in @page_array
+ * @page_array: Output array of page pointers (populated entries are skipped)
+ * @frozen: Leave allocated pages frozen at refcount 0 if true
+ *
+ * Return: Number of populated entries at the start of @page_array.
+ */
+unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred_nid,
+				    nodemask_t *nodemask, int nr_pages,
+				    struct page **page_array, bool frozen)
+{
+	struct pisa_alloc *pa = NULL;
+
+	if (unlikely(nr_pages <= 0))
+		return 0;
+	if (likely(!nodemask) && (!order || (gfp & __GFP_COMP)))
+		pa = pisa_node_pa(preferred_nid, order, !(gfp & __GFP_WRITE));
+	return pisa_alloc_bulk(pa, gfp & ~__GFP_PISA_RW, nr_pages, page_array, frozen);
+}
+
+/*
+ * Split a non-compound page of @old_order into 1 << (@old_order - @new_order)
+ * pages of @new_order (compound if @new_order > 0), all frozen at refcount 0.
+ * Fails with -EBUSY if a speculative PFN walker holds a reference to @page.
+ */
+static int split_page_compound(struct page *page, unsigned int old_order, unsigned int new_order)
+{
+	unsigned int i;
+
+	if (WARN_ON_ONCE(PageCompound(page) || !page_count(page) ||
+			 new_order > old_order ||
+			 folio_memcg_charged(page_folio(page))))
+		return -EINVAL;
+
+	/* Freeze @page[0] (1 -> 0) so all resulting pieces start at refcount 0. */
+	if (!page_ref_freeze(page, 1))
+		return -EBUSY;
+
+	if (new_order < old_order) {
+		split_page_owner(page, old_order, new_order);
+		pgalloc_tag_split(page_folio(page), old_order, new_order);
+	}
+
+	/* Subpages of non-compound pages are already initialized as order 0. */
+	if (new_order == 0)
+		return 0;
+
+	for (i = 0; i < (1U << old_order); i += (1U << new_order))
+		prep_compound_page(page + i, new_order);
+
+	return 0;
+}
+
+/* Obtain and split a new PISA page on @nid into blocks of @order. */
+static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, int nid)
+{
+	bool can_block = gfpflags_allow_blocking(gfp), clean;
+	unsigned int bpp = PISA_BLOCKS(order);
+	struct pisa_meta *meta;
+	struct page *page;
+
+	/* __GFP_DMA/__GFP_DMA32 were already declined by pisa_alloc_bulk(). */
+	meta = pisa_reservoir_pop(nid, gfp & ~__GFP_ZERO, &clean);
+	if (IS_ERR(meta))
+		return meta;
+
+	page = pfn_to_page(pisa_meta_to_pfn(meta));
+
+	/* Fails with -EBUSY if a concurrent PFN walker holds a speculative ref. */
+	if (split_page_compound(page, PISA_ORDER, order)) {
+		pisa_release_page(meta);
+		pisa_alloc_backoff(nid, can_block);
+		return ERR_PTR(-EBUSY);
+	}
+
+	INIT_LIST_HEAD(&meta->list);
+
+	if (clean) {
+		bitmap_set(meta->clean_bitmap, 0, bpp);
+		meta->nr_clean = bpp;
+	} else {
+		bitmap_set(meta->dirty_bitmap, 0, bpp);
+		meta->nr_dirty = bpp;
+	}
+
+	return meta;
+}
+
+/* Reset fields normally cleared by prep_new_page()/post_alloc_hook(). */
+static void pisa_block_prep(struct page *block)
+{
+	set_page_private(block, 0);
+	clear_page_pfmemalloc(block);
+}
+
+/*
+ * Collect up to @want blocks from @meta's dirty or clean bitmap. With
+ * @unfreeze they get refcount 1; otherwise they stay at refcount 0.
+ */
+static unsigned int pisa_scan_bitmap(struct pisa_meta *meta, bool dirty,
+				     unsigned int want, struct page **out, bool unfreeze)
+{
+	unsigned long *bitmap = dirty ? meta->dirty_bitmap : meta->clean_bitmap;
+	u16 *countp = dirty ? &meta->nr_dirty : &meta->nr_clean;
+	struct pisa_alloc *pa = meta->pa;
+	unsigned int idx, got = 0, used = 0;
+	unsigned long base_pfn;
+
+	if (!*countp || !want)
+		return 0;
+
+	base_pfn = pisa_meta_to_pfn(meta);
+	for_each_set_bit(idx, bitmap, PISA_BLOCKS(pa->order)) {
+		struct page *block = pfn_to_page(base_pfn + (idx << pa->order));
+
+		__clear_bit(idx, bitmap);
+		used++;
+		if (!pisa_block_poisoned(pa, block)) {
+			pisa_block_prep(block);
+			if (unfreeze)
+				page_ref_unfreeze(block, 1);
+			out[got++] = block;
+		}
+
+		if (used == *countp || got == want)
+			break;
+	}
+	*countp -= used;
+	return got;
+}
+
+/* @zero: prefer PISA pages with blocks in @meta->clean_bitmap. */
+static struct pisa_meta *pisa_pick_meta(struct pisa_alloc *pa, bool zero)
+{
+	struct pisa_meta *m_dirty, *m_clean, *meta;
+
+	if (zero) {
+		/* Clean blocks first: the head of @partial, then of @idle. */
+		if (!list_empty(&pa->partial))
+			return list_first_entry(&pa->partial, struct pisa_meta, list);
+		meta = list_first_entry_or_null(&pa->idle, struct pisa_meta, list);
+		if (meta && meta->nr_clean) {
+			pa->num_idle_pages--;
+			WRITE_ONCE(pa->idle_jiffies, jiffies);
+			return meta;
+		}
+	}
+
+	m_dirty = list_first_entry_or_null(&pa->partial_dirty, struct pisa_meta, list);
+	m_clean = list_first_entry_or_null(&pa->partial, struct pisa_meta, list);
+	if (m_dirty && m_clean) {
+		bool dirty_dense = m_dirty->on_list == PISA_LIST_PARTIAL_DIRTY_DENSE;
+		bool clean_dense = m_clean->on_list == PISA_LIST_PARTIAL_CLEAN_DENSE;
+
+		if (dirty_dense != clean_dense)
+			return dirty_dense ? m_dirty : m_clean;
+		return pisa_meta_avail(m_dirty) <= pisa_meta_avail(m_clean) ?
+		       m_dirty : m_clean;
+	}
+	if (m_dirty)
+		return m_dirty;
+	if (m_clean)
+		return m_clean;
+	if (!list_empty(&pa->idle)) {
+		meta = list_last_entry(&pa->idle, struct pisa_meta, list);
+		pa->num_idle_pages--;
+		WRITE_ONCE(pa->idle_jiffies, jiffies);
+		return meta;
+	}
+	return NULL;
+}
+
+/* Extract up to @want blocks from @meta under @pa->lock. */
+static unsigned int take_blocks(struct pisa_meta *meta, unsigned int want,
+				struct page **out, bool zero, bool frozen)
+{
+	unsigned int avail_before = pisa_meta_avail(meta), got = 0, used;
+	struct pisa_alloc *pa = meta->pa;
+
+	lockdep_assert_held(&pa->lock);
+
+	if (zero) {
+		unsigned int dirty, i;
+
+		/* First choice are clean blocks, followed by dirty */
+		got += pisa_scan_bitmap(meta, false, want, out, !frozen);
+		dirty = pisa_scan_bitmap(meta, true, want - got, out + got, false);
+		for (i = got; i < got + dirty; i++)
+			set_page_private(out[i], 1);
+		got += dirty;
+	} else {
+		/* First choice are dirty blocks, followed by clean */
+		got += pisa_scan_bitmap(meta, true, want, out, !frozen);
+		got += pisa_scan_bitmap(meta, false, want - got, out + got, !frozen);
+	}
+
+	used = avail_before - pisa_meta_avail(meta);
+	/* If counts disagreed with bitmaps, zero them so @meta moves to @pa->full. */
+	if (WARN_ON_ONCE(!used)) {
+		meta->nr_clean = 0;
+		meta->nr_dirty = 0;
+	}
+	pisa_place_meta(meta);
+
+	return got;
+}
+
+/* Allocate @nr_pages blocks from @pa. */
+static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigned long nr_pages,
+				       struct page **pages, bool zero, bool frozen)
+{
+	unsigned long n, flags, i;
+	struct pisa_meta *meta;
+	unsigned int want;
+
+	/* Held across bitmap scans; dropped around slow-path pisa_alloc_split_page(). */
+	spin_lock_irqsave(&pa->lock, flags);
+	for (n = 0; n < nr_pages; n += take_blocks(meta, want, &pages[n], zero, frozen)) {
+		want = min_t(unsigned long, nr_pages - n, PISA_BLOCKS(pa->order));
+		meta = pisa_pick_meta(pa, zero);
+		if (meta)
+			continue;
+
+		/* Fallback to a new allocation */
+		spin_unlock_irqrestore(&pa->lock, flags);
+		/* With @zero, fresh dirty blocks are zeroed below. */
+		meta = pisa_alloc_split_page(pa->order, gfp, pa->nid);
+		if (IS_ERR(meta))
+			goto out;
+		spin_lock_irqsave(&pa->lock, flags);
+		meta->pa = pa;
+		/* Set PISA_ACTIVE after @meta is fully set up. */
+		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
+	}
+	spin_unlock_irqrestore(&pa->lock, flags);
+
+out:
+	for (i = 0; zero && i < n; i++) {
+		/* Dirty blocks for a zeroing caller were marked with page_private = 1. */
+		if (!page_private(pages[i]))
+			continue;
+		set_page_private(pages[i], 0);
+		memset(page_address(pages[i]), 0, PAGE_SIZE << pa->order);
+		if (frozen) /* Order zeroing before caller publishes the page. */
+			smp_wmb();
+		else
+			page_ref_unfreeze(pages[i], 1);
+	}
+	return n;
+}
+
+/**
+ * pisa_alloc_bulk - Allocate up to @nr_pages blocks from @pa
+ * @pa: Allocator to allocate from
+ * @gfp: GFP flags (requests with __GFP_THISNODE, __GFP_DMA, __GFP_DMA32, or
+ *	__GFP_ACCOUNT are declined)
+ * @nr_pages: Number of entries in @page_array (populated entries are skipped)
+ * @page_array: Output array of page pointers
+ * @frozen: Leave allocated pages frozen at refcount 0 if true
+ *
+ * Return: Number of populated entries at the start of @page_array.
+ */
+unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
+			      unsigned long nr_pages, struct page **page_array, bool frozen)
+{
+	unsigned long i = 0, n, got;
+
+	if (unlikely(!pa ||
+		     (gfp & (__GFP_DMA | __GFP_DMA32 | __GFP_THISNODE | __GFP_ACCOUNT))))
+		goto skip;
+
+	while (i < nr_pages) {
+		if (page_array[i]) {
+			i++;
+			continue;
+		}
+		/* Fill the run of @n NULL entries at @i. */
+		for (n = 1; i + n < nr_pages && !page_array[i + n]; n++)
+			;
+		got = __pisa_alloc_bulk(pa, gfp, n, page_array + i,
+					want_init_on_alloc(gfp), frozen);
+		i += got;
+		if (got < n)
+			break;
+	}
+	return i;
+
+skip:
+	/* Declined: report the populated prefix, as alloc_pages_bulk_node() does. */
+	while (i < nr_pages && page_array[i])
+		i++;
+	return i;
+}
+
+
 /**
  * __pisa_free_page - Recycle a freed block back into its PISA allocator
  * @page: Block being freed (called from __free_pages_prepare() under RCU)
@@ -372,8 +690,35 @@ bool __pisa_free_page(struct page *page)
 
 static int __init pisa_init(void)
 {
+	const struct {
+		u8 order;
+		bool ro;
+	} cfg[] = {
+		{ 0, false },
+		{ 2, true },
+		{ SKB_FRAG_PAGE_ORDER, true },
+	};
+	int nid, i;
+
 	pisa_node_init();
 
+	/* Preallocate the supported per-node allocators. */
+	for_each_node_state(nid, N_MEMORY) {
+		for (i = 0; i < ARRAY_SIZE(cfg); i++) {
+			unsigned int order = cfg[i].order;
+			bool ro = cfg[i].ro;
+			struct pisa_alloc *pa;
+
+			if (order > PISA_ORDER || pisa_nodes[nid].pa[ro][order])
+				continue;
+			pa = pisa_create(nid, order, ro ? DMA_TO_DEVICE : DMA_BIDIRECTIONAL);
+			if (!pa)
+				continue;
+			pisa_set_name(pa, "pisa%s_o%u_n%d", ro ? "_ro" : "", order, nid);
+			pisa_nodes[nid].pa[ro][order] = pa;
+		}
+	}
+
 	/* Dedicated WQ_MEM_RECLAIM workqueue so reclaim never blocks behind system_wq. */
 	pisa_wq = alloc_workqueue("pisa", WQ_MEM_RECLAIM, 0);
 	if (!pisa_wq)
drivers/iommu/pisa-kunit.c +75 -3

103 lines not on this page · raw message

drivers/iommu/pisa-priv.h +19 -5
index 0d097c665c790..f15934ccdeea4 100644
@@ -100,6 +100,7 @@ struct pisa_alloc {
 /* Per-NUMA-node PISA state. */
 struct pisa_node {
 	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
+	struct pisa_alloc	*pa[2][PISA_ORDER + 1]; /* [0]=RW, [1]=RO by order */
 
 	spinlock_t		lock;		/* protects @pages and @nr_pages */
 	struct list_head	pages;		/* reservoir */
@@ -114,11 +115,6 @@ int pisa_meta_ensure_pfn(unsigned long pfn, bool can_block);
 struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn);
 unsigned long pisa_meta_to_pfn(const struct pisa_meta *meta);
 
-struct pisa_alloc *pisa_create(int nid, unsigned int order, enum dma_data_direction dir);
-__printf(2, 3)
-void pisa_set_name(struct pisa_alloc *pa, const char *fmt, ...);
-void pisa_release_page(struct pisa_meta *meta);
-
 static inline int pisa_sanitize_nid(int nid)
 {
 	if ((unsigned int)nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
@@ -135,6 +131,24 @@ static inline void pisa_alloc_backoff(int nid, bool can_block)
 		WRITE_ONCE(pisa_nodes[nid].next_alloc, jiffies + DIV_ROUND_UP(HZ, 100));
 }
 
+/* pisa-alloc.c, also used by the per-node code in pisa-node.c */
+struct pisa_alloc *pisa_create(int nid, unsigned int order, enum dma_data_direction dir);
+struct pisa_alloc *pisa_node_pa(int nid, unsigned int order, bool ro);
+__printf(2, 3)
+void pisa_set_name(struct pisa_alloc *pa, const char *fmt, ...);
+void pisa_release_page(struct pisa_meta *meta);
+unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
+			      unsigned long nr_pages, struct page **page_array, bool frozen);
+
+static inline struct page *pisa_alloc(struct pisa_alloc *pa, gfp_t gfp)
+{
+	struct page *page = NULL;
+
+	if (pa)
+		pisa_alloc_bulk(pa, gfp, 1, &page, false);
+	return page;
+}
+
 /* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
 extern unsigned int pisa_reservoir_max;
 void pisa_node_init(void);
include/linux/gfp_types.h +15 -2
index c1331bf0b2398..65fbfca3e08d1 100644
@@ -33,7 +33,7 @@ enum {
 	___GFP_IO_BIT,
 	___GFP_FS_BIT,
 	___GFP_ZERO_BIT,
-	___GFP_UNUSED_BIT,	/* 0x200u unused */
+	___GFP_PISA_RO_BIT,
 	___GFP_DIRECT_RECLAIM_BIT,
 	___GFP_KSWAPD_RECLAIM_BIT,
 	___GFP_WRITE_BIT,
@@ -68,7 +68,11 @@ enum {
 #define ___GFP_IO		BIT(___GFP_IO_BIT)
 #define ___GFP_FS		BIT(___GFP_FS_BIT)
 #define ___GFP_ZERO		BIT(___GFP_ZERO_BIT)
-/* 0x200u unused */
+#ifdef CONFIG_PISA
+#define ___GFP_PISA_RO		BIT(___GFP_PISA_RO_BIT)
+#else
+#define ___GFP_PISA_RO		0
+#endif
 #define ___GFP_DIRECT_RECLAIM	BIT(___GFP_DIRECT_RECLAIM_BIT)
 #define ___GFP_KSWAPD_RECLAIM	BIT(___GFP_KSWAPD_RECLAIM_BIT)
 #define ___GFP_WRITE		BIT(___GFP_WRITE_BIT)
@@ -95,6 +99,11 @@ enum {
 #else
 #define ___GFP_NOLOCKDEP	0
 #endif
+#ifdef CONFIG_PISA
+#define ___GFP_PISA_RW			(___GFP_PISA_RO | ___GFP_WRITE)
+#else
+#define ___GFP_PISA_RW			0
+#endif
 
 /*
  * Physical address zone modifiers (see linux/mmzone.h - low four bits)
@@ -289,6 +298,10 @@ enum {
 /* Disable lockdep for GFP context tracking */
 #define __GFP_NOLOCKDEP ((__force gfp_t)___GFP_NOLOCKDEP)
 
+/* Allocate from per-node PISA allocators (fall back to buddy on failure) */
+#define __GFP_PISA_RO			((__force gfp_t)___GFP_PISA_RO)
+#define __GFP_PISA_RW			((__force gfp_t)___GFP_PISA_RW)
+
 /* Room for N __GFP_FOO bits */
 #define __GFP_BITS_SHIFT ___GFP_LAST_BIT
 #define __GFP_BITS_MASK ((__force gfp_t)((1 << __GFP_BITS_SHIFT) - 1))
include/linux/pisa.h +25 -0
index dddcedb8c93f6..18ba1c83bd6d3 100644
@@ -7,6 +7,7 @@
 #include <linux/bitops.h>
 #include <linux/jump_label.h>
 #include <linux/mm.h>
+#include <linux/numa.h>
 #include <linux/rcupdate.h>
 
 #ifdef CONFIG_PISA
@@ -72,6 +73,11 @@ static inline bool pisa_free_page(struct page *page)
 	return ret;
 }
 
+unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
+				    int preferred_nid, nodemask_t *nodemask,
+				    int nr_pages, struct page **page_array,
+				    bool frozen);
+
 #else /* !CONFIG_PISA */
 
 static inline int pisa_meta_init(void)
@@ -91,8 +97,26 @@ static inline bool pisa_free_page(struct page *page)
 	return false;
 }
 
+static inline unsigned long
+pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred_nid,
+		      nodemask_t *nodemask, int nr_pages,
+		      struct page **page_array, bool frozen)
+{
+	return 0;
+}
+
 #endif /* CONFIG_PISA */
 
+static inline struct page *
+pisa_alloc_pages(gfp_t gfp, unsigned int order, int preferred_nid,
+		 nodemask_t *nodemask)
+{
+	struct page *page = NULL;
+
+	pisa_alloc_pages_bulk(gfp, order, preferred_nid, nodemask, 1, &page, true);
+	return page;
+}
+
 static inline bool is_pisa_phys(phys_addr_t phys)
 {
 	return is_pisa_pfn(phys >> PAGE_SHIFT);
@@ -102,4 +126,5 @@ static inline bool is_pisa_page(const struct page *page)
 {
 	return is_pisa_pfn(page_to_pfn(page));
 }
+
 #endif /* _LINUX_PISA_H */
include/trace/events/mmflags.h +9 -2
index 3c153b3ad8450..65331bd8f0315 100644
@@ -54,10 +54,18 @@
 # define TRACE_GFP_FLAGS_LOCKDEP
 #endif
 
+#ifdef CONFIG_PISA
+# define TRACE_GFP_FLAGS_PISA			\
+	TRACE_GFP_EM(PISA_RO)
+#else
+# define TRACE_GFP_FLAGS_PISA
+#endif
+
 #define TRACE_GFP_FLAGS				\
 	TRACE_GFP_FLAGS_GENERAL			\
 	TRACE_GFP_FLAGS_KASAN			\
-	TRACE_GFP_FLAGS_LOCKDEP
+	TRACE_GFP_FLAGS_LOCKDEP			\
+	TRACE_GFP_FLAGS_PISA
 
 #undef TRACE_GFP_EM
 #define TRACE_GFP_EM(a) TRACE_DEFINE_ENUM(___GFP_##a##_BIT);
@@ -65,7 +73,6 @@
 TRACE_GFP_FLAGS
 
 /* Just in case these are ever used */
-TRACE_DEFINE_ENUM(___GFP_UNUSED_BIT);
 TRACE_DEFINE_ENUM(___GFP_LAST_BIT);
 
 #define gfpflag_string(flag) {(__force unsigned long)flag, #flag}
mm/page_alloc.c +39 -1
index 48df87a19d312..b8e1f0fcb3f41 100644
@@ -1302,17 +1302,40 @@ static inline void pgalloc_tag_sub_pages(struct alloc_tag *tag, unsigned int nr)
 /*
  * pisa_free_page() in __free_pages_prepare() recycles a PISA block into
  * its allocator before the rest of that function runs. __pisa_free_page() calls
- * this to apply the buddy allocator's checks.
+ * this to apply the buddy allocator's checks, and to clear the order-0 state of
+ * blocks that were user pages (see drivers/iommu/pisa-user.c).
  *
  * Return: false if the block is in a bad state (already reported): leak it.
  */
 bool free_page_prepare_pisa(struct page *page, unsigned int order)
 {
+	struct folio *folio;
+	unsigned int i;
+
 	if (!IS_ENABLED(CONFIG_PISA))
 		return true;
+
+	folio = page_folio(page);
+
+	if (!order) {
+		if (unlikely(folio_test_mlocked(folio))) {
+			__folio_clear_mlocked(folio);
+			zone_stat_mod_folio(folio, NR_MLOCK, -1);
+			count_vm_events(UNEVICTABLE_PGCLEARED, 1);
+		}
+		folio->mapping = NULL;
+	}
 	if (is_check_pages_enabled() && free_page_is_bad(page))
 		return false;
 	page_table_check_free(page, order);
+	for (i = 0; i < (1U << order); i++)
+		page_kasan_tag_reset(page + i);
+	kasan_unpoison_range(page_address(page), PAGE_SIZE << order);
+	if (!order) {
+		page_cpupid_reset_last(page);
+		page->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP;
+		page->private = 0;
+	}
 	return true;
 }
 
@@ -5223,6 +5246,14 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
 	while (nr_populated < nr_pages && page_array[nr_populated])
 		nr_populated++;
 
+	if (unlikely(gfp & __GFP_PISA_RO)) {
+		nr_populated = pisa_alloc_pages_bulk(gfp, 0, preferred_nid, nodemask,
+						     nr_pages, page_array, false);
+		gfp &= ~__GFP_PISA_RW;
+		if (nr_populated == nr_pages)
+			goto out;
+	}
+
 	/* No pages requested? */
 	if (unlikely(nr_pages <= 0))
 		goto out;
@@ -5457,6 +5488,13 @@ struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order,
 		fastpath_alloc_flags |= ALLOC_WMARK_LOW;
 	}
 
+	if (unlikely(gfp & __GFP_PISA_RO)) {
+		page = pisa_alloc_pages(gfp, order, preferred_nid, nodemask);
+		if (page)
+			return page;
+		gfp &= ~__GFP_PISA_RW;
+	}
+
 	gfp &= gfp_allowed_mask;
 	/*
 	 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#122 lore raw

Re: [RFC PATCH v2 04/25] iommu/dma: Add PISA block allocation

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] mm: page_alloc: PISA hooks bypass gfp_allowed_mask and current_gfp_context() - [Medium] iommu/dma…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] mm: page_alloc: PISA hooks bypass gfp_allowed_mask and current_gfp_context()
- [Medium] iommu/dma: reclaim lock inversion on pisa_meta_mutex in PISA page allocation
- [Low] iommu/pisa: KUnit test_alloc_and_recycle() fails when SKB_FRAG_PAGE_ORDER is 0
--

commit c88623dbd052fba1d3099d39b6d0533caf0d54a7
Author: Luigi Rizzo <[email protected]>

iommu/dma: Add PISA block allocation

This commit adds PISA block allocation and compound page splitting, along with __GFP_PISA_RO and __GFP_PISA_RW flags hooked into the page allocator.

Quoted 4 lines
drivers/iommu/pisa-alloc.c +0 -0
index cf559ee86d6f9..1f1b99023094c 100644

[ ... ]

drivers/iommu/pisa-alloc.c static void pisa_return_block_locked(struct pisa_alloc *pa, struct page *block, · line 416

Quoted 10 lines
drivers/iommu/pisa-alloc.c +10 -0
+/* Obtain and split a new PISA page on @nid into blocks of @order. */
+static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, int nid)
+{
+	bool can_block = gfpflags_allow_blocking(gfp), clean;
+	unsigned int bpp = PISA_BLOCKS(order);
+	struct pisa_meta *meta;
+	struct page *page;
+
+	/* __GFP_DMA/__GFP_DMA32 were already declined by pisa_alloc_bulk(). */
+	meta = pisa_reservoir_pop(nid, gfp & ~__GFP_ZERO, &clean);

[Severity: Medium]
Can a GFP_NOFS or GFP_NOIO allocation invert lock ordering on pisa_meta_mutex when the reservoir misses?

pisa_meta_init() and pisa_meta_memory_cb() hold pisa_meta_mutex across GFP_KERNEL allocations, establishing pisa_meta_mutex -> fs_reclaim. Here, GFP_NOFS and GFP_NOIO still have __GFP_DIRECT_RECLAIM set, so pisa_reservoir_pop() -> __pisa_page_alloc() calls pisa_meta_ensure_pfn() with can_block == true while the caller holds filesystem or I/O locks:

drivers/iommu/pisa-meta.c:pisa_meta_ensure_pfn() {
    ...
	if (can_block && !pisa_meta_pte((unsigned long)pisa_meta_array + (idx << PAGE_SHIFT))) {
		int err;

		mutex_lock(&pisa_meta_mutex);
		err = pisa_meta_prealloc(pisa_meta_array, pisa_meta_nframes, pfn, pfn + 1);
		mutex_unlock(&pisa_meta_mutex);
    ...
}

CPU0 CPU1
---- ----
lock(fs_lock)

                                  mutex_lock(&pisa_meta_mutex)
                                  apply_to_page_range()
                                    /* fs_reclaim */
                                    lock(fs_lock)
pisa_alloc_split_page(GFP_NOFS)
  ...
    pisa_meta_ensure_pfn(..., true)
      mutex_lock(&pisa_meta_mutex)

*** DEADLOCK ***

[ ... ]

Quoted 17 lines
drivers/iommu/pisa-kunit.c +7 -2
index 079f6220e742a..bdc52e6497b05 100644
@@ -87,9 +90,78 @@ static void test_meta_active_toggle(struct kunit *test)
 
 static void test_alloc_and_recycle(struct kunit *test)
 {
-	KUNIT_EXPECT_NULL(test, pisa_create(NUMA_NO_NODE, 0, DMA_NONE));
-	KUNIT_EXPECT_NULL(test, pisa_create(NUMA_NO_NODE, PISA_ORDER + 1, DMA_BIDIRECTIONAL));
+	const struct {
+		unsigned int order;
+		bool ro;
+	} cases[] = {
+		{ 0, false },
+		{ 2, true },
+		{ SKB_FRAG_PAGE_ORDER, true },

drivers/iommu/pisa-kunit.c static void test_meta_active_toggle(struct kunit *test) · line 109

Quoted 10 lines
drivers/iommu/pisa-kunit.c +10 -0
+	};
+	struct page *p1, *p2, *bulk[3];
+	struct pisa_alloc *pa;
+	unsigned int i;
+
+	KUNIT_EXPECT_NULL(test, pisa_create(first_memory_node, 0, DMA_NONE));
+	KUNIT_EXPECT_NULL(test, pisa_create(first_memory_node, PISA_ORDER + 1,
+					    DMA_BIDIRECTIONAL));
+	KUNIT_EXPECT_NULL(test, pisa_node_pa(first_memory_node, 1, false));
+	KUNIT_EXPECT_NULL(test, pisa_node_pa(first_memory_node, 0, true));

[Severity: Low]
Doesn't this KUNIT_EXPECT_NULL(test, pisa_node_pa(first_memory_node, 0, true)) check fail on arm64 with CONFIG_ARM64_64K_PAGES=y?

With 64KB pages, SKB_FRAG_PAGE_ORDER is get_order(32768) == 0, so pisa_init() populates pisa_nodes[nid].pa[true][0] for the { SKB_FRAG_PAGE_ORDER, true } entry that this test also asserts is non-NULL in the loop below.

[ ... ]

Quoted 4 lines
mm/page_alloc.c +0 -0
index 48df87a19d312..b8e1f0fcb3f41 100644

[ ... ]

Quoted 19 lines
mm/page_alloc.c +8 -0
@@ -5223,6 +5246,14 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
 	while (nr_populated < nr_pages && page_array[nr_populated])
 		nr_populated++;
 
+	if (unlikely(gfp & __GFP_PISA_RO)) {
+		nr_populated = pisa_alloc_pages_bulk(gfp, 0, preferred_nid, nodemask,
+						     nr_pages, page_array, false);
+		gfp &= ~__GFP_PISA_RW;
+		if (nr_populated == nr_pages)
+			goto out;
+	}
+
 	/* No pages requested? */
 	if (unlikely(nr_pages <= 0))
 		goto out;
@@ -5457,6 +5488,13 @@ struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order,
 		fastpath_alloc_flags |= ALLOC_WMARK_LOW;
 	}
 

mm/page_alloc.c struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order, · line 5500

Quoted 10 lines
mm/page_alloc.c +7 -0
+	if (unlikely(gfp & __GFP_PISA_RO)) {
+		page = pisa_alloc_pages(gfp, order, preferred_nid, nodemask);
+		if (page)
+			return page;
+		gfp &= ~__GFP_PISA_RW;
+	}
+
 	gfp &= gfp_allowed_mask;
 	/*
 	 * Apply scoped allocation constraints. This is mainly about GFP_NOFS

[Severity: Medium]
Should both PISA hooks run only after gfp &= gfp_allowed_mask and gfp = current_gfp_context(gfp)?

Callers inside a memalloc_nofs_save() or memalloc_noio_save() scope (or during system suspend when pm_restrict_gfp_mask() clears __GFP_IO | __GFP_FS in gfp_allowed_mask) pass GFP_KERNEL | __GFP_PISA_* and rely on the page allocator to strip __GFP_FS and __GFP_IO. Passing the raw gfp into pisa_alloc_pages_bulk() and pisa_alloc_pages() lets __pisa_page_alloc() see (__GFP_FS | __GFP_IO) still set:

drivers/iommu/pisa-node.c:__pisa_page_alloc() {
	if (unlikely(!static_branch_unlikely(&pisa_key))) {
		if (!can_block || (gfp & (__GFP_FS | __GFP_IO)) != (__GFP_FS | __GFP_IO) ||
		    pisa_meta_init())
			return ERR_PTR(-EAGAIN);
	}
    ...
	if (can_block)
		memflags = pisa_memalloc_save(gfp);
}

As a result, __pisa_page_alloc() can invoke pisa_meta_init() inside a NOFS, NOIO, or suspend context, and pisa_memalloc_save(gfp) fails to set PF_MEMALLOC_NOIO | PF_MEMALLOC_NOFS when gfp_allowed_mask has restricted I/O or filesystem reclaim.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#123 lore raw

RFC PATCH v2 5/25 iommu/dma: Add global cap and shrinker for PISA pages

In reply to Luigi Rizzo

Add two mechanisms to bound the number of unused PISA pages:

- a global ceiling, pisa.max_pages, on the number of PISA pages pinned across all allocators and reservoirs, defaulting to one eighth of RAM, with a floor for small machines.

- a shrinker that, under reclaim, drains the per-node reservoirs first and then completely idle pages across all allocators.
Idle pages are detached under the allocator lock but retired outside it, to avoid holding the lock during the expensive unmaps/iotlb flush.

---
 drivers/iommu/pisa-alloc.c | 91 ++++++++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-kunit.c | 15 +++++++
 drivers/iommu/pisa-node.c  | 25 +++++++++++
 drivers/iommu/pisa-priv.h  | 15 +++++++
 4 files changed, 146 insertions(+)
drivers/iommu/pisa-alloc.c +91 -0
index 1f1b99023094c..de8009fd6fff3 100644
@@ -4,6 +4,7 @@
  * See Documentation/core-api/pisa.rst for the architecture overview.
  */
 
+#include <kunit/visibility.h>
 #include <linux/atomic.h>
 #include <linux/bitmap.h>
 #include <linux/bitops.h>
@@ -22,6 +23,7 @@
 #include <linux/pgalloc_tag.h>
 #include <linux/rcupdate.h>
 #include <linux/sched/mm.h>
+#include <linux/shrinker.h>
 #include <linux/skbuff.h>
 #include <linux/slab.h>
 #include <linux/spinlock.h>
@@ -40,6 +42,11 @@ static LLIST_HEAD(pisa_free_list);
 /* Dedicated WQ_MEM_RECLAIM workqueue, can run without allocations. */
 static struct workqueue_struct *pisa_wq __ro_after_init;
 
+/* Global count and ceiling on PISA pages across all allocators and reservoirs (0 = 1/8 RAM). */
+atomic_long_t pisa_nr_pages __cacheline_aligned_in_smp;
+unsigned long pisa_max_pages __read_mostly;
+module_param_named(max_pages, pisa_max_pages, ulong, 0644);
+
 /* Max completely idle PISA pages kept per allocator before async release. */
 static unsigned int pisa_max_idle __read_mostly = 1;
 module_param_named(max_idle, pisa_max_idle, uint, 0644);
@@ -81,6 +88,7 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 
 	WRITE_ONCE(meta->pa, NULL);
 
+	atomic_long_dec(&pisa_nr_pages);
 	for (i = 0; i < PISA_BLOCKS(order); i++) {
 		block = page + (i << order);
 		page_ref_unfreeze(block, 1);
@@ -93,6 +101,7 @@ void pisa_release_page(struct pisa_meta *meta)
 {
 	if (!meta->pa) {
 		__free_pages(pfn_to_page(pisa_meta_to_pfn(meta)), PISA_ORDER);
+		atomic_long_dec(&pisa_nr_pages);
 		return;
 	}
 
@@ -688,6 +697,72 @@ bool __pisa_free_page(struct page *page)
 	return true;
 }
 
+/* Shrinker: releases reservoir pages first, then idle allocator pages. */
+static unsigned long pisa_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
+{
+	unsigned long nr = pisa_reservoir_count();
+	struct pisa_alloc *pa;
+
+	read_lock(&pisa_allocs_lock);
+	list_for_each_entry(pa, &pisa_allocs, node)
+		nr += READ_ONCE(pa->num_idle_pages);
+	read_unlock(&pisa_allocs_lock);
+
+	return nr << PISA_ORDER;
+}
+
+/* Detach PISA pages from @list onto @release_list up to @nr_to_scan base pages. */
+unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
+			       unsigned int *nr, struct list_head *release_list,
+			       unsigned long nr_to_scan)
+{
+	unsigned long freed = 0, flags;
+
+	spin_lock_irqsave(lock, flags);
+	while (freed < nr_to_scan && !list_empty(list)) {
+		list_move(list->next, release_list);
+		(*nr)--;
+		freed += 1UL << PISA_ORDER;
+	}
+	spin_unlock_irqrestore(lock, flags);
+
+	return freed;
+}
+
+VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
+{
+	struct pisa_meta *meta, *tmp;
+	struct pisa_alloc *pa;
+	unsigned long freed;
+	LIST_HEAD(release_list);
+
+	freed = pisa_reservoir_shrink(&release_list, sc->nr_to_scan);
+
+	if (freed < sc->nr_to_scan) {
+		read_lock(&pisa_allocs_lock);
+		list_for_each_entry(pa, &pisa_allocs, node) {
+			freed += pisa_shrink_list(&pa->lock, &pa->idle,
+						  &pa->num_idle_pages, &release_list,
+						  sc->nr_to_scan - freed);
+
+			if (freed >= sc->nr_to_scan)
+				break;
+		}
+		read_unlock(&pisa_allocs_lock);
+	}
+
+	/* Retiring must not run under @pa->lock. */
+	list_for_each_entry_safe(meta, tmp, &release_list, list) {
+		list_del_init(&meta->list);
+		pisa_release_page(meta);
+	}
+
+	/* Charge do_shrink_slab() for the full PISA pages reclaimed. */
+	sc->nr_scanned = freed;
+
+	return freed ?: SHRINK_STOP;
+}
+
 static int __init pisa_init(void)
 {
 	const struct {
@@ -698,10 +773,15 @@ static int __init pisa_init(void)
 		{ 2, true },
 		{ SKB_FRAG_PAGE_ORDER, true },
 	};
+	struct shrinker *shrink;
 	int nid, i;
 
 	pisa_node_init();
 
+	/* Default ceiling is 1/8th of RAM (floor of 16 PISA pages). */
+	if (!pisa_max_pages)
+		pisa_max_pages = max(totalram_pages() >> (PISA_ORDER + 3), 16UL);
+
 	/* Preallocate the supported per-node allocators. */
 	for_each_node_state(nid, N_MEMORY) {
 		for (i = 0; i < ARRAY_SIZE(cfg); i++) {
@@ -724,6 +804,17 @@ static int __init pisa_init(void)
 	if (!pisa_wq)
 		pr_warn("pisa: no reclaim workqueue, falling back to system_wq\n");
 
+	shrink = shrinker_alloc(0, "pisa");
+	if (!shrink) {
+		pr_warn("pisa: shrinker registration failed\n");
+		return 0;
+	}
+
+	shrink->count_objects = pisa_shrink_count;
+	shrink->scan_objects = pisa_shrink_scan;
+	shrink->seeks = DEFAULT_SEEKS;
+	shrinker_register(shrink);
+
 	return 0;
 }
 subsys_initcall(pisa_init);
drivers/iommu/pisa-kunit.c +15 -0
index bdc52e6497b05..96bc8dbc38fb4 100644
@@ -6,6 +6,7 @@
 #include <linux/gfp.h>
 #include <linux/pisa.h>
 #include <linux/mm.h>
+#include <linux/shrinker.h>
 #include <linux/skbuff.h>
 #include <net/sock.h>
 
@@ -98,8 +99,10 @@ static void test_alloc_and_recycle(struct kunit *test)
 		{ 2, true },
 		{ SKB_FRAG_PAGE_ORDER, true },
 	};
+	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	struct page *p1, *p2, *bulk[3];
 	struct pisa_alloc *pa;
+	unsigned long old_max;
 	unsigned int i;
 
 	KUNIT_EXPECT_NULL(test, pisa_create(first_memory_node, 0, DMA_NONE));
@@ -115,6 +118,7 @@ static void test_alloc_and_recycle(struct kunit *test)
 
 		pa = pisa_node_pa(first_memory_node, order, cases[i].ro);
 		KUNIT_ASSERT_NOT_NULL(test, pa);
+		pisa_shrink_scan(NULL, &sc);
 		KUNIT_EXPECT_NULL(test, pisa_alloc(pa, GFP_KERNEL | __GFP_ACCOUNT));
 		KUNIT_EXPECT_NULL(test, pisa_alloc(pa, GFP_KERNEL | __GFP_DMA32));
 		KUNIT_EXPECT_NULL(test, pisa_alloc(pa, GFP_KERNEL | __GFP_THISNODE));
@@ -155,6 +159,7 @@ static void test_alloc_and_recycle(struct kunit *test)
 
 		if (p2)
 			__free_pages(p2, order);
+		pisa_shrink_scan(NULL, &sc);
 	}
 
 	/* Plain alloc_page() without __GFP_PISA_* comes from the buddy allocator. */
@@ -162,6 +167,16 @@ static void test_alloc_and_recycle(struct kunit *test)
 	KUNIT_ASSERT_NOT_NULL(test, p1);
 	KUNIT_EXPECT_FALSE(test, is_pisa_page(p1));
 	__free_pages(p1, 0);
+
+	/* Global budget cap (pisa_max_pages = 0) refuses new PISA pages. */
+	pa = pisa_node_pa(first_memory_node, 2, true);
+	KUNIT_ASSERT_NOT_NULL(test, pa);
+	old_max = READ_ONCE(pisa_max_pages);
+	WRITE_ONCE(pisa_max_pages, 0);
+	WRITE_ONCE(pisa_reservoir_max, 0);
+	KUNIT_EXPECT_NULL(test, pisa_alloc(pa, GFP_KERNEL));
+	WRITE_ONCE(pisa_reservoir_max, 16);
+	WRITE_ONCE(pisa_max_pages, old_max);
 }
 
 static void test_reservoir_and_scrubber(struct kunit *test)
drivers/iommu/pisa-node.c +25 -0
index 524f0d4457ad7..0f23b94a7a6f8 100644
@@ -74,6 +74,10 @@ static struct pisa_meta *__pisa_page_alloc(gfp_t gfp, int nid, bool can_block,
 			return ERR_PTR(-EAGAIN);
 	}
 
+	/* Racy check against global ceiling across allocators and reservoirs. */
+	if (atomic_long_read(&pisa_nr_pages) >= READ_ONCE(pisa_max_pages))
+		return ERR_PTR(-ENOSPC);
+
 	/*
 	 * Long-lived active pages must be unmovable, lowmem, non-compound, and
 	 * must not dip into emergency reserves or trigger OOM/warnings.
@@ -102,6 +106,8 @@ static struct pisa_meta *__pisa_page_alloc(gfp_t gfp, int nid, bool can_block,
 
 	meta = pisa_meta_of_pfn(page_to_pfn(page));
 	memset(meta, 0, sizeof(*meta));
+
+	atomic_long_inc(&pisa_nr_pages);
 	*clean = (gfp & __GFP_ZERO) || want_init_on_alloc(0) || want_init_on_free();
 
 	return meta;
@@ -256,6 +262,25 @@ unsigned long pisa_reservoir_count(void)
 	return nr;
 }
 
+/* Detach up to @nr_to_scan base pages from reservoirs onto @release_list. */
+unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan)
+{
+	unsigned long freed = 0;
+	int nid;
+
+	for_each_node_state(nid, N_MEMORY) {
+		struct pisa_node *res = &pisa_nodes[nid];
+
+		if (!READ_ONCE(res->nr_pages))
+			continue;
+		freed += pisa_shrink_list(&res->lock, &res->pages, &res->nr_pages,
+					  release_list, nr_to_scan - freed);
+		if (freed >= nr_to_scan)
+			break;
+	}
+	return freed;
+}
+
 void __init pisa_node_init(void)
 {
 	int nid;
drivers/iommu/pisa-priv.h +15 -0
index f15934ccdeea4..d5ea83745ba47 100644
@@ -115,6 +115,16 @@ int pisa_meta_ensure_pfn(unsigned long pfn, bool can_block);
 struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn);
 unsigned long pisa_meta_to_pfn(const struct pisa_meta *meta);
 
+struct shrink_control;
+struct shrinker;
+#if IS_ENABLED(CONFIG_KUNIT)
+unsigned long pisa_shrink_scan(struct shrinker *shrink, struct shrink_control *sc);
+#endif
+
+/* Global PISA page budget across all allocators and per-node reservoirs. */
+extern atomic_long_t pisa_nr_pages;
+extern unsigned long pisa_max_pages;
+
 static inline int pisa_sanitize_nid(int nid)
 {
 	if ((unsigned int)nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
@@ -149,12 +159,17 @@ static inline struct page *pisa_alloc(struct pisa_alloc *pa, gfp_t gfp)
 	return page;
 }
 
+unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
+			       unsigned int *nr, struct list_head *release_list,
+			       unsigned long nr_to_scan);
+
 /* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
 extern unsigned int pisa_reservoir_max;
 void pisa_node_init(void);
 void pisa_schedule_reservoir(void);
 struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean);
 unsigned long pisa_reservoir_count(void);
+unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan);
 
 #endif /* CONFIG_PISA */
 #endif /* _DRIVERS_IOMMU_PISA_PRIV_H */
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#124 lore raw

RFC PATCH v2 6/25 iommu/dma: Reserve a per-domain IOVA window for PISA pages

In reply to Luigi Rizzo

PISA buffers need to be quickly identified from their iova, and may need to be mapped in multiple domains. We can achieve both by reserving an IOVA range for PISA pages in each domain.

Add per-domain PISA IOVA window descriptors in struct iommu_dma_cookie and a global slot allocator (pisa_slot_alloc() / pisa_slot_free()). The window is sized to twice the maximum allowed PISA buffer space, defaulting to max(64MB, 1/4 of physical RAM).

A buffer is mapped at the same slot offset in all windows for the domains that need to access it. IOVA allocation is done with a bitmap (1 bit per 2MB buffer, hence a 4KB bitmap supports 64GB of buffer space) at negligible cost.

---
 drivers/iommu/Makefile     |  3 ++
 drivers/iommu/dma-iommu.c  | 18 ++++++++
 drivers/iommu/dma-iommu.h  | 16 +++++++
 drivers/iommu/pisa-alloc.c | 12 ++++-
 drivers/iommu/pisa-kunit.c | 24 ++++++++++
 drivers/iommu/pisa-map.c   | 90 ++++++++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-priv.h  | 58 ++++++++++++++++++++++++
 7 files changed, 220 insertions(+), 1 deletion(-)
 create mode 100644 drivers/iommu/pisa-map.c
drivers/iommu/Makefile +3 -0
index bc58166f9303a..125cf7e813cdc 100644
@@ -12,6 +12,9 @@ obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
 obj-$(CONFIG_PISA) += pisa-meta.o pisa-alloc.o pisa-node.o
+ifeq ($(CONFIG_IOMMU_DMA),y)
+obj-$(CONFIG_PISA) += pisa-map.o
+endif
 obj-$(CONFIG_PISA_META_KUNIT_TEST) += pisa-kunit.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE) += io-pgtable.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_ARMV7S) += io-pgtable-arm-v7s.o
drivers/iommu/dma-iommu.c +18 -0
index 78742aeba932d..fba6084feac81 100644
@@ -36,6 +36,7 @@
 #include <trace/events/swiotlb.h>
 
 #include "dma-iommu.h"
+#include "pisa-priv.h"
 #include "iommu-pages.h"
 #include "iommu-priv.h"
 
@@ -76,6 +77,8 @@ struct iommu_dma_cookie {
 	struct iommu_domain *fq_domain;
 	/* Options for dma-iommu use */
 	struct iommu_dma_options options;
+	/* IOVA window reserved for PISA pages. Nothing else can go here. */
+	struct pisa_window win_pisa;
 };
 
 struct iommu_dma_msi_cookie {
@@ -1215,6 +1218,21 @@ static inline size_t iova_unaligned(struct iova_domain *iovad, phys_addr_t phys,
 	return iova_offset(iovad, phys | size);
 }
 
+/* Return @domain's PISA window, or NULL if @domain cannot use PISA. */
+struct pisa_window *pisa_dma_window(struct iommu_domain *domain)
+{
+	if (static_branch_unlikely(&iommu_deferred_attach_enabled) ||
+	    !domain || domain->cookie_type != IOMMU_COOKIE_DMA_IOVA)
+		return NULL;
+
+	return &domain->iova_cookie->win_pisa;
+}
+
+struct iova_domain *pisa_dma_iovad(struct iommu_domain *domain)
+{
+	return pisa_dma_window(domain) ? &domain->iova_cookie->iovad : NULL;
+}
+
 dma_addr_t iommu_dma_map_phys(struct device *dev, phys_addr_t phys, size_t size,
 		enum dma_data_direction dir, unsigned long attrs)
 {
drivers/iommu/dma-iommu.h +16 -0
index 040d002525632..f112b47396984 100644
@@ -7,6 +7,9 @@
 
 #include <linux/iommu.h>
 
+struct pisa_window;
+struct iova_domain;
+
 #ifdef CONFIG_IOMMU_DMA
 
 void iommu_setup_dma_ops(struct device *dev, struct iommu_domain *domain);
@@ -22,6 +25,9 @@ void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list);
 int iommu_dma_sw_msi(struct iommu_domain *domain, struct msi_desc *desc,
 		     phys_addr_t msi_addr);
 
+struct iova_domain *pisa_dma_iovad(struct iommu_domain *domain);
+struct pisa_window *pisa_dma_window(struct iommu_domain *domain);
+
 extern bool iommu_dma_forcedac;
 
 #else /* CONFIG_IOMMU_DMA */
@@ -59,5 +65,15 @@ static inline int iommu_dma_sw_msi(struct iommu_domain *domain,
 	return -ENODEV;
 }
 
+static inline struct iova_domain *pisa_dma_iovad(struct iommu_domain *domain)
+{
+	return NULL;
+}
+
+static inline struct pisa_window *pisa_dma_window(struct iommu_domain *domain)
+{
+	return NULL;
+}
+
 #endif	/* CONFIG_IOMMU_DMA */
 #endif	/* __DMA_IOMMU_H */
drivers/iommu/pisa-alloc.c +11 -1
index de8009fd6fff3..d7b73c3a6c0b6 100644
@@ -84,10 +84,12 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 	/* Read @meta before freeing blocks; the frame can be reused immediately. */
 	struct pisa_meta *meta = container_of(head, struct pisa_meta, rcu);
 	struct page *block, *page = pfn_to_page(pisa_meta_to_pfn(meta));
-	unsigned int i, order = meta->pa->order;
+	unsigned int i, order = meta->pa->order, slot = meta->slot;
 
 	WRITE_ONCE(meta->pa, NULL);
 
+	/* The page has been unmapped from every domain by pisa_release_page() */
+	pisa_slot_free(slot);
 	atomic_long_dec(&pisa_nr_pages);
 	for (i = 0; i < PISA_BLOCKS(order); i++) {
 		block = page + (i << order);
@@ -426,10 +428,16 @@ static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, in
 	if (IS_ERR(meta))
 		return meta;
 
+	if (unlikely(pisa_slot_alloc(meta))) {
+		pisa_release_page(meta);
+		return ERR_PTR(-ENOSPC);
+	}
+
 	page = pfn_to_page(pisa_meta_to_pfn(meta));
 
 	/* Fails with -EBUSY if a concurrent PFN walker holds a speculative ref. */
 	if (split_page_compound(page, PISA_ORDER, order)) {
+		pisa_slot_free(meta->slot);
 		pisa_release_page(meta);
 		pisa_alloc_backoff(nid, can_block);
 		return ERR_PTR(-EBUSY);
@@ -782,6 +790,8 @@ static int __init pisa_init(void)
 	if (!pisa_max_pages)
 		pisa_max_pages = max(totalram_pages() >> (PISA_ORDER + 3), 16UL);
 
+	pisa_slots_init();
+
 	/* Preallocate the supported per-node allocators. */
 	for_each_node_state(nid, N_MEMORY) {
 		for (i = 0; i < ARRAY_SIZE(cfg); i++) {
drivers/iommu/pisa-kunit.c +24 -0
index 96bc8dbc38fb4..5a2e806e74654 100644
@@ -10,6 +10,7 @@
 #include <linux/skbuff.h>
 #include <net/sock.h>
 
+#include "dma-iommu.h"
 #include "pisa-priv.h"
 
 static void test_meta_init_and_roundtrip(struct kunit *test)
@@ -179,6 +180,26 @@ static void test_alloc_and_recycle(struct kunit *test)
 	WRITE_ONCE(pisa_max_pages, old_max);
 }
 
+#ifdef CONFIG_IOMMU_DMA
+static void test_window_helpers(struct kunit *test)
+{
+	struct pisa_window win = {};
+
+	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
+
+	/* Empty window (base == 0) never owns any IOVA. */
+	KUNIT_EXPECT_FALSE(test, is_pisa_iova(&win, 0));
+	KUNIT_EXPECT_FALSE(test, is_pisa_iova(&win, SZ_4G));
+
+	win.base = SZ_4G;
+	KUNIT_EXPECT_FALSE(test, is_pisa_iova(&win, SZ_4G - 1));
+	KUNIT_EXPECT_TRUE(test, is_pisa_iova(&win, SZ_4G));
+	KUNIT_EXPECT_TRUE(test, is_pisa_iova(&win, SZ_4G + pisa_window_size - 1));
+	KUNIT_EXPECT_FALSE(test, is_pisa_iova(&win, SZ_4G + pisa_window_size));
+}
+
+#endif /* CONFIG_IOMMU_DMA */
+
 static void test_reservoir_and_scrubber(struct kunit *test)
 {
 	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
@@ -190,6 +211,9 @@ static struct kunit_case pisa_meta_test_cases[] = {
 	KUNIT_CASE(test_meta_invalid_phys),
 	KUNIT_CASE(test_meta_active_toggle),
 	KUNIT_CASE(test_alloc_and_recycle),
+#ifdef CONFIG_IOMMU_DMA
+	KUNIT_CASE(test_window_helpers),
+#endif
 	KUNIT_CASE(test_reservoir_and_scrubber),
 	{}
 };
drivers/iommu/pisa-map.c new file +90 -0

90 lines not on this page · raw message

drivers/iommu/pisa-priv.h +58 -0

86 lines not on this page · raw message

Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#125 lore raw

RFC PATCH v2 7/25 iommu/dma: Release PISA domain mappings on domain teardown

In reply to Luigi Rizzo

Each PISA page can be mapped by multiple IOMMU domains.

Add pisa_domain_release() (called from iommu_put_dma_cookie()) to drop a dying domain from the registry, clear its bit across all active PISA pages, and wait on SRCU before reusing the domain index. If iommu_unmap() fails on page release, mark the 2MB page PISA_QUARANTINED and leak it so a device can never access reallocated memory.

When a group's last DMA API user detaches (iommu_device_unuse_default_domain() with owner_cnt reaching 0), call pisa_domain_quiesce() to unmap all active PISA pages from the default domain and flush the IOTLB while keeping the domain's window and index for future demand mappings.

---
 drivers/iommu/dma-iommu.c  |   3 +
 drivers/iommu/iommu.c      |   5 +
 drivers/iommu/pisa-alloc.c |  14 ++-
 drivers/iommu/pisa-kunit.c |  18 ++++
 drivers/iommu/pisa-map.c   | 214 ++++++++++++++++++++++++++++++++++++-
 drivers/iommu/pisa-priv.h  |  56 +++++++++-
 include/linux/pisa.h       |   1 +
 7 files changed, 306 insertions(+), 5 deletions(-)
drivers/iommu/dma-iommu.c +3 -0
index fba6084feac81..025bceebb2262 100644
@@ -430,6 +430,9 @@ void iommu_put_dma_cookie(struct iommu_domain *domain)
 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
 	struct iommu_dma_msi_page *msi, *tmp;
 
+	/* Drop cached PISA mappings before the IOVA domain goes away. */
+	pisa_domain_release(domain);
+
 	if (cookie->iovad.granule) {
 		iommu_dma_free_fq(cookie);
 		put_iova_domain(&cookie->iovad);
drivers/iommu/iommu.c +5 -0
index b486b8bbd1fcd..dfba3d5c277c2 100644
@@ -37,6 +37,7 @@
 #include <linux/generic_pt/iommu.h>
 
 #include "dma-iommu.h"
+#include "pisa-priv.h"
 #include "iommu-priv.h"
 
 static struct kset *iommu_group_kset;
@@ -3363,6 +3364,10 @@ void iommu_device_unuse_default_domain(struct device *dev)
 	if (!WARN_ON(!group->owner_cnt || !xa_empty(&group->pasid_array)))
 		group->owner_cnt--;
 
+	/* Unmap persistent PISA windows when the last driver detaches. */
+	if (!group->owner_cnt)
+		pisa_domain_quiesce(group->default_domain);
+
 	mutex_unlock(&group->mutex);
 }
 
drivers/iommu/pisa-alloc.c +11 -3
index d7b73c3a6c0b6..dd90aad296edf 100644
@@ -13,6 +13,7 @@
 #include <linux/pisa.h>
 #include <linux/export.h>
 #include <linux/gfp.h>
+#include <linux/iommu.h>
 #include <linux/list.h>
 #include <linux/llist.h>
 #include <linux/memcontrol.h>
@@ -30,6 +31,7 @@
 #include <linux/workqueue.h>
 #include <net/sock.h>
 
+#include "dma-iommu.h"
 #include "pisa-priv.h"
 
 /* Parameters are pisa.<name> at boot and in /sys/module/pisa/parameters/. */
@@ -88,6 +90,10 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 
 	WRITE_ONCE(meta->pa, NULL);
 
+	/* Possibly still mapped by a device: leak it, still charged. */
+	if (meta->flags & PISA_QUARANTINED)
+		return;
+
 	/* The page has been unmapped from every domain by pisa_release_page() */
 	pisa_slot_free(slot);
 	atomic_long_dec(&pisa_nr_pages);
@@ -107,7 +113,8 @@ void pisa_release_page(struct pisa_meta *meta)
 		return;
 	}
 
-	/* pisa_unmap_all(meta) will be called here once IOMMU mappings are added. */
+	/* Quarantined on unmap failure and leaked in pisa_release_page_rcu(). */
+	pisa_unmap_all(meta);
 
 	/* Clear PISA_ACTIVE before the RCU grace period so new readers stop entering. */
 	WRITE_ONCE(meta->flags, meta->flags & ~PISA_ACTIVE);
@@ -194,7 +201,8 @@ static bool pisa_place_meta(struct pisa_meta *meta)
 	lockdep_assert_held(&pa->lock);
 
 	if (avail == bpp) {
-		if (pa->num_idle_pages >= pa->max_idle_pages && !READ_ONCE(pisa_idle_ms)) {
+		if ((meta->flags & PISA_QUARANTINED) ||
+		    (pa->num_idle_pages >= pa->max_idle_pages && !READ_ONCE(pisa_idle_ms))) {
 			list_del_init(&meta->list);
 			WRITE_ONCE(meta->on_list, PISA_LIST_NONE);
 			llist_add(&meta->llnode, &pisa_free_list);
@@ -204,7 +212,7 @@ static bool pisa_place_meta(struct pisa_meta *meta)
 			WRITE_ONCE(pa->idle_jiffies, jiffies);
 		pa->num_idle_pages++;
 		on_list = meta->nr_dirty ? PISA_LIST_IDLE_DIRTY : PISA_LIST_IDLE_CLEAN;
-	} else if (!avail) {
+	} else if (!avail || unlikely(meta->flags & PISA_QUARANTINED)) {
 		on_list = PISA_LIST_FULL;
 	} else {
 		bool sparse;
drivers/iommu/pisa-kunit.c +18 -0
index 5a2e806e74654..f0775aa45a058 100644
@@ -5,6 +5,7 @@
 #include <kunit/test.h>
 #include <linux/gfp.h>
 #include <linux/pisa.h>
+#include <linux/iommu.h>
 #include <linux/mm.h>
 #include <linux/shrinker.h>
 #include <linux/skbuff.h>
@@ -183,6 +184,7 @@ static void test_alloc_and_recycle(struct kunit *test)
 #ifdef CONFIG_IOMMU_DMA
 static void test_window_helpers(struct kunit *test)
 {
+	struct iommu_domain dummy_domain = {};
 	struct pisa_window win = {};
 
 	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
@@ -196,6 +198,22 @@ static void test_window_helpers(struct kunit *test)
 	KUNIT_EXPECT_TRUE(test, is_pisa_iova(&win, SZ_4G));
 	KUNIT_EXPECT_TRUE(test, is_pisa_iova(&win, SZ_4G + pisa_window_size - 1));
 	KUNIT_EXPECT_FALSE(test, is_pisa_iova(&win, SZ_4G + pisa_window_size));
+
+	/* Sentinel values in pisa_window_declined(). */
+	win.domain_idx = PISA_IDX_NONE;
+	KUNIT_EXPECT_EQ(test, pisa_window_declined(&win), 0);
+	win.domain_idx = PISA_IDX_NOHUGE;
+	KUNIT_EXPECT_EQ(test, pisa_window_declined(&win), -EOPNOTSUPP);
+	win.domain_idx = PISA_IDX_NOWINDOW;
+	KUNIT_EXPECT_EQ(test, pisa_window_declined(&win), -ENOSPC);
+	win.domain_idx = PISA_IDX_NOIDX;
+	win.idx_gen = READ_ONCE(pisa_idx_gen);
+	KUNIT_EXPECT_EQ(test, pisa_window_declined(&win), -EBUSY);
+	win.idx_gen--;
+	KUNIT_EXPECT_EQ(test, pisa_window_declined(&win), 0);
+
+	/* Releasing an unregistered domain with an active allocator is a safe no-op. */
+	pisa_domain_release(&dummy_domain);
 }
 
 #endif /* CONFIG_IOMMU_DMA */
drivers/iommu/pisa-map.c +213 -1

229 lines not on this page · raw message

drivers/iommu/pisa-priv.h +55 -1

122 lines not on this page · raw message

include/linux/pisa.h +1 -0
index 18ba1c83bd6d3..ab1c32e065bbb 100644
@@ -27,6 +27,7 @@
 
 enum {
 	PISA_ACTIVE		= BIT(0), /* page is owned by a pisa_alloc */
+	PISA_QUARANTINED	= BIT(1), /* IOMMU unmap failed: never reuse */
 };
 
 /* Enabled on first pisa_meta_init() to activate fast-path hooks. */
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#126 lore raw

Re: [RFC PATCH v2 07/25] iommu/dma: Release PISA domain mappings on domain teardown

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] iommu/dma: list and RCU corruption in pisa_domain_quiesce() on quarantine - [Medium] iommu/dma…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] iommu/dma: list and RCU corruption in pisa_domain_quiesce() on quarantine
- [Medium] iommu/dma: data race on meta->flags in pisa_quarantine_meta() and release
- [Medium] iommu/dma: build failure in pisa_domain_quiesce() due to static symbols
- [Medium] iommu/dma: missing struct pisa_meta declaration in pisa-priv.h stubs
--

commit 72b9f4d8d1b40452a8315c8a6e6bdaec17fbdb98
Author: Luigi Rizzo <[email protected]>

iommu/dma: Release PISA domain mappings on domain teardown

This commit adds pisa_domain_release() and pisa_domain_quiesce() to unmap active PISA pages and release or quiesce domain mappings when an IOMMU domain is torn down or its last DMA API user detaches, quarantining and leaking any 2MB page whose iommu_unmap() fails.

Quoted 4 lines
drivers/iommu/pisa-map.c +0 -0
index 2e8d635dec34c..2ba977bb68734 100644

[ ... ]

Quoted 8 lines
drivers/iommu/pisa-map.c +8 -0
+/* Report a short IOMMU unmap and mark @meta quarantined so it is never reused. */
+static void pisa_quarantine_meta(struct pisa_meta *meta, struct iommu_domain *domain,
+				 int idx, dma_addr_t iova, size_t unmapped)
+{
+	pr_err_ratelimited("pisa: unmap of IOVA %pad in domain %p (index %d) returned %zu, quarantining PISA page\n",
+			   &iova, domain, idx, unmapped);
+	WRITE_ONCE(meta->flags, meta->flags | PISA_QUARANTINED);
+}

[ ... ]

Quoted 6 lines
drivers/iommu/pisa-map.c +6 -0
+static unsigned int pisa_unmap_domain_locked(struct pisa_meta *meta,
+					     struct iommu_domain *domain,
+					     int idx, dma_addr_t base,
+					     struct iommu_iotlb_gather *gather)
+{
+	dma_addr_t iova = base + pisa_meta_win_offset(meta);

drivers/iommu/pisa-map.c void __init pisa_slots_init(void) · line 244

Quoted 10 lines
drivers/iommu/pisa-map.c +10 -0
+	size_t unmapped;
+
+	if (!test_and_clear_bit(idx, meta->domains_mapped))
+		return 0;
+
+	unmapped = iommu_unmap_fast(domain, iova, PISA_SIZE, gather);
+	if (unlikely(unmapped != PISA_SIZE))
+		pisa_quarantine_meta(meta, domain, idx, iova, unmapped);
+	return 1;
+}

[Severity: Medium]
Can concurrent updates to meta->flags in pisa_quarantine_meta() and pisa_release_page() clobber each other?

pisa_unmap_domain_locked() clears idx in meta->domains_mapped before calling iommu_unmap_fast() and pisa_quarantine_meta(), so a concurrent pisa_release_page() -> pisa_unmap_all() can see bit idx already cleared and proceed to update meta->flags without synchronization:

CPU0 CPU1
pisa_domain_quiesce() pisa_release_page()
pisa_unmap_domain_locked()

    test_and_clear_bit(idx, ...)
                                        pisa_unmap_all()
                                        flags = meta->flags
    iommu_unmap_fast() [short unmap]
    pisa_quarantine_meta()
      meta->flags |= PISA_QUARANTINED
                                        meta->flags = flags & ~PISA_ACTIVE
                                          <-- drops PISA_QUARANTINED

When PISA_QUARANTINED is lost, pisa_release_page_rcu() frees the IOVA slot and returns the still-mapped 2MB page to the buddy allocator. With the opposite interleaving, pisa_quarantine_meta() restores PISA_ACTIVE on the retired page.

Quoted 43 lines
drivers/iommu/pisa-map.c +43 -0
+/*
+ * Unmap all PISA leaf PTEs from a domain whose last DMA API user detached,
+ * keeping its window and domain index so mappings are re-installed on demand.
+ */
+void pisa_domain_quiesce(struct iommu_domain *domain)
+{
+	struct iommu_iotlb_gather gather;
+	struct pisa_window *win;
+	unsigned int slot, done = 0;
+	bool release = false;
+	dma_addr_t base;
+	int idx;
+
+	if (!static_branch_unlikely(&pisa_key))
+		return;
+	win = pisa_dma_window(domain);
+	/* Pairs with smp_store_release() in pisa_window_assign(). */
+	base = win ? smp_load_acquire(&win->base) : 0;
+	if (!base)
+		return;
+	idx = win->domain_idx - PISA_IDX_FIRST;
+
+	iommu_iotlb_gather_init(&gather);
+	/* Keep call_rcu()-freed pages from reaching the buddy allocator before IOTLB sync. */
+	rcu_read_lock();
+	for_each_set_bit(slot, pisa_slot_bitmap, pisa_nr_slots) {
+		struct pisa_meta *meta = READ_ONCE(pisa_slot2meta[slot]);
+		struct pisa_alloc *pa;
+		unsigned long flags;
+
+		if (!meta || !test_bit(idx, meta->domains_mapped))
+			continue;
+		done += pisa_unmap_domain_locked(meta, domain, idx, base, &gather);
+		if (likely(!(meta->flags & PISA_QUARANTINED)))
+			continue;
+		pa = READ_ONCE(meta->pa);
+		if (!pa)
+			continue;
+		spin_lock_irqsave(&pa->lock, flags);
+		if (meta->pa == pa) {
+			if (meta->on_list == PISA_LIST_IDLE_CLEAN ||
+			    meta->on_list == PISA_LIST_IDLE_DIRTY)
+				pa->num_idle_pages--;

drivers/iommu/pisa-map.c void __init pisa_slots_init(void) · line 298

Quoted 10 lines
drivers/iommu/pisa-map.c +10 -0
+			release |= pisa_place_meta(meta);
+		}
+		spin_unlock_irqrestore(&pa->lock, flags);
+	}
+
+	if (done)
+		iommu_iotlb_sync(domain, &gather);
+	rcu_read_unlock();
+	if (release)
+		pisa_schedule_reclaim();

[Severity: Medium]
Does pisa-map.o fail to build at this commit because PISA_LIST_IDLE_CLEAN, PISA_LIST_IDLE_DIRTY, pisa_place_meta(), and pisa_schedule_reclaim() are still static or local to drivers/iommu/pisa-alloc.c?

Those declarations are only moved to drivers/iommu/pisa-priv.h in a later patch in the series, commit "block, mm, iommu/dma: Support PISA for disk I/O and scrub migration", which breaks bisection when CONFIG_PISA and CONFIG_IOMMU_DMA are enabled.

[Severity: Medium]
Can pisa_domain_quiesce() call pisa_place_meta() on an idle page that has already been detached from pa for release, corrupting pisa_free_list or meta->rcu?

When an idle page (avail == bpp) is detached onto pisa_free_list or queued with call_rcu(), meta->pa remains non-NULL until pisa_release_page_rcu() runs after the grace period, and its slot stays set in pisa_slot_bitmap. If pisa_domain_quiesce() sees PISA_QUARANTINED on that page, meta->pa == pa is still true and pisa_place_meta() runs llist_add(&meta->llnode, &pisa_free_list) on it:

CPU0 CPU1
pisa_reclaim_work_fn() pisa_domain_quiesce()
... rcu_read_lock()
pisa_release_page(meta)

    call_rcu(&meta->rcu, ...)
                                        pisa_unmap_domain_locked()
                                          pisa_quarantine_meta()
                                        spin_lock_irqsave(&pa->lock, ...)
                                        if (meta->pa == pa)
                                          pisa_place_meta(meta)
                                            llist_add(&meta->llnode,
                                                      &pisa_free_list)
                                              <-- overwrites live meta->rcu

Because meta->llnode and meta->rcu share an anonymous union, adding meta->llnode to pisa_free_list overwrites the active RCU head (or creates a cycle in pisa_free_list if pisa_reclaim_work_fn() has not popped it yet), and a second pisa_release_page() after meta->pa is cleared to NULL hits the !meta->pa branch and frees the quarantined 2MB page to the buddy allocator.

In addition, pisa_shrink_list() moves idle pages onto pisa_shrink_scan()'s local release_list and decrements pa->num_idle_pages without setting meta->on_list to PISA_LIST_NONE, so pisa_domain_quiesce() will also decrement pa->num_idle_pages a second time and run list_del_init() on meta->list while pisa_shrink_scan() walks release_list unlocked.

Quoted 4 lines
drivers/iommu/pisa-priv.h +0 -0
index 3ef6e51402ceb..f97f69a13d1a9 100644

[ ... ]

Quoted 5 lines

#define pisa_nr_slots 0U
static inline void pisa_slots_init(void) {}
static inline int pisa_slot_alloc(struct pisa_meta *meta) { return 0; } static inline void pisa_slot_free(unsigned int slot) {}
+static inline int pisa_unmap_all(struct pisa_meta *meta) { return 0; }

[Severity: Medium]
Does including pisa-priv.h in drivers/iommu/iommu.c trigger a -Wvisibility warning on struct pisa_meta when CONFIG_PISA is disabled?

struct pisa_meta is only declared inside #ifdef CONFIG_PISA, so when CONFIG_PISA=n the parameter lists of pisa_slot_alloc() and pisa_unmap_all() declare a local struct pisa_meta type, failing the build under CONFIG_WERROR=y.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#127 lore raw

RFC PATCH v2 8/25 iommu/dma: Use per-domain IOVA window to map PISA memory

In reply to Luigi Rizzo

Intercept the DMA mapping and unmapping functions so that PISA buffers are mapped within the reserved IOVA range.

This is implemented as follows:
- each domain that enables PISA (via per-device optin) is dynamically assigned an IOVA window and a compact index the first time it maps a PISA page.
This way, one bit in pisa_meta suffices to record whether the domain has already mapped the page.
- The page is mapped in the domain at win->base + slot * 2MB on first use, and subsequent mappings reuse that translation.

---
 drivers/iommu/Kconfig      |   1 +
 drivers/iommu/dma-iommu.c  |  15 +++
 drivers/iommu/iommu.c      |   5 +-
 drivers/iommu/pisa-alloc.c |   5 +-
 drivers/iommu/pisa-kunit.c | 133 +++++++++++++++++++++++++++
 drivers/iommu/pisa-map.c   | 184 +++++++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-priv.h  |  35 ++++++-
 include/linux/pisa.h       |   3 +
 8 files changed, 377 insertions(+), 4 deletions(-)
drivers/iommu/Kconfig +1 -0
index 15e06eaed0924..52cce0963525b 100644
@@ -428,6 +428,7 @@ config PISA
 	bool "Pre-mapped IOVA Superpage Allocator"
 	depends on X86_64 || ARM64
 	depends on !PREEMPT_RT
+	select NEED_SG_DMA_FLAGS
 	default y
 	help
 	  PISA is a specialized memory allocator with an API similar to
drivers/iommu/dma-iommu.c +15 -0
index 025bceebb2262..eb920ad77c783 100644
@@ -837,6 +837,8 @@ static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
 	struct iommu_iotlb_gather iotlb_gather;
 	size_t unmapped;
 
+	if (is_pisa_iova(&cookie->win_pisa, dma_addr))
+		return;
 	dma_addr -= iova_off;
 	size = iova_align(iovad, size + iova_off);
 	iommu_iotlb_gather_init(&iotlb_gather);
@@ -863,6 +865,8 @@ static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys,
 	    iommu_deferred_attach(dev, domain))
 		return DMA_MAPPING_ERROR;
 
+	if (!pisa_map_phys(&iova, dev, domain, phys, size, prot))
+		return iova;
 	/* If anyone ever wants this we'd need support in the IOVA allocator */
 	if (dev_WARN_ONCE(dev, dma_get_min_align_mask(dev) > iova_mask(iovad),
 	    "Unsupported alignment constraint\n"))
@@ -1277,6 +1281,10 @@ void iommu_dma_unmap_phys(struct device *dev, dma_addr_t dma_handle,
 {
 	phys_addr_t phys;
 
+	/* PISA mapped buffer: nothing to unmap or release. */
+	if (is_pisa_iova(&iommu_get_dma_domain(dev)->iova_cookie->win_pisa, dma_handle))
+		return;
+
 	if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT)) {
 		__iommu_dma_unmap(dev, dma_handle, size);
 		return;
@@ -1478,6 +1486,13 @@ int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
 			 */
 			break;
 		case PCI_P2PDMA_MAP_NONE:
+			/* Map PISA pages and mark as bus addresses to skip IOVA alloc and unmap. */
+			if (!pisa_map_phys(&s->dma_address, dev, domain,
+					   sg_phys(s), s_length, prot)) {
+				sg_dma_len(s) = s_length;
+				sg_dma_mark_bus_address(s);
+				continue;
+			}
 			break;
 		case PCI_P2PDMA_MAP_BUS_ADDR:
 			/*
drivers/iommu/iommu.c +3 -2
index dfba3d5c277c2..068eaf262c7f6 100644
@@ -2867,8 +2867,9 @@ ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
 
 	while (i <= nents) {
 		phys_addr_t s_phys = sg_phys(sg);
+		bool is_bus = i < nents && sg_dma_is_bus_address(sg);
 
-		if (len && s_phys != start + len) {
+		if (len && (is_bus || s_phys != start + len)) {
 			ret = iommu_map_nosync(domain, iova + mapped, start,
 					len, prot, gfp);
 			if (ret)
@@ -2878,7 +2879,7 @@ ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
 			len = 0;
 		}
 
-		if (sg_dma_is_bus_address(sg))
+		if (is_bus)
 			goto next;
 
 		if (len) {
drivers/iommu/pisa-alloc.c +4 -1
index dd90aad296edf..f98142882519c 100644
@@ -299,9 +299,11 @@ struct pisa_alloc *pisa_create(int nid, unsigned int order, enum dma_data_direct
 
 	spin_lock_init(&pa->lock);
 	pa->order = order;
-	pa->nid = pisa_sanitize_nid(nid);
+	pa->prot = (dir != DMA_FROM_DEVICE ? IOMMU_READ : 0) |
+		     (dir != DMA_TO_DEVICE ? IOMMU_WRITE : 0);
 	pa->max_idle_pages = READ_ONCE(pisa_max_idle) ? : 1;
 	pisa_set_name(pa, "%ps", (void *)_RET_IP_);
+	pa->nid = pisa_sanitize_nid(nid);
 	INIT_LIST_HEAD(&pa->partial);
 	INIT_LIST_HEAD(&pa->partial_dirty);
 	INIT_LIST_HEAD(&pa->idle);
@@ -607,6 +609,7 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 			goto out;
 		spin_lock_irqsave(&pa->lock, flags);
 		meta->pa = pa;
+		meta->prot = pa->prot;
 		/* Set PISA_ACTIVE after @meta is fully set up. */
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
 	}
drivers/iommu/pisa-kunit.c +133 -0

163 lines not on this page · raw message

drivers/iommu/pisa-map.c +184 -0

199 lines not on this page · raw message

drivers/iommu/pisa-priv.h +34 -1
index f97f69a13d1a9..8d83ec09c19a9 100644
@@ -2,7 +2,7 @@
 #ifndef _DRIVERS_IOMMU_PISA_PRIV_H
 #define _DRIVERS_IOMMU_PISA_PRIV_H
 
-#include <linux/dma-direction.h>
+#include <linux/dma-mapping.h>
 #include <linux/pisa.h>
 #include <linux/jiffies.h>
 #include <linux/list.h>
@@ -13,6 +13,7 @@
 #include <linux/types.h>
 #include <linux/workqueue.h>
 
+struct device;
 struct iommu_domain;
 struct iommu_iotlb_gather;
 
@@ -53,6 +54,7 @@ enum {
  * - pisa_allocs_lock (rwlock): outermost; protects pisa_allocs list.
  * - pisa_meta_mutex (mutex): serializes pisa_meta_init() and page-table alloc.
  * - pa->lock (spinlock, irqsave): per-allocator lists, bitmaps, and stats.
+ * - pisa_domains[].map_lock (spinlock, irqsave): first-time iommu_map() in __pisa_map_phys().
  * - pisa_domains_lock (spinlock, irqsave): leaf lock over pisa_domains[]/windows.
  * - pisa_srcu: protects pisa_domains[] readers against pisa_domain_release().
  */
@@ -60,6 +62,7 @@ enum {
 /**
  * struct pisa_meta - Metadata for a single PISA page in @pisa_meta_array
  * @flags:	PISA_ACTIVE / PISA_QUARANTINED
+ * @prot:	Owning allocator's IOMMU_READ/WRITE protection bits
  * @nr_clean:	Zeroed available blocks in @clean_bitmap
  * @nr_dirty:	Dirty available blocks in @dirty_bitmap
  * @on_list:	Current placement in @pa (enum pisa_meta_list)
@@ -74,6 +77,7 @@ enum {
  */
 struct pisa_meta {
 	u8 flags;
+	u8 prot;
 	u16 nr_clean;
 	u16 nr_dirty;
 	u8 on_list;
@@ -105,6 +109,7 @@ static inline unsigned int pisa_meta_avail(const struct pisa_meta *meta)
  * struct pisa_alloc - Allocator managing 2MB-backed blocks of a fixed order
  * @lock:	Spinlock protecting lists and block bitmaps
  * @order:	Block order managed by this allocator (<= PISA_ORDER)
+ * @prot:	IOMMU_READ and/or IOMMU_WRITE from @dir passed to pisa_create()
  * @partial:	Partially used PISA pages with @nr_clean > 0
  * @partial_dirty: Partially used PISA pages with @nr_clean == 0 and @nr_dirty > 0
  * @idle:	Completely free PISA pages (reclaimable under pressure)
@@ -120,6 +125,7 @@ struct pisa_alloc {
 	/* First cacheline: hot fields touched on block alloc and free. */
 	spinlock_t		lock;
 	u8			order;
+	u8			prot;
 	struct list_head	partial;
 	struct list_head	partial_dirty;
 	struct list_head	idle;
@@ -148,6 +154,14 @@ struct pisa_node {
 /* Per-NUMA-node PISA state (ring/TX/user allocators, reservoir). */
 extern struct pisa_node pisa_nodes[MAX_NUMNODES];
 
+/* IOVA of @phys inside active RAM page @meta in @win. */
+static inline dma_addr_t pisa_phys_to_iova(const struct pisa_window *win,
+					  const struct pisa_meta *meta, phys_addr_t phys)
+{
+	return win->base + ((dma_addr_t)meta->slot << PISA_SHIFT) +
+	       (phys & (PISA_SIZE - 1));
+}
+
 /* Offset of @meta from the start of a domain's window. */
 static inline dma_addr_t pisa_meta_win_offset(const struct pisa_meta *meta)
 {
@@ -228,6 +242,18 @@ void pisa_slots_init(void);
 int pisa_slot_alloc(struct pisa_meta *meta);
 void pisa_slot_free(unsigned int slot);
 int pisa_unmap_all(struct pisa_meta *meta);
+int pisa_window_assign(struct device *dev, struct iommu_domain *domain, struct pisa_window *win);
+int __pisa_map_phys(dma_addr_t *iova, struct device *dev,
+		    struct iommu_domain *domain, phys_addr_t phys,
+		    size_t size, int prot);
+
+static inline int pisa_map_phys(dma_addr_t *iova, struct device *dev,
+				struct iommu_domain *domain, phys_addr_t phys,
+				size_t size, int prot)
+{
+	return is_pisa_phys(phys) ?
+	       __pisa_map_phys(iova, dev, domain, phys, size, prot) : -EINVAL;
+}
 
 /* Return negative errno if @win's domain was permanently/currently declined, or 0. */
 static inline int pisa_window_declined(const struct pisa_window *win)
@@ -265,6 +291,13 @@ static inline int pisa_slot_alloc(struct pisa_meta *meta) { return 0; }
 static inline void pisa_slot_free(unsigned int slot) {}
 static inline int pisa_unmap_all(struct pisa_meta *meta) { return 0; }
 
+static inline int pisa_map_phys(dma_addr_t *iova, struct device *dev,
+				struct iommu_domain *domain, phys_addr_t phys,
+				size_t size, int prot)
+{
+	return -EOPNOTSUPP;
+}
+
 static inline int pisa_window_declined(const struct pisa_window *win)
 {
 	return -EOPNOTSUPP;
include/linux/pisa.h +3 -0
index ab1c32e065bbb..c64689b81befe 100644
@@ -5,11 +5,14 @@
 
 #include <linux/types.h>
 #include <linux/bitops.h>
+#include <linux/dma-mapping.h>
 #include <linux/jump_label.h>
 #include <linux/mm.h>
 #include <linux/numa.h>
 #include <linux/rcupdate.h>
 
+struct device;
+
 #ifdef CONFIG_PISA
 
 #define PISA_SHIFT		21U
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#128 lore raw

Re: [RFC PATCH v2 08/25] iommu/dma: Use per-domain IOVA window to map PISA memory

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] iommu/dma: untrusted devices not excluded in __pisa_map_phys() - [Medium] iommu/dma…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] iommu/dma: untrusted devices not excluded in __pisa_map_phys()
- [Medium] iommu/dma: pisa_domain_quiesce() races with PISA page retirement
--

commit 5ad49a194c307768ccdbdc801e7b8a723eed2bfc
Author: Luigi Rizzo <[email protected]>

iommu/dma: Use per-domain IOVA window to map PISA memory

This commit intercepts DMA map and unmap operations in dma-iommu to map PISA pages using a dynamically assigned per-domain IOVA window and 2MB leaf PTEs.

Quoted 4 lines
drivers/iommu/pisa-map.c +0 -0
index 2ba977bb68734..2c481e514575c 100644

[ ... ]

Quoted 4 lines
drivers/iommu/pisa-map.c +0 -0
@@ -300,3 +303,184 @@ void pisa_domain_quiesce(struct iommu_domain *domain)
 		pr_debug("pisa: unmapped %u PISA pages from idle domain %p (index %d)\n",
 			 done, domain, idx);
 }

[ ... ]

drivers/iommu/pisa-map.c void pisa_domain_quiesce(struct iommu_domain *domain) · line 353

Quoted 12 lines
drivers/iommu/pisa-map.c +12 -0
+int pisa_window_assign(struct device *dev, struct iommu_domain *domain, struct pisa_window *win)
+{
+	u64 limit = min_not_zero(dma_get_mask(dev), dev->bus_dma_limit);
+	u64 size = pisa_window_size;
+	unsigned long flags;
+	dma_addr_t base = 0;
+	int idx, ret;
+
+	limit = min_not_zero(limit, dev->coherent_dma_mask);
+
+	if (!dev_is_dma_coherent(dev))
+		return -EOPNOTSUPP;

[Severity: High]
Should pisa_window_assign() and __pisa_map_phys() also reject untrusted devices when dev_is_untrusted(dev) is true?

In iommu_dma_map_phys(), SWIOTLB bounce buffering for untrusted PCI devices is only used when the buffer is not aligned to the IOMMU granule, so granule-aligned buffers reach __iommu_dma_map() -> pisa_map_phys() directly:

drivers/iommu/dma-iommu.c:iommu_dma_map_phys() {
    ...
	if (!(attrs & DMA_ATTR_MMIO) && dev_use_swiotlb(dev, size, dir) &&
	    iova_unaligned(iovad, phys, size)) {
    ...
	iova = __iommu_dma_map(dev, phys, size, prot, dma_mask);
}

When an untrusted external PCI device maps a 4KB-aligned PISA buffer, __pisa_map_phys() maps the entire 2MB PISA superpage into the device's domain with meta->prot (including IOMMU_WRITE on bidirectional allocators even for DMA_TO_DEVICE mappings), and iommu_dma_unmap_phys() and __iommu_dma_unmap() leave the 2MB mapping active across unmap, exposing all sibling blocks in the same 2MB page to the untrusted device.

[ ... ]

Quoted 5 lines
drivers/iommu/pisa-map.c +5 -0
+	/* First use of this PISA page in this domain: install the leaf PTE. */
+	ret = 0;
+	spin_lock_irqsave(&pisa_domains[domain_idx].map_lock, flags);
+	if (!test_bit(domain_idx, meta->domains_mapped)) {
+		phys_addr_t pisa_phys = phys & PISA_MASK;

drivers/iommu/pisa-map.c void pisa_domain_quiesce(struct iommu_domain *domain) · line 480

Quoted 10 lines
drivers/iommu/pisa-map.c +10 -0
+
+		ret = iommu_map(domain, pisa_phys_to_iova(win, meta, pisa_phys),
+				pisa_phys, PISA_SIZE, block_prot, GFP_ATOMIC);
+		if (likely(!ret)) {
+			/* Ensure leaf PTE is visible before setting the domain bit. */
+			smp_mb__before_atomic();
+			set_bit(domain_idx, meta->domains_mapped);
+		}
+	}
+	spin_unlock_irqrestore(&pisa_domains[domain_idx].map_lock, flags);

[Severity: Medium]
Once __pisa_map_phys() sets domain_idx in meta->domains_mapped, can pisa_domain_quiesce() corrupt meta->rcu or pisa_free_list if an idle PISA page is retired concurrently while an IOMMU unmap fails?

When an idle page is detached for retirement by pisa_reclaim_work_fn(), pisa_place_meta(), or pisa_shrink_list(), meta->pa and pisa_slot2meta[slot] remain set until pisa_release_page_rcu() runs after the RCU grace period. If pisa_domain_quiesce() sees PISA_QUARANTINED set after an unmap failure, it only checks meta->pa == pa under pa->lock before calling pisa_place_meta(meta), which re-queues meta->llnode (unioned with meta->rcu) onto pisa_free_list when all blocks are free:

CPU0 (pisa_reclaim_work_fn) CPU1 (pisa_domain_quiesce)
spin_lock_irqsave(&pa->lock)
list_del_init(&meta->list)
meta->on_list = PISA_LIST_NONE
llist_add(&meta->llnode,
&pisa_free_list)
spin_unlock_irqrestore(&pa->lock)
llist_del_all(&pisa_free_list)
pisa_release_page(meta)
pisa_unmap_all(meta)
call_rcu(&meta->rcu, ...)

                                  pisa_unmap_domain_locked(meta, ...)
                                    /* unmap fails, sets PISA_QUARANTINED */
                                  spin_lock_irqsave(&pa->lock)
                                  if (meta->pa == pa)
                                    pisa_place_meta(meta)
                                      llist_add(&meta->llnode,
                                                &pisa_free_list)
                                                <-- overwrites meta->rcu

Similarly, if pisa_shrink_list() moved meta onto pisa_shrink_scan()'s local release_list (which decrements pa->num_idle_pages without clearing meta->on_list), pisa_domain_quiesce() decrements pa->num_idle_pages a second time and calls list_del_init(&meta->list) while pisa_shrink_scan() iterates release_list without pa->lock. In addition, pisa_quarantine_meta() updates meta->flags with an unlocked WRITE_ONCE(meta->flags, meta->flags | PISA_QUARANTINED) that can race with WRITE_ONCE(meta->flags, meta->flags & ~PISA_ACTIVE) in pisa_release_page(), losing PISA_QUARANTINED and allowing pisa_release_page_rcu() to free the quarantined page to the buddy allocator.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#129 lore raw

RFC PATCH v2 9/25 driver core: Add per-device pisa_* sysfs attributes for PISA optin

In reply to Luigi Rizzo

Because of the performance and security implications, the use of PISA features is opt-in and configurable per device with a fine granularity.

Add boolean attributes to struct device exposed under /sys/devices/*/*/pisa_*:

  - pisa_coherent:     enable PISA for coherent allocations
  - pisa_rx_bufs:      enable PISA for RX buffers / page_pool
  - pisa_tx_bufs:      enable PISA for TX socket page frags

- pisa_tx_skb_heads: enable PISA slab cache for small TX skb heads

---
 drivers/base/core.c        | 64 ++++++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-alloc.c | 24 ++++++++++++++
 drivers/iommu/pisa-kunit.c | 67 ++++++++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-priv.h  |  1 -
 include/linux/device.h     | 12 +++++++
 include/linux/pisa.h       | 19 +++++++++++
 6 files changed, 186 insertions(+), 1 deletion(-)
drivers/base/core.c +64 -0
index cbe05197d4a0b..97cd2d03ff77c 100644
@@ -25,6 +25,7 @@
 #include <linux/notifier.h>
 #include <linux/of.h>
 #include <linux/of_device.h>
+#include <linux/pisa.h>
 #include <linux/pm_runtime.h>
 #include <linux/sched/mm.h>
 #include <linux/sched/signal.h>
@@ -2907,6 +2908,54 @@ static ssize_t removable_show(struct device *dev, const struct device_attribute
 }
 static const DEVICE_ATTR_RO(removable);
 
+/* Per-device configuration to selectively enable PISA */
+static ssize_t pisa_attr_store(const char *buf, size_t count, bool *field)
+{
+	bool val;
+	int ret = kstrtobool(buf, &val);
+
+	if (ret < 0)
+		return ret;
+	if (val) {
+		ret = pisa_meta_init();
+		if (ret < 0)
+			return ret;
+	}
+	WRITE_ONCE(*field, val);
+	return count;
+}
+
+#define PISA_BOOL_ATTR(name)						\
+static ssize_t name##_show(struct device *dev,				\
+			   struct device_attribute *attr, char *buf)	\
+{									\
+	return sysfs_emit(buf, "%u\n", READ_ONCE(dev->name));		\
+}									\
+static ssize_t name##_store(struct device *dev,				\
+			    struct device_attribute *attr,		\
+			    const char *buf, size_t count)		\
+{									\
+	return pisa_attr_store(buf, count, &dev->name);			\
+}									\
+static DEVICE_ATTR_RW(name)
+
+PISA_BOOL_ATTR(pisa_coherent);
+PISA_BOOL_ATTR(pisa_rx_bufs);
+PISA_BOOL_ATTR(pisa_tx_bufs);
+PISA_BOOL_ATTR(pisa_tx_skb_heads);
+
+static struct attribute *dev_attr_pisa[] = {
+	&dev_attr_pisa_coherent.attr,
+	&dev_attr_pisa_rx_bufs.attr,
+	&dev_attr_pisa_tx_bufs.attr,
+	&dev_attr_pisa_tx_skb_heads.attr,
+	NULL,
+};
+
+static const struct attribute_group dev_attr_pisa_group = {
+	.attrs = dev_attr_pisa,
+};
+
 int device_add_groups(struct device *dev,
 		      const struct attribute_group *const *groups)
 {
@@ -3014,8 +3063,20 @@ static int device_add_attrs(struct device *dev)
 			goto err_remove_dev_removable;
 	}
 
+	if (IS_ENABLED(CONFIG_PISA) && dev->dma_mask) {
+		error = device_add_group(dev, &dev_attr_pisa_group);
+		if (error)
+			goto err_remove_dev_physical_location;
+	}
+
 	return 0;
 
+ err_remove_dev_physical_location:
+	if (dev->physical_location) {
+		device_remove_group(dev, &dev_attr_physical_location_group);
+		kfree(dev->physical_location);
+		dev->physical_location = NULL;
+	}
  err_remove_dev_removable:
 	device_remove_file(dev, &dev_attr_removable);
  err_remove_dev_waiting_for_supplier:
@@ -3039,6 +3100,9 @@ static void device_remove_attrs(struct device *dev)
 	const struct class *class = dev->class;
 	const struct device_type *type = dev->type;
 
+	if (IS_ENABLED(CONFIG_PISA) && dev->dma_mask)
+		device_remove_group(dev, &dev_attr_pisa_group);
+
 	if (dev->physical_location) {
 		device_remove_group(dev, &dev_attr_physical_location_group);
 		kfree(dev->physical_location);
drivers/iommu/pisa-alloc.c +24 -0
index f98142882519c..b0d968aa9181c 100644
@@ -9,6 +9,7 @@
 #include <linux/bitmap.h>
 #include <linux/bitops.h>
 #include <linux/cache.h>
+#include <linux/device.h>
 #include <linux/dma-mapping.h>
 #include <linux/pisa.h>
 #include <linux/export.h>
@@ -392,6 +393,29 @@ unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred
 	return pisa_alloc_bulk(pa, gfp & ~__GFP_PISA_RW, nr_pages, page_array, frozen);
 }
 
+/**
+ * pisa_has_free_blocks_rx - Check if @dev has free PISA RX blocks of @order on @nid
+ * @dev: Device to check
+ * @order: Block order
+ * @nid: Target NUMA node (or NUMA_NO_NODE)
+ *
+ * Return: true if @dev->pisa_rx_bufs is enabled and the per-node allocator
+ * has a free block available.
+ */
+bool pisa_has_free_blocks_rx(const struct device *dev, unsigned int order, int nid)
+{
+	struct pisa_alloc *pa;
+
+	if (!dev || !READ_ONCE(dev->pisa_rx_bufs))
+		return false;
+	pa = pisa_node_pa(nid, order, false);
+	return pa &&
+	       (!list_empty_careful(&pa->partial) ||
+		!list_empty_careful(&pa->partial_dirty) ||
+		!list_empty_careful(&pa->idle));
+}
+EXPORT_SYMBOL(pisa_has_free_blocks_rx);
+
 /*
  * Split a non-compound page of @old_order into 1 << (@old_order - @new_order)
  * pages of @new_order (compound if @new_order > 0), all frozen at refcount 0.
drivers/iommu/pisa-kunit.c +67 -0

85 lines not on this page · raw message

drivers/iommu/pisa-priv.h +0 -1
index 8d83ec09c19a9..e5ca95d2654cd 100644
@@ -133,7 +133,6 @@ struct pisa_alloc {
 	unsigned int		num_idle_pages;
 	unsigned int		max_idle_pages;
 	unsigned long		idle_jiffies;
-
 	/* Cold. */
 	int			nid;
 	struct list_head	node;
include/linux/device.h +12 -0
index 429e39f647cf9..b3c11e32116ca 100644
@@ -695,6 +695,13 @@ enum struct_device_flags {
  * @removable:  Whether the device can be removed from the system. This
  *              should be set by the subsystem / bus driver that discovered
  *              the device.
+ * @pisa_coherent: Back coherent dma_alloc_attrs() with PISA
+ *		(sysfs pisa_coherent).
+ * @pisa_rx_bufs: Use PISA allocators for RX buffers (sysfs pisa_rx_bufs).
+ * @pisa_tx_bufs: Use PISA allocators for socket TX page fragments
+ *		(sysfs pisa_tx_bufs).
+ * @pisa_tx_skb_heads: Use PISA slab cache for small TX skb heads
+ *		(sysfs pisa_tx_skb_heads).
  * @flags:	DEV_FLAG_XXX flags. Use atomic bitfield operations to modify.
  *
  * At the lowest level, every device in a Linux system is represented by an
@@ -799,6 +806,11 @@ struct device {
 
 	enum device_removable	removable;
 
+	bool			pisa_coherent;
+	bool			pisa_rx_bufs;
+	bool			pisa_tx_bufs;
+	bool			pisa_tx_skb_heads;
+
 	DECLARE_BITMAP(flags, DEV_FLAG_COUNT);
 };
 
include/linux/pisa.h +19 -0
index c64689b81befe..92482fce943e9 100644
@@ -7,6 +7,7 @@
 #include <linux/bitops.h>
 #include <linux/dma-mapping.h>
 #include <linux/jump_label.h>
+#include <linux/device.h>
 #include <linux/mm.h>
 #include <linux/numa.h>
 #include <linux/rcupdate.h>
@@ -82,6 +83,13 @@ unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
 				    int nr_pages, struct page **page_array,
 				    bool frozen);
 
+bool pisa_has_free_blocks_rx(const struct device *dev, unsigned int order, int nid);
+
+static inline gfp_t pisa_rx_gfp(const struct device *dev)
+{
+	return dev && READ_ONCE(dev->pisa_rx_bufs) ? __GFP_PISA_RW : 0;
+}
+
 #else /* !CONFIG_PISA */
 
 static inline int pisa_meta_init(void)
@@ -109,6 +117,17 @@ pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred_nid,
 	return 0;
 }
 
+static inline gfp_t pisa_rx_gfp(const struct device *dev)
+{
+	return 0;
+}
+
+static inline bool pisa_has_free_blocks_rx(const struct device *dev,
+					   unsigned int order, int nid)
+{
+	return false;
+}
+
 #endif /* CONFIG_PISA */
 
 static inline struct page *
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#130 lore raw

Re: [RFC PATCH v2 09/25] driver core: Add per-device pisa_* sysfs attributes for PISA optin

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] iommu/pisa: missing CONFIG_SYSFS guard in test_dev_pisa_attrs() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] iommu/pisa: missing CONFIG_SYSFS guard in test_dev_pisa_attrs() --

commit 6fe77bab9a66f127e26564b7f0b1c45730cf6ab8
Author: Luigi Rizzo <[email protected]>

driver core: Add per-device pisa_* sysfs attributes for PISA optin

This commit adds per-device boolean sysfs attributes (pisa_coherent, pisa_rx_bufs, pisa_tx_bufs, and pisa_tx_skb_heads) to struct device for selective PISA opt-in, along with helper functions and a KUnit test.

Quoted 4 lines
drivers/iommu/pisa-kunit.c +0 -0
index e16268d55f3de..ab64657ad5c58 100644

[ ... ]

Quoted 7 lines
drivers/iommu/pisa-kunit.c +3 -0
@@ -350,6 +352,70 @@ static void test_map_and_domain_lifecycle(struct kunit *test)
 }
 #endif /* CONFIG_IOMMU_DMA */
 
+static void kunit_check_pisa_attr(struct kunit *test, struct device *dev,
+				  const char *name, bool *field)
+{

drivers/iommu/pisa-kunit.c static void test_map_and_domain_lifecycle(struct kunit *test) · line 367

Quoted 10 lines
drivers/iommu/pisa-kunit.c +10 -0
+	const struct sysfs_ops *ops = dev->kobj.ktype->sysfs_ops;
+	struct kernfs_node *kn;
+	char *buf;
+
+	buf = (char *)__get_free_page(GFP_KERNEL);
+	KUNIT_EXPECT_NOT_NULL(test, buf);
+	if (!buf)
+		return;
+	kn = kernfs_find_and_get(dev->kobj.sd, name);
+	KUNIT_EXPECT_NOT_NULL(test, kn);

[Severity: Low]
Should test_dev_pisa_attrs() be guarded by CONFIG_SYSFS?

When CONFIG_SYSFS is disabled, device_register() leaves dev->kobj.sd as NULL. Passing NULL to kernfs_find_and_get() causes a NULL pointer dereference in kernfs_root() when CONFIG_KERNFS=y, or fails the KUNIT_EXPECT_NOT_NULL(test, kn) assertion when CONFIG_KERNFS=n.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#131 lore raw

RFC PATCH v2 10/25 iommu/dma: Use PISA for coherent DMA allocations

In reply to Luigi Rizzo

Coherent DMA allocations (e.g. TX/RX descriptor rings allocated via dma_alloc_attrs() / dma_alloc_coherent()) are long-lived and accessed on every packet or I/O operation, so they benefit from sharing 2MB IOMMU leaf mappings.

When dev->pisa_coherent is enabled, serve coherent DMA allocations up to 2MB from the device's per-NUMA-node order-0 read-write PISA allocator.

---
 drivers/iommu/dma-iommu.c  |  10 +++
 drivers/iommu/pisa-alloc.c | 146 +++++++++++++++++++++++++++++++++++++
 drivers/iommu/pisa-kunit.c |  67 +++++++++++++++++
 include/linux/pisa.h       |  30 ++++++++
 kernel/dma/direct.c        |   9 +++
 5 files changed, 262 insertions(+)
drivers/iommu/dma-iommu.c +10 -0
index eb920ad77c783..a0c5ddab7a8b6 100644
@@ -1658,6 +1658,8 @@ static void __iommu_dma_free(struct device *dev, size_t size, void *cpu_addr)
 	} else {
 		/* Lowmem means a coherent atomic or CMA allocation */
 		page = virt_to_page(cpu_addr);
+		if (pisa_free_coherent(page, alloc_size))
+			return;
 	}
 
 	if (pages)
@@ -1716,6 +1718,7 @@ void *iommu_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
 		gfp_t gfp, unsigned long attrs)
 {
 	bool coherent = dev_is_dma_coherent(dev);
+	struct iommu_domain *domain = iommu_get_dma_domain(dev);
 	int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs);
 	bool is_alloc_cc_shared = attrs & __DMA_ATTR_ALLOC_CC_SHARED;
 	struct page *page = NULL;
@@ -1727,6 +1730,12 @@ void *iommu_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
 
 	gfp |= __GFP_ZERO;
 
+	if (domain) {
+		cpu_addr = pisa_alloc_coherent(&page, dev, domain, size, gfp, attrs);
+		if (cpu_addr)
+			goto map;
+	}
+
 	if (gfpflags_allow_blocking(gfp) &&
 	    !(attrs & DMA_ATTR_FORCE_CONTIGUOUS)) {
 		return iommu_dma_alloc_remap(dev, size, handle, gfp, attrs);
@@ -1744,6 +1753,7 @@ void *iommu_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
 			return NULL;
 	}
 
+map:
 	*handle = __iommu_dma_map(dev, page_to_phys(page), size, ioprot,
 			dev->coherent_dma_mask);
 	if (*handle == DMA_MAPPING_ERROR) {
drivers/iommu/pisa-alloc.c +146 -0

158 lines not on this page · raw message

drivers/iommu/pisa-kunit.c +67 -0

79 lines not on this page · raw message

include/linux/pisa.h +30 -0
index 92482fce943e9..a6556aa403a09 100644
@@ -13,6 +13,7 @@
 #include <linux/rcupdate.h>
 
 struct device;
+struct iommu_domain;
 
 #ifdef CONFIG_PISA
 
@@ -78,6 +79,21 @@ static inline bool pisa_free_page(struct page *page)
 	return ret;
 }
 
+void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
+			  struct iommu_domain *domain, size_t size,
+			  gfp_t gfp, unsigned long attrs);
+
+static inline bool pisa_free_coherent(struct page *page, size_t size)
+{
+	unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
+
+	if (!page || !is_pisa_page(page))
+		return false;
+	while (count--)
+		__free_page(page++);
+	return true;
+}
+
 unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
 				    int preferred_nid, nodemask_t *nodemask,
 				    int nr_pages, struct page **page_array,
@@ -109,6 +125,20 @@ static inline bool pisa_free_page(struct page *page)
 	return false;
 }
 
+static inline void *pisa_alloc_coherent(struct page **pagep,
+					struct device *dev,
+					struct iommu_domain *domain,
+					size_t size, gfp_t gfp,
+					unsigned long attrs)
+{
+	return NULL;
+}
+
+static inline bool pisa_free_coherent(struct page *page, size_t size)
+{
+	return false;
+}
+
 static inline unsigned long
 pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred_nid,
 		      nodemask_t *nodemask, int nr_pages,
kernel/dma/direct.c +9 -0
index 25e9a86835fd3..11052b65e573b 100644
@@ -15,6 +15,7 @@
 #include <linux/slab.h>
 #include <linux/pci-p2pdma.h>
 #include <linux/cc_platform.h>
+#include <linux/pisa.h>
 
 #include "direct.h"
 
@@ -244,6 +245,12 @@ void *dma_direct_alloc(struct device *dev, size_t size,
 	if (attrs & DMA_ATTR_NO_WARN)
 		gfp |= __GFP_NOWARN;
 
+	cpu_addr = pisa_alloc_coherent(&page, dev, NULL, size, gfp, attrs);
+	if (cpu_addr) {
+		*dma_handle = phys_to_dma_direct(dev, page_to_phys(page), false);
+		return cpu_addr;
+	}
+
 	if (dma_direct_use_no_mapping(dev, attrs))
 		return dma_direct_alloc_no_mapping(dev, size, dma_handle, gfp);
 
@@ -424,6 +431,8 @@ void dma_direct_free(struct device *dev, size_t size,
 
 	if (is_vmalloc_addr(cpu_addr)) {
 		vunmap(cpu_addr);
+	} else if (pisa_free_coherent(virt_to_page(cpu_addr), size)) {
+		return;
 	} else {
 		if (IS_ENABLED(CONFIG_ARCH_HAS_DMA_CLEAR_UNCACHED))
 			arch_dma_clear_uncached(cpu_addr, size);
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#132 lore raw

Re: [RFC PATCH v2 10/25] iommu/dma: Use PISA for coherent DMA allocations

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] iommu/pisa: unsafe list_for_each_entry() in pisa_alloc_coherent() - [Medium] iommu/pisa: NULL…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] iommu/pisa: unsafe list_for_each_entry() in pisa_alloc_coherent()
- [Medium] iommu/pisa: NULL deref in is_swiotlb_for_alloc() in KUnit test
- [Medium] iommu/dma: incomplete DMA range check in pisa_alloc_coherent()
- [Low] iommu/dma: uninitialized stack device in test_coherent_alloc_and_free()
--

commit 707db606f2421a5bae5c7fa193156ad4c820f976
Author: Luigi Rizzo <[email protected]>

iommu/dma: Use PISA for coherent DMA allocations

This commit serves coherent DMA allocations up to 2MB from the per-NUMA-node order-0 read-write PISA allocator when dev->pisa_coherent is enabled.

Quoted 63 lines
drivers/iommu/pisa-alloc.c +48 -0
index b0d968aa9181c..25e4645310678 100644
@@ -10,6 +10,8 @@
 #include <linux/bitops.h>
 #include <linux/cache.h>
 #include <linux/device.h>
+#include <linux/dma-direct.h>
+#include <linux/dma-map-ops.h>
 #include <linux/dma-mapping.h>
 #include <linux/pisa.h>
 #include <linux/export.h>
@@ -697,6 +699,150 @@ unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
 	return i;
 }
 
+/* Find and reserve @nblocks aligned contiguous blocks in @meta under @pa->lock. */
+static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblocks,
+				     unsigned long align_mask)
+{
+	DECLARE_BITMAP(busy, PISA_MAX_BLOCKS);
+	struct pisa_alloc *pa = meta->pa;
+	unsigned int bpp = PISA_BLOCKS(0), i;
+	bool poisoned = false;
+	unsigned long off;
+	struct page *page;
+
+	if (pisa_meta_avail(meta) < nblocks)
+		return NULL;
+
+	bitmap_or(busy, meta->clean_bitmap, meta->dirty_bitmap, bpp);
+	bitmap_complement(busy, busy, bpp);
+
+	off = 0;
+	for (;;) {
+		off = bitmap_find_next_zero_area(busy, bpp, off, nblocks, align_mask);
+		if (off >= bpp) {
+			if (poisoned) {
+				if (meta->on_list == PISA_LIST_IDLE_CLEAN ||
+				    meta->on_list == PISA_LIST_IDLE_DIRTY)
+					pa->num_idle_pages--;
+				pisa_place_meta(meta);
+			}
+			return NULL;
+		}
+
+		page = pfn_to_page(pisa_meta_to_pfn(meta) + off);
+		for (i = 0; i < nblocks; i++) {
+			if (!pisa_block_poisoned(pa, page + i))
+				continue;
+			if (__test_and_clear_bit(off + i, meta->clean_bitmap))
+				meta->nr_clean--;
+			else if (__test_and_clear_bit(off + i, meta->dirty_bitmap))
+				meta->nr_dirty--;
+			__set_bit(off + i, busy);
+			poisoned = true;
+			off += i + 1;
+			break;
+		}
+		if (i == nblocks)
+			break;
+	}

[ ... ]

Quoted 41 lines
drivers/iommu/pisa-alloc.c +41 -0
+void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
+			  struct iommu_domain *domain, size_t size,
+			  gfp_t gfp, unsigned long attrs)
+{
+	bool should_release = false;
+	struct list_head *lists[3];
+	unsigned long align_mask, flags;
+	unsigned int nblocks, i;
+	struct pisa_meta *meta;
+	struct pisa_alloc *pa;
+	struct page *page = NULL;
+
+	size = PAGE_ALIGN(size);
+	if (!pagep || !dev || !READ_ONCE(dev->pisa_coherent) ||
+	    !dev_is_dma_coherent(dev) || !size || size > PISA_SIZE)
+		return NULL;
+	if (min_not_zero(dev->coherent_dma_mask, dev->bus_dma_limit) <= DMA_BIT_MASK(32))
+		return NULL;
+	if ((current_gfp_context(gfp) & ~(__GFP_ZERO | __GFP_NOWARN)) != GFP_KERNEL ||
+	    (attrs & ~DMA_ATTR_NO_WARN))
+		return NULL;
+
+	if (domain) {
+		struct pisa_window *win = pisa_dma_window(domain);
+
+		if (!win || pisa_window_declined(win) || !(domain->pgsize_bitmap & PISA_SIZE))
+			return NULL;
+	} else if (is_swiotlb_for_alloc(dev) ||
+		   force_dma_unencrypted(dev) ||
+		   !dma_coherent_ok(dev, PFN_PHYS(max_pfn) - 1, 1)) {
+		return NULL;
+	}
+
+	pa = pisa_node_pa(dev_to_node(dev), 0, false);
+	if (!pa)
+		return NULL;
+
+	nblocks = size >> PAGE_SHIFT;
+	align_mask = (1UL << get_order(size)) - 1;
+	lists[0] = &pa->partial;
+	lists[1] = &pa->partial_dirty;

drivers/iommu/pisa-alloc.c unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, · line 823

Quoted 10 lines
drivers/iommu/pisa-alloc.c +10 -0
+	lists[2] = &pa->idle;
+
+	spin_lock_irqsave(&pa->lock, flags);
+	for (i = 0; i < ARRAY_SIZE(lists) && !page; i++) {
+		list_for_each_entry(meta, lists[i], list) {
+			page = pisa_take_contig(meta, nblocks, align_mask);
+			if (page)
+				break;
+		}
+	}

[Severity: Medium]
Can list_for_each_entry() walk off lists[i] onto a different list when pisa_take_contig() encounters a poisoned block?

If pisa_take_contig() clears a poisoned block in meta and then fails to find nblocks contiguous blocks (off >= bpp), it calls pisa_place_meta(meta) before returning NULL. pisa_place_meta() can move meta->list to another list (for example from pa->idle to pa->partial, or from pa->partial to pa->partial_dirty or pa->full). Because pisa_take_contig() returns NULL, list_for_each_entry() does not break; it follows meta->list.next on the new list while testing for termination against lists[i], and then treats the new list's head embedded in struct pisa_alloc as a struct pisa_meta. Using list_for_each_entry_safe() avoids following relinked nodes.

[ ... ]

drivers/iommu/pisa-kunit.c static void test_map_and_domain_lifecycle(struct kunit *test) · line 359

Quoted 13 lines
drivers/iommu/pisa-kunit.c +5 -0
index ab64657ad5c58..72ee8986b4802 100644
@@ -352,6 +352,72 @@ static void test_map_and_domain_lifecycle(struct kunit *test)
 }
 #endif /* CONFIG_IOMMU_DMA */
 
+static void test_coherent_alloc_and_free(struct kunit *test)
+{
+	struct device dev = { .init_name = "pisa_kunit", .numa_node = NUMA_NO_NODE,
+			      .coherent_dma_mask = DMA_BIT_MASK(64),
+			      .pisa_coherent = true };

[Severity: Medium]
Does passing this stack-allocated struct device with a NULL domain to pisa_alloc_coherent() cause a NULL pointer dereference when CONFIG_DMA_RESTRICTED_POOL is enabled?

Because dev is neither initialized via device_initialize() nor swiotlb_dev_init(), dev.dma_io_tlb_mem is NULL. When test_coherent_alloc_and_free() later calls pisa_alloc_coherent() with domain == NULL, pisa_alloc_coherent() calls is_swiotlb_for_alloc(dev), which dereferences dev->dma_io_tlb_mem->for_alloc under CONFIG_DMA_RESTRICTED_POOL=y.

[ ... ]

drivers/iommu/pisa-kunit.c static void test_map_and_domain_lifecycle(struct kunit *test) · line 419

Quoted 9 lines
drivers/iommu/pisa-kunit.c +9 -0
+	/* Freeing p1 returns its 16 order-0 pages; next 64K alloc reuses them. */
+	KUNIT_EXPECT_TRUE(test, pisa_free_coherent(p1, SZ_64K));
+	v3 = pisa_alloc_coherent(&p3, &dev, NULL, SZ_64K, GFP_KERNEL, 0);
+	KUNIT_ASSERT_NOT_NULL(test, v3);
+	KUNIT_EXPECT_PTR_EQ(test, p3, p1);
+
+	KUNIT_EXPECT_TRUE(test, pisa_free_coherent(p2, SZ_64K));
+	KUNIT_EXPECT_TRUE(test, pisa_free_coherent(p3, SZ_64K));
+}

[Severity: Low]
In addition to the uninitialized dev.dma_io_tlb_mem above, does this call with domain == NULL fail the test and leak p2 on Confidential Computing guests?

When domain is NULL, pisa_alloc_coherent() rejects the allocation if force_dma_unencrypted(&dev) is true, so v3 is NULL and KUNIT_ASSERT_NOT_NULL(test, v3) aborts before pisa_free_coherent(p2, SZ_64K) runs (until commit "iommu/dma: Support decrypted PISA pages" later in the series).

[ ... ]

kernel/dma/direct.c void *dma_direct_alloc(struct device *dev, size_t size, · line 252

Quoted 13 lines
kernel/dma/direct.c +5 -0
index 25e9a86835fd3..11052b65e573b 100644
@@ -244,6 +245,12 @@ void *dma_direct_alloc(struct device *dev, size_t size,
 	if (attrs & DMA_ATTR_NO_WARN)
 		gfp |= __GFP_NOWARN;
 
+	cpu_addr = pisa_alloc_coherent(&page, dev, NULL, size, gfp, attrs);
+	if (cpu_addr) {
+		*dma_handle = phys_to_dma_direct(dev, page_to_phys(page), false);
+		return cpu_addr;
+	}

[Severity: Medium]
Can dma_direct_alloc() return a valid cpu_addr with *dma_handle set to DMA_MAPPING_ERROR (or an out-of-mask DMA address) when dev->dma_range_map does not cover all of system RAM?

pisa_alloc_coherent() only checks dma_coherent_ok(dev, PFN_PHYS(max_pfn) - 1, 1) before allocating, and dma_direct_alloc() does not check dma_coherent_ok(dev, page_to_phys(page), size) on the allocated page. If dev->dma_range_map covers the top of RAM at max_pfn - 1 but has holes in lower RAM (where !dma_direct_all_ram_mapped(dev) is true, as in a409d9600959 ("dma-mapping: fix dma_addressing_limited() if dma_range_map can't cover all system RAM")) or translates regions with different offsets, pisa_alloc_coherent() can return a page outside dev->dma_range_map and phys_to_dma_direct() will set *dma_handle to DMA_MAPPING_ERROR.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#133 lore raw

RFC PATCH v2 11/25 iommu/dma: Add per-CPU block caches to PISA allocators

In reply to Luigi Rizzo

Every block allocation and free takes the allocator's lock. Highly concurrent users e.g. socket tx fragments, can cause significant lock contention.

Add pisa_enable_pcp(), an opt-in per-CPU front cache, similar to the page allocator's per-CPU lists:

- Each per-CPU cache keeps up to 64 free blocks, and refills it from the main allocator in batches of 32.
- returned blocks belonging to the local NUMA node are kept in the local cache.
- returned blocks belonging to a remote NUMA node are returned to the proper per-node allocator.
The cache is fully integrated with the shrinker and CPU offlining to drain the cache.

Enable per-CPU caches for the per-node order-0 RW and SKB_FRAG_PAGE_ORDER RO allocators.

---
 drivers/iommu/pisa-alloc.c | 342 +++++++++++++++++++++++++++++++++++--
 drivers/iommu/pisa-kunit.c |  78 +++++++++
 drivers/iommu/pisa-priv.h  |  35 +++-
 include/linux/pisa.h       |   6 +
 4 files changed, 448 insertions(+), 13 deletions(-)
drivers/iommu/pisa-alloc.c +330 -12
index 25e4645310678..913706a503341 100644
@@ -9,6 +9,7 @@
 #include <linux/bitmap.h>
 #include <linux/bitops.h>
 #include <linux/cache.h>
+#include <linux/cpuhotplug.h>
 #include <linux/device.h>
 #include <linux/dma-direct.h>
 #include <linux/dma-map-ops.h>
@@ -24,6 +25,7 @@
 #include <linux/moduleparam.h>
 #include <linux/mutex.h>
 #include <linux/page_owner.h>
+#include <linux/percpu.h>
 #include <linux/pgalloc_tag.h>
 #include <linux/rcupdate.h>
 #include <linux/sched/mm.h>
@@ -60,6 +62,10 @@ module_param_named(max_idle, pisa_max_idle, uint, 0644);
 static unsigned int pisa_idle_ms __read_mostly = 200;
 module_param_named(idle_ms, pisa_idle_ms, uint, 0644);
 
+/* Stop recycling partial-page blocks when free blocks exceed @pisa_compact PISA pages. */
+static unsigned int pisa_compact __read_mostly;
+module_param_named(compact, pisa_compact, uint, 0644);
+
 /* All live allocators, protected by pisa_allocs_lock. */
 static LIST_HEAD(pisa_allocs);
 static DEFINE_RWLOCK(pisa_allocs_lock);
@@ -90,7 +96,11 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 	struct pisa_meta *meta = container_of(head, struct pisa_meta, rcu);
 	struct page *block, *page = pfn_to_page(pisa_meta_to_pfn(meta));
 	unsigned int i, order = meta->pa->order, slot = meta->slot;
+	unsigned long flags;
 
+	spin_lock_irqsave(&meta->pa->lock, flags);
+	meta->pa->stats.page_free_cnt++;
+	spin_unlock_irqrestore(&meta->pa->lock, flags);
 	WRITE_ONCE(meta->pa, NULL);
 
 	/* Possibly still mapped by a device: leak it, still charged. */
@@ -355,9 +365,223 @@ static void pisa_return_block_locked(struct pisa_alloc *pa, struct page *block,
 		__set_bit(idx, meta->dirty_bitmap);
 		meta->nr_dirty++;
 	}
+	pa->blocks_in_use--;
 	*release |= pisa_place_meta(meta);
 }
 
+/**
+ * pisa_page_can_recycle - Check if a block can stay cached in a caller pool
+ * @page: Block head page
+ *
+ * Called on the recycle fast path (per-CPU cache, TX page_frag, page_pool).
+ * Fast-path cost is a static-key branch plus a READ_ONCE() of module parameters
+ * (~1-2 ns when compaction is off); when enabled, it does a lockless RCU +
+ * metadata array lookup (~5-10 ns).
+ *
+ * Return: true if @page can be recycled in place, false if it should be
+ * released back to its allocator so sparse 2MB pages can drain.
+ */
+bool pisa_page_can_recycle(const struct page *page)
+{
+	unsigned long bpp, in_use, free_blocks, pfn;
+	const struct pisa_meta *meta;
+	const struct pisa_alloc *pa;
+	unsigned int compact;
+	bool ret = true;
+	u8 on_list;
+	long held;
+
+	if (!static_branch_unlikely(&pisa_key))
+		return true;
+
+	compact = READ_ONCE(pisa_compact);
+	if (!compact)
+		return true;
+
+	pfn = page_to_pfn(page);
+	rcu_read_lock();
+	if (!is_pisa_pfn(pfn))
+		goto out;
+
+	meta = pisa_meta_of_pfn(pfn);
+	on_list = READ_ONCE(meta->on_list);
+	if (on_list == PISA_LIST_FULL || on_list == PISA_LIST_NONE)
+		goto out;
+
+	pa = meta->pa;
+	if (!pa)
+		goto out;
+
+	/* Do not drain the partial page currently being filled at list head. */
+	if (READ_ONCE(pa->partial_dirty.next) == &meta->list ||
+	    READ_ONCE(pa->partial.next) == &meta->list)
+		goto out;
+
+	bpp = PISA_BLOCKS(pa->order);
+	/* Do not drain dense pages that still have more than half their blocks in use. */
+	if (READ_ONCE(meta->nr_clean) + READ_ONCE(meta->nr_dirty) < (bpp >> 1))
+		goto out;
+
+	held = pisa_alloc_held_pages(pa);
+	in_use = READ_ONCE(pa->blocks_in_use);
+	free_blocks = held > 0 && (unsigned long)held * bpp > in_use ?
+		      (unsigned long)held * bpp - in_use : 0;
+
+	ret = free_blocks <= (unsigned long)compact * bpp;
+out:
+	rcu_read_unlock();
+	return ret;
+}
+EXPORT_SYMBOL_GPL(pisa_page_can_recycle);
+
+/* Return @n freed blocks to @pa under a single acquisition of @pa->lock. */
+static void pisa_free_bulk(struct pisa_alloc *pa, struct page **blocks, unsigned int n)
+{
+	bool release = false;
+	unsigned long flags;
+	unsigned int i;
+
+	spin_lock_irqsave(&pa->lock, flags);
+	for (i = 0; i < n; i++) {
+		if (likely(!pisa_block_poisoned(pa, blocks[i])))
+			pisa_return_block_locked(pa, blocks[i], &release);
+	}
+	spin_unlock_irqrestore(&pa->lock, flags);
+
+	if (release)
+		pisa_schedule_reclaim();
+}
+
+/*
+ * Per-CPU block cache: each CPU caches up to PISA_PCP_HIGH free blocks
+ * (refcount 0, not in bitmaps), refilling and flushing in PISA_PCP_BATCH
+ * batches. Drained by the shrinker and CPU hotplug.
+ */
+
+/* Max blocks moved per per-CPU cache refill or flush (1..PISA_PCP_BATCH). */
+static unsigned int pisa_pcp_batch __read_mostly = PISA_PCP_BATCH;
+
+static int pisa_pcp_batch_set(const char *val, const struct kernel_param *kp)
+{
+	return param_set_uint_minmax(val, kp, 1, PISA_PCP_BATCH);
+}
+
+static const struct kernel_param_ops pisa_pcp_batch_ops = {
+	.set = pisa_pcp_batch_set,
+	.get = param_get_uint,
+};
+module_param_cb(pcp_batch, &pisa_pcp_batch_ops, &pisa_pcp_batch, 0644);
+
+/* Cache @n blocks at refcount 0 on this CPU, @n <= PISA_PCP_BATCH. */
+static void pisa_pcp_push(struct pisa_alloc *pa, struct page **blocks, unsigned int n)
+{
+	unsigned int i, batch = READ_ONCE(pisa_pcp_batch);
+	struct pisa_pcp *pcp;
+	unsigned long flags;
+
+	local_irq_save(flags);
+	pcp = this_cpu_ptr(pa->pcp);
+	spin_lock(&pcp->lock);
+	for (i = 0; i < n; i++) {
+		if (pcp->count == PISA_PCP_HIGH) {
+			/* Keep the most recently freed, likely still in cache. */
+			pisa_free_bulk(pa, pcp->blocks, batch);
+			pcp->count -= batch;
+			memmove(pcp->blocks, pcp->blocks + batch,
+				pcp->count * sizeof(*pcp->blocks));
+		}
+		pcp->blocks[pcp->count++] = blocks[i];
+	}
+	spin_unlock(&pcp->lock);
+	local_irq_restore(flags);
+}
+
+/* Take up to @nr blocks, at refcount 0, from this CPU's cache. */
+static unsigned int pisa_pcp_pop(struct pisa_alloc *pa, unsigned int nr, struct page **out)
+{
+	struct pisa_pcp *pcp;
+	unsigned int got = 0;
+	unsigned long flags;
+
+	local_irq_save(flags);
+	pcp = this_cpu_ptr(pa->pcp);
+	spin_lock(&pcp->lock);
+	while (got < nr && pcp->count)
+		out[got++] = pcp->blocks[--pcp->count];
+	spin_unlock(&pcp->lock);
+	local_irq_restore(flags);
+
+	return got;
+}
+
+/* Return the blocks @cpu caches for @pa. Process context. */
+static void pisa_pcp_drain_cpu(struct pisa_alloc *pa, int cpu)
+{
+	struct pisa_pcp *pcp = per_cpu_ptr(pa->pcp, cpu);
+	unsigned long flags;
+
+	spin_lock_irqsave(&pcp->lock, flags);
+	if (pcp->count) {
+		pisa_free_bulk(pa, pcp->blocks, pcp->count);
+		pcp->count = 0;
+	}
+	spin_unlock_irqrestore(&pcp->lock, flags);
+}
+
+/* Drain every non-empty CPU cache of @pa. */
+void pisa_pcp_drain(struct pisa_alloc *pa)
+{
+	int cpu;
+
+	/* Pairs with smp_store_release() in pisa_enable_pcp(). */
+	if (!smp_load_acquire(&pa->pcp))
+		return;
+	for_each_possible_cpu(cpu) {
+		if (!READ_ONCE(per_cpu_ptr(pa->pcp, cpu)->count))
+			continue;
+		pisa_pcp_drain_cpu(pa, cpu);
+	}
+}
+
+/* Blocks in @pa's caches, for shrinker and debugfs. */
+static unsigned long pisa_pcp_count(struct pisa_alloc *pa)
+{
+	unsigned long n = 0;
+	int cpu;
+
+	if (!pa->pcp)
+		return 0;
+	for_each_possible_cpu(cpu) {
+		/* A racy sum is good enough for reclaim and statistics. */
+		n += data_race(per_cpu_ptr(pa->pcp, cpu)->count);
+	}
+	return n;
+}
+
+/**
+ * pisa_enable_pcp - Put per-CPU block caches in front of an allocator
+ * @pa: Allocator to cache
+ *
+ * Return: 0, or -ENOMEM; @pa works without the cache.
+ */
+int pisa_enable_pcp(struct pisa_alloc *pa)
+{
+	struct pisa_pcp __percpu *pcp;
+	int cpu;
+
+	if (!pa || pa->pcp)
+		return 0;
+	pcp = alloc_percpu(struct pisa_pcp);
+	if (!pcp)
+		return -ENOMEM;
+	for_each_possible_cpu(cpu)
+		spin_lock_init(&per_cpu_ptr(pcp, cpu)->lock);
+	/* Publish initialized locks; readers depend on the pointer. */
+	if (cmpxchg_release(&pa->pcp, NULL, pcp))
+		free_percpu(pcp);
+	return 0;
+}
+
 /*
  * Return the predefined per-node allocator for (@nid, @order, @ro), or NULL.
  */
@@ -412,7 +636,9 @@ bool pisa_has_free_blocks_rx(const struct device *dev, unsigned int order, int n
 		return false;
 	pa = pisa_node_pa(nid, order, false);
 	return pa &&
-	       (!list_empty_careful(&pa->partial) ||
+	       /* Pairs with cmpxchg_release() in pisa_enable_pcp(). */
+	       ((smp_load_acquire(&pa->pcp) && raw_cpu_read(pa->pcp->count)) ||
+		!list_empty_careful(&pa->partial) ||
 		!list_empty_careful(&pa->partial_dirty) ||
 		!list_empty_careful(&pa->idle));
 }
@@ -532,6 +758,7 @@ static unsigned int pisa_scan_bitmap(struct pisa_meta *meta, bool dirty,
 			break;
 	}
 	*countp -= used;
+	pa->blocks_in_use += used;
 	return got;
 }
 
@@ -638,6 +865,7 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 		meta->prot = pa->prot;
 		/* Set PISA_ACTIVE after @meta is fully set up. */
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
+		pa->stats.page_alloc_cnt++;
 	}
 	spin_unlock_irqrestore(&pa->lock, flags);
 
@@ -656,6 +884,49 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 	return n;
 }
 
+/* Allocate @nr_pages blocks through this CPU's cache, refilling in batches on miss. */
+static unsigned long pisa_pcp_alloc(struct pisa_alloc *pa, gfp_t gfp, unsigned long nr_pages,
+				    struct page **page_array, bool frozen)
+{
+	unsigned int pcp_batch = READ_ONCE(pisa_pcp_batch);
+	unsigned long got, n, i, j;
+
+	got = pisa_pcp_pop(pa, nr_pages, page_array);
+	if (got < nr_pages) {
+		if (nr_pages - got >= pcp_batch) {
+			got += __pisa_alloc_bulk(pa, gfp, nr_pages - got,
+						 page_array + got, false, true);
+		} else {
+			struct page *batch[PISA_PCP_BATCH];
+
+			n = __pisa_alloc_bulk(pa, gfp, pcp_batch, batch, false, true);
+			for (i = 0; i < n && got < nr_pages; i++)
+				page_array[got++] = batch[i];
+			if (i < n)
+				pisa_pcp_push(pa, batch + i, n - i);
+		}
+	}
+
+	for (i = j = 0; i < got; i++) {
+		struct page *block = page_array[i];
+
+		page_array[i] = NULL;
+		/* Poisoned while cached: leak it, as pisa_scan_bitmap() does. */
+		if (pisa_block_poisoned(pa, block))
+			continue;
+		pisa_block_prep(block);
+		if (want_init_on_alloc(gfp)) {
+			memset(page_address(block), 0, PAGE_SIZE << pa->order);
+			if (frozen) /* Order zeroing before caller publishes the page. */
+				smp_wmb();
+		}
+		if (!frozen)
+			page_ref_unfreeze(block, 1);
+		page_array[j++] = block;
+	}
+	return j;
+}
+
 /**
  * pisa_alloc_bulk - Allocate up to @nr_pages blocks from @pa
  * @pa: Allocator to allocate from
@@ -681,11 +952,16 @@ unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
 			i++;
 			continue;
 		}
+
 		/* Fill the run of @n NULL entries at @i. */
 		for (n = 1; i + n < nr_pages && !page_array[i + n]; n++)
 			;
-		got = __pisa_alloc_bulk(pa, gfp, n, page_array + i,
-					want_init_on_alloc(gfp), frozen);
+		/* Pairs with smp_store_release() in pisa_enable_pcp(). */
+		if (smp_load_acquire(&pa->pcp))
+			got = pisa_pcp_alloc(pa, gfp, n, page_array + i, frozen);
+		else
+			got = __pisa_alloc_bulk(pa, gfp, n, page_array + i,
+						want_init_on_alloc(gfp), frozen);
 		i += got;
 		if (got < n)
 			break;
@@ -733,10 +1009,13 @@ static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock
 		for (i = 0; i < nblocks; i++) {
 			if (!pisa_block_poisoned(pa, page + i))
 				continue;
-			if (__test_and_clear_bit(off + i, meta->clean_bitmap))
+			if (__test_and_clear_bit(off + i, meta->clean_bitmap)) {
 				meta->nr_clean--;
-			else if (__test_and_clear_bit(off + i, meta->dirty_bitmap))
+				pa->blocks_in_use++;
+			} else if (__test_and_clear_bit(off + i, meta->dirty_bitmap)) {
 				meta->nr_dirty--;
+				pa->blocks_in_use++;
+			}
 			__set_bit(off + i, busy);
 			poisoned = true;
 			off += i + 1;
@@ -760,6 +1039,7 @@ static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock
 		pisa_block_prep(page + i);
 		page_ref_unfreeze(page + i, 1);
 	}
+	pa->blocks_in_use += nblocks;
 	pisa_place_meta(meta);
 	return page;
 }
@@ -806,6 +1086,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 	pa = pisa_node_pa(dev_to_node(dev), 0, false);
 	if (!pa)
 		return NULL;
+	pisa_pcp_drain(pa);
 
 	nblocks = size >> PAGE_SHIFT;
 	align_mask = (1UL << get_order(size)) - 1;
@@ -830,6 +1111,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		meta->pa = pa;
 		meta->prot = pa->prot;
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
+		pa->stats.page_alloc_cnt++;
 		page = pisa_take_contig(meta, nblocks, align_mask);
 		if (unlikely(!page))
 			should_release = pisa_place_meta(meta);
@@ -876,6 +1158,17 @@ bool __pisa_free_page(struct page *page)
 	if (want_init_on_free())
 		memset(page_address(page), 0, PAGE_SIZE << pa->order);
 
+	/* Pairs with cmpxchg_release() in pisa_enable_pcp(). */
+	if (smp_load_acquire(&pa->pcp) && pa->nid == numa_mem_id() &&
+	    page_to_nid(page) == numa_mem_id()) {
+		if (pisa_page_can_recycle(page)) {
+			pisa_pcp_push(pa, &page, 1);
+			return true;
+		}
+		if (this_cpu_read(pa->pcp->count))
+			pisa_pcp_drain_cpu(pa, raw_smp_processor_id());
+	}
+
 	spin_lock_irqsave(&pa->lock, flags);
 	pisa_return_block_locked(pa, page, &should_release);
 	spin_unlock_irqrestore(&pa->lock, flags);
@@ -889,15 +1182,17 @@ bool __pisa_free_page(struct page *page)
 /* Shrinker: releases reservoir pages first, then idle allocator pages. */
 static unsigned long pisa_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
 {
-	unsigned long nr = pisa_reservoir_count();
+	unsigned long nr = pisa_reservoir_count() << PISA_ORDER;
 	struct pisa_alloc *pa;
 
 	read_lock(&pisa_allocs_lock);
-	list_for_each_entry(pa, &pisa_allocs, node)
-		nr += READ_ONCE(pa->num_idle_pages);
+	list_for_each_entry(pa, &pisa_allocs, node) {
+		nr += (unsigned long)READ_ONCE(pa->num_idle_pages) << PISA_ORDER;
+		nr += pisa_pcp_count(pa) << pa->order;
+	}
 	read_unlock(&pisa_allocs_lock);
 
-	return nr << PISA_ORDER;
+	return nr;
 }
 
 /* Detach PISA pages from @list onto @release_list up to @nr_to_scan base pages. */
@@ -930,6 +1225,8 @@ VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct
 	if (freed < sc->nr_to_scan) {
 		read_lock(&pisa_allocs_lock);
 		list_for_each_entry(pa, &pisa_allocs, node) {
+			/* Cached blocks keep PISA pages from going idle. */
+			pisa_pcp_drain(pa);
 			freed += pisa_shrink_list(&pa->lock, &pa->idle,
 						  &pa->num_idle_pages, &release_list,
 						  sc->nr_to_scan - freed);
@@ -952,15 +1249,30 @@ VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct
 	return freed ?: SHRINK_STOP;
 }
 
+/* Return the blocks a dead CPU cached, which nothing else would. */
+static int pisa_cpu_dead(unsigned int cpu)
+{
+	struct pisa_alloc *pa;
+
+	read_lock(&pisa_allocs_lock);
+	list_for_each_entry(pa, &pisa_allocs, node)
+		/* Pairs with smp_store_release() in pisa_enable_pcp(). */
+		if (smp_load_acquire(&pa->pcp))
+			pisa_pcp_drain_cpu(pa, cpu);
+	read_unlock(&pisa_allocs_lock);
+	return 0;
+}
+
 static int __init pisa_init(void)
 {
 	const struct {
 		u8 order;
 		bool ro;
+		bool pcp;
 	} cfg[] = {
-		{ 0, false },
-		{ 2, true },
-		{ SKB_FRAG_PAGE_ORDER, true },
+		{ 0, false, true },
+		{ 2, true, false },
+		{ SKB_FRAG_PAGE_ORDER, true, true },
 	};
 	struct shrinker *shrink;
 	int nid, i;
@@ -986,6 +1298,8 @@ static int __init pisa_init(void)
 			if (!pa)
 				continue;
 			pisa_set_name(pa, "pisa%s_o%u_n%d", ro ? "_ro" : "", order, nid);
+			if (cfg[i].pcp)
+				pisa_enable_pcp(pa);
 			pisa_nodes[nid].pa[ro][order] = pa;
 		}
 	}
@@ -995,6 +1309,10 @@ static int __init pisa_init(void)
 	if (!pisa_wq)
 		pr_warn("pisa: no reclaim workqueue, falling back to system_wq\n");
 
+	if (cpuhp_setup_state_nocalls(CPUHP_BP_PREPARE_DYN, "iommu/pisa:dead", NULL,
+				      pisa_cpu_dead) < 0)
+		pr_warn("pisa: no CPU hotplug callback, offline CPUs keep cached blocks\n");
+
 	shrink = shrinker_alloc(0, "pisa");
 	if (!shrink) {
 		pr_warn("pisa: shrinker registration failed\n");
drivers/iommu/pisa-kunit.c +78 -0

90 lines not on this page · raw message

drivers/iommu/pisa-priv.h +34 -1
index e5ca95d2654cd..8f87bdf7d4ee2 100644
@@ -53,6 +53,7 @@ enum {
  * Lock hierarchy:
  * - pisa_allocs_lock (rwlock): outermost; protects pisa_allocs list.
  * - pisa_meta_mutex (mutex): serializes pisa_meta_init() and page-table alloc.
+ * - pcp->lock (spinlock, irqsave): per-CPU block cache.
  * - pa->lock (spinlock, irqsave): per-allocator lists, bitmaps, and stats.
  * - pisa_domains[].map_lock (spinlock, irqsave): first-time iommu_map() in __pisa_map_phys().
  * - pisa_domains_lock (spinlock, irqsave): leaf lock over pisa_domains[]/windows.
@@ -105,11 +106,28 @@ static inline unsigned int pisa_meta_avail(const struct pisa_meta *meta)
 	return meta->nr_clean + meta->nr_dirty;
 }
 
+/* Per-CPU front cache of free blocks at refcount 0, see pisa_enable_pcp(). */
+#define PISA_PCP_HIGH	64U	/* blocks cached per CPU at most */
+#define PISA_PCP_BATCH	32U	/* blocks moved per refill or flush */
+
+struct pisa_pcp {
+	spinlock_t	lock;	/* by this CPU, or by a drain from any CPU */
+	unsigned int	count;
+	struct page	*blocks[PISA_PCP_HIGH];
+};
+
+/* Per-allocator statistics, see pisa_allocs_show(). */
+struct pisa_alloc_stats {
+	u64		page_alloc_cnt;
+	u64		page_free_cnt;
+};
+
 /**
  * struct pisa_alloc - Allocator managing 2MB-backed blocks of a fixed order
- * @lock:	Spinlock protecting lists and block bitmaps
+ * @lock:	Spinlock protecting lists, block bitmaps, and u64 @stats
  * @order:	Block order managed by this allocator (<= PISA_ORDER)
  * @prot:	IOMMU_READ and/or IOMMU_WRITE from @dir passed to pisa_create()
+ * @pcp:	Per-CPU block caches, or NULL (see pisa_enable_pcp())
  * @partial:	Partially used PISA pages with @nr_clean > 0
  * @partial_dirty: Partially used PISA pages with @nr_clean == 0 and @nr_dirty > 0
  * @idle:	Completely free PISA pages (reclaimable under pressure)
@@ -117,15 +135,18 @@ static inline unsigned int pisa_meta_avail(const struct pisa_meta *meta)
  * @num_idle_pages: Length of @idle
  * @max_idle_pages: High watermark of @idle before async release to the buddy allocator
  * @idle_jiffies: Timestamp (jiffies) when @idle last exceeded @max_idle_pages
+ * @blocks_in_use: Blocks handed out and not yet freed
  * @nid:	NUMA node id
  * @node:	Node in the global pisa_allocs list
  * @name:	Debug name (defaults to caller of pisa_create())
+ * @stats:	Per-allocator statistics
  */
 struct pisa_alloc {
 	/* First cacheline: hot fields touched on block alloc and free. */
 	spinlock_t		lock;
 	u8			order;
 	u8			prot;
+	struct pisa_pcp __percpu *pcp;
 	struct list_head	partial;
 	struct list_head	partial_dirty;
 	struct list_head	idle;
@@ -133,12 +154,22 @@ struct pisa_alloc {
 	unsigned int		num_idle_pages;
 	unsigned int		max_idle_pages;
 	unsigned long		idle_jiffies;
+	unsigned long		blocks_in_use;
 	/* Cold. */
 	int			nid;
 	struct list_head	node;
 	char			name[48];
+	struct pisa_alloc_stats	stats;
 } ____cacheline_aligned;
 
+/* Active non-idle PISA pages held by @pa, for soft compaction checks. */
+static inline long pisa_alloc_held_pages(const struct pisa_alloc *pa)
+{
+	return (long)(READ_ONCE(pa->stats.page_alloc_cnt) -
+		      READ_ONCE(pa->stats.page_free_cnt)) -
+	       READ_ONCE(pa->num_idle_pages);
+}
+
 /* Per-NUMA-node PISA state. */
 struct pisa_node {
 	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
@@ -202,6 +233,8 @@ struct pisa_alloc *pisa_create(int nid, unsigned int order, enum dma_data_direct
 struct pisa_alloc *pisa_node_pa(int nid, unsigned int order, bool ro);
 __printf(2, 3)
 void pisa_set_name(struct pisa_alloc *pa, const char *fmt, ...);
+int pisa_enable_pcp(struct pisa_alloc *pa);
+void pisa_pcp_drain(struct pisa_alloc *pa);
 void pisa_release_page(struct pisa_meta *meta);
 unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
 			      unsigned long nr_pages, struct page **page_array, bool frozen);
include/linux/pisa.h +6 -0
index a6556aa403a09..cdf176464d74a 100644
@@ -100,6 +100,7 @@ unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
 				    bool frozen);
 
 bool pisa_has_free_blocks_rx(const struct device *dev, unsigned int order, int nid);
+bool pisa_page_can_recycle(const struct page *page);
 
 static inline gfp_t pisa_rx_gfp(const struct device *dev)
 {
@@ -139,6 +140,11 @@ static inline bool pisa_free_coherent(struct page *page, size_t size)
 	return false;
 }
 
+static inline bool pisa_page_can_recycle(const struct page *page)
+{
+	return true;
+}
+
 static inline unsigned long
 pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred_nid,
 		      nodemask_t *nodemask, int nr_pages,
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#134 lore raw

Re: [RFC PATCH v2 11/25] iommu/dma: Add per-CPU block caches to PISA allocators

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] iommu/dma: cross-node per-CPU cache refill in pisa_alloc_bulk() - [Medium] iommu/dma: hardcoded…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] iommu/dma: cross-node per-CPU cache refill in pisa_alloc_bulk()
- [Medium] iommu/dma: hardcoded order 3 in test_gfp_pisa() fails on 16K/64K pages
- [Low] iommu/dma: changelog omits pisa_page_can_recycle() and pisa.compact
- [Low] iommu/dma: short allocation in pisa_pcp_alloc() on poisoned block
--

commit 6d45ca2b93f2e0d3d72f8ae4375bcf8901944ad1
Author: Luigi Rizzo <[email protected]>

Quoted 18 lines

iommu/dma: Add per-CPU block caches to PISA allocators

Every block allocation and free takes the allocator's lock. Highly concurrent users e.g. socket tx fragments, can cause significant lock contention.

Add pisa_enable_pcp(), an opt-in per-CPU front cache, similar to the page allocator's per-CPU lists:

- Each per-CPU cache keeps up to 64 free blocks, and refills it from the main allocator in batches of 32.
- returned blocks belonging to the local NUMA node are kept in the local cache.
- returned blocks belonging to a remote NUMA node are returned to the proper per-node allocator.
The cache is fully integrated with the shrinker and CPU offlining to drain the cache.

Quoted 4 lines

Enable per-CPU caches for the per-node order-0 RW and SKB_FRAG_PAGE_ORDER RO allocators.

[Severity: Low]
This isn't a bug, but this patch also adds and exports pisa_page_can_recycle(), the pisa.compact module parameter, and the per-allocator block and page accounting used for soft compaction, none of which are mentioned in the commit message.

Quoted 4 lines
drivers/iommu/pisa-alloc.c +0 -0
index 25e4645310678..913706a503341 100644

[ ... ]

Quoted 55 lines
drivers/iommu/pisa-alloc.c +44 -1
+/* Allocate @nr_pages blocks through this CPU's cache, refilling in batches on miss. */
+static unsigned long pisa_pcp_alloc(struct pisa_alloc *pa, gfp_t gfp, unsigned long nr_pages,
+				    struct page **page_array, bool frozen)
+{
+	unsigned int pcp_batch = READ_ONCE(pisa_pcp_batch);
+	unsigned long got, n, i, j;
+
+	got = pisa_pcp_pop(pa, nr_pages, page_array);
+	if (got < nr_pages) {
+		if (nr_pages - got >= pcp_batch) {
+			got += __pisa_alloc_bulk(pa, gfp, nr_pages - got,
+						 page_array + got, false, true);
+		} else {
+			struct page *batch[PISA_PCP_BATCH];
+
+			n = __pisa_alloc_bulk(pa, gfp, pcp_batch, batch, false, true);
+			for (i = 0; i < n && got < nr_pages; i++)
+				page_array[got++] = batch[i];
+			if (i < n)
+				pisa_pcp_push(pa, batch + i, n - i);
+		}
+	}
+
+	for (i = j = 0; i < got; i++) {
+		struct page *block = page_array[i];
+
+		page_array[i] = NULL;
+		/* Poisoned while cached: leak it, as pisa_scan_bitmap() does. */
+		if (pisa_block_poisoned(pa, block))
+			continue;
+		pisa_block_prep(block);
+		if (want_init_on_alloc(gfp)) {
+			memset(page_address(block), 0, PAGE_SIZE << pa->order);
+			if (frozen) /* Order zeroing before caller publishes the page. */
+				smp_wmb();
+		}
+		if (!frozen)
+			page_ref_unfreeze(block, 1);
+		page_array[j++] = block;
+	}
+	return j;
+}
+
 /**
  * pisa_alloc_bulk - Allocate up to @nr_pages blocks from @pa
  * @pa: Allocator to allocate from
@@ -681,11 +952,16 @@ unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
 			i++;
 			continue;
 		}
+
 		/* Fill the run of @n NULL entries at @i. */
 		for (n = 1; i + n < nr_pages && !page_array[i + n]; n++)
 			;
-		got = __pisa_alloc_bulk(pa, gfp, n, page_array + i,

drivers/iommu/pisa-alloc.c unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, · line 967

Quoted 10 lines
drivers/iommu/pisa-alloc.c +6 -1
-					want_init_on_alloc(gfp), frozen);
+		/* Pairs with smp_store_release() in pisa_enable_pcp(). */
+		if (smp_load_acquire(&pa->pcp))
+			got = pisa_pcp_alloc(pa, gfp, n, page_array + i, frozen);
+		else
+			got = __pisa_alloc_bulk(pa, gfp, n, page_array + i,
+						want_init_on_alloc(gfp), frozen);
 		i += got;
 		if (got < n)
 			break;

[Severity: Low]
If a block popped from pa->pcp was poisoned while cached, does pisa_pcp_alloc() return fewer than n blocks without refilling a replacement? Unlike pisa_scan_bitmap(), skipping the poisoned block after the refill stage causes pisa_alloc_bulk() to see got < n and abort the allocation early even when healthy blocks are available.

[ ... ]

Quoted 4 lines
drivers/iommu/pisa-alloc.c +0 -0
@@ -876,6 +1158,17 @@ bool __pisa_free_page(struct page *page)
 	if (want_init_on_free())
 		memset(page_address(page), 0, PAGE_SIZE << pa->order);
 

drivers/iommu/pisa-alloc.c bool __pisa_free_page(struct page *page) · line 1170

Quoted 10 lines
drivers/iommu/pisa-alloc.c +10 -0
+	/* Pairs with cmpxchg_release() in pisa_enable_pcp(). */
+	if (smp_load_acquire(&pa->pcp) && pa->nid == numa_mem_id() &&
+	    page_to_nid(page) == numa_mem_id()) {
+		if (pisa_page_can_recycle(page)) {
+			pisa_pcp_push(pa, &page, 1);
+			return true;
+		}
+		if (this_cpu_read(pa->pcp->count))
+			pisa_pcp_drain_cpu(pa, raw_smp_processor_id());
+	}

[Severity: Medium]
Can pisa_alloc_bulk() -> pisa_pcp_alloc() populate pa->pcp on a CPU where numa_mem_id() != pa->nid?

__pisa_free_page() only pushes freed blocks to or compact-drains pa->pcp when pa->nid == numa_mem_id(), but pisa_alloc_bulk() calls pisa_pcp_alloc() without checking whether the current CPU belongs to pa->nid (and __pisa_alloc_bulk() can also sleep and migrate the task before pisa_pcp_push() runs).

On a multi-node NUMA system, a cross-node allocation refills 32 blocks and leaves up to 31 blocks cached in that remote CPU's pa->pcp, where normal frees never compact-drain them and CPUs on pa->nid never pop them, pinning their backing 2MB PISA pages in pa->blocks_in_use. This also causes test_pcp_cache() and test_alloc_and_recycle() in drivers/iommu/pisa-kunit.c to fail KUNIT_EXPECT_PTR_EQ(test, p2, p1) whenever the KUnit kthread runs on a CPU with numa_mem_id() != first_memory_node: p1 = pisa_alloc(pa, ...) refills 32 blocks into the remote CPU's pa->pcp and returns batch[0], __free_page(p1) bypasses pa->pcp and returns p1 to the bitmap, and p2 = pisa_alloc(pa, ...) pops batch[31] from pa->pcp instead of p1.

Quoted 4 lines
drivers/iommu/pisa-kunit.c +0 -0
index 72ee8986b4802..5bbb540eb505e 100644

[ ... ]

Quoted 2 lines
drivers/iommu/pisa-kunit.c +2 -0
+static void test_gfp_pisa(struct kunit *test)
+{

[ ... ]

drivers/iommu/pisa-kunit.c static void test_dev_pisa_attrs(struct kunit *test) · line 550

Quoted 8 lines
drivers/iommu/pisa-kunit.c +8 -0
+	p_ro = alloc_pages(GFP_KERNEL | __GFP_COMP | __GFP_PISA_RO, 3);
+	KUNIT_ASSERT_NOT_NULL(test, p_ro);
+	if (p_ro) {
+		KUNIT_EXPECT_TRUE(test, is_pisa_page(p_ro));
+		KUNIT_EXPECT_EQ(test, pisa_meta_of_pfn(page_to_pfn(p_ro))->prot,
+				IOMMU_READ);
+		__free_pages(p_ro, 3);
+	}

[Severity: Medium]
Should test_gfp_pisa() pass SKB_FRAG_PAGE_ORDER (or 2) instead of hardcoding order 3? pisa_init() only creates read-only per-node allocators for orders 2 and SKB_FRAG_PAGE_ORDER, and on arm64 with 16KB or 64KB base pages SKB_FRAG_PAGE_ORDER is 1 or 0, so order 3 has no read-only PISA allocator and falls back to the buddy allocator, failing is_pisa_page(p_ro).

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#135 lore raw

RFC PATCH v2 12/25 net/core: Use per-node PISA allocators for skb_page_frag_refill()

In reply to Luigi Rizzo

Transmit socket buffers use memory coming from skb_page_frag_refill(). Sockets whose leaf device has enabled pisa_tx_bufs should use PISA memory.

Add a dedicated per-task page_frag, current->task_frag_pisa, populated with read-only PISA blocks via __GFP_PISA_RO, and select it on TX when the socket's (or cork's) route goes out in the clear through a PISA-enabled device.

Because walking lower devices can be expensive (e.g. bonded devices), cache the leaf device check on the net_device and refresh it at most once every ~250ms. Special paths that hold plaintext before encryption (IPsec, kTLS) or do not use a DMA device keep using regular pages; ESP output uses skb_page_frag_refill_dev() to opt in when the egress device has pisa_tx_bufs enabled.

---
 drivers/base/core.c        | 24 +++++++---
 drivers/iommu/pisa-alloc.c | 57 ++++++++++++++++++++++++
 drivers/iommu/pisa-kunit.c |  3 +-
 include/linux/device.h     |  9 ++++
 include/linux/netdevice.h  |  4 ++
 include/linux/pisa.h       | 20 +++++++++
 include/linux/sched.h      |  4 ++
 include/linux/skbuff.h     |  2 +
 include/net/sock.h         | 89 ++++++++++++++++++++++++++++++++++++++
 kernel/exit.c              |  2 +
 kernel/fork.c              |  2 +
 net/core/sock.c            | 41 ++++++++++++++++++
 net/ipv4/esp4.c            |  4 +-
 net/ipv4/ip_output.c       | 11 +++--
 net/ipv4/tcp.c             |  3 +-
 net/ipv6/esp6.c            |  4 +-
 net/ipv6/ip6_output.c      | 11 +++--
 17 files changed, 270 insertions(+), 20 deletions(-)
drivers/base/core.c +18 -6
index 97cd2d03ff77c..ade0c94b02ae7 100644
@@ -2909,7 +2909,8 @@ static ssize_t removable_show(struct device *dev, const struct device_attribute
 static const DEVICE_ATTR_RO(removable);
 
 /* Per-device configuration to selectively enable PISA */
-static ssize_t pisa_attr_store(const char *buf, size_t count, bool *field)
+static ssize_t pisa_attr_store(struct device *dev, const char *buf, size_t count,
+			       bool *field, int (*setter)(struct device *, bool))
 {
 	bool val;
 	int ret = kstrtobool(buf, &val);
@@ -2921,11 +2922,17 @@ static ssize_t pisa_attr_store(const char *buf, size_t count, bool *field)
 		if (ret < 0)
 			return ret;
 	}
-	WRITE_ONCE(*field, val);
+	if (setter) {
+		ret = setter(dev, val);
+		if (ret < 0)
+			return ret;
+	} else {
+		WRITE_ONCE(*field, val);
+	}
 	return count;
 }
 
-#define PISA_BOOL_ATTR(name)						\
+#define PISA_SET_ATTR(name, setter)					\
 static ssize_t name##_show(struct device *dev,				\
 			   struct device_attribute *attr, char *buf)	\
 {									\
@@ -2935,13 +2942,15 @@ static ssize_t name##_store(struct device *dev,				\
 			    struct device_attribute *attr,		\
 			    const char *buf, size_t count)		\
 {									\
-	return pisa_attr_store(buf, count, &dev->name);			\
+	return pisa_attr_store(dev, buf, count, &dev->name, setter);	\
 }									\
 static DEVICE_ATTR_RW(name)
 
+#define PISA_BOOL_ATTR(name)	PISA_SET_ATTR(name, NULL)
+
 PISA_BOOL_ATTR(pisa_coherent);
 PISA_BOOL_ATTR(pisa_rx_bufs);
-PISA_BOOL_ATTR(pisa_tx_bufs);
+PISA_SET_ATTR(pisa_tx_bufs, net_pisa_tx_bufs_set);
 PISA_BOOL_ATTR(pisa_tx_skb_heads);
 
 static struct attribute *dev_attr_pisa[] = {
@@ -3100,8 +3109,11 @@ static void device_remove_attrs(struct device *dev)
 	const struct class *class = dev->class;
 	const struct device_type *type = dev->type;
 
-	if (IS_ENABLED(CONFIG_PISA) && dev->dma_mask)
+	if (IS_ENABLED(CONFIG_PISA) && dev->dma_mask) {
 		device_remove_group(dev, &dev_attr_pisa_group);
+		if (dev->pisa_tx_bufs)
+			net_pisa_tx_bufs_set(dev, false);
+	}
 
 	if (dev->physical_location) {
 		device_remove_group(dev, &dev_attr_physical_location_group);
drivers/iommu/pisa-alloc.c +57 -0

63 lines not on this page · raw message

drivers/iommu/pisa-kunit.c +2 -1
index 5bbb540eb505e..5f6b2ebcab1d9 100644
@@ -477,7 +477,8 @@ static void test_dev_pisa_attrs(struct kunit *test)
 	}
 	kunit_check_pisa_attr(test, dev, "pisa_coherent", &dev->pisa_coherent);
 	kunit_check_pisa_attr(test, dev, "pisa_rx_bufs", &dev->pisa_rx_bufs);
-	kunit_check_pisa_attr(test, dev, "pisa_tx_bufs", &dev->pisa_tx_bufs);
+	if (IS_ENABLED(CONFIG_NET))
+		kunit_check_pisa_attr(test, dev, "pisa_tx_bufs", &dev->pisa_tx_bufs);
 	kunit_check_pisa_attr(test, dev, "pisa_tx_skb_heads", &dev->pisa_tx_skb_heads);
 	device_unregister(dev);
 }
include/linux/device.h +9 -0
index b3c11e32116ca..08f511b978ded 100644
@@ -814,6 +814,15 @@ struct device {
 	DECLARE_BITMAP(flags, DEV_FLAG_COUNT);
 };
 
+#if defined(CONFIG_NET) && defined(CONFIG_PISA)
+int net_pisa_tx_bufs_set(struct device *dev, bool val);
+#else
+static inline int net_pisa_tx_bufs_set(struct device *dev, bool val)
+{
+	return -EOPNOTSUPP;
+}
+#endif
+
 #define __create_dev_flag_accessors(accessor_name, flag_name) \
 static inline bool dev_##accessor_name(const struct device *dev) \
 { \
include/linux/netdevice.h +4 -0
index 435be7880d7e5..41c999223a15e 100644
@@ -2161,6 +2161,7 @@ enum netdev_reg_state {
  *	@neighbours:	List heads pointing to this device's neighbours'
  *			dev_list, one per address-family.
  *	@hwprov: Tracks which PTP performs hardware packet time stamping.
+ *	@pisa_tx_stamp:	Cached leaf pisa flags and timestamp.
  *
  *	FIXME: cleanup struct net_device such that network protocol info
  *	moves out.
@@ -2276,6 +2277,9 @@ struct net_device {
 	} adj_list;
 
 	/* Read-mostly cache-line for fast-path access */
+#ifdef CONFIG_PISA
+	u32			pisa_tx_stamp;
+#endif
 	xdp_features_t		xdp_features;
 	const struct xdp_metadata_ops *xdp_metadata_ops;
 	const struct xsk_tx_metadata_ops *xsk_tx_metadata_ops;
include/linux/pisa.h +20 -0
index cdf176464d74a..822e1556d78ef 100644
@@ -107,6 +107,18 @@ static inline gfp_t pisa_rx_gfp(const struct device *dev)
 	return dev && READ_ONCE(dev->pisa_rx_bufs) ? __GFP_PISA_RW : 0;
 }
 
+/* current->task_frag_pisa lifetime, see task_page_frag(). */
+static inline void pisa_task_frag_init(struct task_struct *tsk)
+{
+	tsk->task_frag_pisa.page = NULL;
+}
+
+static inline void pisa_task_frag_release(struct task_struct *tsk)
+{
+	if (tsk->task_frag_pisa.page)
+		put_page(tsk->task_frag_pisa.page);
+}
+
 #else /* !CONFIG_PISA */
 
 static inline int pisa_meta_init(void)
@@ -164,6 +176,14 @@ static inline bool pisa_has_free_blocks_rx(const struct device *dev,
 	return false;
 }
 
+static inline void pisa_task_frag_init(struct task_struct *tsk)
+{
+}
+
+static inline void pisa_task_frag_release(struct task_struct *tsk)
+{
+}
+
 #endif /* CONFIG_PISA */
 
 static inline struct page *
include/linux/sched.h +4 -0
index 1c93da75226e3..1c7ef0d90dc35 100644
@@ -1453,6 +1453,10 @@ struct task_struct {
 	struct pipe_inode_info		*splice_pipe;
 
 	struct page_frag		task_frag;
+#ifdef CONFIG_PISA
+	/* TX frag that may hold PISA pages, see sk_page_frag_dst(). */
+	struct page_frag		task_frag_pisa;
+#endif
 
 #ifdef CONFIG_ARCH_HAS_LAZY_MMU_MODE
 	struct lazy_mmu_state		lazy_mmu_state;
include/linux/skbuff.h +2 -0
index 6787fcf6ac3e4..2fce6eafa1cb3 100644
@@ -3808,6 +3808,8 @@ static inline void skb_frag_page_copy(skb_frag_t *fragto,
 }
 
 bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t prio);
+bool skb_page_frag_refill_dev(unsigned int sz, struct page_frag *pfrag,
+			      const struct sk_buff *skb);
 
 /**
  * __skb_frag_dma_map - maps a paged fragment via the DMA API
include/net/sock.h +89 -0

95 lines not on this page · raw message

kernel/exit.c +2 -0
index d5e7bc2af804a..ac7ca1fb180c3 100644
@@ -6,6 +6,7 @@
  */
 
 #include <linux/mm.h>
+#include <linux/pisa.h>
 #include <linux/slab.h>
 #include <linux/sched/autogroup.h>
 #include <linux/sched/mm.h>
@@ -1009,6 +1010,7 @@ void __noreturn do_exit(long code)
 
 	if (tsk->task_frag.page)
 		put_page(tsk->task_frag.page);
+	pisa_task_frag_release(tsk);
 
 	exit_task_stack_account(tsk);
 
kernel/fork.c +2 -0
index 5efceb8d58a78..d235d7ab04687 100644
@@ -44,6 +44,7 @@
 #include <linux/mmu_notifier.h>
 #include <linux/fs.h>
 #include <linux/mm.h>
+#include <linux/pisa.h>
 #include <linux/mm_inline.h>
 #include <linux/memblock.h>
 #include <linux/nsproxy.h>
@@ -982,6 +983,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
 #endif
 	tsk->splice_pipe = NULL;
 	tsk->task_frag.page = NULL;
+	pisa_task_frag_init(tsk);
 	tsk->wake_q.next = NULL;
 	tsk->worker_private = NULL;
 
net/core/sock.c +41 -0

66 lines not on this page · raw message

net/ipv4/esp4.c +2 -2
index ae701561d9f12..feecf094f582c 100644
@@ -451,7 +451,7 @@ int esp_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *
 
 			spin_lock_bh(&x->lock);
 
-			if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
+			if (unlikely(!skb_page_frag_refill_dev(allocsize, pfrag, skb))) {
 				spin_unlock_bh(&x->lock);
 				goto cow;
 			}
@@ -560,7 +560,7 @@ int esp_output_tail(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *
 		allocsize = ALIGN(skb->data_len, L1_CACHE_BYTES);
 
 		spin_lock_bh(&x->lock);
-		if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
+		if (unlikely(!skb_page_frag_refill_dev(allocsize, pfrag, skb))) {
 			spin_unlock_bh(&x->lock);
 			goto error_free;
 		}
net/ipv4/ip_output.c +7 -4
index 3396f177a18d0..a5ea530bc8b5b 100644
@@ -986,7 +986,10 @@ static int __ip_append_data(struct sock *sk,
 
 	exthdrlen = !skb ? rt->dst.header_len : 0;
 	mtu = cork->gso_size ? IP_MAX_MTU : cork->fragsize;
-	paged = !!cork->gso_size;
+	paged = !!cork->gso_size ||
+		(sk->sk_type != SOCK_RAW &&
+		 (rt->dst.dev->features & NETIF_F_SG) &&
+		 is_pisa_pfrag(pfrag));
 
 	hh_len = LL_RESERVED_SPACE(rt->dst.dev);
 
@@ -1383,8 +1386,8 @@ int ip_append_data(struct sock *sk, struct flowi4 *fl4,
 	}
 
 	return __ip_append_data(sk, fl4, &sk->sk_write_queue, &inet->cork.base,
-				sk_page_frag(sk), getfrag,
-				from, length, transhdrlen, flags);
+				sk_page_frag_dst(sk, inet->cork.base.dst),
+				getfrag, from, length, transhdrlen, flags);
 }
 
 static void ip_cork_release(struct inet_cork *cork)
@@ -1592,7 +1595,7 @@ struct sk_buff *ip_make_skb(struct sock *sk,
 		return ERR_PTR(err);
 
 	err = __ip_append_data(sk, fl4, &queue, cork,
-			       &current->task_frag, getfrag,
+			       task_page_frag(cork->dst), getfrag,
 			       from, length, transhdrlen, flags);
 	if (err) {
 		__ip_flush_pending_frames(sk, &queue, cork);
net/ipv4/tcp.c +2 -1
index b9de7c302ba83..b8d44a0638914 100644
@@ -1290,9 +1290,10 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 			copy = msg_data_left(msg);
 
 		if (zc == 0) {
+			const struct dst_entry *dst = __sk_dst_get(sk);
 			bool merge = true;
 			int i = skb_shinfo(skb)->nr_frags;
-			struct page_frag *pfrag = sk_page_frag(sk);
+			struct page_frag *pfrag = sk_page_frag_dst(sk, dst);
 
 			if (!sk_page_frag_refill(sk, pfrag))
 				goto wait_for_space;
net/ipv6/esp6.c +2 -2
index d654f0f442388..cdedda548749a 100644
@@ -481,7 +481,7 @@ int esp6_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info
 
 			spin_lock_bh(&x->lock);
 
-			if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
+			if (unlikely(!skb_page_frag_refill_dev(allocsize, pfrag, skb))) {
 				spin_unlock_bh(&x->lock);
 				goto cow;
 			}
@@ -592,7 +592,7 @@ int esp6_output_tail(struct xfrm_state *x, struct sk_buff *skb, struct esp_info
 		allocsize = ALIGN(skb->data_len, L1_CACHE_BYTES);
 
 		spin_lock_bh(&x->lock);
-		if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
+		if (unlikely(!skb_page_frag_refill_dev(allocsize, pfrag, skb))) {
 			spin_unlock_bh(&x->lock);
 			goto error_free;
 		}
net/ipv6/ip6_output.c +7 -4
index 25fe0ba98b1a6..957c38a08680c 100644
@@ -1486,7 +1486,10 @@ static int __ip6_append_data(struct sock *sk,
 		dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
 	}
 
-	paged = !!cork->gso_size;
+	paged = !!cork->gso_size ||
+		(sk->sk_type != SOCK_RAW &&
+		 (rt->dst.dev->features & NETIF_F_SG) &&
+		 is_pisa_pfrag(pfrag));
 	mtu = cork->gso_size ? IP6_MAX_MTU : cork->fragsize;
 	orig_mtu = mtu;
 
@@ -1889,8 +1892,8 @@ int ip6_append_data(struct sock *sk,
 	}
 
 	return __ip6_append_data(sk, &sk->sk_write_queue, &inet->cork,
-				 sk_page_frag(sk), getfrag,
-				 from, length, transhdrlen, flags);
+				 sk_page_frag_dst(sk, inet->cork.base.dst),
+				 getfrag, from, length, transhdrlen, flags);
 }
 EXPORT_SYMBOL_GPL(ip6_append_data);
 
@@ -2092,7 +2095,7 @@ struct sk_buff *ip6_make_skb(struct sock *sk,
 	}
 
 	err = __ip6_append_data(sk, &queue, cork,
-				&current->task_frag, getfrag, from,
+				task_page_frag(cork->base.dst), getfrag, from,
 				length + exthdrlen, transhdrlen + exthdrlen,
 				flags);
 	if (err) {
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#136 lore raw

Re: [RFC PATCH v2 12/25] net/core: Use per-node PISA allocators for skb_page_frag_refill()

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [High] net: ip_make_skb() and ip6_make_skb() ignore sk_use_task_frag for PISA - [Medium] net…

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [High] net: ip_make_skb() and ip6_make_skb() ignore sk_use_task_frag for PISA
- [Medium] net: skb_page_frag_refill_dev() checks ingress skb->dev on forwarded ESP packets
- [Medium] net: mismatched PISA and buddy page recycling in skb_page_frag_refill()
- [Medium] net: odd-offset checksum corruption in ping_getfrag() with PISA paged mode
- [Medium] net: plaintext TX data placed in PISA pages on MACsec in dst_tx_pisa_ok()
- [Low] iommu/pisa: netdev_tx_pisa_refresh() skips lower walk when dev.parent is set
--

commit 8f85f66c700b51ce7332c64edba9f65c4414c1f0
Author: Luigi Rizzo <[email protected]>

net/core: Use per-node PISA allocators for skb_page_frag_refill()

This commit adds per-task PISA page_frag support (current->task_frag_pisa) and routes TX page_frag allocations to read-only PISA blocks when the egress device has pisa_tx_bufs enabled.

Quoted 5 lines
drivers/iommu/pisa-alloc.c +0 -0
index 913706a503341..7b9d0a7acc101 100644
@@ -644,6 +644,63 @@ bool pisa_has_free_blocks_rx(const struct device *dev, unsigned int order, int n

[ ... ]

Quoted 8 lines
drivers/iommu/pisa-alloc.c +8 -0
+/* Slow path of __netdev_tx_pisa_ok(): refresh dev->pisa_tx_stamp. */
+bool netdev_tx_pisa_refresh(struct net_device *dev, u32 now)
+{
+	bool ok;
+
+	if (dev->dev.parent) {
+		ok = READ_ONCE(dev->dev.parent->pisa_tx_bufs);
+	} else {

drivers/iommu/pisa-alloc.c bool pisa_has_free_blocks_rx(const struct device *dev, unsigned int order, int n · line 700

Quoted 10 lines
drivers/iommu/pisa-alloc.c +10 -0
+		rcu_read_lock();
+		ok = netdev_walk_all_lower_dev_rcu(dev,
+						   netdev_pisa_tx_bufs_walk,
+						   NULL) != 0;
+		rcu_read_unlock();
+	}
+	now |= ok ? PISA_TX_STAMP_OK : 0;
+	WRITE_ONCE(dev->pisa_tx_stamp, now);
+	return now & PISA_TX_STAMP_OK;
+}

[Severity: Low]
Does checking dev->dev.parent before walking lower devices miss lower DMA NICs under upper devices that set dev->dev.parent?

Stacked interfaces such as net_failover, hv_netvsc, and DSA user ports set dev->dev.parent via SET_NETDEV_DEV() while linking the underlying PCI VF or conduit NIC as a lower device. When pisa_tx_bufs is enabled on that lower device, netdev_tx_pisa_refresh() only reads the upper device's dev->dev.parent->pisa_tx_bufs (false) and skips netdev_walk_all_lower_dev_rcu(), leaving TX allocations on regular buddy pages.

Quoted 5 lines
include/net/sock.h +0 -0
index 173b37b2b8bb0..73906351d11db 100644
@@ -2670,6 +2670,95 @@ static inline struct page_frag *sk_page_frag(struct sock *sk)

[ ... ]

Quoted 9 lines
include/net/sock.h +9 -0
+/*
+ * May TX payload routed through @dst be copied into PISA pages? Those pages
+ * stay readable by every device that mapped them for as long as they are
+ * active, so only data that leaves the host in clear qualifies: IPsec payload
+ * is still plaintext here.
+ */
+static inline bool dst_tx_pisa_ok(const struct dst_entry *dst)
+{
+	bool ok = false;

include/net/sock.h static inline struct page_frag *sk_page_frag(struct sock *sk) · line 2729

Quoted 10 lines
include/net/sock.h +10 -0
+
+	if (!net_pisa_tx_bufs_enabled() || !dst)
+		return false;
+
+	rcu_read_lock();
+	if (!dst_xfrm(dst))
+		ok = __netdev_tx_pisa_ok(dst_dev_rcu(dst));
+	rcu_read_unlock();
+	return ok;
+}

[Severity: Medium]
Can dst_tx_pisa_ok() place unencrypted plaintext into PISA pages when routing over software MACsec?

A MACsec net_device has dev->dev.parent == NULL and links its physical NIC as a lower device, so netdev_tx_pisa_refresh() propagates PISA_TX_STAMP_OK from the NIC to the MACsec interface while !dst_xfrm(dst) is true. Socket send paths then copy plaintext into current->task_frag_pisa before macsec_encrypt() runs, exposing cleartext in DMA-readable (and on CoCo guests, shared/decrypted) PISA pages and holding it in tcp_rtx_queue until ACKed. In addition, forcing paged = true in __ip_append_data() and __ip6_append_data() causes macsec_encrypt() -> skb_cow_data() to immediately reallocate skb->head and linearize the fragments.

Quoted 4 lines
net/core/sock.c +0 -0
index e2401d735c5a7..695fefe316925 100644

[ ... ]

Quoted 10 lines
net/core/sock.c +5 -0
@@ -3257,13 +3258,20 @@ DEFINE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
  */
 bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
 {
+	/* PISA pages only go into current->task_frag_pisa, see sk_page_frag_dst(). */
+	if (is_pisa_pfrag(pfrag))
+		gfp |= __GFP_PISA_RO;
+
 	if (pfrag->page) {
+		if ((gfp & __GFP_PISA_RO) && !pisa_page_can_recycle(pfrag->page))

net/core/sock.c DEFINE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key); · line 3276

Quoted 10 lines
net/core/sock.c +2 -0
+			goto drop_page;
 		if (page_ref_count(pfrag->page) == 1) {
 			pfrag->offset = 0;
 			return true;
 		}
 		if (pfrag->offset + sz <= pfrag->size)
 			return true;
+drop_page:
 		put_page(pfrag->page);
 	}

[Severity: Medium]
Does skb_page_frag_refill() recycle a page of the wrong type when page_ref_count(pfrag->page) == 1?

pisa_page_can_recycle() returns true for non-PISA pages:

drivers/iommu/pisa-alloc.c:pisa_page_can_recycle() {
	if (!is_pisa_pfn(pfn))
		goto out;
    ...
}

If current->task_frag_pisa or x->xfrag caches a fallback buddy page (for example after a high-order PISA pool miss or before pisa_tx_bufs was enabled), skb_page_frag_refill() resets pfrag->offset = 0 whenever page_ref_count(pfrag->page) == 1 and reuses the buddy page indefinitely instead of allocating a PISA page. Conversely, if x->xfrag holds a PISA page and pisa_tx_bufs is later disabled on the egress device, !(gfp & __GFP_PISA_RO) skips pisa_page_can_recycle() and keeps recycling and pinning the 2MB PISA frame at refcount 1.

Quoted 26 lines
net/core/sock.c +22 -0
@@ -3289,6 +3297,39 @@ bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
 }
 EXPORT_SYMBOL(skb_page_frag_refill);
 
+/**
+ * skb_page_frag_refill_dev - GFP_ATOMIC skb_page_frag_refill() for @skb TX
+ * @sz: minimum size of the fragment we want to get
+ * @pfrag: pointer to page_frag, private to the caller
+ * @skb: packet being transmitted
+ *
+ * Pages come from the per-node DMA_TO_DEVICE PISA allocators when they are
+ * useful for @skb's egress device (__netdev_tx_pisa_ok()), otherwise from the
+ * buddy allocator. PISA pages are readable by every device that maps them
+ * while they stay active, so @pfrag must only ever hold data meant for devices,
+ * e.g. ciphertext; it may mix PISA and ordinary pages.
+ */
+bool skb_page_frag_refill_dev(unsigned int sz, struct page_frag *pfrag,
+			      const struct sk_buff *skb)
+{
+	gfp_t gfp = GFP_ATOMIC;
+
+	/*
+	 * Before ip_finish_output2() populates skb->dev (e.g. esp_output),
+	 * the egress device is carried by skb_dst(skb).
+	 */
+	if (net_pisa_tx_bufs_enabled()) {

net/core/sock.c bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp) · line 3331

Quoted 10 lines
net/core/sock.c +10 -0
+		const struct dst_entry *dst = skb_dst(skb);
+
+		rcu_read_lock();
+		if (__netdev_tx_pisa_ok(skb->dev ?: (dst ? dst_dev_rcu(dst) : NULL)))
+			gfp |= __GFP_PISA_RO;
+		rcu_read_unlock();
+	}
+	return skb_page_frag_refill(sz, pfrag, gfp);
+}
+EXPORT_SYMBOL(skb_page_frag_refill_dev);

[Severity: Medium]
On forwarded packets entering esp_output() or esp6_output(), doesn't skb->dev still point to the ingress device?

In ip_forward() -> xfrm4_output() -> esp_output() (and the IPv6 equivalent), skb->dev is not updated to the egress device until ip_output() runs after xfrm_output() finishes. Preferring skb->dev over dst_dev_rcu(dst) checks pisa_tx_bufs on the ingress interface instead of the egress interface for all forwarded ESP traffic.

net/ipv4/ip_output.c static int __ip_append_data(struct sock *sk, · line 992

Quoted 13 lines
net/ipv4/ip_output.c +4 -1
index 3396f177a18d0..a5ea530bc8b5b 100644
@@ -986,7 +986,10 @@ static int __ip_append_data(struct sock *sk,
 
 	exthdrlen = !skb ? rt->dst.header_len : 0;
 	mtu = cork->gso_size ? IP_MAX_MTU : cork->fragsize;
-	paged = !!cork->gso_size;
+	paged = !!cork->gso_size ||
+		(sk->sk_type != SOCK_RAW &&
+		 (rt->dst.dev->features & NETIF_F_SG) &&
+		 is_pisa_pfrag(pfrag));

[Severity: Medium]
Can setting paged = true for all sk->sk_type != SOCK_RAW sockets corrupt IPv4 ICMP checksums on SOCK_DGRAM ping sockets?

IPv4 ping sockets have sk->sk_type == SOCK_DGRAM and use ping_getfrag():

net/ipv4/ping.c:ping_getfrag() {
	if (!csum_and_copy_from_iter_full(to, fraglen, &pfh->wcheck,
					  &pfh->msg->msg_iter))
		return -EFAULT;
#if IS_ENABLED(CONFIG_IPV6)
	if (pfh->family == AF_INET6) {
		skb->csum = csum_block_add(skb->csum, pfh->wcheck, odd);
		skb->ip_summed = CHECKSUM_NONE;
		pfh->wcheck = 0;
	}
#endif
	return 0;
}

When paged is true and a ping payload crosses the end of current->task_frag_pisa.page starting from an odd pfrag->offset, the first chunk has an odd length (pfrag->size - pfrag->offset) and the second ping_getfrag() call starts at an odd packet offset. Because the AF_INET path accumulates directly into pfh->wcheck with progress = 0 and ignores odd, the second chunk's bytes are added with inverted byte lane alignment, producing an invalid ICMPv4 checksum.

[ ... ]

net/ipv4/ip_output.c struct sk_buff *ip_make_skb(struct sock *sk, · line 1601

Quoted 9 lines
net/ipv4/ip_output.c +1 -1
@@ -1592,7 +1595,7 @@ struct sk_buff *ip_make_skb(struct sock *sk,
 		return ERR_PTR(err);
 
 	err = __ip_append_data(sk, fl4, &queue, cork,
-			       &current->task_frag, getfrag,
+			       task_page_frag(cork->dst), getfrag,
 			       from, length, transhdrlen, flags);
 	if (err) {
 		__ip_flush_pending_frames(sk, &queue, cork);

[Severity: High]
Can ip_make_skb() and ip6_make_skb() re-enter current->task_frag_pisa and cause a use-after-free when a socket has sk_use_task_frag == false?

In-kernel sockets that transmit during memory reclaim or page faults (such as SUNRPC/NFS over UDP, which sets sk->sk_use_task_frag = false in xs_udp_finish_connecting()) call ip_make_skb() and ip6_make_skb(). Before this patch, non-GSO sends in __ip_append_data() and __ip6_append_data() had paged = false, so normal RPC datagrams never used pfrag. Now ip_make_skb() and ip6_make_skb() pass task_page_frag() without checking sk->sk_use_task_frag, and __ip_append_data() / __ip6_append_data() force paged = true when is_pisa_pfrag(pfrag) is true:

tcp_sendmsg_locked()
pfrag = sk_page_frag_dst(sk, dst) /* &current->task_frag_pisa */ sk_page_frag_refill(sk, pfrag) skb_copy_to_page_nocache(..., pfrag->page, pfrag->offset, copy)

    <page fault on user buffer / direct reclaim>
      xs_udp_send_request()          /* sk->sk_use_task_frag == false */
        ip_make_skb()
          __ip_append_data(..., task_page_frag(cork->dst), ...)
            skb_page_frag_refill(..., pfrag, ...)
              put_page(pfrag->page)  /* frees outer page at refcount 1 */

/* writes to freed pfrag->page, or corrupts pfrag->offset */

Passing sk_page_frag_dst(sk, ...) in ip_make_skb() and ip6_make_skb() would respect sk->sk_use_task_frag and use &sk->sk_frag instead.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#137 lore raw

RFC PATCH v2 13/25 net/core: Use PISA for page_pool memory

In reply to Luigi Rizzo

When a page_pool performs DMA mapping (PP_FLAG_DMA_MAP) on a device with pisa_rx_bufs enabled, pass __GFP_PISA_RW to use PISA memory.

---
 net/core/page_pool.c | 3 +++
 1 file changed, 3 insertions(+)
net/core/page_pool.c +3 -0
index d7c88c0b67e53..91cae5ba78373 100644
@@ -16,6 +16,7 @@
 #include <net/page_pool/helpers.h>
 #include <net/page_pool/memory_provider.h>
 #include <net/xdp.h>
+#include <linux/pisa.h>
 
 #include <linux/dma-direction.h>
 #include <linux/dma-mapping.h>
@@ -622,6 +623,8 @@ static noinline netmem_ref __page_pool_alloc_netmems_slow(struct page_pool *pool
 	 */
 	if ((gfp & GFP_ATOMIC) == GFP_ATOMIC)
 		gfp |= __GFP_NOWARN;
+	if (dma_map)
+		gfp |= pisa_rx_gfp(pool->p.dev);
 
 	/* Don't support bulk alloc for high-order pages */
 	if (unlikely(pp_order))
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#138 lore raw

RFC PATCH v2 14/25 iommu/dma: Support decrypted PISA pages

In reply to Luigi Rizzo

In Confidential Computing (CoCo) guests (AMD SEV-SNP, Intel TDX, ARM CCA), guest memory is private/encrypted by default, and DMA buffers must be converted to shared/decrypted in the host page tables before a device can access them.

Doing that hypercall per-packet on 4KB pages is prohibitively expensive, so guests normally bounce DMA through swiotlb. With PISA, 2MB pages are decrypted once upfront when allocated and re-encrypted only when retired back to the buddy allocator, avoiding both per-packet hypercalls and bounce-buffer copies.

Add pisa.decrypt (auto-enabled when CC_ATTR_GUEST_MEM_ENCRYPT is active) and the PISA_DECRYPTED flag to manage 2MB page decryption/re-encryption and bypass swiotlb bouncing for decrypted PISA pages.

---
 drivers/iommu/pisa-alloc.c | 117 ++++++++++++++++++++++++++++++++-----
 drivers/iommu/pisa-kunit.c |  11 ++++
 drivers/iommu/pisa-map.c   |   2 +-
 drivers/iommu/pisa-meta.c  |  13 +++++
 drivers/iommu/pisa-node.c  |  86 ++++++++++++++++-----------
 drivers/iommu/pisa-priv.h  |  16 ++++-
 include/linux/pisa.h       |  16 +++++
 kernel/dma/direct.c        |   5 +-
 8 files changed, 212 insertions(+), 54 deletions(-)
drivers/iommu/pisa-alloc.c +103 -14
index 7b9d0a7acc101..b4a25c65bf97e 100644
@@ -9,6 +9,7 @@
 #include <linux/bitmap.h>
 #include <linux/bitops.h>
 #include <linux/cache.h>
+#include <linux/cc_platform.h>
 #include <linux/cpuhotplug.h>
 #include <linux/device.h>
 #include <linux/dma-direct.h>
@@ -29,6 +30,7 @@
 #include <linux/pgalloc_tag.h>
 #include <linux/rcupdate.h>
 #include <linux/sched/mm.h>
+#include <linux/set_memory.h>
 #include <linux/shrinker.h>
 #include <linux/skbuff.h>
 #include <linux/slab.h>
@@ -49,6 +51,10 @@ static LLIST_HEAD(pisa_free_list);
 /* Dedicated WQ_MEM_RECLAIM workqueue, can run without allocations. */
 static struct workqueue_struct *pisa_wq __ro_after_init;
 
+/* Mark active PISA pages decrypted for DMA (auto-enabled on CoCo guests). */
+static bool pisa_decrypt __read_mostly;
+module_param_named(decrypt, pisa_decrypt, bool, 0444);
+
 /* Global count and ceiling on PISA pages across all allocators and reservoirs (0 = 1/8 RAM). */
 atomic_long_t pisa_nr_pages __cacheline_aligned_in_smp;
 unsigned long pisa_max_pages __read_mostly;
@@ -80,6 +86,51 @@ struct pisa_node pisa_nodes[MAX_NUMNODES] = {
 
 static void pisa_schedule_reclaim(void);
 
+/* Return true if a new PISA page should be decrypted. */
+bool pisa_want_decrypt(void)
+{
+	if (!pisa_decrypt)
+		return false;
+
+	/* Explicit page decryption is for CoCo guests, not bare-metal SME hosts. */
+	return !WARN_ON_ONCE(cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT));
+}
+
+/* Decrypt and zero a new PISA page. Must be called from sleepable context. */
+int pisa_page_prepare(struct page *page, struct pisa_meta *meta)
+{
+	void *vaddr = page_address(page);
+	int ret;
+
+	ret = set_memory_decrypted((unsigned long)vaddr, 1 << PISA_ORDER);
+	if (ret) {
+		/* Leak partially shared page rather than returning it to the buddy allocator. */
+		pr_warn_ratelimited("pisa: leaking PISA page that could not be decrypted\n");
+		return ret;
+	}
+	/* Initialize cleartext cachelines after flipping encryption state. */
+	memset(vaddr, 0, PISA_SIZE);
+	meta->flags |= PISA_DECRYPTED;
+	return 0;
+}
+
+/* Undo pisa_page_prepare(). */
+int pisa_page_unprepare(struct pisa_meta *meta)
+{
+	struct page *page;
+
+	if (!(meta->flags & PISA_DECRYPTED))
+		return 0;
+	page = pfn_to_page(pisa_meta_to_pfn(meta));
+	if (set_memory_encrypted((unsigned long)page_address(page), 1 << PISA_ORDER)) {
+		pr_warn_ratelimited("pisa: leaking PISA page that could not be re-encrypted\n");
+		return -EIO;
+	}
+	WRITE_ONCE(meta->flags, meta->flags & ~PISA_DECRYPTED);
+	return 0;
+}
+
+
 /*
  * Idle PISA page release proceeds in three stages:
  * 1. Detach onto lockless pisa_free_list and schedule pisa_reclaim_work.
@@ -103,12 +154,13 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 	spin_unlock_irqrestore(&meta->pa->lock, flags);
 	WRITE_ONCE(meta->pa, NULL);
 
-	/* Possibly still mapped by a device: leak it, still charged. */
-	if (meta->flags & PISA_QUARANTINED)
-		return;
-
 	/* The page has been unmapped from every domain by pisa_release_page() */
-	pisa_slot_free(slot);
+	if (!(meta->flags & PISA_QUARANTINED))
+		pisa_slot_free(slot);
+
+	/* Still shared with the host, or possibly still mapped by a device. */
+	if (meta->flags & (PISA_DECRYPTED | PISA_QUARANTINED))
+		return;
 	atomic_long_dec(&pisa_nr_pages);
 	for (i = 0; i < PISA_BLOCKS(order); i++) {
 		block = page + (i << order);
@@ -120,7 +172,12 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 /* Unmap a retired PISA page, clear PISA_ACTIVE, and queue RCU release. */
 void pisa_release_page(struct pisa_meta *meta)
 {
+	u8 flags;
+
 	if (!meta->pa) {
+		/* Unbound (reservoir) page: leaked if re-encryption fails. */
+		if (pisa_page_unprepare(meta))
+			return;
 		__free_pages(pfn_to_page(pisa_meta_to_pfn(meta)), PISA_ORDER);
 		atomic_long_dec(&pisa_nr_pages);
 		return;
@@ -128,9 +185,15 @@ void pisa_release_page(struct pisa_meta *meta)
 
 	/* Quarantined on unmap failure and leaked in pisa_release_page_rcu(). */
 	pisa_unmap_all(meta);
+	flags = meta->flags & ~PISA_ACTIVE;
 
 	/* Clear PISA_ACTIVE before the RCU grace period so new readers stop entering. */
-	WRITE_ONCE(meta->flags, meta->flags & ~PISA_ACTIVE);
+	WRITE_ONCE(meta->flags, flags);
+	if ((flags & (PISA_DECRYPTED | PISA_QUARANTINED)) == PISA_DECRYPTED) {
+		synchronize_rcu();
+		pisa_page_unprepare(meta);
+	}
+
 	call_rcu(&meta->rcu, pisa_release_page_rcu);
 }
 
@@ -741,15 +804,16 @@ static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, in
 	unsigned int bpp = PISA_BLOCKS(order);
 	struct pisa_meta *meta;
 	struct page *page;
+	int ret;
 
 	/* __GFP_DMA/__GFP_DMA32 were already declined by pisa_alloc_bulk(). */
-	meta = pisa_reservoir_pop(nid, gfp & ~__GFP_ZERO, &clean);
+	meta = pisa_reservoir_pop(nid, gfp & ~__GFP_ZERO, pisa_want_decrypt(), &clean);
 	if (IS_ERR(meta))
 		return meta;
 
 	if (unlikely(pisa_slot_alloc(meta))) {
-		pisa_release_page(meta);
-		return ERR_PTR(-ENOSPC);
+		ret = -ENOSPC;
+		goto err_free;
 	}
 
 	page = pfn_to_page(pisa_meta_to_pfn(meta));
@@ -757,9 +821,9 @@ static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, in
 	/* Fails with -EBUSY if a concurrent PFN walker holds a speculative ref. */
 	if (split_page_compound(page, PISA_ORDER, order)) {
 		pisa_slot_free(meta->slot);
-		pisa_release_page(meta);
 		pisa_alloc_backoff(nid, can_block);
-		return ERR_PTR(-EBUSY);
+		ret = -EBUSY;
+		goto err_free;
 	}
 
 	INIT_LIST_HEAD(&meta->list);
@@ -773,6 +837,16 @@ static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, in
 	}
 
 	return meta;
+
+err_free:
+	if (!can_block && (meta->flags & PISA_DECRYPTED)) {
+		/* set_memory_encrypted() may sleep; defer to reclaim worker. */
+		llist_add(&meta->llnode, &pisa_free_list);
+		pisa_schedule_reclaim();
+	} else {
+		pisa_release_page(meta);
+	}
+	return ERR_PTR(ret);
 }
 
 /* Reset fields normally cleared by prep_new_page()/post_alloc_hook(). */
@@ -1135,7 +1209,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		if (!win || pisa_window_declined(win) || !(domain->pgsize_bitmap & PISA_SIZE))
 			return NULL;
 	} else if (is_swiotlb_for_alloc(dev) ||
-		   force_dma_unencrypted(dev) ||
+		   (force_dma_unencrypted(dev) && !pisa_want_decrypt()) ||
 		   !dma_coherent_ok(dev, PFN_PHYS(max_pfn) - 1, 1)) {
 		return NULL;
 	}
@@ -1294,10 +1368,15 @@ VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct
 		read_unlock(&pisa_allocs_lock);
 	}
 
-	/* Retiring must not run under @pa->lock. */
+	/* Unmap outside locks; defer decrypted pages to workqueue outside fs_reclaim. */
 	list_for_each_entry_safe(meta, tmp, &release_list, list) {
 		list_del_init(&meta->list);
-		pisa_release_page(meta);
+		if (meta->flags & PISA_DECRYPTED) {
+			llist_add(&meta->llnode, &pisa_free_list);
+			pisa_schedule_reclaim();
+		} else {
+			pisa_release_page(meta);
+		}
 	}
 
 	/* Charge do_shrink_slab() for the full PISA pages reclaimed. */
@@ -1342,6 +1421,16 @@ static int __init pisa_init(void)
 
 	pisa_slots_init();
 
+	/*
+	 * CoCo guests require decrypted pages and cannot decrypt in atomic
+	 * context, so ensure the per-node reservoir is enabled to serve them.
+	 */
+	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) {
+		pisa_decrypt = true;
+		if (!pisa_reservoir_max)
+			pisa_reservoir_max = 16;
+	}
+
 	/* Preallocate the supported per-node allocators. */
 	for_each_node_state(nid, N_MEMORY) {
 		for (i = 0; i < ARRAY_SIZE(cfg); i++) {
drivers/iommu/pisa-kunit.c +11 -0
index 5f6b2ebcab1d9..b63cd6585b673 100644
@@ -63,6 +63,7 @@ static void test_meta_active_toggle(struct kunit *test)
 	unsigned long pfn, base_pfn;
 	struct pisa_meta *meta;
 	struct page *page;
+	phys_addr_t pa;
 
 	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
 
@@ -80,16 +81,26 @@ static void test_meta_active_toggle(struct kunit *test)
 	}
 	KUNIT_EXPECT_EQ(test, pisa_meta_ensure_pfn(pfn, false), 0);
 	meta = pisa_meta_of_pfn(pfn);
+	pa = page_to_phys(page);
 
 	KUNIT_EXPECT_FALSE(test, is_pisa_pfn(pfn));
+	KUNIT_EXPECT_FALSE(test, is_pisa_direct(pa, PAGE_SIZE));
 
 	pisa_meta_set_active(meta, true);
 	KUNIT_EXPECT_TRUE(test, is_pisa_pfn(base_pfn));
 	KUNIT_EXPECT_TRUE(test, is_pisa_pfn(pfn));
 	KUNIT_EXPECT_TRUE(test, is_pisa_pfn(base_pfn + (1UL << PISA_ORDER) - 1));
+	KUNIT_EXPECT_FALSE(test, is_pisa_direct(pa, PAGE_SIZE));
+	KUNIT_EXPECT_EQ(test, pisa_pte_phys(meta, pa), pa);
+
+	WRITE_ONCE(meta->flags, PISA_ACTIVE | PISA_DECRYPTED);
+	KUNIT_EXPECT_TRUE(test, is_pisa_direct(pa, PAGE_SIZE));
+	KUNIT_EXPECT_FALSE(test, is_pisa_direct(pa, PISA_SIZE + PAGE_SIZE));
+	KUNIT_EXPECT_EQ(test, pisa_pte_phys(meta, pa), dma_addr_unencrypted(pa));
 
 	pisa_meta_set_active(meta, false);
 	KUNIT_EXPECT_FALSE(test, is_pisa_pfn(pfn));
+	KUNIT_EXPECT_FALSE(test, is_pisa_direct(pa, PAGE_SIZE));
 
 	__free_pages(page, PISA_ORDER);
 }
drivers/iommu/pisa-map.c +1 -1
index 2c481e514575c..fc58c639f3288 100644
@@ -470,7 +470,7 @@ int __pisa_map_phys(dma_addr_t *iova, struct device *dev,
 		phys_addr_t pisa_phys = phys & PISA_MASK;
 
 		ret = iommu_map(domain, pisa_phys_to_iova(win, meta, pisa_phys),
-				pisa_phys, PISA_SIZE, block_prot, GFP_ATOMIC);
+				pisa_pte_phys(meta, pisa_phys), PISA_SIZE, block_prot, GFP_ATOMIC);
 		if (likely(!ret)) {
 			/* Ensure leaf PTE is visible before setting the domain bit. */
 			smp_mb__before_atomic();
drivers/iommu/pisa-meta.c +13 -0
index 00939c366ba6d..3acdec815935f 100644
@@ -78,6 +78,19 @@ struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn)
 	return &pisa_meta_array[frame];
 }
 
+bool __is_pisa_direct(phys_addr_t phys, size_t size)
+{
+	u8 flags = READ_ONCE(pisa_meta_of_pfn(PHYS_PFN(phys))->flags);
+
+	/*
+	 * Only decrypted active pages can bypass swiotlb bouncing, and the
+	 * transfer must not straddle the end of the PISA frame.
+	 */
+	return (flags & (PISA_ACTIVE | PISA_DECRYPTED)) ==
+	       (PISA_ACTIVE | PISA_DECRYPTED) &&
+	       (phys & (PISA_SIZE - 1)) + size <= PISA_SIZE;
+}
+
 /* Base PFN of @meta's PISA frame, or ULONG_MAX if out-of-range/sink. */
 unsigned long pisa_meta_to_pfn(const struct pisa_meta *meta)
 {
drivers/iommu/pisa-node.c +51 -35

175 lines not on this page · raw message

drivers/iommu/pisa-priv.h +14 -2
index 8f87bdf7d4ee2..f08388f003fad 100644
@@ -7,6 +7,7 @@
 #include <linux/jiffies.h>
 #include <linux/list.h>
 #include <linux/llist.h>
+#include <linux/mem_encrypt.h>
 #include <linux/nodemask.h>
 #include <linux/spinlock.h>
 #include <linux/topology.h>
@@ -62,7 +63,7 @@ enum {
 
 /**
  * struct pisa_meta - Metadata for a single PISA page in @pisa_meta_array
- * @flags:	PISA_ACTIVE / PISA_QUARANTINED
+ * @flags:	PISA_ACTIVE / PISA_QUARANTINED / PISA_DECRYPTED
  * @prot:	Owning allocator's IOMMU_READ/WRITE protection bits
  * @nr_clean:	Zeroed available blocks in @clean_bitmap
  * @nr_dirty:	Dirty available blocks in @dirty_bitmap
@@ -101,6 +102,14 @@ struct pisa_meta {
 static_assert(offsetof(struct pisa_meta, flags) == 0);
 static_assert(sizeof(struct pisa_meta) == PISA_META_SIZE);
 
+/* Physical address for IOMMU PTE of @meta at @phys (shared alias if decrypted). */
+static inline phys_addr_t pisa_pte_phys(const struct pisa_meta *meta, phys_addr_t phys)
+{
+	if (meta->flags & PISA_DECRYPTED)
+		return dma_addr_unencrypted(phys);
+	return phys;
+}
+
 static inline unsigned int pisa_meta_avail(const struct pisa_meta *meta)
 {
 	return meta->nr_clean + meta->nr_dirty;
@@ -227,6 +236,9 @@ static inline void pisa_alloc_backoff(int nid, bool can_block)
 	if (!can_block)
 		WRITE_ONCE(pisa_nodes[nid].next_alloc, jiffies + DIV_ROUND_UP(HZ, 100));
 }
+bool pisa_want_decrypt(void);
+int pisa_page_prepare(struct page *page, struct pisa_meta *meta);
+int pisa_page_unprepare(struct pisa_meta *meta);
 
 /* pisa-alloc.c, also used by the per-node code in pisa-node.c */
 struct pisa_alloc *pisa_create(int nid, unsigned int order, enum dma_data_direction dir);
@@ -256,7 +268,7 @@ unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
 extern unsigned int pisa_reservoir_max;
 void pisa_node_init(void);
 void pisa_schedule_reservoir(void);
-struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean);
+struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool decrypt, bool *clean);
 unsigned long pisa_reservoir_count(void);
 unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan);
 
include/linux/pisa.h +16 -0
index 822e1556d78ef..89eb0722d90bc 100644
@@ -33,6 +33,7 @@ struct iommu_domain;
 enum {
 	PISA_ACTIVE		= BIT(0), /* page is owned by a pisa_alloc */
 	PISA_QUARANTINED	= BIT(1), /* IOMMU unmap failed: never reuse */
+	PISA_DECRYPTED		= BIT(2), /* page was set_memory_decrypted() */
 };
 
 /* Enabled on first pisa_meta_init() to activate fast-path hooks. */
@@ -45,6 +46,8 @@ extern unsigned long *pisa_chunk_bitmap;
 
 int pisa_meta_init(void);
 
+bool __is_pisa_direct(phys_addr_t phys, size_t size);
+
 /* fast membership check for pisa pfn/pages */
 static inline bool is_pisa_pfn(unsigned long pfn)
 {
@@ -61,6 +64,14 @@ static inline bool is_pisa_pfn(unsigned long pfn)
 	return READ_ONCE(*flags) & PISA_ACTIVE;
 }
 
+static inline bool is_pisa_direct(phys_addr_t phys, size_t size)
+{
+	if (!static_branch_unlikely(&pisa_key))
+		return false;
+
+	return __is_pisa_direct(phys, size);
+}
+
 static inline bool is_pisa_page(const struct page *page);
 
 bool __pisa_free_page(struct page *page);
@@ -133,6 +144,11 @@ static inline bool is_pisa_pfn(unsigned long pfn)
 	return false;
 }
 
+static inline bool is_pisa_direct(phys_addr_t phys, size_t size)
+{
+	return false;
+}
+
 static inline bool pisa_free_page(struct page *page)
 {
 	return false;
kernel/dma/direct.c +3 -2
index 11052b65e573b..a7fa1efc0ba09 100644
@@ -707,8 +707,9 @@ dma_addr_t dma_direct_map_phys(struct device *dev, phys_addr_t phys,
 	if (is_swiotlb_force_bounce(dev)) {
 		if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT))
 			return DMA_MAPPING_ERROR;
-
-		return swiotlb_map(dev, phys, size, dir, attrs);
+		if (!is_pisa_direct(phys, size))
+			return swiotlb_map(dev, phys, size, dir, attrs);
+		attrs |= DMA_ATTR_CC_SHARED;
 	}
 
 	if (attrs & DMA_ATTR_CC_SHARED)
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#139 lore raw

Re: [RFC PATCH v2 14/25] iommu/dma: Support decrypted PISA pages

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [High] dma-direct: broken CoCo PISA SWIOTLB bypass in dma_direct_map_phys() - [Medium] iommu/dma: broken…

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [High] dma-direct: broken CoCo PISA SWIOTLB bypass in dma_direct_map_phys()
- [Medium] iommu/dma: broken CoCo coherent allocation in pisa_alloc_coherent()
- [Medium] iommu/dma: race on meta->flags in pisa_release_page() loses quarantine
- [Medium] iommu/dma: stale meta->on_list when pisa_shrink_scan() defers pages
- [Medium] iommu/dma: unprotected set_memory_encrypted() in pisa_alloc_split_page()
- [Low] iommu/dma: undocumented pisa.decrypt boot parameter in kernel-parameters.txt
--

commit a76278fa4c67f9594be2d54e0f11085d9e07d5d3
Author: Luigi Rizzo <[email protected]>

iommu/dma: Support decrypted PISA pages

This commit adds support for decrypting 2MB PISA pages upfront via a pisa.decrypt parameter and PISA_DECRYPTED flag so Confidential Computing guests can map them without per-packet hypercalls or swiotlb bouncing.

Quoted 4 lines
drivers/iommu/pisa-alloc.c +0 -0
index 7b9d0a7acc101..b4a25c65bf97e 100644

[ ... ]

drivers/iommu/pisa-alloc.c static LLIST_HEAD(pisa_free_list); · line 56

Quoted 7 lines
drivers/iommu/pisa-alloc.c +3 -0
@@ -49,6 +51,10 @@ static LLIST_HEAD(pisa_free_list);
 /* Dedicated WQ_MEM_RECLAIM workqueue, can run without allocations. */
 static struct workqueue_struct *pisa_wq __ro_after_init;
 
+/* Mark active PISA pages decrypted for DMA (auto-enabled on CoCo guests). */
+static bool pisa_decrypt __read_mostly;
+module_param_named(decrypt, pisa_decrypt, bool, 0444);

[Severity: Low]
Since CONFIG_PISA is a bool Kconfig symbol, pisa.decrypt is a built-in kernel command-line parameter and should be documented in Documentation/admin-guide/kernel-parameters.txt.

[ ... ]

Quoted 6 lines
drivers/iommu/pisa-alloc.c +1 -0
@@ -128,9 +185,15 @@ void pisa_release_page(struct pisa_meta *meta)
 
 	/* Quarantined on unmap failure and leaked in pisa_release_page_rcu(). */
 	pisa_unmap_all(meta);
+	flags = meta->flags & ~PISA_ACTIVE;
 

drivers/iommu/pisa-alloc.c void pisa_release_page(struct pisa_meta *meta) · line 198

Quoted 10 lines
drivers/iommu/pisa-alloc.c +5 -1
 	/* Clear PISA_ACTIVE before the RCU grace period so new readers stop entering. */
-	WRITE_ONCE(meta->flags, meta->flags & ~PISA_ACTIVE);
+	WRITE_ONCE(meta->flags, flags);
+	if ((flags & (PISA_DECRYPTED | PISA_QUARANTINED)) == PISA_DECRYPTED) {
+		synchronize_rcu();
+		pisa_page_unprepare(meta);
+	}
 
 	call_rcu(&meta->rcu, pisa_release_page_rcu);
 }

[Severity: Medium]
Can a concurrent pisa_domain_quiesce() race with pisa_release_page() on meta->flags and lose PISA_QUARANTINED?

In pisa_unmap_domain_locked(), the domain bit in meta->domains_mapped is cleared via test_and_clear_bit() before iommu_unmap_fast() runs:

CPU0 CPU1
pisa_domain_quiesce() pisa_release_page()
rcu_read_lock()
pisa_unmap_domain_locked()

    test_and_clear_bit(idx, ...)
                                        pisa_unmap_all() (sees bit 0)
                                        flags = meta->flags & ~PISA_ACTIVE
    iommu_unmap_fast() (fails)
    pisa_quarantine_meta()
      WRITE_ONCE(meta->flags,
                 ... | PISA_QUARANTINED)
                                        WRITE_ONCE(meta->flags, flags)
                                          <-- clobbers PISA_QUARANTINED

rcu_read_unlock()
synchronize_rcu() pisa_page_unprepare(meta) call_rcu(..., pisa_release_page_rcu)
<-- frees slot and pages while
IOMMU mapping is still live

Even if pisa_quarantine_meta() sets PISA_QUARANTINED after CPU1's WRITE_ONCE(meta->flags, flags), CPU1 only checks the local pre-grace-period flags variable and still calls pisa_page_unprepare(meta) after synchronize_rcu(), re-encrypting a quarantined page that remains mapped in the IOMMU.

[ ... ]

Quoted 5 lines
drivers/iommu/pisa-alloc.c +1 -0
@@ -773,6 +837,16 @@ static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, in
 	}
 
 	return meta;
+

drivers/iommu/pisa-alloc.c static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, in · line 850

Quoted 10 lines
drivers/iommu/pisa-alloc.c +9 -0
+err_free:
+	if (!can_block && (meta->flags & PISA_DECRYPTED)) {
+		/* set_memory_encrypted() may sleep; defer to reclaim worker. */
+		llist_add(&meta->llnode, &pisa_free_list);
+		pisa_schedule_reclaim();
+	} else {
+		pisa_release_page(meta);
+	}
+	return ERR_PTR(ret);
 }

[Severity: Medium]
When pisa_alloc_split_page() is called with GFP_NOFS or GFP_NOIO, can_block is true, so can this err_free path call pisa_release_page() -> pisa_page_unprepare() -> set_memory_encrypted() without memalloc_nofs/noio protection?

Unlike __pisa_page_alloc(), which wraps pisa_page_prepare() in pisa_memalloc_save(gfp), this unwind path runs outside any memalloc scope. Because set_memory_encrypted() can perform internal GFP_KERNEL page-table or hypercall buffer allocations, hitting -ENOSPC or -EBUSY here under GFP_NOFS or GFP_NOIO can recurse into filesystem or block I/O reclaim and deadlock. Deferring PISA_DECRYPTED pages to pisa_free_list whenever
(gfp & (__GFP_FS | __GFP_IO)) != (__GFP_FS | __GFP_IO) (or unconditionally) would avoid this.

[ ... ]

drivers/iommu/pisa-alloc.c void *pisa_alloc_coherent(struct page **pagep, struct device *dev, · line 1215

Quoted 9 lines
drivers/iommu/pisa-alloc.c +1 -1
@@ -1135,7 +1209,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		if (!win || pisa_window_declined(win) || !(domain->pgsize_bitmap & PISA_SIZE))
 			return NULL;
 	} else if (is_swiotlb_for_alloc(dev) ||
-		   force_dma_unencrypted(dev) ||
+		   (force_dma_unencrypted(dev) && !pisa_want_decrypt()) ||
 		   !dma_coherent_ok(dev, PFN_PHYS(max_pfn) - 1, 1)) {
 		return NULL;
 	}

[Severity: Medium]
Is this new force_dma_unencrypted(dev) && !pisa_want_decrypt() path reachable when allocating coherent DMA memory on a CoCo guest?

Both dma_alloc_attrs() and dma_direct_alloc() set __DMA_ATTR_ALLOC_CC_SHARED in attrs when force_dma_unencrypted(dev) is true, but pisa_alloc_coherent() rejects any attrs other than DMA_ATTR_NO_WARN just above:

drivers/iommu/pisa-alloc.c:pisa_alloc_coherent() {
    ...
	if ((current_gfp_context(gfp) & ~(__GFP_ZERO | __GFP_NOWARN)) != GFP_KERNEL ||
	    (attrs & ~DMA_ATTR_NO_WARN))
		return NULL;
}

As a result, pisa_alloc_coherent() always returns NULL on CoCo guests before reaching this check.

In addition, when pisa_alloc_coherent() succeeds in dma_direct_alloc() for a decrypted PISA page, dma_direct_alloc() computes *dma_handle via phys_to_dma_direct(dev, page_to_phys(page), false) with unencrypted hardcoded to false, returning an encrypted DMA address for a page that was decrypted via set_memory_decrypted(). And when pisa_alloc_coherent() scans existing pages on pa->partial, pa->partial_dirty, and pa->idle, it does not check that meta->flags has PISA_DECRYPTED set when force_dma_unencrypted(dev) is true.

[ ... ]

Quoted 6 lines
drivers/iommu/pisa-alloc.c +1 -1
@@ -1294,10 +1368,15 @@ VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct
 		read_unlock(&pisa_allocs_lock);
 	}
 
-	/* Retiring must not run under @pa->lock. */
+	/* Unmap outside locks; defer decrypted pages to workqueue outside fs_reclaim. */

drivers/iommu/pisa-alloc.c VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct · line 1380

Quoted 10 lines
drivers/iommu/pisa-alloc.c +6 -1
 	list_for_each_entry_safe(meta, tmp, &release_list, list) {
 		list_del_init(&meta->list);
-		pisa_release_page(meta);
+		if (meta->flags & PISA_DECRYPTED) {
+			llist_add(&meta->llnode, &pisa_free_list);
+			pisa_schedule_reclaim();
+		} else {
+			pisa_release_page(meta);
+		}
 	}

[Severity: Medium]
When pisa_shrink_scan() defers a PISA_DECRYPTED allocator page to pisa_free_list, can a concurrent pisa_domain_quiesce() see a stale meta->on_list and corrupt pisa_free_list?

Unlike pisa_place_meta() and pisa_reclaim_work_fn(), pisa_shrink_list() detaches idle pages from pa->idle without setting meta->on_list to PISA_LIST_NONE. While the deferred page sits on pisa_free_list waiting for pisa_reclaim_work_fn(), meta->pa is still non-NULL and meta->on_list is still PISA_LIST_IDLE_CLEAN or PISA_LIST_IDLE_DIRTY:

CPU0 CPU1
pisa_shrink_scan() pisa_domain_quiesce()
pisa_shrink_list()

    list_move(..., &release_list)
    pa->num_idle_pages--
    (meta->on_list left as IDLE)
  list_del_init(&meta->list)
  llist_add(&meta->llnode,
            &pisa_free_list)
                                        pisa_unmap_domain_locked()
                                          (unmap fails -> quarantined)
                                        spin_lock(&pa->lock)
                                        if (meta->on_list == IDLE_...)
                                          pa->num_idle_pages--
                                        pisa_place_meta(meta)
                                          llist_add(&meta->llnode,
                                                    &pisa_free_list)
                                            <-- duplicate llist_add

Resetting WRITE_ONCE(meta->on_list, PISA_LIST_NONE) inside pisa_shrink_list() under lock would prevent both the pa->num_idle_pages underflow and the double insertion onto pisa_free_list.

Quoted 5 lines
kernel/dma/direct.c +0 -0
index 11052b65e573b..a7fa1efc0ba09 100644

kernel/dma/direct.c dma_addr_t dma_direct_map_phys(struct device *dev, phys_addr_t phys, · line 713

Quoted 9 lines
kernel/dma/direct.c +3 -2
@@ -707,8 +707,9 @@ dma_addr_t dma_direct_map_phys(struct device *dev, phys_addr_t phys,
 	if (is_swiotlb_force_bounce(dev)) {
 		if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT))
 			return DMA_MAPPING_ERROR;
-
-		return swiotlb_map(dev, phys, size, dir, attrs);
+		if (!is_pisa_direct(phys, size))
+			return swiotlb_map(dev, phys, size, dir, attrs);
+		attrs |= DMA_ATTR_CC_SHARED;
 	}

[Severity: High]
Does gating is_pisa_direct(phys, size) on is_swiotlb_force_bounce(dev) prevent decrypted PISA pages from bypassing swiotlb on CoCo guests?

Since commit 30c5e45ee2c5 ("dma-direct: make dma_direct_map_phys() honor DMA_ATTR_CC_SHARED"), CoCo guests do not set SWIOTLB_FORCE, so is_swiotlb_force_bounce(dev) is false during normal CoCo operation. Instead, CoCo guests enforce bouncing via force_dma_unencrypted(dev) inside dma_capable():

include/linux/dma-direct.h:dma_capable() {
    ...
	if (!(attrs & DMA_ATTR_CC_SHARED) && force_dma_unencrypted(dev))
		return false;
    ...
}

Because is_pisa_direct(phys, size) is only checked inside
if (is_swiotlb_force_bounce(dev)), CoCo guests skip it, leave DMA_ATTR_CC_SHARED unset, fail dma_capable(), and bounce every decrypted PISA page through swiotlb_map().

Conversely, is_swiotlb_force_bounce(dev) is true when swiotlb=force is passed on the command line or when a device is bound to a restricted-dma-pool via rmem_swiotlb_device_init(); bypassing swiotlb_map() there hands the device a general RAM address outside its restricted pool. Checking force_dma_unencrypted(dev) && is_pisa_direct(phys, size) outside the is_swiotlb_force_bounce(dev) block to set DMA_ATTR_CC_SHARED would fix both cases.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#140 lore raw

RFC PATCH v2 15/25 iommu/dma: Add background page scrubber for PISA allocators

In reply to Luigi Rizzo

Blocks returned to a pisa_alloc are marked dirty and need to be zeroed before they can serve __GFP_ZERO requests. Zeroing blocks inline at allocation time adds CPU cost and latency.

Add an optional background scrubber (enabled via pisa.scrub_max) that runs on the allocator's home NUMA node work item, zeroes dirty blocks outside pa->lock in batches, and moves them to meta->clean_bitmap[]. Scrubbing is demand-driven by the number of dirty blocks that __GFP_ZERO allocations had to zero inline.

---
 drivers/iommu/pisa-alloc.c | 188 ++++++++++++++++++++++++++++++++++++-
 drivers/iommu/pisa-kunit.c |  49 +++++++++-
 drivers/iommu/pisa-node.c  |  31 ++++++
 drivers/iommu/pisa-priv.h  |  11 ++-
 4 files changed, 272 insertions(+), 7 deletions(-)
drivers/iommu/pisa-alloc.c +185 -3
index b4a25c65bf97e..4b61ec84ed6d1 100644
@@ -29,6 +29,7 @@
 #include <linux/percpu.h>
 #include <linux/pgalloc_tag.h>
 #include <linux/rcupdate.h>
+#include <linux/sched/clock.h>
 #include <linux/sched/mm.h>
 #include <linux/set_memory.h>
 #include <linux/shrinker.h>
@@ -72,6 +73,10 @@ module_param_named(idle_ms, pisa_idle_ms, uint, 0644);
 static unsigned int pisa_compact __read_mostly;
 module_param_named(compact, pisa_compact, uint, 0644);
 
+/* Max pages zeroed in each scrubber run (0 = disabled, capped at PISA_SCRUB_MAX_LIMIT). */
+unsigned int pisa_scrub_max __read_mostly;
+#define PISA_SCRUB_MAX_LIMIT	65536U
+
 /* All live allocators, protected by pisa_allocs_lock. */
 static LIST_HEAD(pisa_allocs);
 static DEFINE_RWLOCK(pisa_allocs_lock);
@@ -86,6 +91,24 @@ struct pisa_node pisa_nodes[MAX_NUMNODES] = {
 
 static void pisa_schedule_reclaim(void);
 
+static int pisa_scrub_set(const char *val, const struct kernel_param *kp)
+{
+	int ret = param_set_uint(val, kp);
+
+	if (ret)
+		return ret;
+	WRITE_ONCE(pisa_scrub_max, min(pisa_scrub_max, PISA_SCRUB_MAX_LIMIT));
+	/* Serve demand accumulated while the scrubber was off (once initialized). */
+	if (pisa_scrub_max && static_branch_unlikely(&pisa_key))
+		pisa_schedule_scrub_all();
+	return 0;
+}
+
+static const struct kernel_param_ops pisa_scrub_ops = {
+	.set = pisa_scrub_set,
+	.get = param_get_uint,
+};
+module_param_cb(scrub_max, &pisa_scrub_ops, &pisa_scrub_max, 0644);
 /* Return true if a new PISA page should be decrypted. */
 bool pisa_want_decrypt(void)
 {
@@ -263,6 +286,7 @@ static void pisa_schedule_reclaim(void)
 	else
 		queue_delayed_work(wq, &pisa_reclaim_work, msecs_to_jiffies(idle_ms));
 }
+
 /*
  * Update @meta's position on @pa's lists under @pa->lock. When all blocks
  * become available (avail == bpp), either queues @meta to @pisa_free_list (and
@@ -353,6 +377,148 @@ static bool pisa_block_poisoned(struct pisa_alloc *pa, struct page *block)
 	return false;
 }
 
+/*
+ * Background page scrubber: pre-zeroes dirty blocks in @pa->nid's work item
+ * to match inline-zeroed demand (@pa->scrub_demand) when scrub_max > 0.
+ */
+static struct pisa_meta *pisa_pick_dirty_meta(struct pisa_alloc *pa)
+{
+	struct pisa_meta *meta;
+
+	meta = list_first_entry_or_null(&pa->partial_dirty, struct pisa_meta, list);
+	if (meta)
+		return meta;
+
+	list_for_each_entry(meta, &pa->partial, list) {
+		if (meta->nr_dirty)
+			return meta;
+	}
+
+	if (!list_empty(&pa->idle)) {
+		meta = list_last_entry(&pa->idle, struct pisa_meta, list);
+		if (meta->nr_dirty) {
+			pa->num_idle_pages--;
+			return meta;
+		}
+	}
+
+	return NULL;
+}
+
+/* Dirty blocks per allocator, inline-zeroed since the last run, that queue a run. */
+#define PISA_SCRUB_TRIGGER	32U
+/* Cap on @pa->scrub_demand, so a long-off scrubber does not owe too much. */
+#define PISA_SCRUB_DEMAND_MAX	4096U
+/* Bytes zeroed per batch: a few microseconds of memset(). */
+/* XXX assumes PAGE_SIZE <= SZ_128K (32 * 4KB pages). */
+#define PISA_SCRUB_BYTES	SZ_128K
+#define PISA_SCRUB_BATCH	(PISA_SCRUB_BYTES >> PAGE_SHIFT)
+/* Time after which a run stops and requeues. */
+#define PISA_SCRUB_RUN_NS	(50 * NSEC_PER_USEC)
+
+/*
+ * Scrub one batch of dirty blocks in @pa outside @pa->lock.
+ * Returns the number of PAGE_SIZE pages taken off the dirty bitmap.
+ */
+static unsigned long pisa_scrub_alloc(struct pisa_alloc *pa)
+{
+	unsigned int bpp, order, idx, count = 0, used = 0, want;
+	u16 idxs[PISA_SCRUB_BATCH];
+	unsigned long base_pfn, flags;
+	bool should_release;
+	struct pisa_meta *meta;
+
+	spin_lock_irqsave(&pa->lock, flags);
+	if (!pa->scrub_demand) {
+		spin_unlock_irqrestore(&pa->lock, flags);
+		return 0;
+	}
+
+	meta = pisa_pick_dirty_meta(pa);
+	if (!meta) {
+		pa->scrub_demand = 0;
+		spin_unlock_irqrestore(&pa->lock, flags);
+		return 0;
+	}
+
+	order = pa->order;
+	bpp = PISA_BLOCKS(order);
+	base_pfn = pisa_meta_to_pfn(meta);
+	want = min(max(PISA_SCRUB_BATCH >> order, 1U), pa->scrub_demand);
+
+	for_each_set_bit(idx, meta->dirty_bitmap, bpp) {
+		struct page *block = pfn_to_page(base_pfn + (idx << order));
+
+		__clear_bit(idx, meta->dirty_bitmap);
+		used++;
+		if (!pisa_block_poisoned(pa, block))
+			idxs[count++] = idx;
+		if (used == meta->nr_dirty || count == want)
+			break;
+	}
+	meta->nr_dirty -= used;
+	pa->blocks_in_use += used - count;
+	pisa_place_meta(meta);
+	spin_unlock_irqrestore(&pa->lock, flags);
+
+	if (unlikely(!count))
+		return (unsigned long)used << order;
+
+	for (idx = 0; idx < count; idx++) {
+		struct page *block = pfn_to_page(base_pfn + (idxs[idx] << order));
+
+		memset(page_address(block), 0, PAGE_SIZE << order);
+	}
+
+	spin_lock_irqsave(&pa->lock, flags);
+	for (idx = 0; idx < count; idx++)
+		__set_bit(idxs[idx], meta->clean_bitmap);
+	meta->nr_clean += count;
+	pa->scrub_demand -= min(count, pa->scrub_demand);
+	should_release = pisa_place_meta(meta);
+	spin_unlock_irqrestore(&pa->lock, flags);
+
+	if (should_release)
+		pisa_schedule_reclaim();
+
+	return (unsigned long)used << order;
+}
+
+/*
+ * Scrub dirty blocks for allocators homed on @nid up to @pisa_scrub_max pages or
+ * PISA_SCRUB_RUN_NS. Returns true if stopped early with demand remaining.
+ */
+bool pisa_scrub_node(int nid)
+{
+	unsigned long budget = READ_ONCE(pisa_scrub_max), done = 0, n;
+	u64 deadline = local_clock() + PISA_SCRUB_RUN_NS;
+	struct pisa_alloc *pa;
+	bool more = false;
+
+	read_lock(&pisa_allocs_lock);
+	list_for_each_entry(pa, &pisa_allocs, node) {
+		if (pa->nid != nid || !READ_ONCE(pa->scrub_demand))
+			continue;
+		read_unlock(&pisa_allocs_lock);
+
+		while ((n = pisa_scrub_alloc(pa))) {
+			done += n;
+			if (done >= budget || local_clock() >= deadline) {
+				more = true;
+				break;
+			}
+			cond_resched();
+		}
+
+		read_lock(&pisa_allocs_lock);
+		if (more)
+			break;
+	}
+	read_unlock(&pisa_allocs_lock);
+
+	return more;
+}
+
 /**
  * pisa_create - Create a PISA page allocator
  * @nid: Home NUMA node for this allocator
@@ -952,6 +1118,7 @@ static unsigned int take_blocks(struct pisa_meta *meta, unsigned int want,
 		for (i = got; i < got + dirty; i++)
 			set_page_private(out[i], 1);
 		got += dirty;
+		pa->scrub_demand = min(pa->scrub_demand + dirty, PISA_SCRUB_DEMAND_MAX);
 	} else {
 		/* First choice are dirty blocks, followed by clean */
 		got += pisa_scan_bitmap(meta, true, want, out, !frozen);
@@ -973,6 +1140,7 @@ static unsigned int take_blocks(struct pisa_meta *meta, unsigned int want,
 static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigned long nr_pages,
 				       struct page **pages, bool zero, bool frozen)
 {
+	bool should_scrub = false;
 	unsigned long n, flags, i;
 	struct pisa_meta *meta;
 	unsigned int want;
@@ -986,6 +1154,7 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 			continue;
 
 		/* Fallback to a new allocation */
+		should_scrub |= pa->scrub_demand >= PISA_SCRUB_TRIGGER;
 		spin_unlock_irqrestore(&pa->lock, flags);
 		/* With @zero, fresh dirty blocks are zeroed below. */
 		meta = pisa_alloc_split_page(pa->order, gfp, pa->nid);
@@ -998,6 +1167,8 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
 		pa->stats.page_alloc_cnt++;
 	}
+	/* Queue the scrubber when the inline zeroing crosses the trigger. */
+	should_scrub |= pa->scrub_demand >= PISA_SCRUB_TRIGGER;
 	spin_unlock_irqrestore(&pa->lock, flags);
 
 out:
@@ -1012,6 +1183,8 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 		else
 			page_ref_unfreeze(pages[i], 1);
 	}
+	if (should_scrub)
+		pisa_schedule_scrub(pa->nid);
 	return n;
 }
 
@@ -1112,7 +1285,7 @@ static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock
 {
 	DECLARE_BITMAP(busy, PISA_MAX_BLOCKS);
 	struct pisa_alloc *pa = meta->pa;
-	unsigned int bpp = PISA_BLOCKS(0), i;
+	unsigned int bpp = PISA_BLOCKS(0), i, dirty = 0;
 	bool poisoned = false;
 	unsigned long off;
 	struct page *page;
@@ -1166,11 +1339,13 @@ static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock
 		} else {
 			__clear_bit(off + i, meta->dirty_bitmap);
 			meta->nr_dirty--;
+			dirty++;
 		}
 		pisa_block_prep(page + i);
 		page_ref_unfreeze(page + i, 1);
 	}
 	pa->blocks_in_use += nblocks;
+	pa->scrub_demand = min(pa->scrub_demand + dirty, PISA_SCRUB_DEMAND_MAX);
 	pisa_place_meta(meta);
 	return page;
 }
@@ -1185,7 +1360,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 			  struct iommu_domain *domain, size_t size,
 			  gfp_t gfp, unsigned long attrs)
 {
-	bool should_release = false;
+	bool should_scrub = false, should_release = false;
 	struct list_head *lists[3];
 	unsigned long align_mask, flags;
 	unsigned int nblocks, i;
@@ -1234,10 +1409,14 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		}
 	}
 	if (!page) {
+		should_scrub |= pa->scrub_demand >= PISA_SCRUB_TRIGGER;
 		spin_unlock_irqrestore(&pa->lock, flags);
 		meta = pisa_alloc_split_page(0, gfp, pa->nid);
-		if (IS_ERR(meta))
+		if (IS_ERR(meta)) {
+			if (should_scrub)
+				pisa_schedule_scrub(pa->nid);
 			return NULL;
+		}
 		spin_lock_irqsave(&pa->lock, flags);
 		meta->pa = pa;
 		meta->prot = pa->prot;
@@ -1247,10 +1426,13 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		if (unlikely(!page))
 			should_release = pisa_place_meta(meta);
 	}
+	should_scrub |= pa->scrub_demand >= PISA_SCRUB_TRIGGER;
 	spin_unlock_irqrestore(&pa->lock, flags);
 
 	if (should_release)
 		pisa_schedule_reclaim();
+	if (should_scrub)
+		pisa_schedule_scrub(pa->nid);
 	if (!page)
 		return NULL;
 	*pagep = page;
drivers/iommu/pisa-kunit.c +47 -2

55 lines not on this page · raw message

drivers/iommu/pisa-node.c +31 -0
index dfde9c021fe05..cd29c146c281e 100644
@@ -5,6 +5,7 @@
  */
 
 #include <linux/atomic.h>
+#include <linux/bitops.h>
 #include <linux/pisa.h>
 #include <linux/err.h>
 #include <linux/gfp.h>
@@ -32,6 +33,9 @@
  */
 unsigned int pisa_reservoir_max __read_mostly = 16;
 
+/* Scrub the allocators whose home node (@pa->nid) is this one. */
+#define PISA_NODE_SCRUB	0
+
 static int pisa_reservoir_max_set(const char *val, const struct kernel_param *kp)
 {
 	int ret = param_set_uint(val, kp);
@@ -175,6 +179,30 @@ static void pisa_reservoir_trim_node(int nid, unsigned int max)
 	}
 }
 
+/* Schedule node @nid's work item to scrub allocators homed on @nid. */
+void pisa_schedule_scrub(int nid)
+{
+	struct pisa_node *node;
+
+	if (!READ_ONCE(pisa_scrub_max) || nid == NUMA_NO_NODE)
+		return;
+
+	node = &pisa_nodes[nid];
+	set_bit(PISA_NODE_SCRUB, &node->flags);
+	/* Pairs with the clearing of PENDING before the work runs. */
+	smp_mb__after_atomic();
+	if (!work_pending(&node->work))
+		queue_work_node(nid, system_dfl_wq, &node->work);
+}
+
+void pisa_schedule_scrub_all(void)
+{
+	int nid;
+
+	for_each_node_state(nid, N_MEMORY)
+		pisa_schedule_scrub(nid);
+}
+
 /* Per-node worker: trim/refill the reservoir, then scrub allocators homed on @nid. */
 static void pisa_node_work_fn(struct work_struct *work)
 {
@@ -184,6 +212,9 @@ static void pisa_node_work_fn(struct work_struct *work)
 	pisa_reservoir_trim_node(nid, READ_ONCE(pisa_reservoir_max));
 	if (READ_ONCE(pisa_reservoir_max) && static_branch_unlikely(&pisa_key))
 		pisa_reservoir_refill_node(nid);
+
+	if (test_and_clear_bit(PISA_NODE_SCRUB, &node->flags) && pisa_scrub_node(nid))
+		pisa_schedule_scrub(nid);
 }
 
 /* Queue node @nid's work if its reservoir is below or above the target. */
drivers/iommu/pisa-priv.h +9 -2
index f08388f003fad..ef3abb1db9049 100644
@@ -144,8 +144,9 @@ struct pisa_alloc_stats {
  * @num_idle_pages: Length of @idle
  * @max_idle_pages: High watermark of @idle before async release to the buddy allocator
  * @idle_jiffies: Timestamp (jiffies) when @idle last exceeded @max_idle_pages
+ * @scrub_demand: Dirty blocks zeroed inline since the scrubber last ran
  * @blocks_in_use: Blocks handed out and not yet freed
- * @nid:	NUMA node id
+ * @nid:	NUMA node whose worker scrubs this allocator
  * @node:	Node in the global pisa_allocs list
  * @name:	Debug name (defaults to caller of pisa_create())
  * @stats:	Per-allocator statistics
@@ -162,6 +163,7 @@ struct pisa_alloc {
 	struct list_head	full;
 	unsigned int		num_idle_pages;
 	unsigned int		max_idle_pages;
+	unsigned int		scrub_demand;
 	unsigned long		idle_jiffies;
 	unsigned long		blocks_in_use;
 	/* Cold. */
@@ -187,7 +189,8 @@ struct pisa_node {
 	spinlock_t		lock;		/* protects @pages and @nr_pages */
 	struct list_head	pages;		/* reservoir */
 	unsigned int		nr_pages;
-	struct work_struct	work;		/* refill/trim, on this node */
+	unsigned long		flags;		/* PISA_NODE_* requests */
+	struct work_struct	work;		/* refill/trim/scrub, on this node */
 } ____cacheline_aligned_in_smp;
 
 /* Per-NUMA-node PISA state (ring/TX/user allocators, reservoir). */
@@ -263,11 +266,15 @@ static inline struct page *pisa_alloc(struct pisa_alloc *pa, gfp_t gfp)
 unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
 			       unsigned int *nr, struct list_head *release_list,
 			       unsigned long nr_to_scan);
+extern unsigned int pisa_scrub_max;
+bool pisa_scrub_node(int nid);
 
 /* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
 extern unsigned int pisa_reservoir_max;
 void pisa_node_init(void);
 void pisa_schedule_reservoir(void);
+void pisa_schedule_scrub(int nid);
+void pisa_schedule_scrub_all(void);
 struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool decrypt, bool *clean);
 unsigned long pisa_reservoir_count(void);
 unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan);
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#141 lore raw

Re: [RFC PATCH v2 15/25] iommu/dma: Add background page scrubber for PISA allocators

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] iommu/dma: redundant memset() of scrubbed blocks in pisa_alloc_coherent() - [Low] iommu/dma: race…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] iommu/dma: redundant memset() of scrubbed blocks in pisa_alloc_coherent()
- [Low] iommu/dma: race with async refill when trimming reservoir in KUnit test
--

commit aab269faff1eb0d2c96bc73f80823d9c0113582c
Author: Luigi Rizzo <[email protected]>

iommu/dma: Add background page scrubber for PISA allocators

This commit adds an optional demand-driven background page scrubber for PISA allocators that zeroes dirty blocks on each NUMA node's work item and moves them to clean_bitmap.

Quoted 4 lines
drivers/iommu/pisa-alloc.c +0 -0
index b4a25c65bf97e..4b61ec84ed6d1 100644

[ ... ]

Quoted 43 lines
drivers/iommu/pisa-alloc.c +8 -2
@@ -1166,11 +1339,13 @@ static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock
 		} else {
 			__clear_bit(off + i, meta->dirty_bitmap);
 			meta->nr_dirty--;
+			dirty++;
 		}
 		pisa_block_prep(page + i);
 		page_ref_unfreeze(page + i, 1);
 	}
 	pa->blocks_in_use += nblocks;
+	pa->scrub_demand = min(pa->scrub_demand + dirty, PISA_SCRUB_DEMAND_MAX);
 	pisa_place_meta(meta);
 	return page;
 }
@@ -1185,7 +1360,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 			  struct iommu_domain *domain, size_t size,
 			  gfp_t gfp, unsigned long attrs)
 {
-	bool should_release = false;
+	bool should_scrub = false, should_release = false;
 	struct list_head *lists[3];
 	unsigned long align_mask, flags;
 	unsigned int nblocks, i;
@@ -1234,10 +1409,14 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		}
 	}
 	if (!page) {
+		should_scrub |= pa->scrub_demand >= PISA_SCRUB_TRIGGER;
 		spin_unlock_irqrestore(&pa->lock, flags);
 		meta = pisa_alloc_split_page(0, gfp, pa->nid);
-		if (IS_ERR(meta))
+		if (IS_ERR(meta)) {
+			if (should_scrub)
+				pisa_schedule_scrub(pa->nid);
 			return NULL;
+		}
 		spin_lock_irqsave(&pa->lock, flags);
 		meta->pa = pa;
 		meta->prot = pa->prot;
@@ -1247,10 +1426,13 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		if (unlikely(!page))
 			should_release = pisa_place_meta(meta);
 	}

drivers/iommu/pisa-alloc.c void *pisa_alloc_coherent(struct page **pagep, struct device *dev, · line 1438

Quoted 10 lines
drivers/iommu/pisa-alloc.c +3 -0
+	should_scrub |= pa->scrub_demand >= PISA_SCRUB_TRIGGER;
 	spin_unlock_irqrestore(&pa->lock, flags);
 
 	if (should_release)
 		pisa_schedule_reclaim();
+	if (should_scrub)
+		pisa_schedule_scrub(pa->nid);
 	if (!page)
 		return NULL;
 	*pagep = page;

[Severity: Medium]
Does pisa_alloc_coherent() end up zeroing blocks twice when background scrubbing is enabled?

pisa_take_contig() charges dirty blocks to pa->scrub_demand and pisa_alloc_coherent() schedules the background scrubber on the per-node order-0 RW allocator, which zeroes dirty blocks and moves them to meta->clean_bitmap. However, unlike __pisa_alloc_bulk(), pisa_alloc_coherent() unconditionally calls memset(page_address(page), 0, size) at the end of the function even when blocks were taken from meta->clean_bitmap (and pisa_pcp_alloc() on the same allocator also refills with zero = false and zeroes inline), so background-scrubbed blocks are always zeroed again on allocation.

Quoted 43 lines
drivers/iommu/pisa-kunit.c +33 -2
index b63cd6585b673..40bf7801183da 100644
@@ -572,8 +572,53 @@ static void test_gfp_pisa(struct kunit *test)
 
 static void test_reservoir_and_scrubber(struct kunit *test)
 {
-	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
-	KUNIT_EXPECT_EQ(test, READ_ONCE(pisa_reservoir_max), 16U);
+	unsigned int old_res = READ_ONCE(pisa_reservoir_max);
+	unsigned int old_scrub = READ_ONCE(pisa_scrub_max);
+	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
+	struct pisa_meta *meta;
+	struct pisa_alloc *pa;
+	struct page *p;
+	int nid;
+
+	pisa_shrink_scan(NULL, &sc);
+
+	/* Refill reservoir to 1 PISA page per memory node, then consume one. */
+	WRITE_ONCE(pisa_reservoir_max, 1);
+	pisa_schedule_reservoir();
+	for_each_node_state(nid, N_MEMORY)
+		flush_work(&pisa_nodes[nid].work);
+	KUNIT_EXPECT_GE(test, pisa_reservoir_count(), 1UL);
+
+	pa = pisa_node_pa(first_memory_node, 2, true);
+	KUNIT_ASSERT_NOT_NULL(test, pa);
+	p = pisa_alloc(pa, GFP_KERNEL);
+	if (p) {
+		meta = pisa_meta_of_pfn(page_to_pfn(p));
+		/* Reservoir pages come pre-zeroed (all remaining blocks clean). */
+		KUNIT_EXPECT_EQ(test, meta->nr_dirty, 0U);
+		__free_pages(p, 2);
+		if (!want_init_on_free()) {
+			KUNIT_EXPECT_EQ(test, meta->nr_dirty, 1U);
+
+			/* Scrub dirty block back into clean_bitmap. */
+			pa->scrub_demand = 1;
+			WRITE_ONCE(pisa_scrub_max, 512);
+			pisa_scrub_node(pa->nid);
+			KUNIT_EXPECT_EQ(test, meta->nr_dirty, 0U);

drivers/iommu/pisa-kunit.c static void test_gfp_pisa(struct kunit *test) · line 617

Quoted 10 lines
drivers/iommu/pisa-kunit.c +10 -0
+		}
+	}
+	pisa_shrink_scan(NULL, &sc);
+
+	/* Trim reservoirs back to 0. */
+	WRITE_ONCE(pisa_reservoir_max, 0);
+	pisa_schedule_reservoir();
+	for_each_node_state(nid, N_MEMORY)
+		flush_work(&pisa_nodes[nid].work);
+	KUNIT_EXPECT_EQ(test, pisa_reservoir_count(), 0UL);

[Severity: Low]
Can an in-flight refill race with the trim step and cause KUNIT_EXPECT_EQ(test, pisa_reservoir_count(), 0UL) to fail?

Popping a page from the reservoir in pisa_alloc() drops res->nr_pages from 1 to 0 while pisa_reservoir_max is still 1, which queues res->work to refill the node:

CPU0 (kunit) CPU1 (kworker)
pisa_alloc(pa, GFP_KERNEL)
pisa_reservoir_pop_node()

    res->nr_pages-- (0)
    pisa_schedule_reservoir_node()
      queue_work_node(..., &res->work)
                                  pisa_node_work_fn()
                                    pisa_reservoir_trim_node()
                                    pisa_reservoir_refill_node()
                                      /* reads pisa_reservoir_max == 1 */
                                      __pisa_page_alloc()
WRITE_ONCE(pisa_reservoir_max, 0)
pisa_schedule_reservoir()
  pisa_schedule_reservoir_node()
    /* nr_pages (0) == max (0),
     * does not re-queue res->work
     */
                                      spin_lock_irqsave(&res->lock, ...)
                                      list_add(&meta->list, &res->pages)
                                      res->nr_pages++ (1)
                                      spin_unlock_irqrestore(&res->lock, ...)

flush_work(&pisa_nodes[nid].work) KUNIT_EXPECT_EQ(...,
pisa_reservoir_count(), 0UL) <-- fails (count is 1)

Flushing pisa_nodes[nid].work before setting pisa_reservoir_max to 0 (or re-checking pisa_reservoir_max under res->lock in pisa_reservoir_refill_node()) would avoid this race.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
#142 lore raw

RFC PATCH v2 16/25 mm/slub: Add SLAB_CACHE_PISA_RO for PISA-backed slab caches

In reply to Luigi Rizzo

skb heads are provided by a slab allocator that is fed by alloc_pages().

Add SLAB_CACHE_PISA_RO so that a slab cache can back its slabs with zeroed, read-only PISA folios (__GFP_PISA_RO | __GFP_ZERO) via pisa_alloc_folio(), clamping the slab order to
[2, PAGE_ALLOC_COSTLY_ORDER].
Slabs are still released with free_frozen_pages(), so pages from PISA return to their allocator via __free_pages_prepare(). Caches with SLAB_CACHE_PISA_RO skip KFENCE and are never merged.

Existing caches are unaffected.

---
 drivers/iommu/pisa-alloc.c | 27 +++++++++++++++++++++++++++
 drivers/iommu/pisa-kunit.c | 19 +++++++++++++++++++
 include/linux/pisa.h       |  7 +++++++
 include/linux/slab.h       | 10 ++++++++++
 mm/slab.h                  |  3 ++-
 mm/slab_common.c           |  5 ++++-
 mm/slub.c                  | 14 +++++++++++++-
 7 files changed, 82 insertions(+), 3 deletions(-)
drivers/iommu/pisa-alloc.c +27 -0
index 4b61ec84ed6d1..3b5c49d143a7e 100644
@@ -848,6 +848,33 @@ unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred
 	return pisa_alloc_bulk(pa, gfp & ~__GFP_PISA_RW, nr_pages, page_array, frozen);
 }
 
+/**
+ * pisa_alloc_folio - Allocate a frozen folio for SLUB (SLAB_CACHE_PISA_RO)
+ * @gfp: GFP flags (must have __GFP_PISA_RW or __GFP_PISA_RO set)
+ * @order: Folio order
+ * @nid: Target NUMA node (or NUMA_NO_NODE)
+ *
+ * Drops __GFP_THISNODE before calling the per-node allocator and verifies
+ * node placement afterwards.
+ *
+ * Return: Frozen folio of @order, or NULL.
+ */
+struct folio *pisa_alloc_folio(gfp_t gfp, unsigned int order, int nid)
+{
+	struct page *page;
+
+	page = pisa_alloc_pages(gfp & ~__GFP_THISNODE, order, nid, NULL);
+	if (!page)
+		return NULL;
+	if (unlikely((gfp & __GFP_THISNODE) && nid != NUMA_NO_NODE &&
+		     page_to_nid(page) != nid)) {
+		page_ref_unfreeze(page, 1);
+		__free_pages(page, order);
+		return NULL;
+	}
+	return page_folio(page);
+}
+
 /**
  * pisa_has_free_blocks_rx - Check if @dev has free PISA RX blocks of @order on @nid
  * @dev: Device to check
drivers/iommu/pisa-kunit.c +19 -0
index 40bf7801183da..9cc1328893ace 100644
@@ -12,6 +12,7 @@
 #include <linux/mm.h>
 #include <linux/shrinker.h>
 #include <linux/skbuff.h>
+#include <linux/slab.h>
 #include <net/sock.h>
 
 #include "dma-iommu.h"
@@ -621,6 +622,23 @@ static void test_reservoir_and_scrubber(struct kunit *test)
 	WRITE_ONCE(pisa_scrub_max, old_scrub);
 }
 
+static void test_slub_page_alloc(struct kunit *test)
+{
+	struct kmem_cache *s;
+	void *obj;
+
+	s = kmem_cache_create("pisa_kunit_slab", 1024, NULL,
+			      SLAB_NO_MERGE | SLAB_CACHE_PISA_RO);
+	KUNIT_ASSERT_NOT_NULL(test, s);
+
+	obj = kmem_cache_alloc(s, GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, obj);
+	KUNIT_EXPECT_TRUE(test, is_pisa_page(virt_to_page(obj)));
+	kmem_cache_free(s, obj);
+
+	kmem_cache_destroy(s);
+}
+
 static struct kunit_case pisa_meta_test_cases[] = {
 	KUNIT_CASE(test_meta_init_and_roundtrip),
 	KUNIT_CASE(test_meta_invalid_phys),
@@ -635,6 +653,7 @@ static struct kunit_case pisa_meta_test_cases[] = {
 	KUNIT_CASE(test_pcp_cache),
 	KUNIT_CASE(test_gfp_pisa),
 	KUNIT_CASE(test_reservoir_and_scrubber),
+	KUNIT_CASE(test_slub_page_alloc),
 	{}
 };
 
include/linux/pisa.h +7 -0
index 89eb0722d90bc..b9c5197f2d88d 100644
@@ -110,6 +110,7 @@ unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
 				    int nr_pages, struct page **page_array,
 				    bool frozen);
 
+struct folio *pisa_alloc_folio(gfp_t gfp, unsigned int order, int nid);
 bool pisa_has_free_blocks_rx(const struct device *dev, unsigned int order, int nid);
 bool pisa_page_can_recycle(const struct page *page);
 
@@ -181,6 +182,12 @@ pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred_nid,
 	return 0;
 }
 
+static inline struct folio *
+pisa_alloc_folio(gfp_t gfp, unsigned int order, int nid)
+{
+	return NULL;
+}
+
 static inline gfp_t pisa_rx_gfp(const struct device *dev)
 {
 	return 0;
include/linux/slab.h +10 -0
index cda126def67af..df19c5898e9fe 100644
@@ -66,6 +66,9 @@ enum _slab_flag_bits {
 #endif
 #endif
 	_SLAB_NO_SHEAVES,
+#ifdef CONFIG_PISA
+	_SLAB_CACHE_PISA_RO,
+#endif
 	_SLAB_FLAGS_LAST_BIT
 };
 
@@ -260,6 +263,13 @@ enum _slab_flag_bits {
 #define SLAB_OBJ_EXT_IN_OBJ	__SLAB_FLAG_UNUSED
 #endif
 
+/* Back slabs with zeroed read-only PISA folios (__GFP_PISA_RO | __GFP_ZERO) */
+#ifdef CONFIG_PISA
+#define SLAB_CACHE_PISA_RO	__SLAB_FLAG_BIT(_SLAB_CACHE_PISA_RO)
+#else
+#define SLAB_CACHE_PISA_RO	__SLAB_FLAG_UNUSED
+#endif
+
 /*
  * ZERO_SIZE_PTR will be returned for zero sized kmalloc requests.
  *
mm/slab.h +2 -1
index e94ac63d10dc0..53620e40b216b 100644
@@ -473,7 +473,8 @@ void flush_rcu_sheaves_on_cache(struct kmem_cache *s);
 			 SLAB_TYPESAFE_BY_RCU | SLAB_DEBUG_OBJECTS | \
 			 SLAB_NOLEAKTRACE | SLAB_RECLAIM_ACCOUNT | \
 			 SLAB_TEMPORARY | SLAB_ACCOUNT | \
-			 SLAB_NO_USER_FLAGS | SLAB_KMALLOC | SLAB_NO_MERGE)
+			 SLAB_NO_USER_FLAGS | SLAB_KMALLOC | SLAB_NO_MERGE | \
+			 SLAB_CACHE_PISA_RO)
 
 #define SLAB_DEBUG_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
 			  SLAB_TRACE | SLAB_CONSISTENCY_CHECKS)
mm/slab_common.c +4 -1
index 01c64ef661e7f..d6c00047b1623 100644
@@ -49,7 +49,7 @@ struct kmem_cache *kmem_cache;
  */
 #define SLAB_NEVER_MERGE (SLAB_DEBUG_FLAGS | SLAB_TYPESAFE_BY_RCU | \
 		SLAB_NOLEAKTRACE | SLAB_FAILSLAB | SLAB_NO_MERGE | \
-		SLAB_OBJ_EXT_IN_OBJ)
+		SLAB_OBJ_EXT_IN_OBJ | SLAB_CACHE_PISA_RO)
 
 #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
 			 SLAB_CACHE_DMA32 | SLAB_ACCOUNT | SLAB_MAY_ACCOUNT)
@@ -377,6 +377,9 @@ struct kmem_cache *__kmem_cache_create_args(const char *name,
 	if (s)
 		goto out_unlock;
 
+	if (flags & SLAB_CACHE_PISA_RO)
+		flags |= SLAB_SKIP_KFENCE;
+
 	cache_name = kstrdup_const(name, GFP_KERNEL);
 	if (!cache_name) {
 		err = -ENOMEM;
mm/slub.c +13 -1
index 45e077c7526c2..63609768f4e3f 100644
@@ -46,6 +46,7 @@
 #include <linux/prandom.h>
 #include <kunit/test.h>
 #include <kunit/test-bug.h>
+#include <linux/pisa.h>
 #include <linux/sort.h>
 #include <linux/irq_work.h>
 #include <linux/kprobes.h>
@@ -3378,6 +3379,8 @@ static inline struct slab *alloc_slab_page(gfp_t flags, int node,
 	if (unlikely(!allow_spin))
 		page = alloc_frozen_pages_nolock(0/* __GFP_COMP is implied */,
 								  node, order);
+	else if (unlikely(flags & __GFP_PISA_RO))
+		page = (struct page *)pisa_alloc_folio(flags, order, node);
 	else if (node == NUMA_NO_NODE)
 		page = alloc_frozen_pages(flags, order);
 	else
@@ -3484,7 +3487,7 @@ static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags,
 	gfp_t alloc_gfp;
 	void *start;
 
-	flags &= gfp_allowed_mask;
+	flags &= gfp_allowed_mask & ~__GFP_PISA_RW;
 
 	flags |= s->allocflags;
 
@@ -3495,9 +3498,13 @@ static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags,
 	alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
 	if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
 		alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
+	if (unlikely(s->flags & SLAB_CACHE_PISA_RO))
+		alloc_gfp = (flags | __GFP_NOWARN) & ~__GFP_NOFAIL;
 
 	slab = alloc_slab_page(alloc_gfp, node, oo, allow_spin);
 	if (unlikely(!slab)) {
+		if (s->flags & SLAB_CACHE_PISA_RO)
+			return NULL;
 		oo = s->min;
 		alloc_gfp = flags;
 		/*
@@ -8182,6 +8189,11 @@ static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
 	if (s->flags & SLAB_RECLAIM_ACCOUNT)
 		s->allocflags |= __GFP_RECLAIMABLE;
 
+	if (s->flags & SLAB_CACHE_PISA_RO) {
+		s->allocflags |= __GFP_PISA_RO | __GFP_ZERO;
+		order = clamp_t(unsigned int, order, 2, PAGE_ALLOC_COSTLY_ORDER);
+	}
+
 	/*
 	 * For kmalloc caches we enable sheaves later by
 	 * bootstrap_kmalloc_sheaves() to avoid recursion.
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#143 lore raw

Re: [RFC PATCH v2 16/25] mm/slub: Add SLAB_CACHE_PISA_RO for PISA-backed slab caches

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [High] mm/slub: order clamping in calculate_sizes() breaks non-4K pages and slab->objects - [Medium]…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [High] mm/slub: order clamping in calculate_sizes() breaks non-4K pages and slab->objects
- [Medium] iommu/pisa: pisa_alloc_folio() pollutes per-node allocator on __GFP_THISNODE
- [Medium] mm/slub: __GFP_PISA_RO leaks into alloc_slab_obj_exts() via OBJCGS_CLEAR_MASK
- [Medium] mm/slub: alloc_slab_page() and pisa_alloc_folio() bypass current_gfp_context()
- [Low] iommu/pisa: kmem_cache leak in test_slub_page_alloc() on allocation failure
--

commit 48ed47e1e79e98a68d2521a0d03cf1f63453e5e9
Author: Luigi Rizzo <[email protected]>

mm/slub: Add SLAB_CACHE_PISA_RO for PISA-backed slab caches

This commit adds the SLAB_CACHE_PISA_RO flag so SLUB caches can allocate zeroed, read-only PISA folios via pisa_alloc_folio().

Quoted 24 lines
drivers/iommu/pisa-alloc.c +16 -0
index 4b61ec84ed6d1..3b5c49d143a7e 100644
@@ -848,6 +848,33 @@ unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred
 	return pisa_alloc_bulk(pa, gfp & ~__GFP_PISA_RW, nr_pages, page_array, frozen);
 }
 
+/**
+ * pisa_alloc_folio - Allocate a frozen folio for SLUB (SLAB_CACHE_PISA_RO)
+ * @gfp: GFP flags (must have __GFP_PISA_RW or __GFP_PISA_RO set)
+ * @order: Folio order
+ * @nid: Target NUMA node (or NUMA_NO_NODE)
+ *
+ * Drops __GFP_THISNODE before calling the per-node allocator and verifies
+ * node placement afterwards.
+ *
+ * Return: Frozen folio of @order, or NULL.
+ */
+struct folio *pisa_alloc_folio(gfp_t gfp, unsigned int order, int nid)
+{
+	struct page *page;
+
+	page = pisa_alloc_pages(gfp & ~__GFP_THISNODE, order, nid, NULL);

drivers/iommu/pisa-alloc.c unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, int preferred · line 876

Quoted 10 lines
drivers/iommu/pisa-alloc.c +10 -0
+	if (!page)
+		return NULL;
+	if (unlikely((gfp & __GFP_THISNODE) && nid != NUMA_NO_NODE &&
+		     page_to_nid(page) != nid)) {
+		page_ref_unfreeze(page, 1);
+		__free_pages(page, order);
+		return NULL;
+	}
+	return page_folio(page);
+}

[Severity: Medium]
Can stripping __GFP_THISNODE here attach a remote 2MB PISA page to nid's per-node PISA allocator?

When ___slab_alloc() tries the local node first, it passes GFP_NOWAIT | __GFP_NOWARN | __GFP_THISNODE. If nid's PISA allocator and reservoir are empty, pisa_alloc_pages() reaches __pisa_page_alloc(), which calls alloc_pages_node(nid, gfp, PISA_ORDER) without __GFP_THISNODE. When nid has no free order-9 buddy pages, alloc_pages_node() falls back to a remote node, and __pisa_alloc_bulk() binds that remote 2MB page's pisa_meta to nid's pisa_alloc and sets PISA_ACTIVE.

pisa_alloc_folio() then rejects the block because page_to_nid(page) != nid and calls __free_pages(page, order), which intercepts PISA_ACTIVE in __free_pages_prepare() -> pisa_free_page() and recycles the remote block back into nid's pisa_alloc instead of freeing the 2MB page. Subsequent __GFP_THISNODE allocations on nid will repeatedly pop and reject blocks from that remote 2MB page.

Quoted 4 lines
drivers/iommu/pisa-kunit.c +0 -0
index 40bf7801183da..9cc1328893ace 100644

[ ... ]

Quoted 10 lines
drivers/iommu/pisa-kunit.c +6 -0
@@ -621,6 +622,23 @@ static void test_reservoir_and_scrubber(struct kunit *test)
 	WRITE_ONCE(pisa_scrub_max, old_scrub);
 }
 
+static void test_slub_page_alloc(struct kunit *test)
+{
+	struct kmem_cache *s;
+	void *obj;
+
+	s = kmem_cache_create("pisa_kunit_slab", 1024, NULL,

drivers/iommu/pisa-kunit.c static void test_reservoir_and_scrubber(struct kunit *test) · line 640

Quoted 10 lines
drivers/iommu/pisa-kunit.c +10 -0
+			      SLAB_NO_MERGE | SLAB_CACHE_PISA_RO);
+	KUNIT_ASSERT_NOT_NULL(test, s);
+
+	obj = kmem_cache_alloc(s, GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, obj);
+	KUNIT_EXPECT_TRUE(test, is_pisa_page(virt_to_page(obj)));
+	kmem_cache_free(s, obj);
+
+	kmem_cache_destroy(s);
+}

[Severity: Low]
Does KUNIT_ASSERT_NOT_NULL(test, obj) leak the kmem_cache s if kmem_cache_alloc() fails? KUNIT_ASSERT_NOT_NULL() aborts the test immediately before reaching kmem_cache_destroy(s).

Quoted 4 lines
mm/slub.c +0 -0
index 45e077c7526c2..63609768f4e3f 100644

[ ... ]

mm/slub.c static inline struct slab *alloc_slab_page(gfp_t flags, int node, · line 3386

Quoted 9 lines
mm/slub.c +2 -0
@@ -3378,6 +3379,8 @@ static inline struct slab *alloc_slab_page(gfp_t flags, int node,
 	if (unlikely(!allow_spin))
 		page = alloc_frozen_pages_nolock(0/* __GFP_COMP is implied */,
 								  node, order);
+	else if (unlikely(flags & __GFP_PISA_RO))
+		page = (struct page *)pisa_alloc_folio(flags, order, node);
 	else if (node == NUMA_NO_NODE)
 		page = alloc_frozen_pages(flags, order);
 	else

[Severity: Medium]
Does calling pisa_alloc_folio() directly bypass current_gfp_context()?

alloc_frozen_pages() and __alloc_frozen_pages() apply current_gfp_context(gfp) in __alloc_frozen_pages_noprof() to strip __GFP_DIRECT_RECLAIM, __GFP_FS, or __GFP_IO under scoped memalloc_noreclaim_save(), memalloc_nofs_save(), or memalloc_noio_save() sections. Neither alloc_slab_page() nor pisa_alloc_folio() applies current_gfp_context(flags), so a GFP_KERNEL allocation from a SLAB_CACHE_PISA_RO cache inside memalloc_noreclaim_save() still has gfpflags_allow_blocking(gfp) true and can sleep in pisa_alloc_split_page(), and inside memalloc_nofs_save() or memalloc_noio_save() can enter pisa_meta_init() from __pisa_page_alloc() before pisa_memalloc_save() is called.

mm/slub.c static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags, · line 3492

Quoted 8 lines
mm/slub.c +1 -1
@@ -3484,7 +3487,7 @@ static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags,
 	gfp_t alloc_gfp;
 	void *start;
 
-	flags &= gfp_allowed_mask;
+	flags &= gfp_allowed_mask & ~__GFP_PISA_RW;
 
 	flags |= s->allocflags;

[Severity: Medium]
Does __GFP_PISA_RO in s->allocflags leak into internal slabobj_ext allocations?

flags |= s->allocflags sets __GFP_PISA_RO in flags after ~__GFP_PISA_RW is masked out, and allocate_slab() then passes flags to account_slab() -> alloc_slab_obj_exts(). Because OBJCGS_CLEAR_MASK does not include __GFP_PISA_RW:

mm/slub.c:

#define OBJCGS_CLEAR_MASK	(__GFP_DMA | __GFP_RECLAIMABLE | \
				__GFP_ACCOUNT | __GFP_NOFAIL | \
				__GFP_THISNODE | __GFP_COMP)

alloc_slab_obj_exts() (and alloc_empty_sheaf() when a caller passes __GFP_PISA_RO) leaves __GFP_PISA_RO set on the internal kmalloc call. If the slabobj_ext array exceeds KMALLOC_MAX_CACHE_SIZE, ___kmalloc_large_node() allocates the SLUB metadata array from a PISA RO page. Adding __GFP_PISA_RW to OBJCGS_CLEAR_MASK would prevent this.

[ ... ]

mm/slub.c static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s) · line 8199

Quoted 12 lines
mm/slub.c +5 -0
@@ -8182,6 +8189,11 @@ static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
 	if (s->flags & SLAB_RECLAIM_ACCOUNT)
 		s->allocflags |= __GFP_RECLAIMABLE;
 
+	if (s->flags & SLAB_CACHE_PISA_RO) {
+		s->allocflags |= __GFP_PISA_RO | __GFP_ZERO;
+		order = clamp_t(unsigned int, order, 2, PAGE_ALLOC_COSTLY_ORDER);
+	}
+
 	/*
 	 * For kmalloc caches we enable sheaves later by
 	 * bootstrap_kmalloc_sheaves() to avoid recursion.

[Severity: High]
Does clamping order to [2, PAGE_ALLOC_COSTLY_ORDER] after calculate_order(size) break on 16KB and 64KB page kernels?

In pisa_init(), read-only PISA allocators are only created for order 2 and SKB_FRAG_PAGE_ORDER:

drivers/iommu/pisa-alloc.c:pisa_init() {
	const struct {
		u8 order;
		bool ro;
		bool pcp;
	} cfg[] = {
		{ 0, false, true },
		{ 2, true, false },
		{ SKB_FRAG_PAGE_ORDER, true, true },
	};

On ARM64 with 16KB or 64KB pages, SKB_FRAG_PAGE_ORDER is 1 or 0, so no order-3 (PAGE_ALLOC_COSTLY_ORDER) read-only PISA allocator exists. When calculate_order(size) returns 3, pisa_alloc_folio() looks up pisa_node_pa(nid, 3, true), which returns NULL, and allocate_slab() skips the s->min fallback for SLAB_CACHE_PISA_RO, causing every allocation from the cache to fail.

In addition, clamping order up to 2 runs after calculate_order(size) has enforced MAX_OBJS_PER_PAGE (32767). On 64KB pages with s->size == 8, forcing order 2 produces 32768 objects, which fits in the 16-bit OO_MASK of s->oo but truncates the 15-bit unsigned slab->objects bitfield to 0 in allocate_slab(), corrupting freelist setup in build_slab_freelist() or looping in ___slab_alloc(). Finally, if s->size exceeds PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER when SLUB_DEBUG inflates metadata, clamping order down makes oo_objects(s->oo) == 0 before do_kmem_cache_create() can reach disable_higher_order_debug.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
#144 lore raw

RFC PATCH v2 17/25 net: Allocate small skb heads from PISA

In reply to Luigi Rizzo

The linear part of most transmitted skbs is a small head from the skbuff_small_head cache. To avoid per-packet IOMMU map/unmap operations or bounce-buffer copies for headers, allow backing small TX skb heads with PISA memory.

When per-device pisa_tx_skb_heads is enabled, create a parallel skbuff_small_head_pisa slab cache backed by zeroed, read-only PISA folios (SLAB_CACHE_PISA_RO). Eligible TX paths passing __GFP_PISA_RO allocate small heads from this cache and fall back to skbuff_small_head on failure.

---
 drivers/base/core.c        |   4 +-
 drivers/iommu/pisa-alloc.c | 133 ++++++++++++++++++++++++++++++++-----
 drivers/iommu/pisa-kunit.c |   5 +-
 include/linux/device.h     |   6 ++
 include/linux/pisa.h       |   6 ++
 include/net/sock.h         |  74 ++++++++++++++++++---
 net/core/skbuff.c          |  39 ++++++++---
 net/core/sock.c            |  23 +++++--
 net/ipv4/ip_output.c       |   8 ++-
 net/ipv4/tcp.c             |   2 +-
 net/ipv4/tcp_output.c      |  12 ++--
 net/ipv6/ip6_output.c      |   8 ++-
 12 files changed, 263 insertions(+), 57 deletions(-)
drivers/base/core.c +3 -1
index ade0c94b02ae7..efc1f9b9d255d 100644
@@ -2951,7 +2951,7 @@ static DEVICE_ATTR_RW(name)
 PISA_BOOL_ATTR(pisa_coherent);
 PISA_BOOL_ATTR(pisa_rx_bufs);
 PISA_SET_ATTR(pisa_tx_bufs, net_pisa_tx_bufs_set);
-PISA_BOOL_ATTR(pisa_tx_skb_heads);
+PISA_SET_ATTR(pisa_tx_skb_heads, net_pisa_tx_skb_heads_set);
 
 static struct attribute *dev_attr_pisa[] = {
 	&dev_attr_pisa_coherent.attr,
@@ -3113,6 +3113,8 @@ static void device_remove_attrs(struct device *dev)
 		device_remove_group(dev, &dev_attr_pisa_group);
 		if (dev->pisa_tx_bufs)
 			net_pisa_tx_bufs_set(dev, false);
+		if (dev->pisa_tx_skb_heads)
+			net_pisa_tx_skb_heads_set(dev, false);
 	}
 
 	if (dev->physical_location) {
drivers/iommu/pisa-alloc.c +115 -18

158 lines not on this page · raw message

drivers/iommu/pisa-kunit.c +3 -2
index 9cc1328893ace..3fc17024bc9d0 100644
@@ -489,9 +489,10 @@ static void test_dev_pisa_attrs(struct kunit *test)
 	}
 	kunit_check_pisa_attr(test, dev, "pisa_coherent", &dev->pisa_coherent);
 	kunit_check_pisa_attr(test, dev, "pisa_rx_bufs", &dev->pisa_rx_bufs);
-	if (IS_ENABLED(CONFIG_NET))
+	if (IS_ENABLED(CONFIG_NET)) {
 		kunit_check_pisa_attr(test, dev, "pisa_tx_bufs", &dev->pisa_tx_bufs);
-	kunit_check_pisa_attr(test, dev, "pisa_tx_skb_heads", &dev->pisa_tx_skb_heads);
+		kunit_check_pisa_attr(test, dev, "pisa_tx_skb_heads", &dev->pisa_tx_skb_heads);
+	}
 	device_unregister(dev);
 }
 
include/linux/device.h +6 -0
index 08f511b978ded..d588ae27c960c 100644
@@ -816,11 +816,17 @@ struct device {
 
 #if defined(CONFIG_NET) && defined(CONFIG_PISA)
 int net_pisa_tx_bufs_set(struct device *dev, bool val);
+int net_pisa_tx_skb_heads_set(struct device *dev, bool val);
 #else
 static inline int net_pisa_tx_bufs_set(struct device *dev, bool val)
 {
 	return -EOPNOTSUPP;
 }
+
+static inline int net_pisa_tx_skb_heads_set(struct device *dev, bool val)
+{
+	return -EOPNOTSUPP;
+}
 #endif
 
 #define __create_dev_flag_accessors(accessor_name, flag_name) \
include/linux/pisa.h +6 -0
index b9c5197f2d88d..452b8fa20c8d7 100644
@@ -113,6 +113,7 @@ unsigned long pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
 struct folio *pisa_alloc_folio(gfp_t gfp, unsigned int order, int nid);
 bool pisa_has_free_blocks_rx(const struct device *dev, unsigned int order, int nid);
 bool pisa_page_can_recycle(const struct page *page);
+void *pisa_skb_head_alloc_node(gfp_t flags, int node);
 
 static inline gfp_t pisa_rx_gfp(const struct device *dev)
 {
@@ -169,6 +170,11 @@ static inline bool pisa_free_coherent(struct page *page, size_t size)
 	return false;
 }
 
+static inline void *pisa_skb_head_alloc_node(gfp_t flags, int node)
+{
+	return NULL;
+}
+
 static inline bool pisa_page_can_recycle(const struct page *page)
 {
 	return true;
include/net/sock.h +64 -10

126 lines not on this page · raw message

net/core/skbuff.c +31 -8
index 8da53d5b76fc2..04ae3bb4bd905 100644
@@ -93,6 +93,7 @@
 #include <linux/user_namespace.h>
 #include <linux/indirect_call_wrapper.h>
 #include <linux/textsearch.h>
+#include <linux/pisa.h>
 
 #include "dev.h"
 #include "devmem.h"
@@ -607,16 +608,23 @@ static void *kmalloc_pfmemalloc(size_t obj_size, gfp_t flags, int node)
 static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,
 			     struct sk_buff *skb)
 {
+	bool pisa = flags & __GFP_PISA_RO;
 	size_t obj_size;
 	void *obj;
 
+	flags &= ~__GFP_PISA_RW;
 	obj_size = SKB_HEAD_ALIGN(*size);
 	if (obj_size <= SKB_SMALL_HEAD_CACHE_SIZE &&
 	    !(flags & KMALLOC_NOT_NORMAL_BITS)) {
+		*size = SKB_SMALL_HEAD_CACHE_SIZE;
+		if (unlikely(pisa)) {
+			obj = pisa_skb_head_alloc_node(flags, node);
+			if (likely(obj))
+				goto out;
+		}
 		obj = kmem_cache_alloc_node(net_hotdata.skb_small_head_cache,
 				flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
 				node);
-		*size = SKB_SMALL_HEAD_CACHE_SIZE;
 		if (likely(obj))
 			goto out;
 		/* Try again but now we are using pfmemalloc reserves */
@@ -2144,6 +2152,15 @@ void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
 }
 EXPORT_SYMBOL(skb_copy_header);
 
+static inline gfp_t skb_head_pisa_gfp(const struct sk_buff *skb)
+{
+	if (net_pisa_tx_skb_heads_enabled() &&
+	    !skb->head_frag &&
+	    is_pisa_page(virt_to_page(skb->head)))
+		return __GFP_PISA_RO;
+	return 0;
+}
+
 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
 {
 	if (skb_pfmemalloc(skb))
@@ -2182,7 +2199,7 @@ struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
 
 	headerlen = skb_headroom(skb);
 	size = skb_end_offset(skb) + skb->data_len;
-	n = __alloc_skb(size, gfp_mask,
+	n = __alloc_skb(size, gfp_mask | skb_head_pisa_gfp(skb),
 			skb_alloc_rx_flag(skb), NUMA_NO_NODE);
 	if (!n)
 		return NULL;
@@ -2226,7 +2243,8 @@ struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
 {
 	unsigned int size = skb_headlen(skb) + headroom;
 	int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
-	struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
+	struct sk_buff *n = __alloc_skb(size, gfp_mask | skb_head_pisa_gfp(skb),
+					flags, NUMA_NO_NODE);
 
 	if (!n)
 		goto out;
@@ -2315,7 +2333,8 @@ int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
 	if (skb_pfmemalloc(skb))
 		gfp_mask |= __GFP_MEMALLOC;
 
-	data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
+	data = kmalloc_reserve(&size, gfp_mask | skb_head_pisa_gfp(skb),
+			       NUMA_NO_NODE, NULL);
 	if (!data)
 		goto nodata;
 	size = SKB_WITH_OVERHEAD(size);
@@ -2524,7 +2543,8 @@ struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
 
 	oldheadroom = skb_headroom(skb);
 	n = __alloc_skb(newheadroom + skb->len + newtailroom,
-			gfp_mask, skb_alloc_rx_flag(skb),
+			gfp_mask | skb_head_pisa_gfp(skb),
+			skb_alloc_rx_flag(skb),
 			NUMA_NO_NODE);
 	if (!n)
 		return NULL;
@@ -5025,7 +5045,8 @@ struct sk_buff *skb_segment(struct sk_buff *head_skb,
 				hsize = len;
 
 			nskb = __alloc_skb(hsize + doffset + headroom,
-					   GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
+					   GFP_ATOMIC | skb_head_pisa_gfp(head_skb),
+					   skb_alloc_rx_flag(head_skb),
 					   NUMA_NO_NODE);
 
 			if (unlikely(!nskb))
@@ -6974,7 +6995,8 @@ static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
 	if (skb_pfmemalloc(skb))
 		gfp_mask |= __GFP_MEMALLOC;
 
-	data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
+	data = kmalloc_reserve(&size, gfp_mask | skb_head_pisa_gfp(skb),
+			       NUMA_NO_NODE, NULL);
 	if (!data)
 		return -ENOMEM;
 	size = SKB_WITH_OVERHEAD(size);
@@ -7096,7 +7118,8 @@ static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
 	if (skb_pfmemalloc(skb))
 		gfp_mask |= __GFP_MEMALLOC;
 
-	data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
+	data = kmalloc_reserve(&size, gfp_mask | skb_head_pisa_gfp(skb),
+			       NUMA_NO_NODE, NULL);
 	if (!data)
 		return -ENOMEM;
 	size = SKB_WITH_OVERHEAD(size);
net/core/sock.c +18 -5
index 695fefe316925..0ddb5e57f4969 100644
@@ -3061,9 +3061,10 @@ static long sock_wait_for_wmem(struct sock *sk, long timeo)
  *	Generic send/receive buffer handlers
  */
 
-struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
-				     unsigned long data_len, int noblock,
-				     int *errcode, int max_page_order)
+struct sk_buff *__sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
+				       unsigned long data_len, int noblock,
+				       int *errcode, int max_page_order,
+				       gfp_t gfp)
 {
 	struct sk_buff *skb;
 	long timeo;
@@ -3092,7 +3093,8 @@ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
 		timeo = sock_wait_for_wmem(sk, timeo);
 	}
 	skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
-				   errcode, sk->sk_allocation);
+				   errcode,
+				   sk->sk_allocation | (!data_len ? gfp : 0));
 	if (skb)
 		skb_set_owner_w(skb, sk);
 	return skb;
@@ -3103,6 +3105,16 @@ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
 	*errcode = err;
 	return NULL;
 }
+EXPORT_SYMBOL(__sock_alloc_send_pskb);
+
+struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
+				     unsigned long data_len, int noblock,
+				     int *errcode, int max_page_order)
+{
+	return __sock_alloc_send_pskb(sk, header_len, data_len, noblock,
+				      errcode, max_page_order,
+				      pisa_tx_gfp_sk(sk));
+}
 EXPORT_SYMBOL(sock_alloc_send_pskb);
 
 int __sock_cmsg_send(struct sock *sk, struct cmsghdr *cmsg,
@@ -3322,7 +3334,8 @@ bool skb_page_frag_refill_dev(unsigned int sz, struct page_frag *pfrag,
 		const struct dst_entry *dst = skb_dst(skb);
 
 		rcu_read_lock();
-		if (__netdev_tx_pisa_ok(skb->dev ?: (dst ? dst_dev_rcu(dst) : NULL)))
+		if (__netdev_tx_pisa_ok(skb->dev ?: (dst ? dst_dev_rcu(dst) : NULL),
+					PISA_TX_STAMP_BUFS))
 			gfp |= __GFP_PISA_RO;
 		rcu_read_unlock();
 	}
net/ipv4/ip_output.c +5 -3
index a5ea530bc8b5b..c49a33355ea45 100644
@@ -1134,14 +1134,16 @@ static int __ip_append_data(struct sock *sk,
 			alloclen += alloc_extra;
 
 			if (transhdrlen) {
-				skb = sock_alloc_send_skb(sk, alloclen,
-						(flags & MSG_DONTWAIT), &err);
+				skb = sock_alloc_send_skb_dst(sk, alloclen,
+							      flags & MSG_DONTWAIT,
+							      &err, &rt->dst);
 			} else {
 				skb = NULL;
 				if (refcount_read(&sk->sk_wmem_alloc) + wmem_alloc_delta <=
 				    2 * sk->sk_sndbuf)
 					skb = alloc_skb(alloclen,
-							sk->sk_allocation);
+							sk->sk_allocation |
+							pisa_tx_gfp_dst(&rt->dst));
 				if (unlikely(!skb))
 					err = -ENOBUFS;
 			}
net/ipv4/tcp.c +1 -1
index b8d44a0638914..038063717951c 100644
@@ -931,7 +931,7 @@ struct sk_buff *tcp_stream_alloc_skb(struct sock *sk, gfp_t gfp,
 {
 	struct sk_buff *skb;
 
-	skb = alloc_skb_fclone(MAX_TCP_HEADER, gfp);
+	skb = alloc_skb_fclone(MAX_TCP_HEADER, gfp | pisa_tx_gfp_sk(sk));
 	if (likely(skb)) {
 		bool mem_scheduled;
 
net/ipv4/tcp_output.c +6 -6
index cf3ddc055d48d..b7f04a9df199a 100644
@@ -3892,8 +3892,8 @@ void tcp_send_fin(struct sock *sk)
 		}
 	} else {
 		skb = alloc_skb_fclone(MAX_TCP_HEADER,
-				       sk_gfp_mask(sk, GFP_ATOMIC |
-						       __GFP_NOWARN));
+				       sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN) |
+				       pisa_tx_gfp_sk(sk));
 		if (unlikely(!skb))
 			return;
 
@@ -3921,7 +3921,7 @@ void tcp_send_active_reset(struct sock *sk, enum sk_rst_reason reason)
 	TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTRSTS);
 
 	/* NOTE: No TCP options attached and we never retransmit this. */
-	skb = alloc_skb(MAX_TCP_HEADER, priority);
+	skb = alloc_skb(MAX_TCP_HEADER, priority | pisa_tx_gfp_sk(sk));
 	if (!skb) {
 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED);
 		return;
@@ -4011,7 +4011,7 @@ struct sk_buff *tcp_make_synack(const struct sock *sk, struct dst_entry *dst,
 	int mss;
 	u64 now;
 
-	skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC);
+	skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC | pisa_tx_gfp_dst(dst));
 	if (unlikely(!skb)) {
 		dst_release(dst);
 		return NULL;
@@ -4548,7 +4548,7 @@ void __tcp_send_ack(struct sock *sk, u32 rcv_nxt, u16 flags)
 	 * sock.
 	 */
 	buff = alloc_skb(MAX_TCP_HEADER,
-			 sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN));
+			 sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN) | pisa_tx_gfp_sk(sk));
 	if (unlikely(!buff)) {
 		struct inet_connection_sock *icsk = inet_csk(sk);
 		unsigned long delay;
@@ -4601,7 +4601,7 @@ static int tcp_xmit_probe_skb(struct sock *sk, int urgent, int mib)
 
 	/* We don't queue it, tcp_transmit_skb() sets ownership. */
 	skb = alloc_skb(MAX_TCP_HEADER,
-			sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN));
+			sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN) | pisa_tx_gfp_sk(sk));
 	if (!skb)
 		return -1;
 
net/ipv6/ip6_output.c +5 -3
index 957c38a08680c..47a6fea3456fe 100644
@@ -1695,14 +1695,16 @@ static int __ip6_append_data(struct sock *sk,
 				goto error;
 			}
 			if (transhdrlen) {
-				skb = sock_alloc_send_skb(sk, alloclen,
-						(flags & MSG_DONTWAIT), &err);
+				skb = sock_alloc_send_skb_dst(sk, alloclen,
+							      flags & MSG_DONTWAIT,
+							      &err, &rt->dst);
 			} else {
 				skb = NULL;
 				if (refcount_read(&sk->sk_wmem_alloc) + wmem_alloc_delta <=
 				    2 * sk->sk_sndbuf)
 					skb = alloc_skb(alloclen,
-							sk->sk_allocation);
+							sk->sk_allocation |
+							pisa_tx_gfp_dst(&rt->dst));
 				if (unlikely(!skb))
 					err = -ENOBUFS;
 			}
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#145 lore raw

Re: [RFC PATCH v2 17/25] net: Allocate small skb heads from PISA

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] net: raw_send_hdrinc() uses sk_dst_cache instead of packet dst for PISA --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] net: raw_send_hdrinc() uses sk_dst_cache instead of packet dst for PISA
--

commit 37f3bd5cfa3158313d9a63615631730f2ababf39
Author: Luigi Rizzo <[email protected]>

net: Allocate small skb heads from PISA

This commit adds a skbuff_small_head_pisa slab cache backed by read-only PISA folios and allocates small TX skb heads from it when per-device pisa_tx_skb_heads is enabled.

Quoted 33 lines
net/core/sock.c +7 -4
index 695fefe316925..0ddb5e57f4969 100644
@@ -3061,9 +3061,10 @@ static long sock_wait_for_wmem(struct sock *sk, long timeo)
  *	Generic send/receive buffer handlers
  */
 
-struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
-				     unsigned long data_len, int noblock,
-				     int *errcode, int max_page_order)
+struct sk_buff *__sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
+				       unsigned long data_len, int noblock,
+				       int *errcode, int max_page_order,
+				       gfp_t gfp)
 {
 	struct sk_buff *skb;
 	long timeo;
@@ -3092,7 +3093,8 @@ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
 		timeo = sock_wait_for_wmem(sk, timeo);
 	}
 	skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
-				   errcode, sk->sk_allocation);
+				   errcode,
+				   sk->sk_allocation | (!data_len ? gfp : 0));
 	if (skb)
 		skb_set_owner_w(skb, sk);
 	return skb;
@@ -3103,6 +3105,16 @@ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
 	*errcode = err;
 	return NULL;
 }
+EXPORT_SYMBOL(__sock_alloc_send_pskb);

net/core/sock.c struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, · line 3118

Quoted 10 lines
net/core/sock.c +9 -0
+
+struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
+				     unsigned long data_len, int noblock,
+				     int *errcode, int max_page_order)
+{
+	return __sock_alloc_send_pskb(sk, header_len, data_len, noblock,
+				      errcode, max_page_order,
+				      pisa_tx_gfp_sk(sk));
+}
 EXPORT_SYMBOL(sock_alloc_send_pskb);

[Severity: Medium]
Should raw_send_hdrinc() and rawv6_send_hdrinc() also call sock_alloc_send_skb_dst() with &rt->dst like __ip_append_data() and __ip6_append_data() do?

Both functions still call sock_alloc_send_skb(), which checks sk->sk_dst_cache via pisa_tx_gfp_sk() instead of the per-packet route and then copies the entire packet into skb->head. If a connected raw socket with IP_HDRINCL or IPV6_HDRINCL has a PISA-eligible route cached in sk->sk_dst_cache, sending a packet whose per-packet route uses IPsec XFRM (for example via msg_name) places the plaintext payload into a PISA page before encryption, violating the !dst_xfrm(dst) requirement in __dst_tx_pisa_ok(). Conversely, unconnected HDRINCL raw sockets have a NULL sk->sk_dst_cache and never use PISA heads even when the packet route qualifies.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
#146 lore raw

RFC PATCH v2 18/25 iommu/dma: Migrate user pages into PISA for TX zerocopy

In reply to Luigi Rizzo

MSG_ZEROCOPY sends map each user page with a per-buffer IOMMU mapping and IOTLB flush. Moving user TX buffers into PISA blocks once allows subsequent zerocopy sends to reuse pre-mapped 2MB IOMMU entries.

Add drivers/iommu/pisa-user.c to migrate private anonymous order-0 user pages into per-node DMA_TO_DEVICE PISA allocators, controlled by pisa.user_max_4K_pages (0 = disabled):
- Explicit migration via madvise(MADV_PISA) and MADV_NOPISA (also supported via process_madvise()).
- Automatic best-effort migration on MSG_ZEROCOPY sends in zerocopy_fill_skb_from_iter() when the egress device has pisa_tx_bufs enabled. For TCP, pages that cannot be migrated fall back to the regular copy path into PISA TX page_frags.

---
 drivers/iommu/Makefile                 |   2 +-
 drivers/iommu/pisa-alloc.c             |   2 +
 drivers/iommu/pisa-priv.h              |   2 +
 drivers/iommu/pisa-user.c              | 278 +++++++++++++++++++++++++
 include/linux/pisa.h                   |  28 +++
 include/linux/swap.h                   |   1 +
 include/uapi/asm-generic/mman-common.h |   2 +
 mm/madvise.c                           |  11 +
 net/core/datagram.c                    |  82 +++++++-
 net/core/skbuff.c                      |   3 +-
 net/ipv4/tcp.c                         |  12 +-
 11 files changed, 416 insertions(+), 7 deletions(-)
 create mode 100644 drivers/iommu/pisa-user.c
drivers/iommu/Makefile +1 -1
index 125cf7e813cdc..cd14f80a594a7 100644
@@ -11,7 +11,7 @@ obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
-obj-$(CONFIG_PISA) += pisa-meta.o pisa-alloc.o pisa-node.o
+obj-$(CONFIG_PISA) += pisa-meta.o pisa-alloc.o pisa-node.o pisa-user.o
 ifeq ($(CONFIG_IOMMU_DMA),y)
 obj-$(CONFIG_PISA) += pisa-map.o
 endif
drivers/iommu/pisa-alloc.c +2 -0
index 7df2ecde32916..1930135880d2b 100644
@@ -1756,6 +1756,8 @@ static int __init pisa_init(void)
 		}
 	}
 
+	pisa_user_boot_enable();
+
 	/* Dedicated WQ_MEM_RECLAIM workqueue so reclaim never blocks behind system_wq. */
 	pisa_wq = alloc_workqueue("pisa", WQ_MEM_RECLAIM, 0);
 	if (!pisa_wq)
drivers/iommu/pisa-priv.h +2 -0
index ef3abb1db9049..fe1bff0bba322 100644
@@ -185,6 +185,7 @@ static inline long pisa_alloc_held_pages(const struct pisa_alloc *pa)
 struct pisa_node {
 	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
 	struct pisa_alloc	*pa[2][PISA_ORDER + 1]; /* [0]=RW, [1]=RO by order */
+	struct pisa_alloc	*user_pa;	/* user page migration pa */
 
 	spinlock_t		lock;		/* protects @pages and @nr_pages */
 	struct list_head	pages;		/* reservoir */
@@ -278,6 +279,7 @@ void pisa_schedule_scrub_all(void);
 struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool decrypt, bool *clean);
 unsigned long pisa_reservoir_count(void);
 unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan);
+void pisa_user_boot_enable(void);
 
 #endif /* CONFIG_PISA */
 
drivers/iommu/pisa-user.c new file +278 -0

278 lines not on this page · raw message

include/linux/pisa.h +28 -0
index 452b8fa20c8d7..d11fd3d663dc1 100644
@@ -132,6 +132,18 @@ static inline void pisa_task_frag_release(struct task_struct *tsk)
 		put_page(tsk->task_frag_pisa.page);
 }
 
+/* User pages in PISA blocks, see drivers/iommu/pisa-user.c */
+DECLARE_STATIC_KEY_FALSE(pisa_user_key);
+bool pisa_upgrade_user_pages(struct page **pages, unsigned int nr);
+int pisa_madvise(struct vm_area_struct *vma, unsigned long start,
+		 unsigned long end, bool to_pisa);
+
+/* Is pisa.user_max_4K_pages non-zero? */
+static inline bool pisa_user_enabled(void)
+{
+	return static_branch_unlikely(&pisa_user_key);
+}
+
 #else /* !CONFIG_PISA */
 
 static inline int pisa_meta_init(void)
@@ -213,6 +225,22 @@ static inline void pisa_task_frag_release(struct task_struct *tsk)
 {
 }
 
+static inline bool pisa_user_enabled(void)
+{
+	return false;
+}
+
+static inline bool pisa_upgrade_user_pages(struct page **pages, unsigned int nr)
+{
+	return false;
+}
+
+static inline int pisa_madvise(struct vm_area_struct *vma, unsigned long start,
+			       unsigned long end, bool to_pisa)
+{
+	return -EINVAL;
+}
+
 #endif /* CONFIG_PISA */
 
 static inline struct page *
include/linux/swap.h +1 -0
index 4f686709d71f0..3736786ccc5a3 100644
@@ -314,6 +314,7 @@ extern unsigned long totalreserve_pages;
 /* linux/mm/folio.c */
 void folio_add_lru(struct folio *folio);
 void folio_mark_accessed(struct folio *folio);
+void lru_add_drain(void);
 void lru_add_drain_all(void);
 
 enum lru_cache_drained {
include/uapi/asm-generic/mman-common.h +2 -0
index ef1c27fa3c570..c4332db8e56ff 100644
@@ -81,6 +81,8 @@
 
 #define MADV_GUARD_INSTALL 102		/* fatal signal on access to range */
 #define MADV_GUARD_REMOVE 103		/* unguard range */
+#define MADV_PISA		210	/* move pages into PISA memory */
+#define MADV_NOPISA		211	/* move pages out of PISA memory */
 
 /* compatibility flags */
 #define MAP_FILE	0
mm/madvise.c +11 -0
index 0214efd2a014f..0eccb44594b04 100644
@@ -6,6 +6,7 @@
  * Copyright (C) 2002  Christoph Hellwig
  */
 
+#include <linux/pisa.h>
 #include <linux/mman.h>
 #include <linux/pagemap.h>
 #include <linux/syscalls.h>
@@ -1393,6 +1394,9 @@ static int madvise_vma_behavior(struct madvise_behavior *madv_behavior)
 		return madvise_guard_install(madv_behavior);
 	case MADV_GUARD_REMOVE:
 		return madvise_guard_remove(madv_behavior);
+	case MADV_PISA:
+	case MADV_NOPISA:
+		return pisa_madvise(vma, range->start, range->end, behavior == MADV_PISA);
 
 	/* The below behaviours update VMAs via madvise_update_vma(). */
 
@@ -1582,6 +1586,9 @@ madvise_behavior_valid(int behavior)
 	case MADV_HWPOISON:
 #endif
 		return true;
+	case MADV_PISA:
+	case MADV_NOPISA:
+		return IS_ENABLED(CONFIG_PISA);
 
 	default:
 		return false;
@@ -1596,6 +1603,8 @@ static bool process_madvise_remote_valid(int behavior)
 	case MADV_PAGEOUT:
 	case MADV_WILLNEED:
 	case MADV_COLLAPSE:
+	case MADV_PISA:
+	case MADV_NOPISA:
 		return true;
 	default:
 		return false;
@@ -1782,6 +1791,8 @@ static enum madvise_lock_mode get_lock_mode(struct madvise_behavior *madv_behavi
 	case MADV_POPULATE_READ:
 	case MADV_POPULATE_WRITE:
 	case MADV_COLLAPSE:
+	case MADV_PISA:
+	case MADV_NOPISA:
 		return MADVISE_MMAP_READ_LOCK;
 	case MADV_GUARD_INSTALL:
 	case MADV_GUARD_REMOVE:
net/core/datagram.c +78 -4

120 lines not on this page · raw message

net/core/skbuff.c +2 -1
index 04ae3bb4bd905..739d09615638c 100644
@@ -1935,7 +1935,8 @@ int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
 
 	err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len,
 				      binding);
-	if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
+	if (err == -EFAULT ||
+	    ((err == -EMSGSIZE || err == -EXDEV) && skb->len == orig_len)) {
 		struct sock *save_sk = skb->sk;
 
 		/* Streams do not free skb on error. Reset to prev state. */
net/ipv4/tcp.c +11 -1
index 038063717951c..9214d6213cae5 100644
@@ -1128,6 +1128,7 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 	int process_backlog = 0;
 	int sockc_err = 0;
 	int zc = 0;
+	bool must_copy = false;	/* copy the next chunk of a MSG_ZEROCOPY send */
 	long timeo;
 
 	flags = msg->msg_flags;
@@ -1289,7 +1290,7 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 		if (copy > msg_data_left(msg))
 			copy = msg_data_left(msg);
 
-		if (zc == 0) {
+		if (zc == 0 || unlikely(must_copy)) {
 			const struct dst_entry *dst = __sk_dst_get(sk);
 			bool merge = true;
 			int i = skb_shinfo(skb)->nr_frags;
@@ -1335,6 +1336,7 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 				page_ref_inc(pfrag->page);
 			}
 			pfrag->offset += copy;
+			must_copy = false;
 		} else if (zc == MSG_ZEROCOPY)  {
 			/* First append to a fragless skb builds initial
 			 * pure zerocopy skb
@@ -1354,6 +1356,14 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 				tcp_mark_push(tp, skb);
 				goto new_segment;
 			}
+			/*
+			 * The next user page is not in PISA memory: copy this
+			 * chunk, without reporting SO_EE_CODE_ZEROCOPY_COPIED.
+			 */
+			if (unlikely(err == -EXDEV)) {
+				must_copy = true;
+				continue;
+			}
 			if (err < 0)
 				goto do_error;
 			copy = err;
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#147 lore raw

Re: [RFC PATCH v2 18/25] iommu/dma: Migrate user pages into PISA for TX zerocopy

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [High] iommu/pisa: unkillable PAGE_SIZE walk under mmap_read_lock in pisa_madvise() - [High] mm/madvise…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [High] iommu/pisa: unkillable PAGE_SIZE walk under mmap_read_lock in pisa_madvise()
- [High] mm/madvise: missing MADV_PISA definitions on alpha, mips, parisc, and xtensa
- [Medium] iommu/pisa: alloc_tag corruption via pgalloc_tag_swap() in pisa_user_migrate()
- [Medium] iommu/pisa: pisa_user_max_4k_pages not restored on error in pisa_user_max_set()
- [Medium] net: pisa_zc_iter() migrates user pages before checking dst_tx_pisa_ok()
--

commit e8400c9a631094526a61a414ed9c1bc933634c72
Author: Luigi Rizzo <[email protected]>

iommu/dma: Migrate user pages into PISA for TX zerocopy

This commit adds support for migrating private anonymous order-0 user pages into per-node PISA allocators via madvise(MADV_PISA / MADV_NOPISA) and automatically during MSG_ZEROCOPY transmissions.

Quoted 6 lines
drivers/iommu/pisa-user.c new file +0 -0
new file mode 100644
index 0000000000000..a16909d429aca
@@ -0,0 +1,278 @@

[ ... ]

Quoted 12 lines
drivers/iommu/pisa-user.c new file +12 -0
+static int pisa_user_max_set(const char *val, const struct kernel_param *kp)
+{
+	unsigned long max_pages;
+	int ret;
+
+	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
+		return -EOPNOTSUPP;
+	ret = kstrtoul(val, 0, &max_pages);
+	if (ret)
+		return ret;
+	WRITE_ONCE(pisa_user_max_4k_pages, max_pages);
+	if (max_pages) {

drivers/iommu/pisa-user.c line 50

Quoted 10 lines
drivers/iommu/pisa-user.c new file +10 -0
+		if (!pisa_nodes[first_memory_node].pa[0][0])
+			return 0;
+		if (!pisa_user_init())
+			return -ENOMEM;
+		static_branch_enable(&pisa_user_key);
+	} else {
+		static_branch_disable(&pisa_user_key);
+	}
+	return 0;
+}

[Severity: Medium]
Does this leave pisa_user_max_4k_pages updated if pisa_user_init() fails and returns -ENOMEM? Sysfs will report the new non-zero limit after the write failed, and a later madvise(MADV_PISA) call can then succeed in pisa_user_init() while pisa_user_key remains disabled.

[ ... ]

Quoted 34 lines
drivers/iommu/pisa-user.c new file +34 -0
+/* new_folio_t for migration into PISA memory. */
+static struct folio *pisa_user_new_folio(struct folio *src, unsigned long private)
+{
+	struct pisa_user_mtc *mtc = (void *)private;
+	int nid = folio_nid(src);
+	struct page *page;
+
+	if (mtc->budget <= 0)
+		return NULL;
+	page = pisa_alloc(pisa_nodes[nid].user_pa, mtc->gfp);
+	if (!page)
+		return NULL;
+	if (pisa_meta_of_pfn(page_to_pfn(page))->flags & PISA_DECRYPTED) {
+		put_page(page);
+		mtc->budget = 0;
+		return NULL;
+	}
+	mtc->budget--;
+	return page_folio(page);
+}
+
+/* new_folio_t for migration out of PISA memory: allocators never serve these. */
+static struct folio *pisa_user_old_folio(struct folio *src, unsigned long private)
+{
+	return __folio_alloc_node(GFP_HIGHUSER_MOVABLE | __GFP_NOWARN, 0, folio_nid(src));
+}
+
+/* Migrate the isolated folios on @list; failures are put back. */
+static void pisa_user_migrate(struct list_head *list, bool to_pisa, gfp_t gfp)
+{
+	struct pisa_user_mtc mtc = { .gfp = gfp, .budget = LONG_MAX };
+	enum migrate_mode mode = MIGRATE_SYNC;
+
+	if (list_empty(list))

drivers/iommu/pisa-user.c line 182

Quoted 10 lines
drivers/iommu/pisa-user.c new file +10 -0
+		return;
+	if (to_pisa) {
+		mtc.budget = pisa_user_budget();
+		if (!gfpflags_allow_blocking(gfp))
+			mode = MIGRATE_ASYNC;
+	}
+	if (migrate_pages(list, to_pisa ? pisa_user_new_folio : pisa_user_old_folio,
+			  NULL, (unsigned long)&mtc, mode, MR_SYSCALL, NULL))
+		putback_movable_pages(list);
+}

[Severity: Medium]
Does migrate_pages() corrupt page allocation profiling counters when CONFIG_MEM_ALLOC_PROFILING is enabled?

When a 2MB PISA page is allocated in __pisa_page_alloc() and split in split_page_compound(), pgalloc_tag_split() assigns __pisa_page_alloc()'s alloc_tag to all 512 blocks, and __pisa_free_page() recycles individual blocks without calling pgalloc_tag_sub(). However, migrate_pages() calls folio_migrate_flags() -> pgalloc_tag_swap(dst, src). Migrating a user folio into a PISA block swaps __pisa_page_alloc()'s tag onto the old buddy folio (which is immediately freed, decrementing __pisa_page_alloc()'s tag while the PISA block is still allocated) and places the user folio's tag onto the PISA block, where it is never decremented when __pisa_free_page() recycles the block. Migrating out via MADV_NOPISA similarly leaves pisa_user_old_folio()'s tag stranded on the recycled PISA block.

[ ... ]

Quoted 21 lines
drivers/iommu/pisa-user.c new file +21 -0
+int pisa_madvise(struct vm_area_struct *vma, unsigned long start, unsigned long end, bool to_pisa)
+{
+	gfp_t gfp = GFP_USER | __GFP_NOWARN;
+	struct folio_walk fw;
+	unsigned long addr;
+	unsigned int n = 0;
+	LIST_HEAD(list);
+
+	if (vma->vm_flags & (VM_SHARED | VM_IO | VM_PFNMAP | VM_HUGETLB))
+		return -EINVAL;
+	if (to_pisa && !pisa_user_init())
+		return -EOPNOTSUPP;
+	lru_add_drain();
+	for (addr = start; addr < end; addr += PAGE_SIZE) {
+		struct folio *folio = folio_walk_start(&fw, vma, addr, 0);
+
+		if (folio) {
+			if (pisa_user_want(folio, to_pisa) && !pisa_user_busy(folio, 0) &&
+			    isolate_folio_to_list(folio, &list))
+				n++;
+			folio_walk_end(&fw, vma);

drivers/iommu/pisa-user.c line 278

Quoted 10 lines
drivers/iommu/pisa-user.c new file +10 -0
+		}
+		if (n == PISA_USER_BATCH) {
+			pisa_user_migrate(&list, to_pisa, gfp);
+			n = 0;
+		}
+		cond_resched();
+	}
+	pisa_user_migrate(&list, to_pisa, gfp);
+	return 0;
+}

[Severity: High]
Can an unprivileged user stall a task in an unkillable loop holding mmap_read_lock by calling madvise(MADV_NOPISA) or madvise(MADV_PISA) on a multi-terabyte unpopulated anonymous mapping?

Unlike walk_page_range_vma(), which skips empty PGD, P4D, PUD, and PMD entries at once, this loop steps by PAGE_SIZE across the entire [start, end) range and calls folio_walk_start() on every 4KB address without checking fatal_signal_pending(), and MADV_NOPISA reaches it even when pisa.user_max_4K_pages is 0. Using walk_page_range_vma() or checking pisa_user_enabled() and fatal_signal_pending() would avoid walking empty page table levels and allow SIGKILL to abort the walk.

include/uapi/asm-generic/mman-common.h line 85

Quoted 10 lines
include/uapi/asm-generic/mman-common.h +2 -0
index ef1c27fa3c570..c4332db8e56ff 100644
@@ -81,6 +81,8 @@
 
 #define MADV_GUARD_INSTALL 102		/* fatal signal on access to range */
 #define MADV_GUARD_REMOVE 103		/* unguard range */
+#define MADV_PISA		210	/* move pages into PISA memory */
+#define MADV_NOPISA		211	/* move pages out of PISA memory */

[Severity: High]
Does mm/madvise.c fail to build on alpha, mips, parisc, and xtensa?

Those four architectures do not include asm-generic/mman-common.h in their arch/*/include/uapi/asm/mman.h headers, while mm/madvise.c references MADV_PISA and MADV_NOPISA unconditionally.

Quoted 4 lines
net/core/datagram.c +0 -0
index ecc30a6f83023..40f20d0faa859 100644

[ ... ]

Quoted 21 lines
net/core/datagram.c +21 -0
+static bool pisa_zc_iter(int *ret, struct sk_buff *skb, struct iov_iter *from, size_t *length,
+			 const struct sock *sk, struct page **pages, int max_pages,
+			 unsigned int orig_len, size_t *start, ssize_t *copied)
+{
+	unsigned int i, nr;
+	ssize_t keep;
+
+	if (!pisa_user_enabled() || !user_backed_iter(from))
+		return false;
+
+	/* Move user pages into PISA memory, then look them up again. */
+	if (pisa_upgrade_user_pages(pages, DIV_ROUND_UP(*start + *copied, PAGE_SIZE))) {
+		iov_iter_revert(from, *copied);
+		*copied = iov_iter_get_pages2(from, pages, *length, max_pages, start);
+		if (*copied < 0) {
+			*ret = -EFAULT;
+			return true;
+		}
+	}
+
+	/* Only TCP (which sets skb->sk at transmit time) handles short appends/-EXDEV. */

net/core/datagram.c int skb_copy_datagram_from_iter_full(struct sk_buff *skb, int offset, · line 673

Quoted 10 lines
net/core/datagram.c +10 -0
+	if (!sk || skb->sk)
+		return false;
+
+	/* Only plain MSG_ZEROCOPY ubufs (not io_uring/vhost/devmem). */
+	if (skb_zcopy(skb) && skb_zcopy(skb)->ops != &msg_zerocopy_ubuf_ops)
+		return false;
+
+	/* Egress device must have pisa_tx_bufs enabled so the copy uses a PISA page_frag. */
+	if (!dst_tx_pisa_ok(__sk_dst_get(sk)))
+		return false;

[Severity: Medium]
Should pisa_zc_iter() check sk and dst_tx_pisa_ok(__sk_dst_get(sk)) before calling pisa_upgrade_user_pages()?

Calling pisa_upgrade_user_pages() first migrates user pages into PISA even when the egress device has pisa_tx_bufs disabled, when sending over loopback or virtual devices, or when the socket is routed over IPsec (where __dst_tx_pisa_ok() excludes dst_xfrm(dst) to keep plaintext out of shared 2MB PISA pages). Because __iommu_dma_map() checks is_pisa_phys() rather than dev->pisa_tx_bufs, migrating pages on a device with pisa_tx_bufs disabled also causes pisa_map_phys() to install 2MB PISA IOMMU mappings on that device.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=18
#148 lore raw

RFC PATCH v2 19/25 iommu/dma: Stop recycling old PISA pages when allocator waste is high

In reply to Luigi Rizzo

When a PISA allocator holds many partially used 2MB pages with low overall utilization, callers that recycle blocks in place (page_pool, per-task TX page_frags, and per-CPU block caches) can keep old 2MB pages pinned indefinitely with only a few blocks in use.

Record @alloc_jiffies in struct pisa_meta when a 2MB page is bound to an allocator or taken from the allocator's idle list, and add two module parameters:
- pisa.wasted_pct (1..99%, 0 disables): wasted block percentage threshold above which compaction kicks in.
- pisa.old_ms (1..100000 ms, 0 disables): age threshold after which a partially used 2MB page is eligible to stop recycling.

When both parameters are set and an allocator's wasted block fraction exceeds wasted_pct, pisa_page_can_recycle() returns false for partial 2MB pages older than old_ms (except the head page actively being filled).

---
 drivers/iommu/pisa-alloc.c | 48 ++++++++++++++++++++++++++++++++------
 drivers/iommu/pisa-priv.h  |  2 ++
 2 files changed, 43 insertions(+), 7 deletions(-)
drivers/iommu/pisa-alloc.c +41 -7
index 1930135880d2b..5054a96f0f4e9 100644
@@ -74,6 +74,14 @@ module_param_named(idle_ms, pisa_idle_ms, uint, 0644);
 static unsigned int pisa_compact __read_mostly;
 module_param_named(compact, pisa_compact, uint, 0644);
 
+/* Stop recycling partial pages older than @pisa_old_ms when wasted blocks > @pisa_wasted_pct%. */
+#define PISA_OLD_MS_MAX		100000U
+static unsigned int pisa_wasted_pct __read_mostly;
+module_param_named(wasted_pct, pisa_wasted_pct, uint, 0644);
+
+static unsigned int pisa_old_ms __read_mostly;
+module_param_named(old_ms, pisa_old_ms, uint, 0644);
+
 /* Max pages zeroed in each scrubber run (0 = disabled, capped at PISA_SCRUB_MAX_LIMIT). */
 unsigned int pisa_scrub_max __read_mostly;
 #define PISA_SCRUB_MAX_LIMIT	65536U
@@ -399,6 +407,7 @@ static struct pisa_meta *pisa_pick_dirty_meta(struct pisa_alloc *pa)
 		meta = list_last_entry(&pa->idle, struct pisa_meta, list);
 		if (meta->nr_dirty) {
 			pa->num_idle_pages--;
+			WRITE_ONCE(meta->alloc_jiffies, jiffies);
 			return meta;
 		}
 	}
@@ -603,7 +612,7 @@ static void pisa_return_block_locked(struct pisa_alloc *pa, struct page *block,
  * pisa_page_can_recycle - Check if a block can stay cached in a caller pool
  * @page: Block head page
  *
- * Called on the recycle fast path (per-CPU cache, TX page_frag, page_pool).
+ * Called on the recycle fast path (per-CPU cache, TX page_frag).
  * Fast-path cost is a static-key branch plus a READ_ONCE() of module parameters
  * (~1-2 ns when compaction is off); when enabled, it does a lockless RCU +
  * metadata array lookup (~5-10 ns).
@@ -613,10 +622,11 @@ static void pisa_return_block_locked(struct pisa_alloc *pa, struct page *block,
  */
 bool pisa_page_can_recycle(const struct page *page)
 {
-	unsigned long bpp, in_use, free_blocks, pfn;
+	unsigned int compact, wasted_pct, old_ms;
+	unsigned long bpp, in_use, free_blocks;
 	const struct pisa_meta *meta;
 	const struct pisa_alloc *pa;
-	unsigned int compact;
+	unsigned long pfn;
 	bool ret = true;
 	u8 on_list;
 	long held;
@@ -625,7 +635,9 @@ bool pisa_page_can_recycle(const struct page *page)
 		return true;
 
 	compact = READ_ONCE(pisa_compact);
-	if (!compact)
+	wasted_pct = READ_ONCE(pisa_wasted_pct);
+	old_ms = READ_ONCE(pisa_old_ms);
+	if (!compact && (!wasted_pct || !old_ms))
 		return true;
 
 	pfn = page_to_pfn(page);
@@ -638,6 +650,13 @@ bool pisa_page_can_recycle(const struct page *page)
 	if (on_list == PISA_LIST_FULL || on_list == PISA_LIST_NONE)
 		goto out;
 
+	if (!compact) {
+		unsigned long max_age = msecs_to_jiffies(min(old_ms, PISA_OLD_MS_MAX));
+
+		if (!time_after(jiffies, READ_ONCE(meta->alloc_jiffies) + max_age))
+			goto out;
+	}
+
 	pa = meta->pa;
 	if (!pa)
 		goto out;
@@ -657,12 +676,21 @@ bool pisa_page_can_recycle(const struct page *page)
 	free_blocks = held > 0 && (unsigned long)held * bpp > in_use ?
 		      (unsigned long)held * bpp - in_use : 0;
 
-	ret = free_blocks <= (unsigned long)compact * bpp;
+	if (compact && free_blocks > (unsigned long)compact * bpp) {
+		ret = false;
+		goto out;
+	}
+	if (wasted_pct && old_ms && held > 0 &&
+	    free_blocks * 100 > (unsigned long)held * bpp * wasted_pct) {
+		unsigned long max_age = msecs_to_jiffies(min(old_ms, PISA_OLD_MS_MAX));
+
+		ret = !time_after(jiffies, READ_ONCE(meta->alloc_jiffies) + max_age);
+	}
 out:
 	rcu_read_unlock();
 	return ret;
 }
-EXPORT_SYMBOL_GPL(pisa_page_can_recycle);
+EXPORT_SYMBOL(pisa_page_can_recycle);
 
 /* Return @n freed blocks to @pa under a single acquisition of @pa->lock. */
 static void pisa_free_bulk(struct pisa_alloc *pa, struct page **blocks, unsigned int n)
@@ -1195,6 +1223,7 @@ static struct pisa_meta *pisa_pick_meta(struct pisa_alloc *pa, bool zero)
 		meta = list_first_entry_or_null(&pa->idle, struct pisa_meta, list);
 		if (meta && meta->nr_clean) {
 			pa->num_idle_pages--;
+			WRITE_ONCE(meta->alloc_jiffies, jiffies);
 			WRITE_ONCE(pa->idle_jiffies, jiffies);
 			return meta;
 		}
@@ -1218,6 +1247,7 @@ static struct pisa_meta *pisa_pick_meta(struct pisa_alloc *pa, bool zero)
 	if (!list_empty(&pa->idle)) {
 		meta = list_last_entry(&pa->idle, struct pisa_meta, list);
 		pa->num_idle_pages--;
+		WRITE_ONCE(meta->alloc_jiffies, jiffies);
 		WRITE_ONCE(pa->idle_jiffies, jiffies);
 		return meta;
 	}
@@ -1287,6 +1317,7 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 		spin_lock_irqsave(&pa->lock, flags);
 		meta->pa = pa;
 		meta->prot = pa->prot;
+		WRITE_ONCE(meta->alloc_jiffies, jiffies);
 		/* Set PISA_ACTIVE after @meta is fully set up. */
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
 		pa->stats.page_alloc_cnt++;
@@ -1454,8 +1485,10 @@ static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock
 	}
 
 	if (meta->on_list == PISA_LIST_IDLE_CLEAN ||
-	    meta->on_list == PISA_LIST_IDLE_DIRTY)
+	    meta->on_list == PISA_LIST_IDLE_DIRTY) {
 		pa->num_idle_pages--;
+		WRITE_ONCE(meta->alloc_jiffies, jiffies);
+	}
 
 	for (i = 0; i < nblocks; i++) {
 		if (__test_and_clear_bit(off + i, meta->clean_bitmap)) {
@@ -1544,6 +1577,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		spin_lock_irqsave(&pa->lock, flags);
 		meta->pa = pa;
 		meta->prot = pa->prot;
+		WRITE_ONCE(meta->alloc_jiffies, jiffies);
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
 		pa->stats.page_alloc_cnt++;
 		page = pisa_take_contig(meta, nblocks, align_mask);
drivers/iommu/pisa-priv.h +2 -0
index fe1bff0bba322..4d04bb191ecea 100644
@@ -74,6 +74,7 @@ enum {
  * @list:	Node in @pa lists or per-node reservoir (pisa_node.pages)
  * @llnode:	Node in lockless pisa_free_list for async release to the buddy allocator
  * @rcu:	RCU head used to defer release to the buddy allocator
+ * @alloc_jiffies: Timestamp (jiffies) when the page entered or re-entered use
  * @clean_bitmap: Bitmap of zeroed available block indices
  * @dirty_bitmap: Bitmap of dirty available block indices
  */
@@ -94,6 +95,7 @@ struct pisa_meta {
 		struct llist_node llnode;
 		struct rcu_head rcu;
 	};
+	unsigned long alloc_jiffies;
 
 	DECLARE_BITMAP(clean_bitmap, PISA_MAX_BLOCKS) ____cacheline_aligned;
 	DECLARE_BITMAP(dirty_bitmap, PISA_MAX_BLOCKS) ____cacheline_aligned;
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#149 lore raw

Re: [RFC PATCH v2 19/25] iommu/dma: Stop recycling old PISA pages when allocator waste is high

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [Medium] iommu/dma: unsafe list traversal in pisa_alloc_coherent() on list move - [Low] iommu/dma: missing…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [Medium] iommu/dma: unsafe list traversal in pisa_alloc_coherent() on list move
- [Low] iommu/dma: missing range check on wasted_pct in pisa_page_can_recycle()
- [Low] iommu/dma: unexplained EXPORT_SYMBOL change on pisa_page_can_recycle()
- [Low] iommu/dma: missing alloc_jiffies update in pisa_take_contig() error path
- [Low] iommu/dma: undocumented pisa.wasted_pct and pisa.old_ms boot parameters
--

commit b3ebe7c969492f612816f0a66cbeefb1c30a4e84
Author: Luigi Rizzo <[email protected]>

iommu/dma: Stop recycling old PISA pages when allocator waste is high

This commit records an allocation timestamp in struct pisa_meta and adds the pisa.wasted_pct and pisa.old_ms parameters so pisa_page_can_recycle() stops recycling blocks from old partially used 2MB pages when allocator waste exceeds the threshold.

Quoted 6 lines
drivers/iommu/pisa-alloc.c +0 -0
index 1930135880d2b..5054a96f0f4e9 100644
@@ -74,6 +74,14 @@ module_param_named(idle_ms, pisa_idle_ms, uint, 0644);
 static unsigned int pisa_compact __read_mostly;

drivers/iommu/pisa-alloc.c module_param_named(idle_ms, pisa_idle_ms, uint, 0644); · line 84

Quoted 10 lines
drivers/iommu/pisa-alloc.c +8 -0
 module_param_named(compact, pisa_compact, uint, 0644);
 
+/* Stop recycling partial pages older than @pisa_old_ms when wasted blocks > @pisa_wasted_pct%. */
+#define PISA_OLD_MS_MAX		100000U
+static unsigned int pisa_wasted_pct __read_mostly;
+module_param_named(wasted_pct, pisa_wasted_pct, uint, 0644);
+
+static unsigned int pisa_old_ms __read_mostly;
+module_param_named(old_ms, pisa_old_ms, uint, 0644);
+

[Severity: Low]
Since CONFIG_PISA is a bool Kconfig symbol, pisa.wasted_pct and pisa.old_ms are built-in kernel command-line parameters. Should they be documented in Documentation/admin-guide/kernel-parameters.txt (with their format, valid ranges, behavior, and architecture constraints)? The later commit "Documentation: Add PISA architecture documentation" in this series lists their names under pisa.*=, but neither kernel-parameters.txt nor Documentation/core-api/pisa.rst describes what they control or their expected ranges.

[ ... ]

Quoted 53 lines
drivers/iommu/pisa-alloc.c +14 -5
@@ -603,7 +612,7 @@ static void pisa_return_block_locked(struct pisa_alloc *pa, struct page *block,
  * pisa_page_can_recycle - Check if a block can stay cached in a caller pool
  * @page: Block head page
  *
- * Called on the recycle fast path (per-CPU cache, TX page_frag, page_pool).
+ * Called on the recycle fast path (per-CPU cache, TX page_frag).
  * Fast-path cost is a static-key branch plus a READ_ONCE() of module parameters
  * (~1-2 ns when compaction is off); when enabled, it does a lockless RCU +
  * metadata array lookup (~5-10 ns).
@@ -613,10 +622,11 @@ static void pisa_return_block_locked(struct pisa_alloc *pa, struct page *block,
  */
 bool pisa_page_can_recycle(const struct page *page)
 {
-	unsigned long bpp, in_use, free_blocks, pfn;
+	unsigned int compact, wasted_pct, old_ms;
+	unsigned long bpp, in_use, free_blocks;
 	const struct pisa_meta *meta;
 	const struct pisa_alloc *pa;
-	unsigned int compact;
+	unsigned long pfn;
 	bool ret = true;
 	u8 on_list;
 	long held;
@@ -625,7 +635,9 @@ bool pisa_page_can_recycle(const struct page *page)
 		return true;
 
 	compact = READ_ONCE(pisa_compact);
-	if (!compact)
+	wasted_pct = READ_ONCE(pisa_wasted_pct);
+	old_ms = READ_ONCE(pisa_old_ms);
+	if (!compact && (!wasted_pct || !old_ms))
 		return true;
 
 	pfn = page_to_pfn(page);
@@ -638,6 +650,13 @@ bool pisa_page_can_recycle(const struct page *page)
 	if (on_list == PISA_LIST_FULL || on_list == PISA_LIST_NONE)
 		goto out;
 
+	if (!compact) {
+		unsigned long max_age = msecs_to_jiffies(min(old_ms, PISA_OLD_MS_MAX));
+
+		if (!time_after(jiffies, READ_ONCE(meta->alloc_jiffies) + max_age))
+			goto out;
+	}
+
 	pa = meta->pa;
 	if (!pa)
 		goto out;
@@ -657,12 +676,21 @@ bool pisa_page_can_recycle(const struct page *page)
 	free_blocks = held > 0 && (unsigned long)held * bpp > in_use ?
 		      (unsigned long)held * bpp - in_use : 0;
 
-	ret = free_blocks <= (unsigned long)compact * bpp;

drivers/iommu/pisa-alloc.c bool pisa_page_can_recycle(const struct page *page) · line 688

Quoted 10 lines
drivers/iommu/pisa-alloc.c +10 -0
+	if (compact && free_blocks > (unsigned long)compact * bpp) {
+		ret = false;
+		goto out;
+	}
+	if (wasted_pct && old_ms && held > 0 &&
+	    free_blocks * 100 > (unsigned long)held * bpp * wasted_pct) {
+		unsigned long max_age = msecs_to_jiffies(min(old_ms, PISA_OLD_MS_MAX));
+
+		ret = !time_after(jiffies, READ_ONCE(meta->alloc_jiffies) + max_age);
+	}

[Severity: Low]
What happens if pisa_wasted_pct is set to 100 or higher?

Unlike pisa_old_ms, which is clamped to PISA_OLD_MS_MAX, pisa_wasted_pct is registered as an unconstrained uint and used unclamped. Setting wasted_pct >= 100 bypasses the early return in pisa_page_can_recycle() and runs the RCU lookup and utilization calculation on every recycle check, even though free_blocks * 100 > held * bpp * wasted_pct can never hold (or can overflow unsigned long for large uint values when held * bpp is large, spuriously forcing compaction). Also, when compact == 0, the earlier !compact block has already verified time_after(jiffies, meta->alloc_jiffies
+ max_age), so recomputing max_age and time_after() here is redundant on that path.

drivers/iommu/pisa-alloc.c bool pisa_page_can_recycle(const struct page *page) · line 693

Quoted 6 lines
drivers/iommu/pisa-alloc.c +1 -1
 out:
 	rcu_read_unlock();
 	return ret;
 }
-EXPORT_SYMBOL_GPL(pisa_page_can_recycle);
+EXPORT_SYMBOL(pisa_page_can_recycle);

[Severity: Low]
Was changing EXPORT_SYMBOL_GPL() to EXPORT_SYMBOL() on pisa_page_can_recycle() intentional? The commit message does not mention dropping the GPL restriction, and it still lists page_pool as a caller governed by pisa_page_can_recycle() even though the kernel-doc update above removes page_pool.

[ ... ]

drivers/iommu/pisa-alloc.c static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock · line 1491

Quoted 9 lines
drivers/iommu/pisa-alloc.c +3 -1
@@ -1454,8 +1485,10 @@ static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock
 	}
 
 	if (meta->on_list == PISA_LIST_IDLE_CLEAN ||
-	    meta->on_list == PISA_LIST_IDLE_DIRTY)
+	    meta->on_list == PISA_LIST_IDLE_DIRTY) {
 		pa->num_idle_pages--;
+		WRITE_ONCE(meta->alloc_jiffies, jiffies);
+	}

[Severity: Low]
Should the poisoned fallback path earlier in pisa_take_contig() also update meta->alloc_jiffies when moving an idle page onto a partial list?

drivers/iommu/pisa-alloc.c:pisa_take_contig() {
    ...
		if (off >= bpp) {
			if (poisoned) {
				if (meta->on_list == PISA_LIST_IDLE_CLEAN ||
				    meta->on_list == PISA_LIST_IDLE_DIRTY)
					pa->num_idle_pages--;
				pisa_place_meta(meta);
			}
			return NULL;
		}
    ...
}

If pisa_take_contig() isolates a poisoned block on an idle page and then fails to find nblocks contiguous blocks, pisa_place_meta() moves meta from pa->idle onto pa->partial or pa->partial_dirty without setting meta->alloc_jiffies. Later allocations from that partial page will not update meta->alloc_jiffies, leaving a stale timestamp from the page's previous use and causing pisa_page_can_recycle() to treat blocks allocated from it as already expired.

[ ... ]

drivers/iommu/pisa-alloc.c void *pisa_alloc_coherent(struct page **pagep, struct device *dev, · line 1583

Quoted 8 lines
drivers/iommu/pisa-alloc.c +1 -0
@@ -1544,6 +1577,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		spin_lock_irqsave(&pa->lock, flags);
 		meta->pa = pa;
 		meta->prot = pa->prot;
+		WRITE_ONCE(meta->alloc_jiffies, jiffies);
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
 		pa->stats.page_alloc_cnt++;
 		page = pisa_take_contig(meta, nblocks, align_mask);

[Severity: Medium]
Can the list_for_each_entry() loop just above this in pisa_alloc_coherent() walk off into the wrong list if pisa_take_contig() encounters a poisoned block and returns NULL?

drivers/iommu/pisa-alloc.c:pisa_alloc_coherent() {
    ...
	for (i = 0; i < ARRAY_SIZE(lists) && !page; i++) {
		list_for_each_entry(meta, lists[i], list) {
			page = pisa_take_contig(meta, nblocks, align_mask);
			if (page)
				break;
		}
	}
    ...
}

When pisa_take_contig() hits a poisoned block and fails to find nblocks contiguous blocks (off >= bpp), it calls pisa_place_meta(meta) and returns NULL. pisa_place_meta() relinks &meta->list onto a different list head in struct pisa_alloc (for example from pa->idle to pa->partial, or from pa->partial to pa->partial_dirty). Because list_for_each_entry() only breaks when page is non-NULL, it then follows meta->list.next along the new list while checking for termination against lists[i], walking past the new list's head in struct pisa_alloc and dereferencing struct pisa_alloc as a struct pisa_meta. This was introduced earlier in this series in commit "iommu/dma: Add PISA block allocation"; using list_for_each_entry_safe() fixes the traversal.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
#150 lore raw

RFC PATCH v2 20/25 net/libeth: Use GFP_KERNEL when pre-filling RX rings

In reply to Luigi Rizzo

libeth_rx_alloc() is called both when pre-filling RX fill queues in process context (for indices 0 .. fq->count - 2, when buf->truesize is still 0) and when refilling RX buffers from NAPI softirq.

Use GFP_KERNEL during the initial process-context ring fill so page_pool and PISA page allocations (including set_memory_decrypted() under CoCo) are not forced into GFP_ATOMIC context.

---
 include/net/libeth/rx.h | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
include/net/libeth/rx.h +9 -2
index 0e736846c5e8a..de1e5fe44aa40 100644
@@ -106,10 +106,17 @@ void libeth_rx_fq_destroy(struct libeth_fq *fq);
 static inline dma_addr_t libeth_rx_alloc(const struct libeth_fq_fp *fq, u32 i)
 {
 	struct libeth_fqe *buf = &fq->fqes[i];
+	/* fq->fqes is zero-allocated and pre-filled in process context for
+	 * indices [0 .. fq->count - 2]; slot fq->count - 1 is first allocated
+	 * in NAPI. Use GFP_KERNEL for initial pre-fill and GFP_ATOMIC after.
+	 */
+	gfp_t gfp = (buf->truesize || i == fq->count - 1) ?
+		    GFP_ATOMIC : GFP_KERNEL;
 
 	buf->truesize = fq->truesize;
-	buf->netmem = page_pool_dev_alloc_netmem(fq->pp, &buf->offset,
-						 &buf->truesize);
+	buf->netmem = page_pool_alloc_netmem(fq->pp, &buf->offset,
+					     &buf->truesize,
+					     gfp | __GFP_NOWARN);
 	if (unlikely(!buf->netmem))
 		return DMA_MAPPING_ERROR;
 
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#151 lore raw

Re: [RFC PATCH v2 20/25] net/libeth: Use GFP_KERNEL when pre-filling RX rings

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] net/libeth: GFP_KERNEL allocation in NAPI softirq in libeth_rx_alloc() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] net/libeth: GFP_KERNEL allocation in NAPI softirq in libeth_rx_alloc()
--

commit 8b7f90733116470d28d79365ee87cd75951698b1
Author: Luigi Rizzo <[email protected]>

net/libeth: Use GFP_KERNEL when pre-filling RX rings

This commit switches libeth_rx_alloc() to use GFP_KERNEL when allocating RX buffers for uninitialized ring slots (where buf->truesize is 0 and i != fq->count - 1) and GFP_ATOMIC afterwards.

Quoted 13 lines
include/net/libeth/rx.h +5 -0
index 0e736846c5e8a..de1e5fe44aa40 100644
@@ -106,10 +106,17 @@ void libeth_rx_fq_destroy(struct libeth_fq *fq);
 static inline dma_addr_t libeth_rx_alloc(const struct libeth_fq_fp *fq, u32 i)
 {
 	struct libeth_fqe *buf = &fq->fqes[i];
+	/* fq->fqes is zero-allocated and pre-filled in process context for
+	 * indices [0 .. fq->count - 2]; slot fq->count - 1 is first allocated
+	 * in NAPI. Use GFP_KERNEL for initial pre-fill and GFP_ATOMIC after.
+	 */
+	gfp_t gfp = (buf->truesize || i == fq->count - 1) ?

include/net/libeth/rx.h void libeth_rx_fq_destroy(struct libeth_fq *fq); · line 121

Quoted 10 lines
include/net/libeth/rx.h +4 -2
+		    GFP_ATOMIC : GFP_KERNEL;
 
 	buf->truesize = fq->truesize;
-	buf->netmem = page_pool_dev_alloc_netmem(fq->pp, &buf->offset,
-						 &buf->truesize);
+	buf->netmem = page_pool_alloc_netmem(fq->pp, &buf->offset,
+					     &buf->truesize,
+					     gfp | __GFP_NOWARN);
 	if (unlikely(!buf->netmem))
 		return DMA_MAPPING_ERROR;

[Severity: High]
Can this allocate with GFP_KERNEL from NAPI softirq context if the initial process-context ring pre-fill fails partway through?

During interface bring-up or reset, iavf_configure() calls iavf_alloc_rx_buffers() to pre-fill indices [0 .. count - 2] and ignores its return value before iavf_up_complete() enables NAPI:

drivers/net/ethernet/intel/iavf/iavf_txrx.c:iavf_alloc_rx_buffers() {
	...
	do {
		addr = libeth_rx_alloc(&fq, ntu);
		if (addr == DMA_MAPPING_ERROR)
			goto no_buffers;
	...
}

If libeth_rx_alloc() fails at index k < fq->count - 2, the loop aborts and leaves fq->fqes[k + 1 .. fq->count - 2].truesize set to 0. When iavf_clean_rx_irq() later calls iavf_alloc_rx_buffers() from NAPI softirq, reaching those remaining unvisited indices will select GFP_KERNEL and sleep in atomic context.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=20
#152 lore raw

RFC PATCH v2 21/25 net/gve: Use GFP_KERNEL when pre-filling RX rings

In reply to Luigi Rizzo

When pre-filling DQO and GQI RX rings in process context before NAPI is enabled (e.g. gve_open), use GFP_KERNEL instead of GFP_ATOMIC so page allocation (and CoCo page decryption) can sleep instead of dipping into atomic reserves.

---
 drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c | 7 ++++++-
 drivers/net/ethernet/google/gve/gve_rx.c              | 8 ++++++--
 2 files changed, 12 insertions(+), 3 deletions(-)
drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c +6 -1
index 6880d1531ba5e..3b13aa4999ae5 100644
@@ -223,13 +223,18 @@ void gve_free_to_page_pool(struct gve_rx_ring *rx,
 static int gve_alloc_from_page_pool(struct gve_rx_ring *rx,
 				    struct gve_rx_buf_state_dqo *buf_state)
 {
+	/*
+	 * Use GFP_KERNEL when pre-filling RX rings in process context (e.g.
+	 * gve_open) so PISA metadata init and CoCo page decryption can sleep.
+	 */
+	gfp_t gfp = gve_get_napi_enabled(rx->gve) ? GFP_ATOMIC : GFP_KERNEL;
 	netmem_ref netmem;
 
 	buf_state->page_info.buf_size = rx->packet_buffer_truesize;
 	netmem = page_pool_alloc_netmem(rx->dqo.page_pool,
 					&buf_state->page_info.page_offset,
 					&buf_state->page_info.buf_size,
-					GFP_ATOMIC);
+					gfp);
 
 	if (!netmem)
 		return -ENOMEM;
drivers/net/ethernet/google/gve/gve_rx.c +6 -2
index 81ea800e66e94..89f287b678bf0 100644
@@ -161,12 +161,16 @@ static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev,
 			       union gve_rx_data_slot *data_slot,
 			       struct gve_rx_ring *rx)
 {
+	/*
+	 * Use GFP_KERNEL when pre-filling RX rings in process context (e.g.
+	 * gve_open) so PISA metadata init and CoCo page decryption can sleep.
+	 */
+	gfp_t gfp = gve_get_napi_enabled(priv) ? GFP_ATOMIC : GFP_KERNEL;
 	struct page *page;
 	dma_addr_t dma;
 	int err;
 
-	err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE,
-			     GFP_ATOMIC);
+	err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE, gfp);
 	if (err) {
 		u64_stats_update_begin(&rx->statss);
 		rx->rx_buf_alloc_fail++;
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#153 lore raw

Re: [RFC PATCH v2 21/25] net/gve: Use GFP_KERNEL when pre-filling RX rings

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] net/gve: sleep-in-atomic GFP_KERNEL alloc in NAPI poll during gve_turnup() - [Medium] net/gve…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] net/gve: sleep-in-atomic GFP_KERNEL alloc in NAPI poll during gve_turnup()
- [Medium] net/gve: gve_rx_alloc_buffer() uses GFP_ATOMIC on live config pre-fill
--

commit 1b07e24554dc827c263c1efbdbd4b2e0d6ee11bf
Author: Luigi Rizzo <[email protected]>

net/gve: Use GFP_KERNEL when pre-filling RX rings

This commit uses GFP_KERNEL instead of GFP_ATOMIC when allocating RX ring buffers in gve_alloc_from_page_pool() and gve_rx_alloc_buffer() while gve_get_napi_enabled() is false.

Quoted 11 lines
drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c +3 -0
index 6880d1531ba5e..3b13aa4999ae5 100644
@@ -223,13 +223,18 @@ void gve_free_to_page_pool(struct gve_rx_ring *rx,
 static int gve_alloc_from_page_pool(struct gve_rx_ring *rx,
 				    struct gve_rx_buf_state_dqo *buf_state)
 {
+	/*
+	 * Use GFP_KERNEL when pre-filling RX rings in process context (e.g.
+	 * gve_open) so PISA metadata init and CoCo page decryption can sleep.

drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c void gve_free_to_page_pool(struct gve_rx_ring *rx, · line 237

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c +3 -1
+	 */
+	gfp_t gfp = gve_get_napi_enabled(rx->gve) ? GFP_ATOMIC : GFP_KERNEL;
 	netmem_ref netmem;
 
 	buf_state->page_info.buf_size = rx->packet_buffer_truesize;
 	netmem = page_pool_alloc_netmem(rx->dqo.page_pool,
 					&buf_state->page_info.page_offset,
 					&buf_state->page_info.buf_size,
-					GFP_ATOMIC);
+					gfp);

[Severity: High]
Can gve_alloc_from_page_pool() (and gve_rx_alloc_buffer() below) be called from NAPI poll with GFP_KERNEL during gve_turnup()?

In gve_turnup(), each RX queue's NAPI is enabled, its IRQ doorbell is unmasked, and napi_schedule() is called inside the per-queue loop before GVE_PRIV_FLAGS_NAPI_ENABLED is set at the end of the function:

drivers/net/ethernet/google/gve/gve_main.c:gve_turnup() {
    ...
	for (i = 0; i < priv->rx_cfg.num_queues; i++) {
        ...
		napi_enable_locked(&block->napi);
        ...
		mb();
		napi_schedule(&block->napi);
	}
    ...
	gve_set_napi_enabled(priv);
}

CPU0 CPU1 (<softirq>)
gve_turnup()
napi_enable_locked(&block->napi)
napi_schedule(&block->napi)

                                  gve_napi_poll_dqo()
                                    gve_rx_poll_dqo()
                                      ...
                                        gve_alloc_from_page_pool()
                                          gve_get_napi_enabled() -> false
                                          page_pool_alloc_netmem(..., GFP_KERNEL)
                                            <-- sleep in atomic context

gve_set_napi_enabled(priv)

If NAPI runs on another CPU or on softirq exit before gve_turnup() finishes the loop and calls gve_set_napi_enabled(priv), refilling buffers from softirq context will use GFP_KERNEL and sleep in atomic context.

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_rx.c +2 -0
index 81ea800e66e94..89f287b678bf0 100644
@@ -161,12 +161,16 @@ static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev,
 			       union gve_rx_data_slot *data_slot,
 			       struct gve_rx_ring *rx)
 {
+	/*
+	 * Use GFP_KERNEL when pre-filling RX rings in process context (e.g.

drivers/net/ethernet/google/gve/gve_rx.c static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev, · line 173

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_rx.c +4 -2
+	 * gve_open) so PISA metadata init and CoCo page decryption can sleep.
+	 */
+	gfp_t gfp = gve_get_napi_enabled(priv) ? GFP_ATOMIC : GFP_KERNEL;
 	struct page *page;
 	dma_addr_t dma;
 	int err;
 
-	err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE,
-			     GFP_ATOMIC);
+	err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE, gfp);

[Severity: Medium]
Does gve_rx_alloc_buffer() still select GFP_ATOMIC when pre-filling GQI RX rings on a running interface?

When reconfiguring queues or ring sizes on a live device, gve_adjust_config() calls gve_queues_mem_alloc() -> gve_rx_alloc_rings_gqi() -> gve_rx_alloc_ring_gqi() -> gve_rx_prefill_pages() before calling gve_close() to turn down the device and clear GVE_PRIV_FLAGS_NAPI_ENABLED (and similarly in gve_rx_queue_mem_alloc()). Because gve_get_napi_enabled() is still true during this process-context pre-fill, gve_rx_alloc_buffer() falls back to GFP_ATOMIC and can still exhaust atomic reserves or fail allocation. Passing a gfp_t parameter explicitly from the pre-fill vs NAPI refill callers would avoid depending on GVE_PRIV_FLAGS_NAPI_ENABLED for both issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
#154 lore raw

RFC PATCH v2 22/25 net/gve: Use PISA memory for RX buffers

In reply to Luigi Rizzo

When dev->pisa_rx_bufs is enabled, allocate GQI-RDA RX packet buffers with pisa_rx_gfp(dev) so they come from the per-node PISA allocator, and evict plain pages when a free PISA RX block is available; DQO-RDA uses page_pool, which checks dev->pisa_rx_bufs directly.

---
 drivers/net/ethernet/google/gve/gve_rx.c | 32 ++++++++++++++++--------
 1 file changed, 22 insertions(+), 10 deletions(-)
drivers/net/ethernet/google/gve/gve_rx.c +22 -10
index 89f287b678bf0..85c243bbdeb33 100644
@@ -4,6 +4,7 @@
  * Copyright (C) 2015-2021 Google, Inc.
  */
 
+#include <linux/pisa.h>
 #include "gve.h"
 #include "gve_adminq.h"
 #include "gve_utils.h"
@@ -170,6 +171,8 @@ static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev,
 	dma_addr_t dma;
 	int err;
 
+	if (rx->data.raw_addressing)
+		gfp |= pisa_rx_gfp(dev);
 	err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE, gfp);
 	if (err) {
 		u64_stats_update_begin(&rx->statss);
@@ -499,13 +502,19 @@ static void gve_rx_flip_buff(struct gve_rx_slot_page_info *page_info, __be64 *sl
 	*(slot_addr) ^= offset;
 }
 
-static int gve_rx_can_recycle_buffer(struct gve_rx_slot_page_info *page_info)
+static int gve_rx_can_recycle_buffer(struct gve_rx_ring *rx,
+				     struct gve_rx_slot_page_info *page_info)
 {
 	int pagecount = page_count(page_info->page);
 
 	/* This page is not being used by any SKBs - reuse */
-	if (pagecount == page_info->pagecnt_bias)
+	if (pagecount == page_info->pagecnt_bias) {
+		if (rx && rx->data.raw_addressing &&
+		    !is_pisa_page(page_info->page) &&
+		    pisa_has_free_blocks_rx(&rx->gve->pdev->dev, 0, rx->gve->numa_node))
+			return 0;
 		return 1;
+	}
 	/* This page is still being used by an SKB - we can't reuse */
 	else if (pagecount > page_info->pagecnt_bias)
 		return 0;
@@ -549,7 +558,7 @@ static struct sk_buff *gve_rx_copy_to_pool(struct gve_rx_ring *rx,
 
 	copy_page_info = &rx->qpl_copy_pool[pool_idx];
 	if (!copy_page_info->can_flip) {
-		int recycle = gve_rx_can_recycle_buffer(copy_page_info);
+		int recycle = gve_rx_can_recycle_buffer(NULL, copy_page_info);
 
 		if (unlikely(recycle < 0)) {
 			gve_schedule_reset(rx->gve);
@@ -669,7 +678,7 @@ static struct sk_buff *gve_rx_skb(struct gve_priv *priv, struct gve_rx_ring *rx,
 			u64_stats_update_end(&rx->statss);
 		}
 	} else {
-		int recycle = gve_rx_can_recycle_buffer(page_info);
+		int recycle = gve_rx_can_recycle_buffer(rx, page_info);
 
 		if (unlikely(recycle < 0)) {
 			gve_schedule_reset(priv);
@@ -975,7 +984,7 @@ static bool gve_rx_refill_buffers(struct gve_priv *priv, struct gve_rx_ring *rx)
 			 * owns half the page it is impossible to tell which half. Either
 			 * the whole page is free or it needs to be replaced.
 			 */
-			int recycle = gve_rx_can_recycle_buffer(page_info);
+			int recycle = gve_rx_can_recycle_buffer(rx, page_info);
 
 			if (recycle < 0) {
 				if (!rx->data.raw_addressing)
@@ -987,12 +996,15 @@ static bool gve_rx_refill_buffers(struct gve_priv *priv, struct gve_rx_ring *rx)
 				union gve_rx_data_slot *data_slot =
 						&rx->data.data_ring[idx];
 				struct device *dev = &priv->pdev->dev;
-				gve_rx_free_buffer(dev, page_info, data_slot);
-				page_info->page = NULL;
-				if (gve_rx_alloc_buffer(priv, dev, page_info,
-							data_slot, rx)) {
+				struct gve_rx_slot_page_info new_info;
+				union gve_rx_data_slot new_slot;
+
+				if (gve_rx_alloc_buffer(priv, dev, &new_info,
+							&new_slot, rx))
 					break;
-				}
+				gve_rx_free_buffer(dev, page_info, data_slot);
+				*page_info = new_info;
+				*data_slot = new_slot;
 			}
 		}
 		fill_cnt++;
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#155 lore raw

Re: [RFC PATCH v2 22/25] net/gve: Use PISA memory for RX buffers

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] net/gve: wrong GFP flags in gve_rx_alloc_buffer() via gve_get_napi_enabled() - [Medium] net/gve…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] net/gve: wrong GFP flags in gve_rx_alloc_buffer() via gve_get_napi_enabled()
- [Medium] net/gve: uninitialized new_info.can_flip copied in gve_rx_refill_buffers()
--

commit 58fd34b0315f121e3fcc6437dac09650326d6a54
Author: Luigi Rizzo <[email protected]>

net/gve: Use PISA memory for RX buffers

This commit allocates GQI-RDA RX packet buffers with pisa_rx_gfp(dev) when PISA RX buffers are enabled, and replaces plain pages when free PISA RX blocks are available.

Quoted 30 lines
drivers/net/ethernet/google/gve/gve_rx.c +5 -1
index 89f287b678bf0..85c243bbdeb33 100644
@@ -4,6 +4,7 @@
  * Copyright (C) 2015-2021 Google, Inc.
  */
 
+#include <linux/pisa.h>
 #include "gve.h"
 #include "gve_adminq.h"
 #include "gve_utils.h"
@@ -170,6 +171,8 @@ static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev,
 	dma_addr_t dma;
 	int err;
 
+	if (rx->data.raw_addressing)
+		gfp |= pisa_rx_gfp(dev);
 	err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE, gfp);
 	if (err) {
 		u64_stats_update_begin(&rx->statss);
@@ -499,13 +502,19 @@ static void gve_rx_flip_buff(struct gve_rx_slot_page_info *page_info, __be64 *sl
 	*(slot_addr) ^= offset;
 }
 
-static int gve_rx_can_recycle_buffer(struct gve_rx_slot_page_info *page_info)
+static int gve_rx_can_recycle_buffer(struct gve_rx_ring *rx,
+				     struct gve_rx_slot_page_info *page_info)
 {
 	int pagecount = page_count(page_info->page);

drivers/net/ethernet/google/gve/gve_rx.c static void gve_rx_flip_buff(struct gve_rx_slot_page_info *page_info, __be64 *sl · line 517

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_rx.c +6 -1
 
 	/* This page is not being used by any SKBs - reuse */
-	if (pagecount == page_info->pagecnt_bias)
+	if (pagecount == page_info->pagecnt_bias) {
+		if (rx && rx->data.raw_addressing &&
+		    !is_pisa_page(page_info->page) &&
+		    pisa_has_free_blocks_rx(&rx->gve->pdev->dev, 0, rx->gve->numa_node))
+			return 0;
 		return 1;
+	}

[Severity: High]
Can gve_rx_alloc_buffer() sleep in softirq context or pass GFP_ATOMIC in process context when selecting GFP flags via gve_get_napi_enabled(priv)?

In gve_turnup(), NAPI is enabled, IRQs are unmasked, and napi_schedule() is called on all RX queues before gve_set_napi_enabled(priv) runs:

drivers/net/ethernet/google/gve/gve_main.c:gve_turnup() {
    ...
		napi_enable_locked(&block->napi);
		netif_queue_set_napi(priv->dev, idx, NETDEV_QUEUE_TYPE_RX,
				     &block->napi);
    ...
		mb();
		napi_schedule(&block->napi);
	}

	if (priv->tx_cfg.num_xdp_queues && gve_supports_xdp_xmit(priv))
		xdp_features_set_redirect_target_locked(priv->dev, false);

	gve_set_napi_enabled(priv);
}

With gve_rx_can_recycle_buffer() returning 0 to evict non-PISA pages even when pagecount == pagecnt_bias, a NAPI poll running before gve_set_napi_enabled(priv) reaches gve_rx_refill_buffers() -> gve_rx_alloc_buffer() while gve_get_napi_enabled(priv) is still false. That passes GFP_KERNEL | __GFP_PISA_RW in softirq context, allowing the page allocator or PISA metadata initialization and page decryption to sleep in atomic context.

Conversely, gve_adjust_config() -> gve_queues_mem_alloc() and gve_rx_queue_mem_alloc() pre-fill new RX rings in process context while the interface is up and gve_get_napi_enabled(priv) is true, passing GFP_ATOMIC | __GFP_PISA_RW and preventing PISA from blocking to initialize metadata or decrypt pages.

Passing an explicit gfp_t parameter from gve_rx_prefill_pages() (GFP_KERNEL) and gve_rx_refill_buffers() (GFP_ATOMIC) into gve_rx_alloc_buffer() would avoid relying on gve_get_napi_enabled(priv).

[ ... ]

Quoted 11 lines
drivers/net/ethernet/google/gve/gve_rx.c +3 -4
@@ -987,12 +996,15 @@ static bool gve_rx_refill_buffers(struct gve_priv *priv, struct gve_rx_ring *rx)
 				union gve_rx_data_slot *data_slot =
 						&rx->data.data_ring[idx];
 				struct device *dev = &priv->pdev->dev;
-				gve_rx_free_buffer(dev, page_info, data_slot);
-				page_info->page = NULL;
-				if (gve_rx_alloc_buffer(priv, dev, page_info,
-							data_slot, rx)) {
+				struct gve_rx_slot_page_info new_info;
+				union gve_rx_data_slot new_slot;
+

drivers/net/ethernet/google/gve/gve_rx.c static bool gve_rx_refill_buffers(struct gve_priv *priv, struct gve_rx_ring *rx) · line 1010

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_rx.c +5 -1
+				if (gve_rx_alloc_buffer(priv, dev, &new_info,
+							&new_slot, rx))
 					break;
-				}
+				gve_rx_free_buffer(dev, page_info, data_slot);
+				*page_info = new_info;
+				*data_slot = new_slot;
 			}
 		}
 		fill_cnt++;

[Severity: Medium]
Does copying new_info into *page_info overwrite page_info->can_flip with uninitialized stack memory?

new_info is declared on the stack without initialization, and gve_rx_alloc_buffer() -> gve_setup_rx_buffer() only initializes page, page_offset, page_address, buf_size, and pagecnt_bias, leaving can_flip (and pad) untouched. Previously, page_info was zero-allocated and this branch was only entered when page_info->can_flip was 0.

When the next packet received into this slot takes the copybreak path in gve_rx_skb(), a non-XDP_PASS verdict, or a drop path in gve_rx(), page_info->can_flip is not updated, so the following gve_rx_refill_buffers() pass checks an uninitialized page_info->can_flip and can spuriously flip the buffer instead of checking whether it can be recycled.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
#156 lore raw

RFC PATCH v2 23/25 block, mm, iommu/dma: Support PISA for disk I/O and scrub migration

In reply to Luigi Rizzo

Extend PISA user/page-cache allocators to support O_DIRECT and buffered disk I/O, gated per block/controller device through pisa_rx_bufs (read) and pisa_tx_bufs (write):

- Split per-node user_pa into DMA_BIDIRECTIONAL, DMA_TO_DEVICE, and DMA_FROM_DEVICE allocators, promoting pages to DMA_BIDIRECTIONAL if later accessed in the opposite direction.
- Upgrade pinned O_DIRECT user pages in bio_iov_iter_get_pages(), and allocate/promote order-0 page-cache folios for buffered I/O when PISA is enabled on the target block device.
- Bypass IOVA allocation in dma_iova_try_alloc() for PISA pages so blk-mq uses the pre-mapped 2MB window.
- Add pisa.scrub_migrate to compact or demote lingering folios off old, sparse user_pa 2MB pages.

---
 block/bio.c                |  46 ++++
 drivers/iommu/dma-iommu.c  |   2 +-
 drivers/iommu/pisa-alloc.c |  36 ++--
 drivers/iommu/pisa-node.c  |   3 +-
 drivers/iommu/pisa-priv.h  |  21 +-
 drivers/iommu/pisa-user.c  | 417 ++++++++++++++++++++++++++++++++-----
 include/linux/pisa.h       | 100 ++++++++-
 mm/filemap.c               |  15 +-
 mm/page-writeback.c        |   8 +
 mm/readahead.c             |   5 +-
 net/core/datagram.c        |   3 +-
 11 files changed, 581 insertions(+), 75 deletions(-)
block/bio.c +46 -0
index b0fcc69de6535..5b43430b5280c 100644
@@ -6,6 +6,7 @@
 #include <linux/swap.h>
 #include <linux/bio-integrity.h>
 #include <linux/blkdev.h>
+#include <linux/pisa.h>
 #include <linux/uio.h>
 #include <linux/iocontext.h>
 #include <linux/slab.h>
@@ -1316,6 +1317,43 @@ static inline bool bio_iov_bvec_aligned(const struct bio *bio,
 }
 #endif
 
+/*
+ * Migrate pinned order-0 user pages in @bio into PISA memory when enabled on
+ * @bio->bi_bdev; returns true if pages were released and the caller must retry.
+ */
+static bool bio_upgrade_pages_to_pisa(struct bio *bio)
+{
+	enum dma_data_direction dir;
+	struct page *pages[64];
+	unsigned int i, nr = 0;
+
+	if (!IS_ENABLED(CONFIG_PISA) || !bio_flagged(bio, BIO_PAGE_PINNED))
+		return false;
+	dir = op_is_write(bio_op(bio)) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
+	if (!is_bdev_pisa_enabled(bio->bi_bdev, dir))
+		return false;
+
+	for (i = 0; i < bio->bi_vcnt && nr < ARRAY_SIZE(pages); i++) {
+		struct page *page = bio->bi_io_vec[i].bv_page;
+
+		if (bvec_nr_pages(&bio->bi_io_vec[i]) == 1 && !is_pisa_page(page)) {
+			get_page(page);
+			pages[nr++] = page;
+		}
+	}
+	if (!nr)
+		return false;
+
+	bio_release_pages(bio, false);
+	bio->bi_vcnt = 0;
+	bio->bi_iter.bi_size = 0;
+	if (!pisa_upgrade_user_pages(pages, nr, dir, false)) {
+		while (nr)
+			put_page(pages[--nr]);
+	}
+	return true;
+}
+
 /**
  * bio_iov_iter_get_pages - add user or kernel pages to a bio
  * @bio: bio to add pages to
@@ -1346,6 +1384,7 @@ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter,
 {
 	iov_iter_extraction_t flags = 0;
 	struct iov_iter saved_iter;
+	bool tried_pisa = false;
 	int ret;
 
 	if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED)))
@@ -1367,6 +1406,7 @@ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter,
 	if (bio->bi_bdev && blk_queue_pci_p2pdma(bio->bi_bdev->bd_disk->queue))
 		flags |= ITER_ALLOW_P2PDMA;
 
+retry:
 	saved_iter = *iter;
 	do {
 		ssize_t size;
@@ -1386,6 +1426,12 @@ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter,
 		bio->bi_iter.bi_size += size;
 	} while (iov_iter_count(iter) && !bio_full(bio, 0));
 
+	if (!tried_pisa && bio_upgrade_pages_to_pisa(bio)) {
+		tried_pisa = true;
+		*iter = saved_iter;
+		goto retry;
+	}
+
 	if (is_pci_p2pdma_page(bio->bi_io_vec->bv_page))
 		bio->bi_opf |= REQ_NOMERGE;
 	ret = bio_iov_iter_align_down(bio, iter, len_align_mask);
drivers/iommu/dma-iommu.c +1 -1
index a0c5ddab7a8b6..acedfe04bde26 100644
@@ -1868,7 +1868,7 @@ bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state,
 	dma_addr_t addr;
 
 	memset(state, 0, sizeof(*state));
-	if (!use_dma_iommu(dev))
+	if (!use_dma_iommu(dev) || is_pisa_phys(phys))
 		return false;
 
 	domain = iommu_get_dma_domain(dev);
drivers/iommu/pisa-alloc.c +17 -19
index 5054a96f0f4e9..cedb1a62d20e2 100644
@@ -75,11 +75,10 @@ static unsigned int pisa_compact __read_mostly;
 module_param_named(compact, pisa_compact, uint, 0644);
 
 /* Stop recycling partial pages older than @pisa_old_ms when wasted blocks > @pisa_wasted_pct%. */
-#define PISA_OLD_MS_MAX		100000U
-static unsigned int pisa_wasted_pct __read_mostly;
+unsigned int pisa_wasted_pct __read_mostly;
 module_param_named(wasted_pct, pisa_wasted_pct, uint, 0644);
 
-static unsigned int pisa_old_ms __read_mostly;
+unsigned int pisa_old_ms __read_mostly;
 module_param_named(old_ms, pisa_old_ms, uint, 0644);
 
 /* Max pages zeroed in each scrubber run (0 = disabled, capped at PISA_SCRUB_MAX_LIMIT). */
@@ -98,8 +97,6 @@ struct pisa_node pisa_nodes[MAX_NUMNODES] = {
 	},
 };
 
-static void pisa_schedule_reclaim(void);
-
 static int pisa_scrub_set(const char *val, const struct kernel_param *kp)
 {
 	int ret = param_set_uint(val, kp);
@@ -229,18 +226,6 @@ void pisa_release_page(struct pisa_meta *meta)
 	call_rcu(&meta->rcu, pisa_release_page_rcu);
 }
 
-/* Value of @meta->on_list. 0 is "not on an allocator list", as for a zeroed @meta. */
-enum pisa_meta_list {
-	PISA_LIST_NONE,
-	PISA_LIST_FULL,
-	PISA_LIST_IDLE_CLEAN,		/* head of @idle */
-	PISA_LIST_IDLE_DIRTY,		/* tail of @idle */
-	PISA_LIST_PARTIAL_CLEAN_DENSE,	/* head of @partial */
-	PISA_LIST_PARTIAL_CLEAN_SPARSE,	/* tail of @partial */
-	PISA_LIST_PARTIAL_DIRTY_DENSE,	/* head of @partial_dirty */
-	PISA_LIST_PARTIAL_DIRTY_SPARSE,	/* tail of @partial_dirty */
-};
-
 static void pisa_reclaim_work_fn(struct work_struct *work);
 
 /* Asynchronous reclaim worker for pisa_free_list and expired idle pages. */
@@ -285,7 +270,7 @@ static void pisa_reclaim_work_fn(struct work_struct *work)
 		queue_delayed_work(pisa_wq ?: system_wq, &pisa_reclaim_work, next_delay);
 }
 
-static void pisa_schedule_reclaim(void)
+void pisa_schedule_reclaim(void)
 {
 	struct workqueue_struct *wq = pisa_wq ?: system_wq;
 	unsigned int idle_ms = READ_ONCE(pisa_idle_ms);
@@ -301,7 +286,7 @@ static void pisa_schedule_reclaim(void)
  * become available (avail == bpp), either queues @meta to @pisa_free_list (and
  * returns true so the caller schedules reclaim) or moves it to @pa->idle.
  */
-static bool pisa_place_meta(struct pisa_meta *meta)
+bool pisa_place_meta(struct pisa_meta *meta)
 {
 	struct pisa_alloc *pa = meta->pa;
 	unsigned int avail = pisa_meta_avail(meta), bpp = PISA_BLOCKS(pa->order);
@@ -505,6 +490,9 @@ bool pisa_scrub_node(int nid)
 	struct pisa_alloc *pa;
 	bool more = false;
 
+	if (!budget)
+		goto migrate;
+
 	read_lock(&pisa_allocs_lock);
 	list_for_each_entry(pa, &pisa_allocs, node) {
 		if (pa->nid != nid || !READ_ONCE(pa->scrub_demand))
@@ -526,6 +514,16 @@ bool pisa_scrub_node(int nid)
 	}
 	read_unlock(&pisa_allocs_lock);
 
+migrate:
+	if (READ_ONCE(pisa_scrub_migrate)) {
+		unsigned long rem = !budget ? 512 : (budget > done ? budget - done : 0);
+
+		if (rem && local_clock() < deadline)
+			more |= pisa_user_scrub_node(nid, rem, deadline);
+		else
+			more = true;
+	}
+
 	return more;
 }
 
drivers/iommu/pisa-node.c +2 -1
index cd29c146c281e..7469674133620 100644
@@ -184,7 +184,8 @@ void pisa_schedule_scrub(int nid)
 {
 	struct pisa_node *node;
 
-	if (!READ_ONCE(pisa_scrub_max) || nid == NUMA_NO_NODE)
+	if ((!READ_ONCE(pisa_scrub_max) && !READ_ONCE(pisa_scrub_migrate)) ||
+	    nid == NUMA_NO_NODE)
 		return;
 
 	node = &pisa_nodes[nid];
drivers/iommu/pisa-priv.h +20 -1
index 4d04bb191ecea..1ecfebbaeb381 100644
@@ -61,6 +61,18 @@ enum {
  * - pisa_srcu: protects pisa_domains[] readers against pisa_domain_release().
  */
 
+/* Value of @meta->on_list. 0 is "not on an allocator list", as for a zeroed @meta. */
+enum pisa_meta_list {
+	PISA_LIST_NONE,
+	PISA_LIST_FULL,
+	PISA_LIST_IDLE_CLEAN,		/* head of @idle */
+	PISA_LIST_IDLE_DIRTY,		/* tail of @idle */
+	PISA_LIST_PARTIAL_CLEAN_DENSE,	/* head of @partial */
+	PISA_LIST_PARTIAL_CLEAN_SPARSE,	/* tail of @partial */
+	PISA_LIST_PARTIAL_DIRTY_DENSE,	/* head of @partial_dirty */
+	PISA_LIST_PARTIAL_DIRTY_SPARSE,	/* tail of @partial_dirty */
+};
+
 /**
  * struct pisa_meta - Metadata for a single PISA page in @pisa_meta_array
  * @flags:	PISA_ACTIVE / PISA_QUARANTINED / PISA_DECRYPTED
@@ -187,7 +199,7 @@ static inline long pisa_alloc_held_pages(const struct pisa_alloc *pa)
 struct pisa_node {
 	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
 	struct pisa_alloc	*pa[2][PISA_ORDER + 1]; /* [0]=RW, [1]=RO by order */
-	struct pisa_alloc	*user_pa;	/* user page migration pa */
+	struct pisa_alloc	*user_pa[3];	/* user/page-cache allocators by dir */
 
 	spinlock_t		lock;		/* protects @pages and @nr_pages */
 	struct list_head	pages;		/* reservoir */
@@ -243,6 +255,8 @@ static inline void pisa_alloc_backoff(int nid, bool can_block)
 		WRITE_ONCE(pisa_nodes[nid].next_alloc, jiffies + DIV_ROUND_UP(HZ, 100));
 }
 bool pisa_want_decrypt(void);
+bool pisa_place_meta(struct pisa_meta *meta);
+void pisa_schedule_reclaim(void);
 int pisa_page_prepare(struct page *page, struct pisa_meta *meta);
 int pisa_page_unprepare(struct pisa_meta *meta);
 
@@ -266,11 +280,16 @@ static inline struct page *pisa_alloc(struct pisa_alloc *pa, gfp_t gfp)
 	return page;
 }
 
+#define PISA_OLD_MS_MAX		100000U
+extern unsigned int pisa_wasted_pct;
+extern unsigned int pisa_old_ms;
+extern unsigned int pisa_scrub_migrate;
 unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
 			       unsigned int *nr, struct list_head *release_list,
 			       unsigned long nr_to_scan);
 extern unsigned int pisa_scrub_max;
 bool pisa_scrub_node(int nid);
+bool pisa_user_scrub_node(int nid, unsigned long budget, u64 deadline);
 
 /* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
 extern unsigned int pisa_reservoir_max;
drivers/iommu/pisa-user.c +369 -48

551 lines not on this page · raw message

include/linux/pisa.h +98 -2

131 lines not on this page · raw message

mm/filemap.c +14 -1
index b04be64a5069f..3860b0c6db4ec 100644
@@ -15,6 +15,7 @@
 #include <linux/dax.h>
 #include <linux/fs.h>
 #include <linux/sched/signal.h>
+#include <linux/pisa.h>
 #include <linux/uaccess.h>
 #include <linux/capability.h>
 #include <linux/kernel_stat.h>
@@ -1976,6 +1977,7 @@ void *filemap_get_entry(struct address_space *mapping, pgoff_t index)
 struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 		pgoff_t index, fgf_t fgp_flags, gfp_t gfp, struct mempolicy *policy)
 {
+	bool tried_pisa = false;
 	struct folio *folio;
 
 repeat:
@@ -1985,6 +1987,13 @@ struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 	if (!folio)
 		goto no_page;
 
+	if (!tried_pisa) {
+		tried_pisa = true;
+		if (pisa_filemap_upgrade(mapping, folio,
+					 (fgp_flags & (FGP_WRITE | FGP_NOWAIT)) == FGP_WRITE))
+			goto repeat;
+	}
+
 	if (fgp_flags & FGP_LOCK) {
 		if (fgp_flags & FGP_NOWAIT) {
 			if (!folio_trylock(folio)) {
@@ -2044,7 +2053,11 @@ struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 			err = -ENOMEM;
 			if (order > min_order)
 				alloc_gfp |= __GFP_NORETRY | __GFP_NOWARN;
-			folio = filemap_alloc_folio(alloc_gfp, order, policy);
+			folio = pisa_filemap_alloc(mapping, alloc_gfp, order,
+						   fgp_flags & FGP_WRITE);
+			if (!folio)
+				folio = filemap_alloc_folio(alloc_gfp, order,
+							    policy);
 			if (!folio)
 				continue;
 
mm/page-writeback.c +8 -0
index 0694ec4098f6d..39cc28f9762c6 100644
@@ -37,6 +37,7 @@
 #include <linux/sched/rt.h>
 #include <linux/sched/signal.h>
 #include <linux/mm_inline.h>
+#include <linux/pisa.h>
 #include <linux/shmem_fs.h>
 #include <trace/events/writeback.h>
 
@@ -2409,6 +2410,7 @@ static pgoff_t wbc_end(struct writeback_control *wbc)
 static struct folio *writeback_get_folio(struct address_space *mapping,
 		struct writeback_control *wbc)
 {
+	pgoff_t upgraded = ULONG_MAX;
 	struct folio *folio;
 
 retry:
@@ -2423,6 +2425,12 @@ static struct folio *writeback_get_folio(struct address_space *mapping,
 			return NULL;
 	}
 
+	if (folio->index != upgraded &&
+	    pisa_writeback_upgrade(mapping, folio, &wbc->index, &wbc->fbatch)) {
+		upgraded = wbc->index;
+		goto retry;
+	}
+
 	folio_lock(folio);
 	if (unlikely(!folio_prepare_writeback(mapping, wbc, folio))) {
 		folio_unlock(folio);
mm/readahead.c +4 -1
index 6e5563290287e..f5cfc69dc9909 100644
@@ -114,6 +114,7 @@
  */
 
 #include <linux/blk_plug.h>
+#include <linux/pisa.h>
 #include <linux/kernel.h>
 #include <linux/dax.h>
 #include <linux/gfp.h>
@@ -197,7 +198,9 @@ static struct folio *ractl_alloc_folio(struct readahead_control *ractl,
 {
 	struct folio *folio;
 
-	folio = filemap_alloc_folio(gfp_mask, order, NULL);
+	folio = pisa_filemap_alloc(ractl->mapping, gfp_mask, order, false);
+	if (!folio)
+		folio = filemap_alloc_folio(gfp_mask, order, NULL);
 	if (folio && ractl->dropbehind)
 		__folio_set_dropbehind(folio);
 
net/core/datagram.c +2 -1
index 40f20d0faa859..8ba9c39cb05ec 100644
@@ -651,7 +651,8 @@ static bool pisa_zc_iter(int *ret, struct sk_buff *skb, struct iov_iter *from, s
 		return false;
 
 	/* Move user pages into PISA memory, then look them up again. */
-	if (pisa_upgrade_user_pages(pages, DIV_ROUND_UP(*start + *copied, PAGE_SIZE))) {
+	if (pisa_upgrade_user_pages(pages, DIV_ROUND_UP(*start + *copied, PAGE_SIZE),
+				    DMA_TO_DEVICE, false)) {
 		iov_iter_revert(from, *copied);
 		*copied = iov_iter_get_pages2(from, pages, *length, max_pages, start);
 		if (*copied < 0) {
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#157 lore raw

Re: [RFC PATCH v2 23/25] block, mm, iommu/dma: Support PISA for disk I/O and scrub migration

Thank you for your contribution! Sashiko AI review found 8 potential issues to consider: - [High] iommu/pisa: double pisa_place_meta() and recycling in pisa_user_scrub_alloc() - [High] iommu/dma…

Thank you for your contribution! Sashiko AI review found 8 potential issues to consider:
- [High] iommu/pisa: double pisa_place_meta() and recycling in pisa_user_scrub_alloc()
- [High] iommu/dma: 2MB PISA pages mapped into untrusted devices in __pisa_map_phys()
- [Medium] block: broken PISA promotion and bio repin in bio_upgrade_pages_to_pisa()
- [Medium] iommu/pisa: scrub worker never scheduled for sparse user_pa pages
- [Medium] iommu/pisa: early scrub loop exit and age reset in pisa_user_scrub_node()
- [Medium] iommu/pisa: block pisa_tx_bufs depends on net_pisa_tx_bufs_set() and CONFIG_NET
- [Medium] iommu/pisa: __pisa_bdev_enabled() misses gendisk sysfs and NVMe multipath
- [Medium] iommu/pisa: direction permission mismatch in __pisa_filemap_alloc() and pisa_zc_iter()
--

commit 07d0de2d5b536e6ca58dfc325de503d0cd0feffd
Author: Luigi Rizzo <[email protected]>

block, mm, iommu/dma: Support PISA for disk I/O and scrub migration

This commit extends the PISA user and page-cache allocators to support O_DIRECT and buffered disk I/O with per-direction per-node allocators, bypasses IOVA allocation for PISA pages in dma_iova_try_alloc(), and adds background scrub migration for sparse user PISA pages.

Quoted 42 lines
block/bio.c +27 -0
index b0fcc69de6535..5b43430b5280c 100644
@@ -6,6 +6,7 @@
 #include <linux/swap.h>
 #include <linux/bio-integrity.h>
 #include <linux/blkdev.h>
+#include <linux/pisa.h>
 #include <linux/uio.h>
 #include <linux/iocontext.h>
 #include <linux/slab.h>
@@ -1316,6 +1317,43 @@ static inline bool bio_iov_bvec_aligned(const struct bio *bio,
 }
 #endif
 
+/*
+ * Migrate pinned order-0 user pages in @bio into PISA memory when enabled on
+ * @bio->bi_bdev; returns true if pages were released and the caller must retry.
+ */
+static bool bio_upgrade_pages_to_pisa(struct bio *bio)
+{
+	enum dma_data_direction dir;
+	struct page *pages[64];
+	unsigned int i, nr = 0;
+
+	if (!IS_ENABLED(CONFIG_PISA) || !bio_flagged(bio, BIO_PAGE_PINNED))
+		return false;
+	dir = op_is_write(bio_op(bio)) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
+	if (!is_bdev_pisa_enabled(bio->bi_bdev, dir))
+		return false;
+
+	for (i = 0; i < bio->bi_vcnt && nr < ARRAY_SIZE(pages); i++) {
+		struct page *page = bio->bi_io_vec[i].bv_page;
+
+		if (bvec_nr_pages(&bio->bi_io_vec[i]) == 1 && !is_pisa_page(page)) {
+			get_page(page);
+			pages[nr++] = page;
+		}
+	}
+	if (!nr)
+		return false;

block/bio.c static inline bool bio_iov_bvec_aligned(const struct bio *bio, · line 1355

Quoted 10 lines
block/bio.c +10 -0
+
+	bio_release_pages(bio, false);
+	bio->bi_vcnt = 0;
+	bio->bi_iter.bi_size = 0;
+	if (!pisa_upgrade_user_pages(pages, nr, dir, false)) {
+		while (nr)
+			put_page(pages[--nr]);
+	}
+	return true;
+}

[Severity: Medium]
Does filtering out !is_pisa_page(page) prevent O_DIRECT buffers that are already in a unidirectional PISA allocator from being promoted to DMA_BIDIRECTIONAL when accessed in the opposite direction? When an O_DIRECT buffer allocated for writes (or via MADV_PISA) is later used for an O_DIRECT read, dma_iova_try_alloc() sees is_pisa_phys(phys) and skips blk-mq IOVA coalescing, and __pisa_map_phys() then rejects the window mapping with -EACCES, falling back to individual 4KB IOVA allocations per segment.

Also, bio_release_pages() and returning true happen before pisa_upgrade_user_pages() checks whether any page is eligible or within pisa.user_max_4K_pages budget, forcing bio_iov_iter_get_pages() to unpin and re-pin the entire bio on every O_DIRECT request whenever migration does not occur.

drivers/iommu/dma-iommu.c bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state, · line 1872

Quoted 11 lines
drivers/iommu/dma-iommu.c +1 -1
index a0c5ddab7a8b6..acedfe04bde26 100644
@@ -1868,7 +1868,7 @@ bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state,
 	dma_addr_t addr;
 
 	memset(state, 0, sizeof(*state));
-	if (!use_dma_iommu(dev) || is_pisa_phys(phys))
+	if (!use_dma_iommu(dev) || is_pisa_phys(phys))
 		return false;

[Severity: High]
Can a 4KB PISA user or page-cache page be mapped into an untrusted external device's IOMMU domain without bounce buffering?

When a 4KB buffer backed by a 2MB PISA frame is used for DMA on an untrusted PCI/Thunderbolt device (dev_is_untrusted(dev) == true), dma_iova_try_alloc() returns false because is_pisa_phys(phys) is true, and iommu_dma_map_phys() skips swiotlb bounce buffering (since the 4KB buffer is iova_aligned) and calls __pisa_map_phys(). Because neither dma_iova_try_alloc() nor __pisa_map_phys() rejects untrusted devices, __pisa_map_phys() installs a persistent 2MB IOMMU leaf PTE in the untrusted device's domain, exposing the other 511 sibling 4KB user and page-cache pages in that 2MB frame to DMA by the untrusted device.

drivers/iommu/pisa-node.c void pisa_schedule_scrub(int nid) · line 189

Quoted 12 lines
drivers/iommu/pisa-node.c +2 -1
index cd29c146c281e..7469674133620 100644
@@ -184,7 +184,8 @@ void pisa_schedule_scrub(int nid)
 {
 	struct pisa_node *node;
 
-	if (!READ_ONCE(pisa_scrub_max) || nid == NUMA_NO_NODE)
+	if ((!READ_ONCE(pisa_scrub_max) && !READ_ONCE(pisa_scrub_migrate)) ||
+	    nid == NUMA_NO_NODE)
 		return;

[Severity: Medium]
What schedules pisa_schedule_scrub() when user_pa pages age past pisa.old_ms and exceed pisa.wasted_pct?

Outside of writing to scrub_max or scrub_migrate in sysfs, pisa_schedule_scrub() is only called from __pisa_alloc_bulk() and pisa_alloc_coherent() when pa->scrub_demand >= PISA_SCRUB_TRIGGER. Because all user_pa[] allocators enable PCP in pisa_user_init() and pisa_pcp_alloc() calls __pisa_alloc_bulk() with zero = false, pa->scrub_demand is never incremented on user_pa[], and neither __pisa_free_page() nor pisa_reclaim_work_fn() calls pisa_schedule_scrub(), so background scrub migration never runs automatically.

Quoted 4 lines
drivers/iommu/pisa-user.c +0 -0
index a16909d429aca..7dca3bf066f0d 100644

[ ... ]

Quoted 17 lines
drivers/iommu/pisa-user.c +17 -0
+struct folio *__pisa_filemap_alloc(const struct address_space *mapping,
+				   gfp_t gfp, bool is_write)
+{
+	enum dma_data_direction dir = is_write ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
+	struct page *page;
+	int nid;
+
+	if (!__pisa_mapping_enabled(mapping, dir))
+		return NULL;
+	if (is_write && __pisa_mapping_enabled(mapping, DMA_FROM_DEVICE))
+		dir = DMA_BIDIRECTIONAL;
+	/* Pairs with smp_store_release() in pisa_user_init(). */
+	if (!smp_load_acquire(&pisa_user_ready) &&
+	    ((gfp & GFP_KERNEL) != GFP_KERNEL || !pisa_user_init()))
+		return NULL;
+	if (pisa_user_budget() <= 0)
+		return NULL;

drivers/iommu/pisa-user.c static struct folio *pisa_user_old_folio(struct folio *src, unsigned long privat · line 367

Quoted 10 lines
drivers/iommu/pisa-user.c +10 -0
+	nid = pisa_sanitize_nid(numa_node_id());
+	page = pisa_alloc(pisa_nodes[nid].user_pa[dir], gfp);
+	if (!page)
+		return NULL;
+	if (pisa_meta_of_pfn(page_to_pfn(page))->flags & PISA_DECRYPTED) {
+		put_page(page);
+		return NULL;
+	}
+	return page_folio(page);
+}

[Severity: Medium]
Can allocating page-cache folios from single-direction user_pa[dir] allocators cause direction permission mismatches on later I/O?

When only pisa_rx_bufs is enabled on a block device, __pisa_filemap_alloc() allocates read and readahead folios from user_pa[DMA_FROM_DEVICE] (IOMMU_WRITE only). If those folios are later dirtied and written back, pisa_filemap_upgrade() and pisa_writeback_upgrade() both check pisa_mapping_enabled(mapping, DMA_TO_DEVICE) and do not promote them; conversely, when only pisa_tx_bufs is enabled, a partial-page buffered write allocates a locked folio from user_pa[DMA_TO_DEVICE] (IOMMU_READ only) and write_begin immediately issues a disk READ into it. Similarly, in net/core/datagram.c:pisa_zc_iter(), checking is_pisa_page(pages[i]) without verifying IOMMU_READ allows a DMA_FROM_DEVICE page (such as a mmap'd page-cache folio, which pisa_upgrade_user_pages() skips because allow_file is false) to be attached zero-copy instead of copied. In all of these cases, dma_iova_try_alloc() sees is_pisa_phys(phys) and disables blk-mq or TSO IOVA coalescing, only for __pisa_map_phys() to fail with -EACCES and fall back to per-page 4KB IOVA mappings.

[ ... ]

Quoted 4 lines
drivers/iommu/pisa-user.c +4 -0
+bool __pisa_bdev_enabled(struct block_device *bdev, enum dma_data_direction dir)
+{
+	struct device *dev;
+

drivers/iommu/pisa-user.c static struct folio *pisa_user_old_folio(struct folio *src, unsigned long privat · line 414

Quoted 10 lines
drivers/iommu/pisa-user.c +10 -0
+	if (!bdev || !bdev->bd_disk)
+		return false;
+	for (dev = disk_to_dev(bdev->bd_disk); dev; dev = dev->parent) {
+		if (dir == DMA_FROM_DEVICE ?
+		    READ_ONCE(dev->pisa_rx_bufs) :
+		    READ_ONCE(dev->pisa_tx_bufs))
+			return true;
+	}
+	return false;
+}

[Severity: Medium]
Does gating block device writes on dev->pisa_tx_bufs tie disk write support to CONFIG_NET and the networking static key?

In drivers/base/core.c, pisa_tx_bufs is wired to net_pisa_tx_bufs_set():

drivers/base/core.c:

    PISA_SET_ATTR(pisa_tx_bufs, net_pisa_tx_bufs_set);

With CONFIG_NET=n, net_pisa_tx_bufs_set() is a stub returning -EOPNOTSUPP, so pisa_tx_bufs cannot be enabled on any block or storage controller device. With CONFIG_NET=y, enabling pisa_tx_bufs on a storage controller enables net_pisa_tx_bufs_key globally across the networking stack even when no network device uses PISA.

[Severity: Medium]
Also in __pisa_bdev_enabled(), does walking dev->parent from disk_to_dev(bdev->bd_disk) work for per-disk configuration or NVMe multipath devices?

In drivers/base/core.c:device_add_attrs(), dev_attr_pisa_group is only added when dev->dma_mask is non-NULL, so gendisk devices never expose pisa_rx_bufs or pisa_tx_bufs in sysfs. Furthermore, with CONFIG_NVME_MULTIPATH=y, nvme_mpath_set_live() sets the namespace gendisk's parent to &head->subsys->dev (nvme-subsysX), which has parent == NULL and dma_mask == NULL, so walking dev->parent from disk_to_dev(bdev->bd_disk) never reaches the underlying PCI controller device.

Quoted 19 lines
drivers/iommu/pisa-user.c +17 -0
+
+bool __pisa_mapping_enabled(const struct address_space *mapping, enum dma_data_direction dir)
+{
+	struct super_block *sb;
+
+	if (!mapping || !mapping->host || !mapping->host->i_sb)
+		return false;
+	sb = mapping->host->i_sb;
+	return __pisa_bdev_enabled(sb_is_blkdev_sb(sb) ?
+				   I_BDEV(mapping->host) : sb->s_bdev, dir);
+}
+
 #define PISA_USER_BATCH	512
 
+static unsigned long pisa_user_scrub_alloc(struct pisa_alloc *pa,
+					  enum dma_data_direction dir,
+					  unsigned int mode,
+					  unsigned long budget)
+{

[ ... ]

Quoted 11 lines
drivers/iommu/pisa-user.c +11 -0
+	if (target) {
+		base_pfn = pisa_meta_to_pfn(target);
+		bitmap_or(inuse_map, target->clean_bitmap, target->dirty_bitmap, bpp);
+		bitmap_complement(inuse_map, inuse_map, bpp);
+		WRITE_ONCE(target->on_list, PISA_LIST_FULL);
+		list_move(&target->list, &pa->full);
+	}
+	spin_unlock_irqrestore(&pa->lock, flags);
+
+	if (!target)
+		return 0;

[ ... ]

Quoted 7 lines
drivers/iommu/pisa-user.c +7 -0
+	if (!list_empty(&list)) {
+		migrated = pisa_user_migrate_dir(&list, mode == 1, dir, true,
+						 GFP_KERNEL | __GFP_NOWARN);
+		pisa_pcp_drain(pa);
+	}
+
+	spin_lock_irqsave(&pa->lock, flags);

drivers/iommu/pisa-user.c static struct folio *pisa_user_old_folio(struct folio *src, unsigned long privat · line 532

Quoted 10 lines
drivers/iommu/pisa-user.c +10 -0
+	if (READ_ONCE(target->pa) == pa) {
+		WRITE_ONCE(target->alloc_jiffies, jiffies);
+		should_release = pisa_place_meta(target);
+	}
+	spin_unlock_irqrestore(&pa->lock, flags);
+	if (should_release)
+		pisa_schedule_reclaim();
+
+	return migrated;
+}

[Severity: High]
Does calling pisa_place_meta(target) after pisa_user_migrate_dir() and pisa_pcp_drain() corrupt pa->num_idle_pages or double-add target->llnode to pisa_free_list when all remaining blocks of target are migrated?

When the last in-use block of target is freed during migration or pisa_pcp_drain(pa), pisa_return_block_locked() already calls pisa_place_meta(target) with avail == bpp. In pisa_place_meta(), that first call either increments pa->num_idle_pages and moves target to pa->idle, or unlinks target and adds target->llnode to pisa_free_list. Because target->pa is only cleared in pisa_release_page_rcu() after an RCU grace period, READ_ONCE(target->pa) == pa is still true here, so pisa_user_scrub_alloc() calls pisa_place_meta(target) a second time with avail == bpp:

drivers/iommu/pisa-alloc.c:pisa_place_meta() {
	if (avail == bpp) {
		if ((meta->flags & PISA_QUARANTINED) ||
		    (pa->num_idle_pages >= pa->max_idle_pages && !READ_ONCE(pisa_idle_ms))) {
			list_del_init(&meta->list);
			WRITE_ONCE(meta->on_list, PISA_LIST_NONE);
			llist_add(&meta->llnode, &pisa_free_list);
			return true;
		}
		if (pa->num_idle_pages >= pa->max_idle_pages)
			WRITE_ONCE(pa->idle_jiffies, jiffies);
		pa->num_idle_pages++;
		on_list = meta->nr_dirty ? PISA_LIST_IDLE_DIRTY : PISA_LIST_IDLE_CLEAN;
	}
    ...
	if (on_list == meta->on_list)
		return avail == bpp && pa->num_idle_pages > pa->max_idle_pages;
}

That second call either increments pa->num_idle_pages a second time for the same page (before the on_list == meta->on_list check), or calls llist_add(&target->llnode, &pisa_free_list) a second time on the same node (or moves a page already being released by pisa_reclaim_work_fn() back onto pa->idle).

In addition, setting target->on_list = PISA_LIST_FULL before migration makes pisa_page_can_recycle() return true for freed blocks of target, so __pisa_free_page() caches them in pa->pcp where mode == 1 compaction can reallocate destination folios right back onto target.

Quoted 16 lines
drivers/iommu/pisa-user.c +16 -0
+
+bool pisa_user_scrub_node(int nid, unsigned long budget, u64 deadline)
+{
+	unsigned int mode = READ_ONCE(pisa_scrub_migrate);
+	unsigned long done = 0;
+	unsigned int dir;
+
+	/* Pairs with smp_store_release() in pisa_user_init(). */
+	if (!mode || mode > 2 || !smp_load_acquire(&pisa_user_ready))
+		return false;
+
+	for (dir = 0; dir < ARRAY_SIZE(pisa_nodes[nid].user_pa); dir++) {
+		struct pisa_alloc *pa = pisa_nodes[nid].user_pa[dir];
+		unsigned long n;
+
+		if (!pa)

drivers/iommu/pisa-user.c static struct folio *pisa_user_old_folio(struct folio *src, unsigned long privat · line 558

Quoted 10 lines
drivers/iommu/pisa-user.c +10 -0
+			continue;
+		while ((n = pisa_user_scrub_alloc(pa, dir, mode, budget - done))) {
+			done += n;
+			if (done >= budget || local_clock() >= deadline)
+				return true;
+			cond_resched();
+		}
+	}
+	return false;
+}

[Severity: Medium]
If the oldest sparse page in pa has only unmigratable folios (for example, locked, under writeback, pinned, or mapped shared), pisa_user_scrub_alloc() updates target->alloc_jiffies and returns 0. Should pisa_user_scrub_node() continue scanning the remaining old sparse pages in pa instead of exiting the while loop on the first target page that migrates 0 folios?

Also, if pisa_user_scrub_alloc() stops isolating folios early because count reaches min(budget - done, PISA_USER_BATCH), resetting target->alloc_jiffies = jiffies hides the still-sparse page from the scrubber for pisa.old_ms.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=23
#158 lore raw

RFC PATCH v2 24/25 Documentation: Add PISA architecture documentation

In reply to Luigi Rizzo

Document the PISA IOMMU 2MB-hugepage-backed DMA memory subsystem in Documentation/core-api/pisa.rst.

---
 .../admin-guide/kernel-parameters.txt         |   6 +
 Documentation/core-api/index.rst              |   1 +
 Documentation/core-api/pisa.rst               | 426 ++++++++++++++++++
 3 files changed, 433 insertions(+)
 create mode 100644 Documentation/core-api/pisa.rst
Documentation/admin-guide/kernel-parameters.txt +6 -0
index 0b3c140babd94..cb978469a7df3 100644
@@ -5345,6 +5345,12 @@ Kernel parameters
 	pirq=		[SMP,APIC] Manual mp-table setup
 			See Documentation/arch/x86/i386/IO-APIC.rst.
 
+	pisa.*=		[IOMMU] Pre-mapped IOVA Superpage Allocator (PISA)
+			tuning parameters (max_bits, max_pages, slots, max_idle,
+			idle_ms, reservoir_max, scrub_max, compact, wasted_pct,
+			old_ms, pcp_batch, user_max_4K_pages, scrub_migrate).
+			See Documentation/core-api/pisa.rst.
+
 	plip=		[PPT,NET] Parallel port network link
 			Format: { parport<nr> | timid | 0 }
 			See also Documentation/admin-guide/parport.rst.
Documentation/core-api/index.rst +1 -0
index 92f91c6a0d79d..4955f477ed797 100644
@@ -113,6 +113,7 @@ more memory-management documentation in Documentation/mm/index.rst.
    dma-attributes
    dma-isa-lpc
    swiotlb
+   pisa
    mm-api
    cgroup
    genalloc
Documentation/core-api/pisa.rst new file +426 -0

426 lines not on this page · raw message

Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#159 lore raw

Re: [RFC PATCH v2 24/25] Documentation: Add PISA architecture documentation

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] docs: incomplete pisa.* boot parameter docs and wrong scrub_max unit - [Low] docs: pisa.rst omits…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] docs: incomplete pisa.* boot parameter docs and wrong scrub_max unit
- [Low] docs: pisa.rst omits block I/O, page-cache folio, and user_pa support
--

commit cadce0626ec3fdede5eca92aaf3542cae769fd37
Author: Luigi Rizzo <[email protected]>

Documentation: Add PISA architecture documentation

This commit adds architecture and runtime control documentation for the Pre-mapped IOVA Superpage Allocator (PISA) in Documentation/core-api/pisa.rst and lists the pisa.* kernel parameters in Documentation/admin-guide/kernel-parameters.txt.

Documentation/admin-guide/kernel-parameters.txt Kernel parameters · line 5352

Quoted 13 lines
Documentation/admin-guide/kernel-parameters.txt +5 -0
index 0b3c140babd94..cb978469a7df3 100644
@@ -5345,6 +5345,12 @@ Kernel parameters
 	pirq=		[SMP,APIC] Manual mp-table setup
 			See Documentation/arch/x86/i386/IO-APIC.rst.
 
+	pisa.*=		[IOMMU] Pre-mapped IOVA Superpage Allocator (PISA)
+			tuning parameters (max_bits, max_pages, slots, max_idle,
+			idle_ms, reservoir_max, scrub_max, compact, wasted_pct,
+			old_ms, pcp_batch, user_max_4K_pages, scrub_migrate).
+			See Documentation/core-api/pisa.rst.

[Severity: Low]
Should this entry also include the pisa.decrypt boot parameter defined in drivers/iommu/pisa-alloc.c, and use [ARM64,X86-64] instead of [IOMMU] (which is not defined in the restriction tag list in kernel-parameters.txt)?

In addition, this entry defers to Documentation/core-api/pisa.rst, which does not describe decrypt, max_idle, idle_ms, compact, wasted_pct, old_ms, pcp_batch, or scrub_migrate, and describes scrub_max as counting idle 2MB PISA pages even though pisa_scrub_alloc() accounts the budget in 4KB base pages ((unsigned long)used << order) and scrubs dirty blocks from partial_dirty and partial pages before idle pages.

Quoted 5 lines
Documentation/core-api/pisa.rst new file +0 -0
new file mode 100644
index 0000000000000..6ed4bd9951f8a

[ ... ]

Quoted 3 lines
Documentation/core-api/pisa.rst new file +3 -0
+  - ``/sys/devices/*/*/pisa_{coherent,rx_bufs,tx_bufs,tx_skb_heads}``
+    per-device entries that control whether a device uses PISA for coherent
+    allocations, RX buffers, TX socket page fragments, and small TX skb heads

[ ... ]

Quoted 4 lines

+- **User pages for MSG_ZEROCOPY** (``drivers/iommu/pisa-user.c``):

Documentation/core-api/pisa.rst new file +3 -0
+
+  - ``madvise(MADV_PISA)`` migrates the present private anonymous pages
+    of a range into blocks of per-node ``DMA_TO_DEVICE`` allocators, so that

Documentation/core-api/pisa.rst

Quoted 10 lines
Documentation/core-api/pisa.rst new file +10 -0
+    zerocopy sends from them use the PISA window instead of per-send IOMMU
+    mappings or hypervisor pinning. ``MADV_NOPISA`` migrates them back to
+    ordinary pages. Both are allowed through ``process_madvise()``.
+    Freeing the pages (``munmap()``, ``MADV_DONTNEED``, exit, reclaim)
+    returns the blocks to their allocators.
+  - ``/sys/module/pisa/parameters/user_max_4K_pages``: Soft cap on user
+    pages held in PISA blocks, in 4 KB pages (``max_pages`` counts PISA
+    pages). When non-zero, eligible pages are also migrated on
+    ``MSG_ZEROCOPY`` sends (best effort, non-blocking, skipping pages still
+    referenced by in-flight skbs); 0 (default) disables both.

[Severity: Low]
Should these sections also document how pisa_rx_bufs, pisa_tx_bufs, and user_max_4K_pages apply to block I/O and page-cache folios?

In drivers/iommu/pisa-user.c, user_pa[] maintains per-node allocators for DMA_BIDIRECTIONAL, DMA_TO_DEVICE, and DMA_FROM_DEVICE. When user_max_4K_pages is non-zero and pisa_rx_bufs or pisa_tx_bufs is enabled on a block device or its parents, PISA also migrates pinned order-0 user pages for O_DIRECT bios in bio_iov_iter_get_pages(), allocates or migrates order-0 page-cache folios in __filemap_get_folio_mpol(), ractl_alloc_folio(), and writeback_get_folio(), and skips blk-mq IOVA allocation for PISA pages in dma_iova_try_alloc().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=24
#160 lore raw

RFC PATCH v2 25/25 iommu/dma: Add PISA statistics and debugfs

In reply to Luigi Rizzo

PISA allocation and mapping failures silently fall back to standard page allocation and per-buffer DMA mappings, making performance regressions hard to diagnose without observability.

Add per-allocator, per-node reservoir, user-page migration, and global shrinker/reclaim counters, and expose them via /sys/kernel/debug/pisa/allocs.
Also emit a one-shot dmesg warning on the first 2MB buddy allocation failure.

---
 drivers/iommu/pisa-alloc.c | 298 +++++++++++++++++++++++++++++++++----
 drivers/iommu/pisa-kunit.c |   7 +-
 drivers/iommu/pisa-map.c   |  79 +++++++++-
 drivers/iommu/pisa-node.c  |  43 +++++-
 drivers/iommu/pisa-priv.h  | 127 +++++++++++++++-
 drivers/iommu/pisa-user.c  |  77 +++++++++-
 include/linux/pisa.h       |   5 +
 net/core/datagram.c        |   2 +
 8 files changed, 589 insertions(+), 49 deletions(-)
drivers/iommu/pisa-alloc.c +273 -25
index cedb1a62d20e2..91b9f00d21985 100644
@@ -11,6 +11,7 @@
 #include <linux/cache.h>
 #include <linux/cc_platform.h>
 #include <linux/cpuhotplug.h>
+#include <linux/debugfs.h>
 #include <linux/device.h>
 #include <linux/dma-direct.h>
 #include <linux/dma-map-ops.h>
@@ -31,6 +32,7 @@
 #include <linux/rcupdate.h>
 #include <linux/sched/clock.h>
 #include <linux/sched/mm.h>
+#include <linux/seq_file.h>
 #include <linux/set_memory.h>
 #include <linux/shrinker.h>
 #include <linux/skbuff.h>
@@ -85,6 +87,13 @@ module_param_named(old_ms, pisa_old_ms, uint, 0644);
 unsigned int pisa_scrub_max __read_mostly;
 #define PISA_SCRUB_MAX_LIMIT	65536U
 
+/* Reclaim statistics, see pisa_allocs_show(). */
+struct pisa_reclaim_stats pisa_reclaim_stats;
+
+char pisa_pages_2m[16] __ro_after_init;
+char pisa_pages_4k[16] __ro_after_init;
+char pisa_no_pages_2m[16] __ro_after_init;
+
 /* All live allocators, protected by pisa_allocs_lock. */
 static LIST_HEAD(pisa_allocs);
 static DEFINE_RWLOCK(pisa_allocs_lock);
@@ -115,6 +124,7 @@ static const struct kernel_param_ops pisa_scrub_ops = {
 	.get = param_get_uint,
 };
 module_param_cb(scrub_max, &pisa_scrub_ops, &pisa_scrub_max, 0644);
+
 /* Return true if a new PISA page should be decrypted. */
 bool pisa_want_decrypt(void)
 {
@@ -179,7 +189,7 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 	unsigned long flags;
 
 	spin_lock_irqsave(&meta->pa->lock, flags);
-	meta->pa->stats.page_free_cnt++;
+	pisa_stat_inc(meta->pa->stats.page_free_cnt);
 	spin_unlock_irqrestore(&meta->pa->lock, flags);
 	WRITE_ONCE(meta->pa, NULL);
 
@@ -190,6 +200,7 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 	/* Still shared with the host, or possibly still mapped by a device. */
 	if (meta->flags & (PISA_DECRYPTED | PISA_QUARANTINED))
 		return;
+
 	atomic_long_dec(&pisa_nr_pages);
 	for (i = 0; i < PISA_BLOCKS(order); i++) {
 		block = page + (i << order);
@@ -238,6 +249,9 @@ static void pisa_reclaim_work_fn(struct work_struct *work)
 	struct pisa_meta *meta, *tmp;
 	struct llist_node *node;
 	struct pisa_alloc *pa;
+	unsigned int n = 0;
+
+	pisa_stat_inc(pisa_reclaim_stats.reclaim_run);
 
 	read_lock(&pisa_allocs_lock);
 	list_for_each_entry(pa, &pisa_allocs, node) {
@@ -263,8 +277,11 @@ static void pisa_reclaim_work_fn(struct work_struct *work)
 	read_unlock(&pisa_allocs_lock);
 
 	node = llist_del_all(&pisa_free_list);
-	llist_for_each_entry_safe(meta, tmp, node, llnode)
+	llist_for_each_entry_safe(meta, tmp, node, llnode) {
 		pisa_release_page(meta);
+		n++;
+	}
+	pisa_stat_add(pisa_reclaim_stats.reclaim_pages, n);
 
 	if (next_delay != MAX_JIFFY_OFFSET)
 		queue_delayed_work(pisa_wq ?: system_wq, &pisa_reclaim_work, next_delay);
@@ -469,6 +486,7 @@ static unsigned long pisa_scrub_alloc(struct pisa_alloc *pa)
 	for (idx = 0; idx < count; idx++)
 		__set_bit(idxs[idx], meta->clean_bitmap);
 	meta->nr_clean += count;
+	pisa_stat_add(pa->stats.block_scrub_cnt, count);
 	pa->scrub_demand -= min(count, pa->scrub_demand);
 	should_release = pisa_place_meta(meta);
 	spin_unlock_irqrestore(&pa->lock, flags);
@@ -603,6 +621,7 @@ static void pisa_return_block_locked(struct pisa_alloc *pa, struct page *block,
 		meta->nr_dirty++;
 	}
 	pa->blocks_in_use--;
+	pisa_stat_inc(pa->stats.block_free_cnt);
 	*release |= pisa_place_meta(meta);
 }
 
@@ -729,7 +748,8 @@ static const struct kernel_param_ops pisa_pcp_batch_ops = {
 module_param_cb(pcp_batch, &pisa_pcp_batch_ops, &pisa_pcp_batch, 0644);
 
 /* Cache @n blocks at refcount 0 on this CPU, @n <= PISA_PCP_BATCH. */
-static void pisa_pcp_push(struct pisa_alloc *pa, struct page **blocks, unsigned int n)
+static void pisa_pcp_push(struct pisa_alloc *pa, struct page **blocks, unsigned int n,
+			  bool is_free)
 {
 	unsigned int i, batch = READ_ONCE(pisa_pcp_batch);
 	struct pisa_pcp *pcp;
@@ -738,6 +758,8 @@ static void pisa_pcp_push(struct pisa_alloc *pa, struct page **blocks, unsigned
 	local_irq_save(flags);
 	pcp = this_cpu_ptr(pa->pcp);
 	spin_lock(&pcp->lock);
+	if (is_free)
+		pisa_stat_add(pcp->free_cnt, n);
 	for (i = 0; i < n; i++) {
 		if (pcp->count == PISA_PCP_HIGH) {
 			/* Keep the most recently freed, likely still in cache. */
@@ -799,18 +821,37 @@ void pisa_pcp_drain(struct pisa_alloc *pa)
 	}
 }
 
-/* Blocks in @pa's caches, for shrinker and debugfs. */
-static unsigned long pisa_pcp_count(struct pisa_alloc *pa)
+/* Aggregate statistics across @pa's per-CPU caches, for shrinker and debugfs. */
+static unsigned long pisa_pcp_stats(struct pisa_alloc *pa, u64 *alloc, u64 *miss,
+				    u64 *free, u64 *ks, u64 *as)
 {
+	u64 a = 0, m = 0, f = 0, s_k = 0, s_a = 0;
 	unsigned long n = 0;
 	int cpu;
 
-	if (!pa->pcp)
-		return 0;
-	for_each_possible_cpu(cpu) {
-		/* A racy sum is good enough for reclaim and statistics. */
-		n += data_race(per_cpu_ptr(pa->pcp, cpu)->count);
+	if (pa->pcp) {
+		for_each_possible_cpu(cpu) {
+			const struct pisa_pcp *pcp = per_cpu_ptr(pa->pcp, cpu);
+
+			/* A racy sum is good enough for reclaim and statistics. */
+			n += READ_ONCE(pcp->count);
+			a += READ_ONCE(pcp->alloc_cnt);
+			m += READ_ONCE(pcp->miss_cnt);
+			f += READ_ONCE(pcp->free_cnt);
+			s_k += READ_ONCE(pcp->alloc_ks);
+			s_a += READ_ONCE(pcp->alloc_as);
+		}
 	}
+	if (alloc)
+		*alloc = a;
+	if (miss)
+		*miss = m;
+	if (free)
+		*free = f;
+	if (ks)
+		*ks = s_k;
+	if (as)
+		*as = s_a;
 	return n;
 }
 
@@ -1206,6 +1247,7 @@ static unsigned int pisa_scan_bitmap(struct pisa_meta *meta, bool dirty,
 	}
 	*countp -= used;
 	pa->blocks_in_use += used;
+	pisa_stat_add(pa->stats.block_alloc_cnt, used);
 	return got;
 }
 
@@ -1254,9 +1296,11 @@ static struct pisa_meta *pisa_pick_meta(struct pisa_alloc *pa, bool zero)
 
 /* Extract up to @want blocks from @meta under @pa->lock. */
 static unsigned int take_blocks(struct pisa_meta *meta, unsigned int want,
-				struct page **out, bool zero, bool frozen)
+				struct page **out, bool can_block, bool zero,
+				bool frozen)
 {
 	unsigned int avail_before = pisa_meta_avail(meta), got = 0, used;
+	unsigned long base_pfn = pisa_meta_to_pfn(meta);
 	struct pisa_alloc *pa = meta->pa;
 
 	lockdep_assert_held(&pa->lock);
@@ -1269,12 +1313,23 @@ static unsigned int take_blocks(struct pisa_meta *meta, unsigned int want,
 		dirty = pisa_scan_bitmap(meta, true, want - got, out + got, false);
 		for (i = got; i < got + dirty; i++)
 			set_page_private(out[i], 1);
+		if (can_block) {
+			pisa_stat_add(pa->stats.alloc_kc, got);
+			pisa_stat_add(pa->stats.alloc_ks, dirty);
+		} else {
+			pisa_stat_add(pa->stats.alloc_ac, got);
+			pisa_stat_add(pa->stats.alloc_as, dirty);
+		}
 		got += dirty;
 		pa->scrub_demand = min(pa->scrub_demand + dirty, PISA_SCRUB_DEMAND_MAX);
 	} else {
 		/* First choice are dirty blocks, followed by clean */
 		got += pisa_scan_bitmap(meta, true, want, out, !frozen);
 		got += pisa_scan_bitmap(meta, false, want - got, out + got, !frozen);
+		if (can_block)
+			pisa_stat_add(pa->stats.alloc_kd, got);
+		else
+			pisa_stat_add(pa->stats.alloc_ad, got);
 	}
 
 	used = avail_before - pisa_meta_avail(meta);
@@ -1284,6 +1339,8 @@ static unsigned int take_blocks(struct pisa_meta *meta, unsigned int want,
 		meta->nr_dirty = 0;
 	}
 	pisa_place_meta(meta);
+	if (page_to_nid(pfn_to_page(base_pfn)) != pa->nid)
+		pisa_stat_add(pa->stats.numa_mismatch_cnt, used);
 
 	return got;
 }
@@ -1292,6 +1349,7 @@ static unsigned int take_blocks(struct pisa_meta *meta, unsigned int want,
 static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigned long nr_pages,
 				       struct page **pages, bool zero, bool frozen)
 {
+	bool can_block = gfpflags_allow_blocking(gfp);
 	bool should_scrub = false;
 	unsigned long n, flags, i;
 	struct pisa_meta *meta;
@@ -1299,7 +1357,8 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 
 	/* Held across bitmap scans; dropped around slow-path pisa_alloc_split_page(). */
 	spin_lock_irqsave(&pa->lock, flags);
-	for (n = 0; n < nr_pages; n += take_blocks(meta, want, &pages[n], zero, frozen)) {
+	for (n = 0; n < nr_pages;
+	     n += take_blocks(meta, want, &pages[n], can_block, zero, frozen)) {
 		want = min_t(unsigned long, nr_pages - n, PISA_BLOCKS(pa->order));
 		meta = pisa_pick_meta(pa, zero);
 		if (meta)
@@ -1310,15 +1369,31 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 		spin_unlock_irqrestore(&pa->lock, flags);
 		/* With @zero, fresh dirty blocks are zeroed below. */
 		meta = pisa_alloc_split_page(pa->order, gfp, pa->nid);
-		if (IS_ERR(meta))
+		if (IS_ERR(meta)) {
+			long err = PTR_ERR(meta);
+
+			if (err == -EAGAIN) {
+				pisa_stat_atomic_inc(pa->stats.fail_backoff);
+			} else if (err == -ENOSPC) {
+				pisa_stat_atomic_inc(pa->stats.fail_budget);
+			} else if (err == -ENOMEM) {
+				pisa_stat_atomic_inc(pa->stats.fail_nomem);
+				pr_warn_once("pisa: order-%u allocation failed for allocator %p; further failures are counted in debugfs only\n",
+					     PISA_ORDER, pa);
+			} else if (err == -EBUSY) {
+				pisa_stat_atomic_inc(pa->stats.fail_split);
+			}
+			if (!n)
+				pisa_stat_atomic_inc(pa->stats.block_alloc_fail);
 			goto out;
+		}
 		spin_lock_irqsave(&pa->lock, flags);
 		meta->pa = pa;
 		meta->prot = pa->prot;
 		WRITE_ONCE(meta->alloc_jiffies, jiffies);
 		/* Set PISA_ACTIVE after @meta is fully set up. */
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
-		pa->stats.page_alloc_cnt++;
+		pisa_stat_inc(pa->stats.page_alloc_cnt);
 	}
 	/* Queue the scrubber when the inline zeroing crosses the trigger. */
 	should_scrub |= pa->scrub_demand >= PISA_SCRUB_TRIGGER;
@@ -1346,9 +1421,11 @@ static unsigned long pisa_pcp_alloc(struct pisa_alloc *pa, gfp_t gfp, unsigned l
 				    struct page **page_array, bool frozen)
 {
 	unsigned int pcp_batch = READ_ONCE(pisa_pcp_batch);
-	unsigned long got, n, i, j;
+	bool zero = want_init_on_alloc(gfp);
+	unsigned long got, local, n, i, j;
 
 	got = pisa_pcp_pop(pa, nr_pages, page_array);
+	local = got;
 	if (got < nr_pages) {
 		if (nr_pages - got >= pcp_batch) {
 			got += __pisa_alloc_bulk(pa, gfp, nr_pages - got,
@@ -1360,7 +1437,7 @@ static unsigned long pisa_pcp_alloc(struct pisa_alloc *pa, gfp_t gfp, unsigned l
 			for (i = 0; i < n && got < nr_pages; i++)
 				page_array[got++] = batch[i];
 			if (i < n)
-				pisa_pcp_push(pa, batch + i, n - i);
+				pisa_pcp_push(pa, batch + i, n - i, false);
 		}
 	}
 
@@ -1369,10 +1446,13 @@ static unsigned long pisa_pcp_alloc(struct pisa_alloc *pa, gfp_t gfp, unsigned l
 
 		page_array[i] = NULL;
 		/* Poisoned while cached: leak it, as pisa_scan_bitmap() does. */
-		if (pisa_block_poisoned(pa, block))
+		if (pisa_block_poisoned(pa, block)) {
+			if (i < local)
+				local--;
 			continue;
+		}
 		pisa_block_prep(block);
-		if (want_init_on_alloc(gfp)) {
+		if (zero) {
 			memset(page_address(block), 0, PAGE_SIZE << pa->order);
 			if (frozen) /* Order zeroing before caller publishes the page. */
 				smp_wmb();
@@ -1381,6 +1461,15 @@ static unsigned long pisa_pcp_alloc(struct pisa_alloc *pa, gfp_t gfp, unsigned l
 			page_ref_unfreeze(block, 1);
 		page_array[j++] = block;
 	}
+	this_cpu_add(pa->pcp->alloc_cnt, j);
+	if (zero) {
+		if (gfpflags_allow_blocking(gfp))
+			this_cpu_add(pa->pcp->alloc_ks, j);
+		else
+			this_cpu_add(pa->pcp->alloc_as, j);
+	}
+	if (j > local)
+		this_cpu_inc(pa->pcp->miss_cnt);
 	return j;
 }
 
@@ -1400,10 +1489,14 @@ unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
 {
 	unsigned long i = 0, n, got;
 
-	if (unlikely(!pa ||
-		     (gfp & (__GFP_DMA | __GFP_DMA32 | __GFP_THISNODE | __GFP_ACCOUNT))))
+	if (unlikely(!pa))
 		goto skip;
 
+	if (unlikely(gfp & (__GFP_DMA | __GFP_DMA32 | __GFP_THISNODE | __GFP_ACCOUNT))) {
+		pisa_stat_atomic_inc(pa->stats.fail_gfp);
+		goto skip;
+	}
+
 	while (i < nr_pages) {
 		if (page_array[i]) {
 			i++;
@@ -1500,6 +1593,9 @@ static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock
 		page_ref_unfreeze(page + i, 1);
 	}
 	pa->blocks_in_use += nblocks;
+	pisa_stat_add(pa->stats.block_alloc_cnt, nblocks);
+	pisa_stat_add(pa->stats.alloc_kc, nblocks - dirty);
+	pisa_stat_add(pa->stats.alloc_ks, dirty);
 	pa->scrub_demand = min(pa->scrub_demand + dirty, PISA_SCRUB_DEMAND_MAX);
 	pisa_place_meta(meta);
 	return page;
@@ -1577,7 +1673,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		meta->prot = pa->prot;
 		WRITE_ONCE(meta->alloc_jiffies, jiffies);
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
-		pa->stats.page_alloc_cnt++;
+		pisa_stat_inc(pa->stats.page_alloc_cnt);
 		page = pisa_take_contig(meta, nblocks, align_mask);
 		if (unlikely(!page))
 			should_release = pisa_place_meta(meta);
@@ -1591,6 +1687,11 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		pisa_schedule_scrub(pa->nid);
 	if (!page)
 		return NULL;
+	/* Pairs with cmpxchg_release() in pisa_enable_pcp(). */
+	if (smp_load_acquire(&pa->pcp)) {
+		this_cpu_add(pa->pcp->alloc_cnt, nblocks);
+		this_cpu_inc(pa->pcp->miss_cnt);
+	}
 	*pagep = page;
 	return memset(page_address(page), 0, size);
 }
@@ -1631,9 +1732,10 @@ bool __pisa_free_page(struct page *page)
 	if (smp_load_acquire(&pa->pcp) && pa->nid == numa_mem_id() &&
 	    page_to_nid(page) == numa_mem_id()) {
 		if (pisa_page_can_recycle(page)) {
-			pisa_pcp_push(pa, &page, 1);
+			pisa_pcp_push(pa, &page, 1, true);
 			return true;
 		}
+		this_cpu_inc(pa->pcp->free_cnt);
 		if (this_cpu_read(pa->pcp->count))
 			pisa_pcp_drain_cpu(pa, raw_smp_processor_id());
 	}
@@ -1657,7 +1759,7 @@ static unsigned long pisa_shrink_count(struct shrinker *shrink, struct shrink_co
 	read_lock(&pisa_allocs_lock);
 	list_for_each_entry(pa, &pisa_allocs, node) {
 		nr += (unsigned long)READ_ONCE(pa->num_idle_pages) << PISA_ORDER;
-		nr += pisa_pcp_count(pa) << pa->order;
+		nr += pisa_pcp_stats(pa, NULL, NULL, NULL, NULL, NULL) << pa->order;
 	}
 	read_unlock(&pisa_allocs_lock);
 
@@ -1685,11 +1787,14 @@ unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
 VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
 {
 	struct pisa_meta *meta, *tmp;
+	unsigned long freed, res_freed;
 	struct pisa_alloc *pa;
-	unsigned long freed;
 	LIST_HEAD(release_list);
 
 	freed = pisa_reservoir_shrink(&release_list, sc->nr_to_scan);
+	res_freed = freed;
+	pisa_stat_atomic_inc(pisa_reclaim_stats.shrink_scan);
+	pisa_stat_atomic_add(pisa_reclaim_stats.pte_pages_res, res_freed);
 
 	if (freed < sc->nr_to_scan) {
 		read_lock(&pisa_allocs_lock);
@@ -1704,6 +1809,7 @@ VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct
 				break;
 		}
 		read_unlock(&pisa_allocs_lock);
+		pisa_stat_atomic_add(pisa_reclaim_stats.pte_pages_idle, freed - res_freed);
 	}
 
 	/* Unmap outside locks; defer decrypted pages to workqueue outside fs_reclaim. */
@@ -1723,6 +1829,141 @@ VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct
 	return freed ?: SHRINK_STOP;
 }
 
+/* See pisa_seq_kv(). */
+void __pisa_seq_kv(struct seq_file *s, const char *title, const struct pisa_kv *st, unsigned int n)
+{
+	seq_printf(s, "  %-12s", title);
+	for (; n; n--, st++)
+		seq_printf(s, " %-10s%11lld", st->name, st->val);
+	seq_putc(s, '\n');
+}
+
+/* Output global and active per-allocator statistics in /sys/kernel/debug/pisa/allocs. */
+static int pisa_allocs_show(struct seq_file *s, void *unused)
+{
+	struct pisa_reclaim_stats *rs = &pisa_reclaim_stats;
+	struct pisa_alloc *pa;
+
+	seq_puts(s, "global (allocators with no activity are omitted)\n");
+	pisa_seq_kv(s, pisa_pages_2m, { "in_use", atomic_long_read(&pisa_nr_pages) },
+		    { "max", pisa_max_pages },
+		    { "slots", pisa_nr_slots });
+	pisa_domains_show(s);
+	pisa_seq_kv(s, "reservoir", { pisa_pages_2m, pisa_reservoir_count() },
+		    { "max_node", pisa_reservoir_max });
+	pisa_seq_kv(s, "shrinker",
+		    { "scan", pisa_stat_atomic_read(rs->shrink_scan) },
+		    { "from_res", pisa_stat_atomic_read(rs->pte_pages_res) },
+		    { "from_idle", pisa_stat_atomic_read(rs->pte_pages_idle) });
+	pisa_seq_kv(s, "reclaim",
+		    { "runs", pisa_stat_read(rs->reclaim_run) },
+		    { pisa_pages_2m, pisa_stat_read(rs->reclaim_pages) },
+		    { "unmap_fail", pisa_stat_atomic_read(rs->unmap_fail) });
+	pisa_reservoir_show(s);
+	pisa_user_show(s);
+
+	read_lock(&pisa_allocs_lock);
+	list_for_each_entry(pa, &pisa_allocs, node) {
+		u64 alloc_pages, free_pages, block_alloc, block_free, block_scrub;
+		u64 pages_in_use, blocks_in_use, used_pct = 0, pcp_alloc, pcp_miss;
+		u64 block_fail, fail_gfp, numa_mismatch, pcp_free, cached;
+		u64 alloc_kd, alloc_kc, alloc_ks, alloc_ad, alloc_ac, alloc_as;
+		u64 pcp_ks, pcp_as;
+		struct pisa_alloc_stats *st = &pa->stats;
+		unsigned int num_idle, max_idle;
+		unsigned long flags;
+
+		block_fail = pisa_stat_atomic_read(st->block_alloc_fail);
+		fail_gfp = pisa_stat_atomic_read(st->fail_gfp);
+		cached = pisa_pcp_stats(pa, &pcp_alloc, &pcp_miss, &pcp_free, &pcp_ks, &pcp_as);
+
+		spin_lock_irqsave(&pa->lock, flags);
+		alloc_pages = st->page_alloc_cnt;
+		free_pages = st->page_free_cnt;
+		block_alloc = st->block_alloc_cnt;
+		block_free = st->block_free_cnt;
+		block_scrub = st->block_scrub_cnt;
+		numa_mismatch = st->numa_mismatch_cnt;
+		alloc_kd = st->alloc_kd;
+		alloc_kc = st->alloc_kc;
+		alloc_ks = st->alloc_ks;
+		alloc_ad = st->alloc_ad;
+		alloc_ac = st->alloc_ac;
+		alloc_as = st->alloc_as;
+		num_idle = pa->num_idle_pages;
+		max_idle = pa->max_idle_pages;
+		spin_unlock_irqrestore(&pa->lock, flags);
+
+		/* Omit allocators that have never allocated or failed an allocation. */
+		if (!alloc_pages && !block_alloc && !block_fail && !fail_gfp)
+			continue;
+
+		pages_in_use = alloc_pages > free_pages ? alloc_pages - free_pages : 0;
+		blocks_in_use = block_alloc > block_free + cached ?
+				block_alloc - block_free - cached : 0;
+		if (pages_in_use)
+			used_pct = div64_u64((blocks_in_use << pa->order) * 100,
+					     pages_in_use << PISA_ORDER);
+
+		seq_printf(s, "alloc %s order %u nid %d%s\n", pa->name, pa->order,
+			   pa->nid, pa->prot == IOMMU_READ ? " tx-only" :
+			   pa->prot == IOMMU_WRITE ? " rx-only" : "");
+		pisa_seq_kv(s, pisa_pages_2m, { "got", alloc_pages },
+			    { "put", free_pages }, { "in_use", pages_in_use },
+			    { "idle", num_idle }, { "idle_max", max_idle });
+		pisa_seq_kv(s, pisa_no_pages_2m,
+			    { "backoff", pisa_stat_atomic_read(st->fail_backoff) },
+			    { "budget", pisa_stat_atomic_read(st->fail_budget) },
+			    { "nomem", pisa_stat_atomic_read(st->fail_nomem) },
+			    { "split", pisa_stat_atomic_read(st->fail_split) });
+		pisa_seq_kv(s, "blocks", { "alloc", block_alloc },
+			    { "free", block_free }, { "in_use", blocks_in_use },
+			    { "used_pct", used_pct }, { "scrub", block_scrub });
+		pisa_seq_kv(s, "blocks", { "failed", block_fail },
+			    { "gfp", fail_gfp }, { "numa_miss", numa_mismatch });
+		pisa_seq_kv(s, "allocations",
+			    { "KD", alloc_kd }, { "KC", alloc_kc }, { "KS", alloc_ks },
+			    { "AD", alloc_ad }, { "AC", alloc_ac }, { "AS", alloc_as });
+		if (pa->pcp) {
+			int cpu;
+
+			pisa_seq_kv(s, "pcpu", { "alloc", pcp_alloc },
+				    { "miss", pcp_miss },
+				    { "free", pcp_free }, { "cached", cached },
+				    { "KS", pcp_ks }, { "AS", pcp_as });
+			for_each_possible_cpu(cpu) {
+				const struct pisa_pcp *pcp = per_cpu_ptr(pa->pcp, cpu);
+				u64 a = READ_ONCE(pcp->alloc_cnt);
+				u64 m = READ_ONCE(pcp->miss_cnt);
+				u64 f = READ_ONCE(pcp->free_cnt);
+				unsigned int c = READ_ONCE(pcp->count);
+				char title[16];
+
+				if (!a && !f && !c)
+					continue;
+				snprintf(title, sizeof(title), "pcpu_%u", cpu);
+				pisa_seq_kv(s, title, { "alloc", a },
+					    { "miss", m },
+					    { "free", f }, { "cached", c });
+			}
+		}
+#ifdef CONFIG_IOMMU_DMA
+		pisa_seq_kv(s, "domains",
+			    { "mapped", pisa_stat_atomic_read(st->page_map_cnt) });
+		pisa_seq_kv(s, "map_fail",
+			    { "no_window", pisa_stat_atomic_read(st->fallback_nowindow) },
+			    { "no_idx", pisa_stat_atomic_read(st->fallback_noidx) },
+			    { "no_huge", pisa_stat_atomic_read(st->fallback_nohuge) },
+			    { "map_err", pisa_stat_atomic_read(st->fallback_maperr) },
+			    { "prot", pisa_stat_atomic_read(st->fallback_prot) });
+#endif
+	}
+	read_unlock(&pisa_allocs_lock);
+
+	return 0;
+}
+DEFINE_SHOW_ATTRIBUTE(pisa_allocs);
+
 /* Return the blocks a dead CPU cached, which nothing else would. */
 static int pisa_cpu_dead(unsigned int cpu)
 {
@@ -1751,6 +1992,10 @@ static int __init pisa_init(void)
 	struct shrinker *shrink;
 	int nid, i;
 
+	snprintf(pisa_pages_2m, sizeof(pisa_pages_2m), "pages_%luM", PISA_SIZE >> 20);
+	snprintf(pisa_pages_4k, sizeof(pisa_pages_4k), "pages_%luK", PAGE_SIZE >> 10);
+	snprintf(pisa_no_pages_2m, sizeof(pisa_no_pages_2m), "no_pages_%luM", PISA_SIZE >> 20);
+
 	pisa_node_init();
 
 	/* Default ceiling is 1/8th of RAM (floor of 16 PISA pages). */
@@ -1787,7 +2032,6 @@ static int __init pisa_init(void)
 			pisa_nodes[nid].pa[ro][order] = pa;
 		}
 	}
-
 	pisa_user_boot_enable();
 
 	/* Dedicated WQ_MEM_RECLAIM workqueue so reclaim never blocks behind system_wq. */
@@ -1799,6 +2043,10 @@ static int __init pisa_init(void)
 				      pisa_cpu_dead) < 0)
 		pr_warn("pisa: no CPU hotplug callback, offline CPUs keep cached blocks\n");
 
+	/* Built-in and never unloaded; debugfs stubs are no-ops when disabled. */
+	debugfs_create_file("allocs", 0444, debugfs_create_dir("pisa", NULL),
+			    NULL, &pisa_allocs_fops);
+
 	shrink = shrinker_alloc(0, "pisa");
 	if (!shrink) {
 		pr_warn("pisa: shrinker registration failed\n");
drivers/iommu/pisa-kunit.c +4 -3
index 3fc17024bc9d0..22f4966412feb 100644
@@ -291,9 +291,9 @@ static int fake_domain_setup(struct kunit *test)
 
 static void test_map_and_domain_lifecycle(struct kunit *test)
 {
+	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	struct device dev = { .init_name = "pisa_map_kunit", .numa_node = NUMA_NO_NODE,
 			      .coherent_dma_mask = DMA_BIT_MASK(64) };
-	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	struct pisa_window *win;
 	struct pisa_meta *meta;
 	struct pisa_alloc *pa;
@@ -574,14 +574,15 @@ static void test_gfp_pisa(struct kunit *test)
 
 static void test_reservoir_and_scrubber(struct kunit *test)
 {
+	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	unsigned int old_res = READ_ONCE(pisa_reservoir_max);
 	unsigned int old_scrub = READ_ONCE(pisa_scrub_max);
-	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	struct pisa_meta *meta;
 	struct pisa_alloc *pa;
 	struct page *p;
 	int nid;
 
+	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
 	pisa_shrink_scan(NULL, &sc);
 
 	/* Refill reservoir to 1 PISA page per memory node, then consume one. */
@@ -607,9 +608,9 @@ static void test_reservoir_and_scrubber(struct kunit *test)
 			WRITE_ONCE(pisa_scrub_max, 512);
 			pisa_scrub_node(pa->nid);
 			KUNIT_EXPECT_EQ(test, meta->nr_dirty, 0U);
+			KUNIT_EXPECT_GE(test, pa->stats.block_scrub_cnt, 1ULL);
 		}
 	}
-	pisa_shrink_scan(NULL, &sc);
 
 	/* Trim reservoirs back to 0. */
 	WRITE_ONCE(pisa_reservoir_max, 0);
drivers/iommu/pisa-map.c +73 -6

161 lines not on this page · raw message

drivers/iommu/pisa-node.c +40 -3

89 lines not on this page · raw message

drivers/iommu/pisa-priv.h +122 -5

192 lines not on this page · raw message

drivers/iommu/pisa-user.c +70 -7

146 lines not on this page · raw message

include/linux/pisa.h +5 -0
index 1d9b07370cc75..667321b18ae47 100644
@@ -147,6 +147,7 @@ bool pisa_folio_upgrade(struct folio *folio, enum dma_data_direction dir,
 bool __pisa_bdev_enabled(struct block_device *bdev, enum dma_data_direction dir);
 bool __pisa_mapping_enabled(const struct address_space *mapping,
 			    enum dma_data_direction dir);
+void pisa_stats_inc_user_copy(void);
 int pisa_madvise(struct vm_area_struct *vma, unsigned long start,
 		 unsigned long end, bool to_pisa);
 
@@ -331,6 +332,10 @@ pisa_filemap_alloc(const struct address_space *mapping, gfp_t gfp,
 	return NULL;
 }
 
+static inline void pisa_stats_inc_user_copy(void)
+{
+}
+
 static inline int pisa_madvise(struct vm_area_struct *vma, unsigned long start,
 			       unsigned long end, bool to_pisa)
 {
net/core/datagram.c +2 -0
index 8ba9c39cb05ec..360ed445fe779 100644
@@ -693,6 +693,8 @@ static bool pisa_zc_iter(int *ret, struct sk_buff *skb, struct iov_iter *from, s
 	if (keep)
 		return false;
 
+	if (skb->len == orig_len)
+		pisa_stats_inc_user_copy();
 	*ret = (skb->len != orig_len) ? 0 : -EXDEV;
 	return true;
 }
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#161 lore raw

Re: [RFC PATCH v2 25/25] iommu/dma: Add PISA statistics and debugfs

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] iommu/dma: missing failure and NUMA stats in pisa_alloc_coherent() - [Low] iommu/dma: miscounted user…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] iommu/dma: missing failure and NUMA stats in pisa_alloc_coherent()
- [Low] iommu/dma: miscounted user page budget and skip stats in pisa-user.c
--

commit 56bd3064c75263649c376476a3726d7efc12bd48
Author: Luigi Rizzo <[email protected]>

iommu/dma: Add PISA statistics and debugfs

This commit adds per-allocator, per-node reservoir, user-page migration, and global shrinker/reclaim statistics for PISA, exposes them in /sys/kernel/debug/pisa/allocs, and logs a one-shot warning on the first 2MB buddy allocation failure.

Quoted 4 lines
drivers/iommu/pisa-alloc.c +0 -0
index cedb1a62d20e2..91b9f00d21985 100644

[ ... ]

Quoted 32 lines
drivers/iommu/pisa-alloc.c +18 -2
@@ -1310,15 +1369,31 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 		spin_unlock_irqrestore(&pa->lock, flags);
 		/* With @zero, fresh dirty blocks are zeroed below. */
 		meta = pisa_alloc_split_page(pa->order, gfp, pa->nid);
-		if (IS_ERR(meta))
+		if (IS_ERR(meta)) {
+			long err = PTR_ERR(meta);
+
+			if (err == -EAGAIN) {
+				pisa_stat_atomic_inc(pa->stats.fail_backoff);
+			} else if (err == -ENOSPC) {
+				pisa_stat_atomic_inc(pa->stats.fail_budget);
+			} else if (err == -ENOMEM) {
+				pisa_stat_atomic_inc(pa->stats.fail_nomem);
+				pr_warn_once("pisa: order-%u allocation failed for allocator %p; further failures are counted in debugfs only\n",
+					     PISA_ORDER, pa);
+			} else if (err == -EBUSY) {
+				pisa_stat_atomic_inc(pa->stats.fail_split);
+			}
+			if (!n)
+				pisa_stat_atomic_inc(pa->stats.block_alloc_fail);
 			goto out;
+		}
 		spin_lock_irqsave(&pa->lock, flags);
 		meta->pa = pa;
 		meta->prot = pa->prot;
 		WRITE_ONCE(meta->alloc_jiffies, jiffies);
 		/* Set PISA_ACTIVE after @meta is fully set up. */
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
-		pa->stats.page_alloc_cnt++;
+		pisa_stat_inc(pa->stats.page_alloc_cnt);
 	}

[ ... ]

Quoted 11 lines
drivers/iommu/pisa-alloc.c +3 -0
@@ -1500,6 +1593,9 @@ static struct page *pisa_take_contig(struct pisa_meta *meta, unsigned int nblock
 		page_ref_unfreeze(page + i, 1);
 	}
 	pa->blocks_in_use += nblocks;
+	pisa_stat_add(pa->stats.block_alloc_cnt, nblocks);
+	pisa_stat_add(pa->stats.alloc_kc, nblocks - dirty);
+	pisa_stat_add(pa->stats.alloc_ks, dirty);
 	pa->scrub_demand = min(pa->scrub_demand + dirty, PISA_SCRUB_DEMAND_MAX);
 	pisa_place_meta(meta);
 	return page;

drivers/iommu/pisa-alloc.c void *pisa_alloc_coherent(struct page **pagep, struct device *dev, · line 1679

Quoted 8 lines
drivers/iommu/pisa-alloc.c +1 -1
@@ -1577,7 +1673,7 @@ void *pisa_alloc_coherent(struct page **pagep, struct device *dev,
 		meta->prot = pa->prot;
 		WRITE_ONCE(meta->alloc_jiffies, jiffies);
 		WRITE_ONCE(meta->flags, meta->flags | PISA_ACTIVE);
-		pa->stats.page_alloc_cnt++;
+		pisa_stat_inc(pa->stats.page_alloc_cnt);
 		page = pisa_take_contig(meta, nblocks, align_mask);
 		if (unlikely(!page))
 			should_release = pisa_place_meta(meta);

[Severity: Low]
Should pisa_alloc_coherent() and pisa_take_contig() also update the allocator failure and NUMA mismatch counters?

Because the failure accounting and pr_warn_once() live in __pisa_alloc_bulk() rather than pisa_alloc_split_page(), a pisa_alloc_split_page() failure in pisa_alloc_coherent() returns NULL without updating pa->stats.fail_*, pa->stats.block_alloc_fail, or emitting the one-shot warning on -ENOMEM, and leaves an allocator with no prior allocations hidden from /sys/kernel/debug/pisa/allocs:

drivers/iommu/pisa-alloc.c:pisa_alloc_coherent() {
	...
		meta = pisa_alloc_split_page(0, gfp, pa->nid);
		if (IS_ERR(meta)) {
			if (should_scrub)
				pisa_schedule_scrub(pa->nid);
			return NULL;
		}
}

In addition, unlike take_blocks(), pisa_take_contig() does not add nblocks to pa->stats.numa_mismatch_cnt when page_to_nid(page) != pa->nid.

Quoted 4 lines
drivers/iommu/pisa-user.c +0 -0
index 7dca3bf066f0d..5cf199943f82c 100644

[ ... ]

Quoted 17 lines
drivers/iommu/pisa-user.c +8 -0
@@ -264,9 +288,17 @@ static unsigned int pisa_user_migrate_dir(struct list_head *list, bool to_pisa,
 		if (!gfpflags_allow_blocking(gfp))
 			mode = MIGRATE_ASYNC;
 	}
+	nr = list_count_nodes(list);	/* all order-0 */
 	if (migrate_pages(list, to_pisa ? pisa_user_new_folio : pisa_user_old_folio,
 			  NULL, (unsigned long)&mtc, mode, MR_SYSCALL, &done))
 		putback_movable_pages(list);
+	if (to_pisa) {
+		pisa_stat_atomic_add(pisa_user_stats.in, done);
+		pisa_stat_atomic_add(pisa_user_stats.in_fail, nr - done);
+	} else {
+		pisa_stat_atomic_add(pisa_user_stats.out, done);
+		pisa_stat_atomic_add(pisa_user_stats.out_fail, nr - done);
+	}
 	return done;
 }

[ ... ]

Quoted 8 lines
drivers/iommu/pisa-user.c +1 -3
@@ -583,9 +623,14 @@ int pisa_madvise(struct vm_area_struct *vma, unsigned long start, unsigned long
 		struct folio *folio = folio_walk_start(&fw, vma, addr, 0);
 
 		if (folio) {
-			if (pisa_user_want_dir(folio, to_pisa, DMA_TO_DEVICE, false) &&
-			    !pisa_user_busy(folio, 0) && isolate_folio_to_list(folio, &list))
-				n++;
+			if (to_pisa && folio_test_large(folio) && folio_test_anon(folio)) {

drivers/iommu/pisa-user.c int pisa_madvise(struct vm_area_struct *vma, unsigned long start, unsigned long · line 636

Quoted 10 lines
drivers/iommu/pisa-user.c +7 -0
+				pisa_stat_atomic_inc(pisa_user_stats.large);
+			} else if (pisa_user_want_dir(folio, to_pisa, DMA_TO_DEVICE, false)) {
+				if (pisa_user_busy(folio, 0))
+					pisa_stat_atomic_inc(pisa_user_stats.busy);
+				else if (isolate_folio_to_list(folio, &list))
+					n++;
+			}
 			folio_walk_end(&fw, vma);
 		}
 		if (n == PISA_USER_BATCH) {

[Severity: Low]
Does pisa_madvise() count budget exhaustion as pisa_user_stats.in_fail instead of pisa_user_stats.no_budget?

Unlike pisa_upgrade_user_pages(), pisa_madvise() isolates folios without checking pisa_user_budget(). When the user page budget is exhausted (or runs out mid-batch in pisa_user_new_folio()), migrate_pages() aborts and pisa_user_migrate_dir() charges the unmigrated folios (nr - done) to pisa_user_stats.in_fail rather than pisa_user_stats.no_budget.

Similarly, pisa_folio_upgrade() returns early when pisa_user_budget() <= 0 or pisa_user_busy(folio, 1) is true without incrementing pisa_user_stats.no_budget or pisa_user_stats.busy.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25