[RFC PATCH 13/45] KVM: arm64: pkvm: Add hyp_page_ref_inc_return()

Jean-Philippe Brucker
2023-02-01T14:07:43Z

Add a page_ref_inc() helper that returns an error on saturation instead
of BUG()ing. There is no limit in the IOMMU API for the number of times
a page can be mapped. Since pKVM has this limit at 2^16, error out
gracefully.

Signed-off-by: Jean-Philippe Brucker <jean-philippe@linaro.org>
---
arch/arm64/kvm/hyp/include/nvhe/memory.h | 15 +++++++++++++--
1 file changed, 13 insertions(+), 2 deletions(-)

diff --git a/arch/arm64/kvm/hyp/include/nvhe/memory.h b/arch/arm64/kvm/hyp/include/nvhe/memory.h
index a8d4a5b919d2..c40fff5d6d22 100644
--- a/arch/arm64/kvm/hyp/include/nvhe/memory.h
+++ b/arch/arm64/kvm/hyp/include/nvhe/memory.h
@@ -57,10 +57,21 @@ static inline int hyp_page_count(void *addr)
return p->refcount;
}

+/*
+ * Increase the refcount and return its new value.
+ * If the refcount is saturated, return a negative error
+ */
+static inline int hyp_page_ref_inc_return(struct hyp_page *p)
+{
+ if (p->refcount == USHRT_MAX)
+ return -EOVERFLOW;
+
+ return ++p->refcount;
+}
+
static inline void hyp_page_ref_inc(struct hyp_page *p)
{
- BUG_ON(p->refcount == USHRT_MAX);
- p->refcount++;
+ BUG_ON(hyp_page_ref_inc_return(p) <= 0);
}

static inline void hyp_page_ref_dec(struct hyp_page *p)
--
2.39.0