sphinx.addnodesdocument)}( rawsourcechildren]( translations LanguagesNode)}(hhh](h pending_xref)}(hhh]docutils.nodesTextChinese (Simplified)}(hhparenthuba attributes}(ids]classes]names]dupnames]backrefs] refdomainstdreftypedoc reftarget#/translations/zh_CN/core-api/rbtreemodnameN classnameN refexplicitutagnamehhh ubh)}(hhh]hChinese (Traditional)}(hhhh2ubah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget#/translations/zh_TW/core-api/rbtreemodnameN classnameN refexplicituh1hhh ubh)}(hhh]hItalian}(hhhhFubah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget#/translations/it_IT/core-api/rbtreemodnameN classnameN refexplicituh1hhh ubh)}(hhh]hJapanese}(hhhhZubah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget#/translations/ja_JP/core-api/rbtreemodnameN classnameN refexplicituh1hhh ubh)}(hhh]hKorean}(hhhhnubah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget#/translations/ko_KR/core-api/rbtreemodnameN classnameN refexplicituh1hhh ubh)}(hhh]hSpanish}(hhhhubah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget#/translations/sp_SP/core-api/rbtreemodnameN classnameN refexplicituh1hhh ubeh}(h]h ]h"]h$]h&]current_languageEnglishuh1h hh _documenthsourceNlineNubhsection)}(hhh](htitle)}(h!Red-black Trees (rbtree) in Linuxh]h!Red-black Trees (rbtree) in Linux}(hhhhhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhhh=/var/lib/git/docbuild/linux/Documentation/core-api/rbtree.rsthKubh field_list)}(hhh](hfield)}(hhh](h field_name)}(hDateh]hDate}(hhhhhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhhhKubh field_body)}(hJanuary 18, 2007h]h paragraph)}(hhh]hJanuary 18, 2007}(hhhhhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhhubah}(h]h ]h"]h$]h&]uh1hhhubeh}(h]h ]h"]h$]h&]uh1hhhhKhhhhubh)}(hhh](h)}(hAuthorh]hAuthor}(hhhhhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhhhKubh)}(hRob Landley h]h)}(hRob Landley h](h Rob Landley <}(h Rob Landley }(h>hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKhjubah}(h]h ]h"]h$]h&]uh1hhhubeh}(h]h ]h"]h$]h&]uh1hhhhKhhhhubeh}(h]h ]h"]h$]h&]uh1hhhhhhhhKubh)}(hhh](h)}(h0What are red-black trees, and what are they for?h]h0What are red-black trees, and what are they for?}(hjDhjBhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj?hhhhhK ubh)}(hXRed-black trees are a type of self-balancing binary search tree, used for storing sortable key/value data pairs. This differs from radix trees (which are used to efficiently store sparse arrays and thus use long integer indexes to insert/access/delete nodes) and hash tables (which are not kept sorted to be easily traversed in order, and must be tuned for a specific size and hash function where rbtrees scale gracefully storing arbitrary keys).h]hXRed-black trees are a type of self-balancing binary search tree, used for storing sortable key/value data pairs. This differs from radix trees (which are used to efficiently store sparse arrays and thus use long integer indexes to insert/access/delete nodes) and hash tables (which are not kept sorted to be easily traversed in order, and must be tuned for a specific size and hash function where rbtrees scale gracefully storing arbitrary keys).}(hjRhjPhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhK hj?hhubh)}(hXRed-black trees are similar to AVL trees, but provide faster real-time bounded worst case performance for insertion and deletion (at most two rotations and three rotations, respectively, to balance the tree), with slightly slower (but still O(log n)) lookup time.h]hXRed-black trees are similar to AVL trees, but provide faster real-time bounded worst case performance for insertion and deletion (at most two rotations and three rotations, respectively, to balance the tree), with slightly slower (but still O(log n)) lookup time.}(hj`hj^hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhj?hhubh)}(hTo quote Linux Weekly News:h]hTo quote Linux Weekly News:}(hjnhjlhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhj?hhubh block_quote)}(hhh]h)}(hXThere are a number of red-black trees in use in the kernel. The deadline and CFQ I/O schedulers employ rbtrees to track requests; the packet CD/DVD driver does the same. The high-resolution timer code uses an rbtree to organize outstanding timer requests. The ext3 filesystem tracks directory entries in a red-black tree. Virtual memory areas (VMAs) are tracked with red-black trees, as are epoll file descriptors, cryptographic keys, and network packets in the "hierarchical token bucket" scheduler.h]hXThere are a number of red-black trees in use in the kernel. The deadline and CFQ I/O schedulers employ rbtrees to track requests; the packet CD/DVD driver does the same. The high-resolution timer code uses an rbtree to organize outstanding timer requests. The ext3 filesystem tracks directory entries in a red-black tree. Virtual memory areas (VMAs) are tracked with red-black trees, as are epoll file descriptors, cryptographic keys, and network packets in the “hierarchical token bucket” scheduler.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhj|ubah}(h]h ]h"]h$]h&]uh1jzhj?hhhhhNubh)}(hThis document covers use of the Linux rbtree implementation. For more information on the nature and implementation of Red Black Trees, see:h]hThis document covers use of the Linux rbtree implementation. For more information on the nature and implementation of Red Black Trees, see:}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhK#hj?hhubj{)}(hhh]hdefinition_list)}(hhh](hdefinition_list_item)}(hNLinux Weekly News article on red-black trees https://lwn.net/Articles/184495/ h](hterm)}(h,Linux Weekly News article on red-black treesh]h,Linux Weekly News article on red-black trees}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1jhhhK'hjubh definition)}(hhh]h)}(h https://lwn.net/Articles/184495/h]j)}(hjh]h https://lwn.net/Articles/184495/}(hhhjhhhNhNubah}(h]h ]h"]h$]h&]refurijuh1jhjubah}(h]h ]h"]h$]h&]uh1hhhhK'hjubah}(h]h ]h"]h$]h&]uh1jhjubeh}(h]h ]h"]h$]h&]uh1jhhhK'hjubj)}(hPWikipedia entry on red-black trees https://en.wikipedia.org/wiki/Red-black_tree h](j)}(h"Wikipedia entry on red-black treesh]h"Wikipedia entry on red-black trees}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1jhhhK*hjubj)}(hhh]h)}(h,https://en.wikipedia.org/wiki/Red-black_treeh]j)}(hjh]h,https://en.wikipedia.org/wiki/Red-black_tree}(hhhjhhhNhNubah}(h]h ]h"]h$]h&]refurijuh1jhjubah}(h]h ]h"]h$]h&]uh1hhhhK*hjubah}(h]h ]h"]h$]h&]uh1jhjubeh}(h]h ]h"]h$]h&]uh1jhhhK*hjubeh}(h]h ]h"]h$]h&]uh1jhjubah}(h]h ]h"]h$]h&]uh1jzhj?hhhNhNubeh}(h].what-are-red-black-trees-and-what-are-they-forah ]h"]0what are red-black trees, and what are they for?ah$]h&]uh1hhhhhhhhK ubh)}(hhh](h)}(h'Linux implementation of red-black treesh]h'Linux implementation of red-black trees}(hj:hj8hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj5hhhhhK-ubh)}(hhLinux's rbtree implementation lives in the file "lib/rbtree.c". To use it, "#include ".h]hrLinux’s rbtree implementation lives in the file “lib/rbtree.c”. To use it, “#include ”.}(hjHhjFhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhK/hj5hhubh)}(hX&The Linux rbtree implementation is optimized for speed, and thus has one less layer of indirection (and better cache locality) than more traditional tree implementations. Instead of using pointers to separate rb_node and data structures, each instance of struct rb_node is embedded in the data structure it organizes. And instead of using a comparison callback function pointer, users are expected to write their own tree search and insert functions which call the provided rbtree functions. Locking is also left up to the user of the rbtree code.h]hX&The Linux rbtree implementation is optimized for speed, and thus has one less layer of indirection (and better cache locality) than more traditional tree implementations. Instead of using pointers to separate rb_node and data structures, each instance of struct rb_node is embedded in the data structure it organizes. And instead of using a comparison callback function pointer, users are expected to write their own tree search and insert functions which call the provided rbtree functions. Locking is also left up to the user of the rbtree code.}(hjVhjThhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhK2hj5hhubeh}(h]'linux-implementation-of-red-black-treesah ]h"]'linux implementation of red-black treesah$]h&]uh1hhhhhhhhK-ubh)}(hhh](h)}(hCreating a new rbtreeh]hCreating a new rbtree}(hjohjmhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjjhhhhhKhjjhhubh literal_block)}(hDstruct mytype { struct rb_node node; char *keystring; };h]hDstruct mytype { struct rb_node node; char *keystring; };}(hhhjubah}(h]h ]h"]h$]h&] xml:spacepreserveuh1jhhhK@hjjhhubh)}(hWhen dealing with a pointer to the embedded struct rb_node, the containing data structure may be accessed with the standard container_of() macro. In addition, individual members may be accessed directly via rb_entry(node, type, member).h]hWhen dealing with a pointer to the embedded struct rb_node, the containing data structure may be accessed with the standard container_of() macro. In addition, individual members may be accessed directly via rb_entry(node, type, member).}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKEhjjhhubh)}(hYAt the root of each rbtree is an rb_root structure, which is initialized to be empty via:h]hYAt the root of each rbtree is an rb_root structure, which is initialized to be empty via:}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKIhjjhhubj{)}(hhh]h)}(h struct rb_root mytree = RB_ROOT;h]h struct rb_root mytree = RB_ROOT;}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKLhjubah}(h]h ]h"]h$]h&]uh1jzhjjhhhhhNubeh}(h]creating-a-new-rbtreeah ]h"]creating a new rbtreeah$]h&]uh1hhhhhhhhKrb_node; while (node) { struct mytype *data = container_of(node, struct mytype, node); int result; result = strcmp(string, data->keystring); if (result < 0) node = node->rb_left; else if (result > 0) node = node->rb_right; else return data; } return NULL; }h]hXstruct mytype *my_search(struct rb_root *root, char *string) { struct rb_node *node = root->rb_node; while (node) { struct mytype *data = container_of(node, struct mytype, node); int result; result = strcmp(string, data->keystring); if (result < 0) node = node->rb_left; else if (result > 0) node = node->rb_right; else return data; } return NULL; }}(hhhjubah}(h]h ]h"]h$]h&]jjuh1jhhhKVhjhhubeh}(h]"searching-for-a-value-in-an-rbtreeah ]h"]"searching for a value in an rbtreeah$]h&]uh1hhhhhhhhKOubh)}(hhh](h)}(hInserting data into an rbtreeh]hInserting data into an rbtree}(hj hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhKkubh)}(hInserting data in the tree involves first searching for the place to insert the new node, then inserting the node and rebalancing ("recoloring") the tree.h]hInserting data in the tree involves first searching for the place to insert the new node, then inserting the node and rebalancing (“recoloring”) the tree.}(hj.hj,hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKmhjhhubh)}(hThe search for insertion differs from the previous search by finding the location of the pointer on which to graft the new node. The new node also needs a link to its parent node for rebalancing purposes.h]hThe search for insertion differs from the previous search by finding the location of the pointer on which to graft the new node. The new node also needs a link to its parent node for rebalancing purposes.}(hj<hj:hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKphjhhubh)}(h Example::h]hExample:}(hExample:hjHhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKthjhhubj)}(hXint my_insert(struct rb_root *root, struct mytype *data) { struct rb_node **new = &(root->rb_node), *parent = NULL; /* Figure out where to put new node */ while (*new) { struct mytype *this = container_of(*new, struct mytype, node); int result = strcmp(data->keystring, this->keystring); parent = *new; if (result < 0) new = &((*new)->rb_left); else if (result > 0) new = &((*new)->rb_right); else return FALSE; } /* Add new node and rebalance tree. */ rb_link_node(&data->node, parent, new); rb_insert_color(&data->node, root); return TRUE; }h]hXint my_insert(struct rb_root *root, struct mytype *data) { struct rb_node **new = &(root->rb_node), *parent = NULL; /* Figure out where to put new node */ while (*new) { struct mytype *this = container_of(*new, struct mytype, node); int result = strcmp(data->keystring, this->keystring); parent = *new; if (result < 0) new = &((*new)->rb_left); else if (result > 0) new = &((*new)->rb_right); else return FALSE; } /* Add new node and rebalance tree. */ rb_link_node(&data->node, parent, new); rb_insert_color(&data->node, root); return TRUE; }}(hhhjWubah}(h]h ]h"]h$]h&]jjuh1jhhhKvhjhhubeh}(h]inserting-data-into-an-rbtreeah ]h"]inserting data into an rbtreeah$]h&]uh1hhhhhhhhKkubh)}(hhh](h)}(h0Removing or replacing existing data in an rbtreeh]h0Removing or replacing existing data in an rbtree}(hjrhjphhhNhNubah}(h]h ]h"]h$]h&]uh1hhjmhhhhhKubh)}(h.To remove an existing node from a tree, call::h]h-To remove an existing node from a tree, call:}(h-To remove an existing node from a tree, call:hj~hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjmhhubj)}(hnode, &mytree); myfree(data); }h]h{struct mytype *data = mysearch(&mytree, "walrus"); if (data) { rb_erase(&data->node, &mytree); myfree(data); }}(hhhjubah}(h]h ]h"]h$]h&]jjuh1jhhhKhjmhhubh)}(hNTo replace an existing node in a tree with a new one with the same key, call::h]hMTo replace an existing node in a tree with a new one with the same key, call:}(hMTo replace an existing node in a tree with a new one with the same key, call:hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjmhhubj)}(hkvoid rb_replace_node(struct rb_node *old, struct rb_node *new, struct rb_root *tree);h]hkvoid rb_replace_node(struct rb_node *old, struct rb_node *new, struct rb_root *tree);}(hhhjubah}(h]h ]h"]h$]h&]jjuh1jhhhKhjmhhubh)}(hReplacing a node this way does not re-sort the tree: If the new node doesn't have the same key as the old node, the rbtree will probably become corrupted.h]hReplacing a node this way does not re-sort the tree: If the new node doesn’t have the same key as the old node, the rbtree will probably become corrupted.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjmhhubeh}(h]0removing-or-replacing-existing-data-in-an-rbtreeah ]h"]0removing or replacing existing data in an rbtreeah$]h&]uh1hhhhhhhhKubh)}(hhh](h)}(hBIterating through the elements stored in an rbtree (in sort order)h]hBIterating through the elements stored in an rbtree (in sort order)}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhKubh)}(hFour functions are provided for iterating through an rbtree's contents in sorted order. These work on arbitrary trees, and should not need to be modified or wrapped (except for locking purposes)::h]hFour functions are provided for iterating through an rbtree’s contents in sorted order. These work on arbitrary trees, and should not need to be modified or wrapped (except for locking purposes):}(hFour functions are provided for iterating through an rbtree's contents in sorted order. These work on arbitrary trees, and should not need to be modified or wrapped (except for locking purposes):hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubj)}(hstruct rb_node *rb_first(struct rb_root *tree); struct rb_node *rb_last(struct rb_root *tree); struct rb_node *rb_next(struct rb_node *node); struct rb_node *rb_prev(struct rb_node *node);h]hstruct rb_node *rb_first(struct rb_root *tree); struct rb_node *rb_last(struct rb_root *tree); struct rb_node *rb_next(struct rb_node *node); struct rb_node *rb_prev(struct rb_node *node);}(hhhj ubah}(h]h ]h"]h$]h&]jjuh1jhhhKhjhhubh)}(hX]To start iterating, call rb_first() or rb_last() with a pointer to the root of the tree, which will return a pointer to the node structure contained in the first or last element in the tree. To continue, fetch the next or previous node by calling rb_next() or rb_prev() on the current node. This will return NULL when there are no more nodes left.h]hX]To start iterating, call rb_first() or rb_last() with a pointer to the root of the tree, which will return a pointer to the node structure contained in the first or last element in the tree. To continue, fetch the next or previous node by calling rb_next() or rb_prev() on the current node. This will return NULL when there are no more nodes left.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubh)}(hThe iterator functions return a pointer to the embedded struct rb_node, from which the containing data structure may be accessed with the container_of() macro, and individual members may be accessed directly via rb_entry(node, type, member).h]hThe iterator functions return a pointer to the embedded struct rb_node, from which the containing data structure may be accessed with the container_of() macro, and individual members may be accessed directly via rb_entry(node, type, member).}(hj)hj'hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubh)}(h Example::h]hExample:}(hExample:hj5hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubj)}(hstruct rb_node *node; for (node = rb_first(&mytree); node; node = rb_next(node)) printk("key=%s\n", rb_entry(node, struct mytype, node)->keystring);h]hstruct rb_node *node; for (node = rb_first(&mytree); node; node = rb_next(node)) printk("key=%s\n", rb_entry(node, struct mytype, node)->keystring);}(hhhjDubah}(h]h ]h"]h$]h&]jjuh1jhhhKhjhhubeh}(h]@iterating-through-the-elements-stored-in-an-rbtree-in-sort-orderah ]h"]Biterating through the elements stored in an rbtree (in sort order)ah$]h&]uh1hhhhhhhhKubh)}(hhh](h)}(hCached rbtreesh]hCached rbtrees}(hj_hj]hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjZhhhhhKubh)}(hXComputing the leftmost (smallest) node is quite a common task for binary search trees, such as for traversals or users relying on a the particular order for their own logic. To this end, users can use 'struct rb_root_cached' to optimize O(logN) rb_first() calls to a simple pointer fetch avoiding potentially expensive tree iterations. This is done at negligible runtime overhead for maintenance; albeit larger memory footprint.h]hXComputing the leftmost (smallest) node is quite a common task for binary search trees, such as for traversals or users relying on a the particular order for their own logic. To this end, users can use ‘struct rb_root_cached’ to optimize O(logN) rb_first() calls to a simple pointer fetch avoiding potentially expensive tree iterations. This is done at negligible runtime overhead for maintenance; albeit larger memory footprint.}(hjmhjkhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjZhhubh)}(hRSimilar to the rb_root structure, cached rbtrees are initialized to be empty via::h]hQSimilar to the rb_root structure, cached rbtrees are initialized to be empty via:}(hQSimilar to the rb_root structure, cached rbtrees are initialized to be empty via:hjyhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjZhhubj)}(h.struct rb_root_cached mytree = RB_ROOT_CACHED;h]h.struct rb_root_cached mytree = RB_ROOT_CACHED;}(hhhjubah}(h]h ]h"]h$]h&]jjuh1jhhhKhjZhhubh)}(hCached rbtree is simply a regular rb_root with an extra pointer to cache the leftmost node. This allows rb_root_cached to exist wherever rb_root does, which permits augmented trees to be supported as well as only a few extra interfaces::h]hCached rbtree is simply a regular rb_root with an extra pointer to cache the leftmost node. This allows rb_root_cached to exist wherever rb_root does, which permits augmented trees to be supported as well as only a few extra interfaces:}(hCached rbtree is simply a regular rb_root with an extra pointer to cache the leftmost node. This allows rb_root_cached to exist wherever rb_root does, which permits augmented trees to be supported as well as only a few extra interfaces:hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjZhhubj)}(hstruct rb_node *rb_first_cached(struct rb_root_cached *tree); void rb_insert_color_cached(struct rb_node *, struct rb_root_cached *, bool); void rb_erase_cached(struct rb_node *node, struct rb_root_cached *);h]hstruct rb_node *rb_first_cached(struct rb_root_cached *tree); void rb_insert_color_cached(struct rb_node *, struct rb_root_cached *, bool); void rb_erase_cached(struct rb_node *node, struct rb_root_cached *);}(hhhjubah}(h]h ]h"]h$]h&]jjuh1jhhhKhjZhhubh)}(hRBoth insert and erase calls have their respective counterpart of augmented trees::h]hQBoth insert and erase calls have their respective counterpart of augmented trees:}(hQBoth insert and erase calls have their respective counterpart of augmented trees:hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjZhhubj)}(hXvoid rb_insert_augmented_cached(struct rb_node *node, struct rb_root_cached *, bool, struct rb_augment_callbacks *); void rb_erase_augmented_cached(struct rb_node *, struct rb_root_cached *, struct rb_augment_callbacks *);h]hXvoid rb_insert_augmented_cached(struct rb_node *node, struct rb_root_cached *, bool, struct rb_augment_callbacks *); void rb_erase_augmented_cached(struct rb_node *, struct rb_root_cached *, struct rb_augment_callbacks *);}(hhhjubah}(h]h ]h"]h$]h&]jjuh1jhhhKhjZhhubeh}(h]cached-rbtreesah ]h"]cached rbtreesah$]h&]uh1hhhhhhhhKubh)}(hhh](h)}(hSupport for Augmented rbtreesh]hSupport for Augmented rbtrees}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhKubh)}(hXAugmented rbtree is an rbtree with "some" additional data stored in each node, where the additional data for node N must be a function of the contents of all nodes in the subtree rooted at N. This data can be used to augment some new functionality to rbtree. Augmented rbtree is an optional feature built on top of basic rbtree infrastructure. An rbtree user who wants this feature will have to call the augmentation functions with the user provided augmentation callback when inserting and erasing nodes.h]hXAugmented rbtree is an rbtree with “some” additional data stored in each node, where the additional data for node N must be a function of the contents of all nodes in the subtree rooted at N. This data can be used to augment some new functionality to rbtree. Augmented rbtree is an optional feature built on top of basic rbtree infrastructure. An rbtree user who wants this feature will have to call the augmentation functions with the user provided augmentation callback when inserting and erasing nodes.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubh)}(hXC files implementing augmented rbtree manipulation must include instead of . Note that linux/rbtree_augmented.h exposes some rbtree implementations details you are not expected to rely on; please stick to the documented APIs there and do not include from header files either so as to minimize chances of your users accidentally relying on such implementation details.h]hXC files implementing augmented rbtree manipulation must include instead of . Note that linux/rbtree_augmented.h exposes some rbtree implementations details you are not expected to rely on; please stick to the documented APIs there and do not include from header files either so as to minimize chances of your users accidentally relying on such implementation details.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubh)}(hXlOn insertion, the user must update the augmented information on the path leading to the inserted node, then call rb_link_node() as usual and rb_augment_inserted() instead of the usual rb_insert_color() call. If rb_augment_inserted() rebalances the rbtree, it will callback into a user provided function to update the augmented information on the affected subtrees.h]hXlOn insertion, the user must update the augmented information on the path leading to the inserted node, then call rb_link_node() as usual and rb_augment_inserted() instead of the usual rb_insert_color() call. If rb_augment_inserted() rebalances the rbtree, it will callback into a user provided function to update the augmented information on the affected subtrees.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubh)}(hWhen erasing a node, the user must call rb_erase_augmented() instead of rb_erase(). rb_erase_augmented() calls back into user provided functions to updated the augmented information on affected subtrees.h]hWhen erasing a node, the user must call rb_erase_augmented() instead of rb_erase(). rb_erase_augmented() calls back into user provided functions to updated the augmented information on affected subtrees.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(hkIn both cases, the callbacks are provided through struct rb_augment_callbacks. 3 callbacks must be defined:h]hkIn both cases, the callbacks are provided through struct rb_augment_callbacks. 3 callbacks must be defined:}(hj#hj!hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh bullet_list)}(hhh](h list_item)}(hA propagation callback, which updates the augmented value for a given node and its ancestors, up to a given stop point (or NULL to update all the way to the root). h]h)}(hA propagation callback, which updates the augmented value for a given node and its ancestors, up to a given stop point (or NULL to update all the way to the root).h]hA propagation callback, which updates the augmented value for a given node and its ancestors, up to a given stop point (or NULL to update all the way to the root).}(hj<hj:hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhj6ubah}(h]h ]h"]h$]h&]uh1j4hj1hhhhhNubj5)}(hhA copy callback, which copies the augmented value for a given subtree to a newly assigned subtree root. h]h)}(hgA copy callback, which copies the augmented value for a given subtree to a newly assigned subtree root.h]hgA copy callback, which copies the augmented value for a given subtree to a newly assigned subtree root.}(hjThjRhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM hjNubah}(h]h ]h"]h$]h&]uh1j4hj1hhhhhNubj5)}(hA tree rotation callback, which copies the augmented value for a given subtree to a newly assigned subtree root AND recomputes the augmented information for the former subtree root. h]h)}(hA tree rotation callback, which copies the augmented value for a given subtree to a newly assigned subtree root AND recomputes the augmented information for the former subtree root.h]hA tree rotation callback, which copies the augmented value for a given subtree to a newly assigned subtree root AND recomputes the augmented information for the former subtree root.}(hjlhjjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjfubah}(h]h ]h"]h$]h&]uh1j4hj1hhhhhNubeh}(h]h ]h"]h$]h&]bullet-uh1j/hhhMhjhhubh)}(hThe compiled code for rb_erase_augmented() may inline the propagation and copy callbacks, which results in a large function, so each augmented rbtree user should have a single rb_erase_augmented() call site in order to limit compiled code size.h]hThe compiled code for rb_erase_augmented() may inline the propagation and copy callbacks, which results in a large function, so each augmented rbtree user should have a single rb_erase_augmented() call site in order to limit compiled code size.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(hhh](h)}(h Sample usageh]h Sample usage}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhMubh)}(hInterval tree is an example of augmented rb tree. Reference - "Introduction to Algorithms" by Cormen, Leiserson, Rivest and Stein. More details about interval trees:h]hInterval tree is an example of augmented rb tree. Reference - “Introduction to Algorithms” by Cormen, Leiserson, Rivest and Stein. More details about interval trees:}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(hClassical rbtree has a single key and it cannot be directly used to store interval ranges like [lo:hi] and do a quick lookup for any overlap with a new lo:hi or to find whether there is an exact match for a new lo:hi.h]hClassical rbtree has a single key and it cannot be directly used to store interval ranges like [lo:hi] and do a quick lookup for any overlap with a new lo:hi or to find whether there is an exact match for a new lo:hi.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(hHowever, rbtree can be augmented to store such interval ranges in a structured way making it possible to do efficient lookup and exact match.h]hHowever, rbtree can be augmented to store such interval ranges in a structured way making it possible to do efficient lookup and exact match.}(hjhjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM#hjhhubh)}(hXeThis "extra information" stored in each node is the maximum hi (max_hi) value among all the nodes that are its descendants. This information can be maintained at each node just be looking at the node and its immediate children. And this will be used in O(log n) lookup for lowest match (lowest start address among all possible matches) with something like::h]hXhThis “extra information” stored in each node is the maximum hi (max_hi) value among all the nodes that are its descendants. This information can be maintained at each node just be looking at the node and its immediate children. And this will be used in O(log n) lookup for lowest match (lowest start address among all possible matches) with something like:}(hXdThis "extra information" stored in each node is the maximum hi (max_hi) value among all the nodes that are its descendants. This information can be maintained at each node just be looking at the node and its immediate children. And this will be used in O(log n) lookup for lowest match (lowest start address among all possible matches) with something like:hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM&hjhhubj)}(hX/struct interval_tree_node * interval_tree_first_match(struct rb_root *root, unsigned long start, unsigned long last) { struct interval_tree_node *node; if (!root->rb_node) return NULL; node = rb_entry(root->rb_node, struct interval_tree_node, rb); while (true) { if (node->rb.rb_left) { struct interval_tree_node *left = rb_entry(node->rb.rb_left, struct interval_tree_node, rb); if (left->__subtree_last >= start) { /* * Some nodes in left subtree satisfy Cond2. * Iterate to find the leftmost such node N. * If it also satisfies Cond1, that's the match * we are looking for. Otherwise, there is no * matching interval as nodes to the right of N * can't satisfy Cond1 either. */ node = left; continue; } } if (node->start <= last) { /* Cond1 */ if (node->last >= start) /* Cond2 */ return node; /* node is leftmost match */ if (node->rb.rb_right) { node = rb_entry(node->rb.rb_right, struct interval_tree_node, rb); if (node->__subtree_last >= start) continue; } } return NULL; /* No match */ } }h]hX/struct interval_tree_node * interval_tree_first_match(struct rb_root *root, unsigned long start, unsigned long last) { struct interval_tree_node *node; if (!root->rb_node) return NULL; node = rb_entry(root->rb_node, struct interval_tree_node, rb); while (true) { if (node->rb.rb_left) { struct interval_tree_node *left = rb_entry(node->rb.rb_left, struct interval_tree_node, rb); if (left->__subtree_last >= start) { /* * Some nodes in left subtree satisfy Cond2. * Iterate to find the leftmost such node N. * If it also satisfies Cond1, that's the match * we are looking for. Otherwise, there is no * matching interval as nodes to the right of N * can't satisfy Cond1 either. */ node = left; continue; } } if (node->start <= last) { /* Cond1 */ if (node->last >= start) /* Cond2 */ return node; /* node is leftmost match */ if (node->rb.rb_right) { node = rb_entry(node->rb.rb_right, struct interval_tree_node, rb); if (node->__subtree_last >= start) continue; } } return NULL; /* No match */ } }}(hhhjubah}(h]h ]h"]h$]h&]jjuh1jhhhM-hjhhubh)}(hGInsertion/removal are defined using the following augmented callbacks::h]hFInsertion/removal are defined using the following augmented callbacks:}(hFInsertion/removal are defined using the following augmented callbacks:hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMWhjhhubj)}(hX static inline unsigned long compute_subtree_last(struct interval_tree_node *node) { unsigned long max = node->last, subtree_last; if (node->rb.rb_left) { subtree_last = rb_entry(node->rb.rb_left, struct interval_tree_node, rb)->__subtree_last; if (max < subtree_last) max = subtree_last; } if (node->rb.rb_right) { subtree_last = rb_entry(node->rb.rb_right, struct interval_tree_node, rb)->__subtree_last; if (max < subtree_last) max = subtree_last; } return max; } static void augment_propagate(struct rb_node *rb, struct rb_node *stop) { while (rb != stop) { struct interval_tree_node *node = rb_entry(rb, struct interval_tree_node, rb); unsigned long subtree_last = compute_subtree_last(node); if (node->__subtree_last == subtree_last) break; node->__subtree_last = subtree_last; rb = rb_parent(&node->rb); } } static void augment_copy(struct rb_node *rb_old, struct rb_node *rb_new) { struct interval_tree_node *old = rb_entry(rb_old, struct interval_tree_node, rb); struct interval_tree_node *new = rb_entry(rb_new, struct interval_tree_node, rb); new->__subtree_last = old->__subtree_last; } static void augment_rotate(struct rb_node *rb_old, struct rb_node *rb_new) { struct interval_tree_node *old = rb_entry(rb_old, struct interval_tree_node, rb); struct interval_tree_node *new = rb_entry(rb_new, struct interval_tree_node, rb); new->__subtree_last = old->__subtree_last; old->__subtree_last = compute_subtree_last(old); } static const struct rb_augment_callbacks augment_callbacks = { augment_propagate, augment_copy, augment_rotate }; void interval_tree_insert(struct interval_tree_node *node, struct rb_root *root) { struct rb_node **link = &root->rb_node, *rb_parent = NULL; unsigned long start = node->start, last = node->last; struct interval_tree_node *parent; while (*link) { rb_parent = *link; parent = rb_entry(rb_parent, struct interval_tree_node, rb); if (parent->__subtree_last < last) parent->__subtree_last = last; if (start < parent->start) link = &parent->rb.rb_left; else link = &parent->rb.rb_right; } node->__subtree_last = last; rb_link_node(&node->rb, rb_parent, link); rb_insert_augmented(&node->rb, root, &augment_callbacks); } void interval_tree_remove(struct interval_tree_node *node, struct rb_root *root) { rb_erase_augmented(&node->rb, root, &augment_callbacks); }h]hX static inline unsigned long compute_subtree_last(struct interval_tree_node *node) { unsigned long max = node->last, subtree_last; if (node->rb.rb_left) { subtree_last = rb_entry(node->rb.rb_left, struct interval_tree_node, rb)->__subtree_last; if (max < subtree_last) max = subtree_last; } if (node->rb.rb_right) { subtree_last = rb_entry(node->rb.rb_right, struct interval_tree_node, rb)->__subtree_last; if (max < subtree_last) max = subtree_last; } return max; } static void augment_propagate(struct rb_node *rb, struct rb_node *stop) { while (rb != stop) { struct interval_tree_node *node = rb_entry(rb, struct interval_tree_node, rb); unsigned long subtree_last = compute_subtree_last(node); if (node->__subtree_last == subtree_last) break; node->__subtree_last = subtree_last; rb = rb_parent(&node->rb); } } static void augment_copy(struct rb_node *rb_old, struct rb_node *rb_new) { struct interval_tree_node *old = rb_entry(rb_old, struct interval_tree_node, rb); struct interval_tree_node *new = rb_entry(rb_new, struct interval_tree_node, rb); new->__subtree_last = old->__subtree_last; } static void augment_rotate(struct rb_node *rb_old, struct rb_node *rb_new) { struct interval_tree_node *old = rb_entry(rb_old, struct interval_tree_node, rb); struct interval_tree_node *new = rb_entry(rb_new, struct interval_tree_node, rb); new->__subtree_last = old->__subtree_last; old->__subtree_last = compute_subtree_last(old); } static const struct rb_augment_callbacks augment_callbacks = { augment_propagate, augment_copy, augment_rotate }; void interval_tree_insert(struct interval_tree_node *node, struct rb_root *root) { struct rb_node **link = &root->rb_node, *rb_parent = NULL; unsigned long start = node->start, last = node->last; struct interval_tree_node *parent; while (*link) { rb_parent = *link; parent = rb_entry(rb_parent, struct interval_tree_node, rb); if (parent->__subtree_last < last) parent->__subtree_last = last; if (start < parent->start) link = &parent->rb.rb_left; else link = &parent->rb.rb_right; } node->__subtree_last = last; rb_link_node(&node->rb, rb_parent, link); rb_insert_augmented(&node->rb, root, &augment_callbacks); } void interval_tree_remove(struct interval_tree_node *node, struct rb_root *root) { rb_erase_augmented(&node->rb, root, &augment_callbacks); }}(hhhjubah}(h]h ]h"]h$]h&]jjuh1jhhhMYhjhhubeh}(h] sample-usageah ]h"] sample usageah$]h&]uh1hhjhhhhhMubeh}(h]support-for-augmented-rbtreesah ]h"]support for augmented rbtreesah$]h&]uh1hhhhhhhhKubeh}(h]red-black-trees-rbtree-in-linuxah ]h"]!red-black trees (rbtree) in linuxah$]h&]uh1hhhhhhhhKubeh}(h]h ]h"]h$]h&]sourcehuh1hcurrent_sourceN current_lineNsettingsdocutils.frontendValues)}(hN generatorN datestampN source_linkN source_urlN toc_backlinksentryfootnote_backlinksK sectnum_xformKstrip_commentsNstrip_elements_with_classesN strip_classesN report_levelK halt_levelKexit_status_levelKdebugNwarning_streamN tracebackinput_encoding utf-8-siginput_encoding_error_handlerstrictoutput_encodingutf-8output_encoding_error_handlerjDerror_encodingUTF-8error_encoding_error_handlerbackslashreplace language_codeenrecord_dependenciesNconfigN id_prefixhauto_id_prefixid dump_settingsNdump_internalsNdump_transformsNdump_pseudo_xmlNexpose_internalsNstrict_visitorN_disable_configN_sourceh _destinationN _config_files]7/var/lib/git/docbuild/linux/Documentation/docutils.confapep_referencesN pep_base_urlhttps://peps.python.org/pep_file_url_templatepep-%04drfc_referencesN rfc_base_url&https://datatracker.ietf.org/doc/html/ tab_widthKtrim_footnote_reference_spacefile_insertion_enabled raw_enabledKline_length_limitM'syntax_highlightlong smart_quotessmartquotes_locales]character_level_inline_markupdoctitle_xform docinfo_xformKsectsubtitle_xform image_loadinglinkembed_stylesheetcloak_email_addressessection_self_link embed_imagesenvNubreporterNindirect_targets]substitution_defs}substitution_names}refnames}refids}nameids}(jjj2j/jgjdjjjjjjjgjjjWjTjjjjjj u nametypes}(jNj2NjgNjNjNjjNjNjWNjNjNjNuh}(jhj/j?jdj5jjjjjjgjjjmjTjjjZjjj ju footnote_refs} citation_refs} autofootnotes]autofootnote_refs]symbol_footnotes]symbol_footnote_refs] footnotes] citations]autofootnote_startKsymbol_footnote_startK id_counter collectionsCounter}Rparse_messages]transform_messages] transformerN include_log] decorationNhhub.