parent(9)
β¨ parent(9) β¨
okay so bestie, welcome to a lil corner of the Kernel API Manual that is genuinely so cute once you get it π this is parent(9), and no it's not about your mom β it's about heap math. slay.
π NAME π
parent β ok so given the offset of the child, find the offset of the parent. that's it. that's the whole vibe. π¦
πΈ SYNOPSIS πΈ
size_t parent (size_t i , unsigned int lsbit , size_t size );
π ARGUMENTS π
iβ the offset of the heap element whose parent is sought. must be non-zero, no cap. like literally don't pass zero, it's not that kind of party πlsbitβ a precomputed 1-bit mask, equal to"size & -size". yes bestie, precompute it, it's giving prepared β¨sizeβ size of each element. the unit. the whole point. π
π₯ DESCRIPTION π₯
so in terms of array indexes, the parent of element j = i/size is simply (j-1)/2. easy, iconic, no notes. π
but β and here's the plot twist β when you're working in byte offsets, we can't use implicit truncation of integer divides. nope. not allowed. the math just doesn't math. π
fortunately (say it with me: fortunately π), we only need one bit of the quotient, not the full divide. size has a least significant bit. that bit will be clear if i is an even multiple of size, and set if it's an odd multiple. one bit carrying the whole team fr fr.
logically, we're doing "if (i & lsbit) i -= size;" β but since the branch is unpredictable, it's done with a bit of clever branch-free code instead. not me writing branch-free code π
π₯ main character optimization energy.
lowkey the whole trick is: unpredictable branches are a vibe check the CPU fails, so we skip the branch entirely. no branch, no problem π§
π SEE ALSO π
- Kernel file
./lib/sort.c is_aligned(9)swap_words_32(9)swap_words_64(9)swap_bytes(9)sort_r(9)sort_r_nonatomic(9)
go read those too, they're all in the same friend group π«Ά
β that's the whole page bestie, ily, go find some parents π
source: ./lib Β· dated: October 2026 πβ¨
π¦ where this page comes from
- nixpkgs unstable: linux-manual 7.3.1
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms