kunit_alloc_...get_resource(9)

πŸ“¦ version 7.3.1, in nixpkgs unstable

πŸ’… kunit_alloc_and_get_resource(9) β€” from the Kernel API Manual, bestie πŸŽ€

okay so real talk, this one lives in the Kernel API Manual and it's lowkey one of my faves because it does your cleanup for you. no cap. let me put you on πŸ’–


✨ NAME ✨

kunit_alloc_and_get_resource β€” allocates and returns a test managed resource. that's it, that's the vibe πŸ¦‹


🌸 SYNOPSIS 🌸

struct kunit_resource * kunit_alloc_and_get_resource (struct kunit *test
, kunit_resource_init_t init , kunit_resource_free_t free , gfp_t
internal_gfp , void *context );

like yes, that's a whole lot of parameters. breathe. we're gonna go through them one by one and it's gonna slay πŸ’…


⭐ ARGUMENTS ⭐

  • test β€” the test context object. this is your main character, the whole test lives here πŸ‘‘
  • init β€” a user supplied function to initialize the resource. you write it, you own it, icon behaviour honestly ✨
  • free β€” a user supplied function to free the resource (if needed). the "(if needed)" is doing a lot of heavy lifting there, ngl πŸ™ˆ
  • internal_gfp β€” the gfp to use for internal allocations. if you're unsure, use GFP_KERNEL. when in doubt, GFP_KERNEL, fr fr πŸ”₯
  • context β€” for the user to pass in arbitrary data to the init function. it's your little messenger bag of stuff πŸŽ€

πŸ¦‹ DESCRIPTION πŸ¦‹

so what it actually does: it allocates a test managed resource β€” meaning a resource that will automatically be cleaned up at the end of a test case. yes, automatic. no manual teardown spiral at 2am. we love her for that πŸ˜­πŸ’œ

if you want an example of the resource itself, go peek at struct kunit_resource, there's one in there.

this function is effectively identical to kunit_alloc_resource, but with one iconic little difference: it returns the struct kunit_resource pointer, not just the 'data' pointer. that's the whole plot twist 🫢

and because it hands you the resource itself, it also increments the resource's refcount. so heads up: you gotta call kunit_put_resource when you've finished with it. don't just walk away from her, that's rude πŸ’€


πŸŽ€ NOTE πŸŽ€

okay important one, bestie. KUnit needs to allocate memory for a kunit_resource object. that's non-negotiable, that's just how it is. so you must specify an internal_gfp that is compatible with the use context of your resource. like, compatible-compatible. don't be out here passing something that doesn't match your context, it's giving undefined chaos 🌈

πŸ’– SEE ALSO πŸ’–

Kernel file ./include/kunit/resource.h, plus the whole friend group:


aaaand that's the whole page πŸ’… this one came out of ./include/kunit in October 2026 β€” so if you're reading this from the future, hiii, hope you called kunit_put_resource πŸ˜€πŸ’œ bye bestie, go write some tests 🧚✨

πŸ“¦ where this page comes from