Skip to content

Commit 88b1a17

Browse files
committed
mm: add 'try_get_page()' helper function
This is the same as the traditional 'get_page()' function, but instead of unconditionally incrementing the reference count of the page, it only does so if the count was "safe". It returns whether the reference count was incremented (and is marked __must_check, since the caller obviously has to be aware of it). Also like 'get_page()', you can't use this function unless you already had a reference to the page. The intent is that you can use this exactly like get_page(), but in situations where you want to limit the maximum reference count. The code currently does an unconditional WARN_ON_ONCE() if we ever hit the reference count issues (either zero or negative), as a notification that the conditional non-increment actually happened. NOTE! The count access for the "safety" check is inherently racy, but that doesn't matter since the buffer we use is basically half the range of the reference count (ie we look at the sign of the count). Acked-by: Matthew Wilcox <[email protected]> Cc: Jann Horn <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]>
1 parent f958d7b commit 88b1a17

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

include/linux/mm.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -980,6 +980,15 @@ static inline void get_page(struct page *page)
980980
page_ref_inc(page);
981981
}
982982

983+
static inline __must_check bool try_get_page(struct page *page)
984+
{
985+
page = compound_head(page);
986+
if (WARN_ON_ONCE(page_ref_count(page) <= 0))
987+
return false;
988+
page_ref_inc(page);
989+
return true;
990+
}
991+
983992
static inline void put_page(struct page *page)
984993
{
985994
page = compound_head(page);

0 commit comments

Comments
 (0)