rbtree.txt 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 each node.
  146. This data can be used to augment some new functionality to rbtree.
  147. Augmented rbtree is an optional feature built on top of basic rbtree
  148. infrastructure. An rbtree user who wants this feature will have to call the
  149. augmentation functions with the user provided augmentation callback
  150. when inserting and erasing nodes.
  151. On insertion, the user must call rb_augment_insert() once the new node is in
  152. place. This will cause the augmentation function callback to be called for
  153. each node between the new node and the root which has been affected by the
  154. insertion.
  155. When erasing a node, the user must call rb_augment_erase_begin() first to
  156. retrieve the deepest node on the rebalance path. Then, after erasing the
  157. original node, the user must call rb_augment_erase_end() with the deepest
  158. node found earlier. This will cause the augmentation function to be called
  159. for each affected node between the deepest node and the root.
  160. Interval tree is an example of augmented rb tree. Reference -
  161. "Introduction to Algorithms" by Cormen, Leiserson, Rivest and Stein.
  162. More details about interval trees:
  163. Classical rbtree has a single key and it cannot be directly used to store
  164. interval ranges like [lo:hi] and do a quick lookup for any overlap with a new
  165. lo:hi or to find whether there is an exact match for a new lo:hi.
  166. However, rbtree can be augmented to store such interval ranges in a structured
  167. way making it possible to do efficient lookup and exact match.
  168. This "extra information" stored in each node is the maximum hi
  169. (max_hi) value among all the nodes that are its descendents. This
  170. information can be maintained at each node just be looking at the node
  171. and its immediate children. And this will be used in O(log n) lookup
  172. for lowest match (lowest start address among all possible matches)
  173. with something like:
  174. find_lowest_match(lo, hi, node)
  175. {
  176. lowest_match = NULL;
  177. while (node) {
  178. if (max_hi(node->left) > lo) {
  179. // Lowest overlap if any must be on left side
  180. node = node->left;
  181. } else if (overlap(lo, hi, node)) {
  182. lowest_match = node;
  183. break;
  184. } else if (lo > node->lo) {
  185. // Lowest overlap if any must be on right side
  186. node = node->right;
  187. } else {
  188. break;
  189. }
  190. }
  191. return lowest_match;
  192. }
  193. Finding exact match will be to first find lowest match and then to follow
  194. successor nodes looking for exact match, until the start of a node is beyond
  195. the hi value we are looking for.