Skip to contentSkip to conversation

x86/sgx: Fix sgx_encl_may_map locking

PATCH Superseded Jarkko Sakkinen 1 participant 1 message Oct 5, 2020

Subsystems (2)

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 x86/sgx: Fix sgx_encl_may_map locking

Fix the issue further discussed in:

1. https://lore.kernel.org/linux-sgx/[email protected]/
2. https://lore.kernel.org/linux-sgx/[email protected]/

Use the approach suggested by Matthew, and supported by the analysis that I wrote:

https://lore.kernel.org/linux-sgx/[email protected]/

---
 arch/x86/kernel/cpu/sgx/encl.c | 24 +++++++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)
arch/x86/kernel/cpu/sgx/encl.c +23 -1
index 4c6407cd857a..2bb3ec6996e9 100644
@@ -307,6 +307,7 @@ int sgx_encl_may_map(struct sgx_encl *encl, unsigned long start,
 	unsigned long idx_start = PFN_DOWN(start);
 	unsigned long idx_end = PFN_DOWN(end - 1);
 	struct sgx_encl_page *page;
+	unsigned long count = 0;
 
 	XA_STATE(xas, &encl->page_array, idx_start);
 
@@ -317,10 +318,31 @@ int sgx_encl_may_map(struct sgx_encl *encl, unsigned long start,
 	if (current->personality & READ_IMPLIES_EXEC)
 		return -EACCES;
 
-	xas_for_each(&xas, page, idx_end)
+	/*
+	 * No need to hold encl->lock:
+	 * 1. None of the page->* get written.
+	 * 2. page->vm_max_prot_bits is set in sgx_encl_page_alloc(). This
+	 *    is before calling xa_insert(). After that it is never modified.
+	 */
+	xas_lock(&xas);
+	xas_for_each(&xas, page, idx_end) {
+		if (++count % XA_CHECK_SCHED)
+			continue;
+
+		xas_pause(&xas);
+		xas_unlock(&xas);
+
+		/*
+		 * Attributes are not protected by the xa_lock, so I'm assuming
+		 * that this is the legit place for the check.
+		 */
 		if (!page || (~page->vm_max_prot_bits & vm_prot_bits))
 			return -EACCES;
 
+		cond_resched();
+		xas_lock(&xas);
+	}
+
 	return 0;
 }
 
Signature · 1 line
2.25.1