[PATCH v2 06/16] cred: Introduce cred_guard() and cred_scoped_guard() helpers

From: Vinicius Costa Gomes
Date: Wed Aug 21 2024 - 21:31:22 EST


These helpers will make it less error prone to use
override_creds_light()/revert_creds_light(). They make sure that they
are paired.

As they use the _light() version of the credentials override/revert
operations, they should only be used when there are guarantees that
the lifetime of the credentials in question is not modified during the
critical section.

Suggested-by: Christian Brauner <brauner@xxxxxxxxxx>
Signed-off-by: Vinicius Costa Gomes <vinicius.gomes@xxxxxxxxx>
---
include/linux/cred.h | 7 +++++++
1 file changed, 7 insertions(+)

diff --git a/include/linux/cred.h b/include/linux/cred.h
index e4a3155fe409..f4f3d55cd6a2 100644
--- a/include/linux/cred.h
+++ b/include/linux/cred.h
@@ -190,6 +190,13 @@ static inline void revert_creds_light(const struct cred *revert_cred)
rcu_assign_pointer(current->cred, revert_cred);
}

+DEFINE_LOCK_GUARD_1(__cred, struct cred,
+ _T->lock = (struct cred *)override_creds_light(_T->lock),
+ revert_creds_light(_T->lock));
+
+#define cred_guard(_cred) guard(__cred)(((struct cred *)_cred))
+#define cred_scoped_guard(_cred) scoped_guard(__cred, ((struct cred *)_cred))
+
/**
* get_new_cred_many - Get references on a new set of credentials
* @cred: The new credentials to reference
--
2.46.0