rbtree.txt 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 anticipatory, deadline, and CFQ I/O schedulers all employ
  20. rbtrees to 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, int, keystring));