refcount_sub_and_test(9)

๐Ÿ“ฆ version 7.3.1, in nixpkgs unstable

๐Ÿ’… refcount_sub_and_test(9) โ€” from the Kernel API Manual, bestie

okay so this is refcount_sub_and_test(9) and honestly it's giving "math but make it kernel" ๐Ÿงฎโœจ

โœจ SYNOPSIS โœจ

bool refcount_sub_and_test (int i , refcount_t *r );

like, you hand it a number and a refcount, and it hands back a bool. slay.

๐ŸŽ€ ARGUMENTS ๐ŸŽ€

  • i โ€” the amount you wanna subtract from the refcount. how much we're taking off. ๐Ÿ’–
  • r โ€” the refcount itself. the main character. the one we're subtracting from. ๐Ÿ‘‘

๐ŸŒธ DESCRIPTION ๐ŸŒธ

so this one is similar to atomic_dec_and_test, but bestie, it has OPINIONS. like, it will not just quietly do the thing. instead:

  • it will WARN on underflow ๐Ÿ˜ญ
  • it will return false on underflow
  • it will ultimately leak on underflow (yes, leak. fr fr. that's the vibe. ๐Ÿ’€)
  • and it will fail to decrement when it's saturated at REFCOUNT_SATURATED

so like... it's the cautious one. it's not gonna let you vibe your way into an underflow without saying something about it. ๐Ÿšจ

it also handles the memory ordering for you, which is honestly so thoughtful:

  • it provides release memory ordering, so prior loads and stores are done before โ€” like, everything that came before is wrapped up and put away first ๐ŸŽ
  • and on success it provides acquire ordering, so free must come after. no cutting in line, periodt. โœ‹
โš ๏ธ but here's the thing: use of this function is not recommended for the normal reference counting use case โ€” you know, the super common one where references are taken and released one at a time. ๐Ÿซถ

in those cases you should use refcount_dec, or one of its variants, to decrement a reference count instead. like, that's the recommended route. refcount_sub_and_test is not the moment for your normal one-at-a-time situation. iykyk ๐Ÿ’…

๐ŸŒˆ RETURN ๐ŸŒˆ

  • true โ€” if the resulting refcount is 0 ๐ŸŽ‰
  • false โ€” otherwise ๐Ÿ˜Œ

๐Ÿฆ‹ SEE ALSO ๐Ÿฆ‹

Kernel file ./include/linux/refcount.h โ€” go read it, it's iconic ๐Ÿ‘‘

plus all these besties:


that's the whole page, bestie! ๐Ÿ’œ straight from ./include/linux, dated October 2026, and yeah โ€” it's refcount_sub_and_test(9), signed, sealed, delivered. mwah ๐Ÿซถโœจ๐ŸŽ€

๐Ÿ“ฆ where this page comes from