rbtree.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. Red-black Trees (rbtree) in Linux
  2. January 18, 2007
  3. Rob Landley <rob@landley.net>
  4. =============================
  5. What are red-black trees, and what are they for?
  6. ------------------------------------------------
  7. Red-black trees are a type of self-balancing binary search tree, used for
  8. storing sortable key/value data pairs. This differs from radix trees (which
  9. are used to efficiently store sparse arrays and thus use long integer indexes
  10. to insert/access/delete nodes) and hash tables (which are not kept sorted to
  11. be easily traversed in order, and must be tuned for a specific size and
  12. hash function where rbtrees scale gracefully storing arbitrary keys).
  13. Red-black trees are similar to AVL trees, but provide faster real-time bounded
  14. worst case performance for insertion and deletion (at most two rotations and
  15. three rotations, respectively, to balance the tree), with slightly slower
  16. (but still O(log n)) lookup time.
  17. To quote Linux Weekly News:
  18. There are a number of red-black trees in use in the kernel.
  19. The deadline and CFQ I/O schedulers employ rbtrees to
  20. track requests; the packet CD/DVD driver does the same.
  21. The high-resolution timer code uses an rbtree to organize outstanding
  22. timer requests. The ext3 filesystem tracks directory entries in a
  23. red-black tree. Virtual memory areas (VMAs) are tracked with red-black
  24. trees, as are epoll file descriptors, cryptographic keys, and network
  25. packets in the "hierarchical token bucket" scheduler.
  26. This document covers use of the Linux rbtree implementation. For more
  27. information on the nature and implementation of Red Black Trees, see:
  28. Linux Weekly News article on red-black trees
  29. http://lwn.net/Articles/184495/
  30. Wikipedia entry on red-black trees
  31. http://en.wikipedia.org/wiki/Red-black_tree
  32. Linux implementation of red-black trees
  33. ---------------------------------------
  34. Linux's rbtree implementation lives in the file "lib/rbtree.c". To use it,
  35. "#include <linux/rbtree.h>".
  36. The Linux rbtree implementation is optimized for speed, and thus has one
  37. less layer of indirection (and better cache locality) than more traditional
  38. tree implementations. Instead of using pointers to separate rb_node and data
  39. structures, each instance of struct rb_node is embedded in the data structure
  40. it organizes. And instead of using a comparison callback function pointer,
  41. users are expected to write their own tree search and insert functions
  42. which call the provided rbtree functions. Locking is also left up to the
  43. user of the rbtree code.
  44. Creating a new rbtree
  45. ---------------------
  46. Data nodes in an rbtree tree are structures containing a struct rb_node member:
  47. struct mytype {
  48. struct rb_node node;
  49. char *keystring;
  50. };
  51. When dealing with a pointer to the embedded struct rb_node, the containing data
  52. structure may be accessed with the standard container_of() macro. In addition,
  53. individual members may be accessed directly via rb_entry(node, type, member).
  54. At the root of each rbtree is an rb_root structure, which is initialized to be
  55. empty via:
  56. struct rb_root mytree = RB_ROOT;
  57. Searching for a value in an rbtree
  58. ----------------------------------
  59. Writing a search function for your tree is fairly straightforward: start at the
  60. root, compare each value, and follow the left or right branch as necessary.
  61. Example:
  62. struct mytype *my_search(struct rb_root *root, char *string)
  63. {
  64. struct rb_node *node = root->rb_node;
  65. while (node) {
  66. struct mytype *data = container_of(node, struct mytype, node);
  67. int result;
  68. result = strcmp(string, data->keystring);
  69. if (result < 0)
  70. node = node->rb_left;
  71. else if (result > 0)
  72. node = node->rb_right;
  73. else
  74. return data;
  75. }
  76. return NULL;
  77. }
  78. Inserting data into an rbtree
  79. -----------------------------
  80. Inserting data in the tree involves first searching for the place to insert the
  81. new node, then inserting the node and rebalancing ("recoloring") the tree.
  82. The search for insertion differs from the previous search by finding the
  83. location of the pointer on which to graft the new node. The new node also
  84. needs a link to its parent node for rebalancing purposes.
  85. Example:
  86. int my_insert(struct rb_root *root, struct mytype *data)
  87. {
  88. struct rb_node **new = &(root->rb_node), *parent = NULL;
  89. /* Figure out where to put new node */
  90. while (*new) {
  91. struct mytype *this = container_of(*new, struct mytype, node);
  92. int result = strcmp(data->keystring, this->keystring);
  93. parent = *new;
  94. if (result < 0)
  95. new = &((*new)->rb_left);
  96. else if (result > 0)
  97. new = &((*new)->rb_right);
  98. else
  99. return FALSE;
  100. }
  101. /* Add new node and rebalance tree. */
  102. rb_link_node(&data->node, parent, new);
  103. rb_insert_color(&data->node, root);
  104. return TRUE;
  105. }
  106. Removing or replacing existing data in an rbtree
  107. ------------------------------------------------
  108. To remove an existing node from a tree, call:
  109. void rb_erase(struct rb_node *victim, struct rb_root *tree);
  110. Example:
  111. struct mytype *data = mysearch(&mytree, "walrus");
  112. if (data) {
  113. rb_erase(&data->node, &mytree);
  114. myfree(data);
  115. }
  116. To replace an existing node in a tree with a new one with the same key, call:
  117. void rb_replace_node(struct rb_node *old, struct rb_node *new,
  118. struct rb_root *tree);
  119. Replacing a node this way does not re-sort the tree: If the new node doesn't
  120. have the same key as the old node, the rbtree will probably become corrupted.
  121. Iterating through the elements stored in an rbtree (in sort order)
  122. ------------------------------------------------------------------
  123. Four functions are provided for iterating through an rbtree's contents in
  124. sorted order. These work on arbitrary trees, and should not need to be
  125. modified or wrapped (except for locking purposes):
  126. struct rb_node *rb_first(struct rb_root *tree);
  127. struct rb_node *rb_last(struct rb_root *tree);
  128. struct rb_node *rb_next(struct rb_node *node);
  129. struct rb_node *rb_prev(struct rb_node *node);
  130. To start iterating, call rb_first() or rb_last() with a pointer to the root
  131. of the tree, which will return a pointer to the node structure contained in
  132. the first or last element in the tree. To continue, fetch the next or previous
  133. node by calling rb_next() or rb_prev() on the current node. This will return
  134. NULL when there are no more nodes left.
  135. The iterator functions return a pointer to the embedded struct rb_node, from
  136. which the containing data structure may be accessed with the container_of()
  137. macro, and individual members may be accessed directly via
  138. rb_entry(node, type, member).
  139. Example:
  140. struct rb_node *node;
  141. for (node = rb_first(&mytree); node; node = rb_next(node))
  142. printk("key=%s\n", rb_entry(node, struct mytype, node)->keystring);
  143. Support for Augmented rbtrees
  144. -----------------------------
  145. Augmented rbtree is an rbtree with "some" additional data stored in
  146. each node, where the additional data for node N must be a function of
  147. the contents of all nodes in the subtree rooted at N. This data can
  148. be used to augment some new functionality to rbtree. Augmented rbtree
  149. is an optional feature built on top of basic rbtree infrastructure.
  150. An rbtree user who wants this feature will have to call the augmentation
  151. functions with the user provided augmentation callback when inserting
  152. and erasing nodes.
  153. C files implementing augmented rbtree manipulation must include
  154. <linux/rbtree_augmented.h> instead of <linux/rbtree.h>. Note that
  155. linux/rbtree_augmented.h exposes some rbtree implementations details
  156. you are not expected to rely on; please stick to the documented APIs
  157. there and do not include <linux/rbtree_augmented.h> from header files
  158. either so as to minimize chances of your users accidentally relying on
  159. such implementation details.
  160. On insertion, the user must update the augmented information on the path
  161. leading to the inserted node, then call rb_link_node() as usual and
  162. rb_augment_inserted() instead of the usual rb_insert_color() call.
  163. If rb_augment_inserted() rebalances the rbtree, it will callback into
  164. a user provided function to update the augmented information on the
  165. affected subtrees.
  166. When erasing a node, the user must call rb_erase_augmented() instead of
  167. rb_erase(). rb_erase_augmented() calls back into user provided functions
  168. to updated the augmented information on affected subtrees.
  169. In both cases, the callbacks are provided through struct rb_augment_callbacks.
  170. 3 callbacks must be defined:
  171. - A propagation callback, which updates the augmented value for a given
  172. node and its ancestors, up to a given stop point (or NULL to update
  173. all the way to the root).
  174. - A copy callback, which copies the augmented value for a given subtree
  175. to a newly assigned subtree root.
  176. - A tree rotation callback, which copies the augmented value for a given
  177. subtree to a newly assigned subtree root AND recomputes the augmented
  178. information for the former subtree root.
  179. The compiled code for rb_erase_augmented() may inline the propagation and
  180. copy callbacks, which results in a large function, so each augmented rbtree
  181. user should have a single rb_erase_augmented() call site in order to limit
  182. compiled code size.
  183. Sample usage:
  184. Interval tree is an example of augmented rb tree. Reference -
  185. "Introduction to Algorithms" by Cormen, Leiserson, Rivest and Stein.
  186. More details about interval trees:
  187. Classical rbtree has a single key and it cannot be directly used to store
  188. interval ranges like [lo:hi] and do a quick lookup for any overlap with a new
  189. lo:hi or to find whether there is an exact match for a new lo:hi.
  190. However, rbtree can be augmented to store such interval ranges in a structured
  191. way making it possible to do efficient lookup and exact match.
  192. This "extra information" stored in each node is the maximum hi
  193. (max_hi) value among all the nodes that are its descendants. This
  194. information can be maintained at each node just be looking at the node
  195. and its immediate children. And this will be used in O(log n) lookup
  196. for lowest match (lowest start address among all possible matches)
  197. with something like:
  198. struct interval_tree_node *
  199. interval_tree_first_match(struct rb_root *root,
  200. unsigned long start, unsigned long last)
  201. {
  202. struct interval_tree_node *node;
  203. if (!root->rb_node)
  204. return NULL;
  205. node = rb_entry(root->rb_node, struct interval_tree_node, rb);
  206. while (true) {
  207. if (node->rb.rb_left) {
  208. struct interval_tree_node *left =
  209. rb_entry(node->rb.rb_left,
  210. struct interval_tree_node, rb);
  211. if (left->__subtree_last >= start) {
  212. /*
  213. * Some nodes in left subtree satisfy Cond2.
  214. * Iterate to find the leftmost such node N.
  215. * If it also satisfies Cond1, that's the match
  216. * we are looking for. Otherwise, there is no
  217. * matching interval as nodes to the right of N
  218. * can't satisfy Cond1 either.
  219. */
  220. node = left;
  221. continue;
  222. }
  223. }
  224. if (node->start <= last) { /* Cond1 */
  225. if (node->last >= start) /* Cond2 */
  226. return node; /* node is leftmost match */
  227. if (node->rb.rb_right) {
  228. node = rb_entry(node->rb.rb_right,
  229. struct interval_tree_node, rb);
  230. if (node->__subtree_last >= start)
  231. continue;
  232. }
  233. }
  234. return NULL; /* No match */
  235. }
  236. }
  237. Insertion/removal are defined using the following augmented callbacks:
  238. static inline unsigned long
  239. compute_subtree_last(struct interval_tree_node *node)
  240. {
  241. unsigned long max = node->last, subtree_last;
  242. if (node->rb.rb_left) {
  243. subtree_last = rb_entry(node->rb.rb_left,
  244. struct interval_tree_node, rb)->__subtree_last;
  245. if (max < subtree_last)
  246. max = subtree_last;
  247. }
  248. if (node->rb.rb_right) {
  249. subtree_last = rb_entry(node->rb.rb_right,
  250. struct interval_tree_node, rb)->__subtree_last;
  251. if (max < subtree_last)
  252. max = subtree_last;
  253. }
  254. return max;
  255. }
  256. static void augment_propagate(struct rb_node *rb, struct rb_node *stop)
  257. {
  258. while (rb != stop) {
  259. struct interval_tree_node *node =
  260. rb_entry(rb, struct interval_tree_node, rb);
  261. unsigned long subtree_last = compute_subtree_last(node);
  262. if (node->__subtree_last == subtree_last)
  263. break;
  264. node->__subtree_last = subtree_last;
  265. rb = rb_parent(&node->rb);
  266. }
  267. }
  268. static void augment_copy(struct rb_node *rb_old, struct rb_node *rb_new)
  269. {
  270. struct interval_tree_node *old =
  271. rb_entry(rb_old, struct interval_tree_node, rb);
  272. struct interval_tree_node *new =
  273. rb_entry(rb_new, struct interval_tree_node, rb);
  274. new->__subtree_last = old->__subtree_last;
  275. }
  276. static void augment_rotate(struct rb_node *rb_old, struct rb_node *rb_new)
  277. {
  278. struct interval_tree_node *old =
  279. rb_entry(rb_old, struct interval_tree_node, rb);
  280. struct interval_tree_node *new =
  281. rb_entry(rb_new, struct interval_tree_node, rb);
  282. new->__subtree_last = old->__subtree_last;
  283. old->__subtree_last = compute_subtree_last(old);
  284. }
  285. static const struct rb_augment_callbacks augment_callbacks = {
  286. augment_propagate, augment_copy, augment_rotate
  287. };
  288. void interval_tree_insert(struct interval_tree_node *node,
  289. struct rb_root *root)
  290. {
  291. struct rb_node **link = &root->rb_node, *rb_parent = NULL;
  292. unsigned long start = node->start, last = node->last;
  293. struct interval_tree_node *parent;
  294. while (*link) {
  295. rb_parent = *link;
  296. parent = rb_entry(rb_parent, struct interval_tree_node, rb);
  297. if (parent->__subtree_last < last)
  298. parent->__subtree_last = last;
  299. if (start < parent->start)
  300. link = &parent->rb.rb_left;
  301. else
  302. link = &parent->rb.rb_right;
  303. }
  304. node->__subtree_last = last;
  305. rb_link_node(&node->rb, rb_parent, link);
  306. rb_insert_augmented(&node->rb, root, &augment_callbacks);
  307. }
  308. void interval_tree_remove(struct interval_tree_node *node,
  309. struct rb_root *root)
  310. {
  311. rb_erase_augmented(&node->rb, root, &augment_callbacks);
  312. }