Skip to content

Commit 36c2cf8

Browse files
dlechPeter Zijlstra
authored andcommitted
cleanup: Add conditional guard helper
Add a new if_not_guard() macro to cleanup.h for handling conditional guards such as mutext_trylock(). This is more ergonomic than scoped_guard() for most use cases. Instead of hiding the error handling statement in the macro args, it works like a normal if statement and allow the error path to be indented while the normal code flow path is not indented. And it avoid unwanted side-effect from hidden for loop in scoped_guard(). Signed-off-by: David Lechner <[email protected]> Co-developed-by: Fabio M. De Francesco <[email protected]> Signed-off-by: Fabio M. De Francesco <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Reviewed-by: Dan Williams <[email protected]> Link: https://lkml.kernel.org/r/20241001-cleanup-if_not_cond_guard-v1-1-7753810b0f7a@baylibre.com
1 parent fcc22ac commit 36c2cf8

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

include/linux/cleanup.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,12 @@ static inline class_##_name##_t class_##_name##ext##_constructor(_init_args) \
273273
* an anonymous instance of the (guard) class, not recommended for
274274
* conditional locks.
275275
*
276+
* if_not_guard(name, args...) { <error handling> }:
277+
* convenience macro for conditional guards that calls the statement that
278+
* follows only if the lock was not acquired (typically an error return).
279+
*
280+
* Only for conditional locks.
281+
*
276282
* scoped_guard (name, args...) { }:
277283
* similar to CLASS(name, scope)(args), except the variable (with the
278284
* explicit name 'scope') is declard in a for-loop such that its scope is
@@ -343,6 +349,15 @@ _label: \
343349

344350
#define scoped_cond_guard(_name, _fail, args...) \
345351
__scoped_cond_guard(_name, _fail, __UNIQUE_ID(label), args)
352+
353+
#define __if_not_guard(_name, _id, args...) \
354+
BUILD_BUG_ON(!__is_cond_ptr(_name)); \
355+
CLASS(_name, _id)(args); \
356+
if (!__guard_ptr(_name)(&_id))
357+
358+
#define if_not_guard(_name, args...) \
359+
__if_not_guard(_name, __UNIQUE_ID(guard), args)
360+
346361
/*
347362
* Additional helper macros for generating lock guards with types, either for
348363
* locks that don't have a native type (eg. RCU, preempt) or those that need a

0 commit comments

Comments
 (0)