1    	/* Copied from linux/lib/rbtree.c */
2    	/*
3    	  Red Black Trees
4    	  (C) 1999  Andrea Arcangeli <andrea@suse.de>
5    	  (C) 2002  David Woodhouse <dwmw2@infradead.org>
6    	  (C) 2012  Michel Lespinasse <walken@google.com>
7    	
8    	
9    	  linux/lib/rbtree.c
10   	*/
11   	
12   	#include "rbtree_augmented.h"
13   	
14   	/*
15   	 * red-black trees properties:  https://en.wikipedia.org/wiki/Rbtree
16   	 *
17   	 *  1) A node is either red or black
18   	 *  2) The root is black
19   	 *  3) All leaves (NULL) are black
20   	 *  4) Both children of every red node are black
21   	 *  5) Every simple path from root to leaves contains the same number
22   	 *     of black nodes.
23   	 *
24   	 *  4 and 5 give the O(log n) guarantee, since 4 implies you cannot have two
25   	 *  consecutive red nodes in a path and every red node is therefore followed by
26   	 *  a black. So if B is the number of black nodes on every simple path (as per
27   	 *  5), then the longest possible path due to 4 is 2B.
28   	 *
29   	 *  We shall indicate color with case, where black nodes are uppercase and red
30   	 *  nodes will be lowercase. Unknown color nodes shall be drawn as red within
31   	 *  parentheses and have some accompanying text comment.
32   	 */
33   	
34   	/*
35   	 * Notes on lockless lookups:
36   	 *
37   	 * All stores to the tree structure (rb_left and rb_right) must be done using
38   	 * WRITE_ONCE(). And we must not inadvertently cause (temporary) loops in the
39   	 * tree structure as seen in program order.
40   	 *
41   	 * These two requirements will allow lockless iteration of the tree -- not
42   	 * correct iteration mind you, tree rotations are not atomic so a lookup might
43   	 * miss entire subtrees.
44   	 *
45   	 * But they do guarantee that any such traversal will only see valid elements
46   	 * and that it will indeed complete -- does not get stuck in a loop.
47   	 *
48   	 * It also guarantees that if the lookup returns an element it is the 'correct'
49   	 * one. But not returning an element does _NOT_ mean it's not present.
50   	 *
51   	 * NOTE:
52   	 *
53   	 * Stores to __rb_parent_color are not important for simple lookups so those
54   	 * are left undone as of now. Nor did I check for loops involving parent
55   	 * pointers.
56   	 */
57   	
58   	static inline void rb_set_black(struct rb_node *rb)
59   	{
60   		rb->__rb_parent_color += RB_BLACK;
61   	}
62   	
63   	static inline struct rb_node *rb_red_parent(struct rb_node *red)
64   	{
65   		return (struct rb_node *)red->__rb_parent_color;
66   	}
67   	
68   	/*
69   	 * Helper function for rotations:
70   	 * - old's parent and color get assigned to new
71   	 * - old gets assigned new as a parent and 'color' as a color.
72   	 */
73   	static inline void
74   	__rb_rotate_set_parents(struct rb_node *old, struct rb_node *new,
75   				struct rb_root *root, int color)
76   	{
77   		struct rb_node *parent = rb_parent(old);
78   		new->__rb_parent_color = old->__rb_parent_color;
79   		rb_set_parent_color(old, new, color);
80   		__rb_change_child(old, new, parent, root);
81   	}
82   	
83   	static __always_inline void
84   	__rb_insert(struct rb_node *node, struct rb_root *root,
85   		    void (*augment_rotate)(struct rb_node *old, struct rb_node *new))
86   	{
87   		struct rb_node *parent = rb_red_parent(node), *gparent, *tmp;
88   	
89   		while (true) {
90   			/*
91   			 * Loop invariant: node is red.
92   			 */
93   			if (!parent) {
94   				/*
95   				 * The inserted node is root. Either this is the
96   				 * first node, or we recursed at Case 1 below and
97   				 * are no longer violating 4).
98   				 */
99   				rb_set_parent_color(node, NULL, RB_BLACK);
100  				break;
101  			}
102  	
103  			/*
104  			 * If there is a black parent, we are done.
105  			 * Otherwise, take some corrective action as,
106  			 * per 4), we don't want a red root or two
107  			 * consecutive red nodes.
108  			 */
109  			if(rb_is_black(parent))
110  				break;
111  	
112  			gparent = rb_red_parent(parent);
113  	
114  			tmp = gparent->rb_right;
115  			if (parent != tmp) {	/* parent == gparent->rb_left */
116  				if (tmp && rb_is_red(tmp)) {
117  					/*
118  					 * Case 1 - node's uncle is red (color flips).
119  					 *
120  					 *       G            g
121  					 *      / \          / \
122  					 *     p   u  -->   P   U
123  					 *    /            /
124  					 *   n            n
125  					 *
126  					 * However, since g's parent might be red, and
127  					 * 4) does not allow this, we need to recurse
128  					 * at g.
129  					 */
130  					rb_set_parent_color(tmp, gparent, RB_BLACK);
131  					rb_set_parent_color(parent, gparent, RB_BLACK);
132  					node = gparent;
133  					parent = rb_parent(node);
134  					rb_set_parent_color(node, parent, RB_RED);
135  					continue;
136  				}
137  	
138  				tmp = parent->rb_right;
139  				if (node == tmp) {
140  					/*
141  					 * Case 2 - node's uncle is black and node is
142  					 * the parent's right child (left rotate at parent).
143  					 *
144  					 *      G             G
145  					 *     / \           / \
146  					 *    p   U  -->    n   U
147  					 *     \           /
148  					 *      n         p
149  					 *
150  					 * This still leaves us in violation of 4), the
151  					 * continuation into Case 3 will fix that.
152  					 */
153  					tmp = node->rb_left;
154  					WRITE_ONCE(parent->rb_right, tmp);
155  					WRITE_ONCE(node->rb_left, parent);
(12) Event example_checked: Example 4: "node->rb_left" has its value checked in "tmp".
Also see events: [null_field][example_checked][example_checked][example_checked][example_checked][alias_transfer][dereference]
156  					if (tmp)
157  						rb_set_parent_color(tmp, parent,
158  								    RB_BLACK);
159  					rb_set_parent_color(parent, node, RB_RED);
160  					augment_rotate(parent, node);
161  					parent = node;
162  					tmp = node->rb_right;
163  				}
164  	
165  				/*
166  				 * Case 3 - node's uncle is black and node is
167  				 * the parent's left child (right rotate at gparent).
168  				 *
169  				 *        G           P
170  				 *       / \         / \
171  				 *      p   U  -->  n   g
172  				 *     /                 \
173  				 *    n                   U
174  				 */
175  				WRITE_ONCE(gparent->rb_left, tmp); /* == parent->rb_right */
176  				WRITE_ONCE(parent->rb_right, gparent);
177  				if (tmp)
178  					rb_set_parent_color(tmp, gparent, RB_BLACK);
179  				__rb_rotate_set_parents(gparent, parent, root, RB_RED);
180  				augment_rotate(gparent, parent);
181  				break;
182  			} else {
183  				tmp = gparent->rb_left;
184  				if (tmp && rb_is_red(tmp)) {
185  					/* Case 1 - color flips */
186  					rb_set_parent_color(tmp, gparent, RB_BLACK);
187  					rb_set_parent_color(parent, gparent, RB_BLACK);
188  					node = gparent;
189  					parent = rb_parent(node);
190  					rb_set_parent_color(node, parent, RB_RED);
191  					continue;
192  				}
193  	
194  				tmp = parent->rb_left;
195  				if (node == tmp) {
196  					/* Case 2 - right rotate at parent */
197  					tmp = node->rb_right;
198  					WRITE_ONCE(parent->rb_left, tmp);
199  					WRITE_ONCE(node->rb_right, parent);
200  					if (tmp)
201  						rb_set_parent_color(tmp, parent,
202  								    RB_BLACK);
203  					rb_set_parent_color(parent, node, RB_RED);
204  					augment_rotate(parent, node);
205  					parent = node;
206  					tmp = node->rb_left;
207  				}
208  	
209  				/* Case 3 - left rotate at gparent */
210  				WRITE_ONCE(gparent->rb_right, tmp); /* == parent->rb_left */
211  				WRITE_ONCE(parent->rb_left, gparent);
212  				if (tmp)
213  					rb_set_parent_color(tmp, gparent, RB_BLACK);
214  				__rb_rotate_set_parents(gparent, parent, root, RB_RED);
215  				augment_rotate(gparent, parent);
216  				break;
217  			}
218  		}
219  	}
220  	
221  	/*
222  	 * Inline version for rb_erase() use - we want to be able to inline
223  	 * and eliminate the dummy_rotate callback there
224  	 */
225  	static __always_inline void
226  	____rb_erase_color(struct rb_node *parent, struct rb_root *root,
227  		void (*augment_rotate)(struct rb_node *old, struct rb_node *new))
228  	{
229  		struct rb_node *node = NULL, *sibling, *tmp1, *tmp2;
230  	
231  		while (true) {
232  			/*
233  			 * Loop invariants:
234  			 * - node is black (or NULL on first iteration)
235  			 * - node is not the root (parent is not NULL)
236  			 * - All leaf paths going through parent and node have a
237  			 *   black node count that is 1 lower than other leaf paths.
238  			 */
239  			sibling = parent->rb_right;
240  			if (node != sibling) {	/* node == parent->rb_left */
241  				if (rb_is_red(sibling)) {
242  					/*
243  					 * Case 1 - left rotate at parent
244  					 *
245  					 *     P               S
246  					 *    / \             / \
247  					 *   N   s    -->    p   Sr
248  					 *      / \         / \
249  					 *     Sl  Sr      N   Sl
250  					 */
251  					tmp1 = sibling->rb_left;
252  					WRITE_ONCE(parent->rb_right, tmp1);
253  					WRITE_ONCE(sibling->rb_left, parent);
254  					rb_set_parent_color(tmp1, parent, RB_BLACK);
255  					__rb_rotate_set_parents(parent, sibling, root,
256  								RB_RED);
257  					augment_rotate(parent, sibling);
258  					sibling = tmp1;
259  				}
260  				tmp1 = sibling->rb_right;
261  				if (!tmp1 || rb_is_black(tmp1)) {
262  					tmp2 = sibling->rb_left;
(10) Event example_checked: Example 2: "sibling->rb_left" has its value checked in "tmp2".
Also see events: [null_field][example_checked][example_checked][example_checked][example_checked][alias_transfer][dereference]
263  					if (!tmp2 || rb_is_black(tmp2)) {
264  						/*
265  						 * Case 2 - sibling color flip
266  						 * (p could be either color here)
267  						 *
268  						 *    (p)           (p)
269  						 *    / \           / \
270  						 *   N   S    -->  N   s
271  						 *      / \           / \
272  						 *     Sl  Sr        Sl  Sr
273  						 *
274  						 * This leaves us violating 5) which
275  						 * can be fixed by flipping p to black
276  						 * if it was red, or by recursing at p.
277  						 * p is red when coming from Case 1.
278  						 */
279  						rb_set_parent_color(sibling, parent,
280  								    RB_RED);
281  						if (rb_is_red(parent))
282  							rb_set_black(parent);
283  						else {
284  							node = parent;
285  							parent = rb_parent(node);
286  							if (parent)
287  								continue;
288  						}
289  						break;
290  					}
291  					/*
292  					 * Case 3 - right rotate at sibling
293  					 * (p could be either color here)
294  					 *
295  					 *   (p)           (p)
296  					 *   / \           / \
297  					 *  N   S    -->  N   sl
298  					 *     / \             \
299  					 *    sl  Sr            S
300  					 *                       \
301  					 *                        Sr
302  					 *
303  					 * Note: p might be red, and then both
304  					 * p and sl are red after rotation(which
305  					 * breaks property 4). This is fixed in
306  					 * Case 4 (in __rb_rotate_set_parents()
307  					 *         which set sl the color of p
308  					 *         and set p RB_BLACK)
309  					 *
310  					 *   (p)            (sl)
311  					 *   / \            /  \
312  					 *  N   sl   -->   P    S
313  					 *       \        /      \
314  					 *        S      N        Sr
315  					 *         \
316  					 *          Sr
317  					 */
318  					tmp1 = tmp2->rb_right;
319  					WRITE_ONCE(sibling->rb_left, tmp1);
320  					WRITE_ONCE(tmp2->rb_right, sibling);
321  					WRITE_ONCE(parent->rb_right, tmp2);
322  					if (tmp1)
323  						rb_set_parent_color(tmp1, sibling,
324  								    RB_BLACK);
325  					augment_rotate(sibling, tmp2);
326  					tmp1 = sibling;
327  					sibling = tmp2;
328  				}
329  				/*
330  				 * Case 4 - left rotate at parent + color flips
331  				 * (p and sl could be either color here.
332  				 *  After rotation, p becomes black, s acquires
333  				 *  p's color, and sl keeps its color)
334  				 *
335  				 *      (p)             (s)
336  				 *      / \             / \
337  				 *     N   S     -->   P   Sr
338  				 *        / \         / \
339  				 *      (sl) sr      N  (sl)
340  				 */
341  				tmp2 = sibling->rb_left;
342  				WRITE_ONCE(parent->rb_right, tmp2);
343  				WRITE_ONCE(sibling->rb_left, parent);
344  				rb_set_parent_color(tmp1, sibling, RB_BLACK);
345  				if (tmp2)
346  					rb_set_parent(tmp2, parent);
347  				__rb_rotate_set_parents(parent, sibling, root,
348  							RB_BLACK);
349  				augment_rotate(parent, sibling);
350  				break;
351  			} else {
352  				sibling = parent->rb_left;
353  				if (rb_is_red(sibling)) {
354  					/* Case 1 - right rotate at parent */
355  					tmp1 = sibling->rb_right;
356  					WRITE_ONCE(parent->rb_left, tmp1);
357  					WRITE_ONCE(sibling->rb_right, parent);
358  					rb_set_parent_color(tmp1, parent, RB_BLACK);
359  					__rb_rotate_set_parents(parent, sibling, root,
360  								RB_RED);
361  					augment_rotate(parent, sibling);
362  					sibling = tmp1;
363  				}
364  				tmp1 = sibling->rb_left;
365  				if (!tmp1 || rb_is_black(tmp1)) {
366  					tmp2 = sibling->rb_right;
367  					if (!tmp2 || rb_is_black(tmp2)) {
368  						/* Case 2 - sibling color flip */
369  						rb_set_parent_color(sibling, parent,
370  								    RB_RED);
371  						if (rb_is_red(parent))
372  							rb_set_black(parent);
373  						else {
374  							node = parent;
375  							parent = rb_parent(node);
376  							if (parent)
377  								continue;
378  						}
379  						break;
380  					}
381  					/* Case 3 - left rotate at sibling */
382  					tmp1 = tmp2->rb_left;
383  					WRITE_ONCE(sibling->rb_right, tmp1);
384  					WRITE_ONCE(tmp2->rb_left, sibling);
385  					WRITE_ONCE(parent->rb_left, tmp2);
386  					if (tmp1)
387  						rb_set_parent_color(tmp1, sibling,
388  								    RB_BLACK);
389  					augment_rotate(sibling, tmp2);
390  					tmp1 = sibling;
391  					sibling = tmp2;
392  				}
393  				/* Case 4 - right rotate at parent + color flips */
394  				tmp2 = sibling->rb_right;
395  				WRITE_ONCE(parent->rb_left, tmp2);
396  				WRITE_ONCE(sibling->rb_right, parent);
397  				rb_set_parent_color(tmp1, sibling, RB_BLACK);
398  				if (tmp2)
399  					rb_set_parent(tmp2, parent);
400  				__rb_rotate_set_parents(parent, sibling, root,
401  							RB_BLACK);
402  				augment_rotate(parent, sibling);
403  				break;
404  			}
405  		}
406  	}
407  	
408  	/* Non-inline version for rb_erase_augmented() use */
409  	void __rb_erase_color(struct rb_node *parent, struct rb_root *root,
410  		void (*augment_rotate)(struct rb_node *old, struct rb_node *new))
411  	{
412  		____rb_erase_color(parent, root, augment_rotate);
413  	}
414  	
415  	/*
416  	 * Non-augmented rbtree manipulation functions.
417  	 *
418  	 * We use dummy augmented callbacks here, and have the compiler optimize them
419  	 * out of the rb_insert_color() and rb_erase() function definitions.
420  	 */
421  	
422  	static inline void dummy_propagate(struct rb_node *node, struct rb_node *stop) {}
423  	static inline void dummy_copy(struct rb_node *old, struct rb_node *new) {}
424  	static inline void dummy_rotate(struct rb_node *old, struct rb_node *new) {}
425  	
426  	static const struct rb_augment_callbacks dummy_callbacks = {
427  		.propagate = dummy_propagate,
428  		.copy = dummy_copy,
429  		.rotate = dummy_rotate
430  	};
431  	
432  	void rb_insert_color(struct rb_node *node, struct rb_root *root)
433  	{
434  		__rb_insert(node, root, dummy_rotate);
435  	}
436  	
437  	void rb_erase(struct rb_node *node, struct rb_root *root)
438  	{
439  		struct rb_node *rebalance;
440  		rebalance = __rb_erase_augmented(node, root, &dummy_callbacks);
441  		if (rebalance)
442  			____rb_erase_color(rebalance, root, dummy_rotate);
443  	}
444  	
445  	/*
446  	 * Augmented rbtree manipulation functions.
447  	 *
448  	 * This instantiates the same __always_inline functions as in the non-augmented
449  	 * case, but this time with user-defined callbacks.
450  	 */
451  	
452  	void __rb_insert_augmented(struct rb_node *node, struct rb_root *root,
453  		void (*augment_rotate)(struct rb_node *old, struct rb_node *new))
454  	{
455  		__rb_insert(node, root, augment_rotate);
456  	}
457  	
458  	/*
459  	 * This function returns the first node (in sort order) of the tree.
460  	 */
461  	struct rb_node *rb_first(const struct rb_root *root)
462  	{
463  		struct rb_node	*n;
464  	
465  		n = root->rb_node;
466  		if (!n)
467  			return NULL;
(13) Event example_checked: Example 5: "n->rb_left" has its value checked in "n->rb_left".
Also see events: [null_field][example_checked][example_checked][example_checked][example_checked][alias_transfer][dereference]
468  		while (n->rb_left)
469  			n = n->rb_left;
470  		return n;
471  	}
472  	
473  	struct rb_node *rb_last(const struct rb_root *root)
474  	{
475  		struct rb_node	*n;
476  	
477  		n = root->rb_node;
478  		if (!n)
479  			return NULL;
480  		while (n->rb_right)
481  			n = n->rb_right;
482  		return n;
483  	}
484  	
485  	struct rb_node *rb_next(const struct rb_node *node)
486  	{
487  		struct rb_node *parent;
488  	
489  		if (RB_EMPTY_NODE(node))
490  			return NULL;
491  	
492  		/*
493  		 * If we have a right-hand child, go down and then left as far
494  		 * as we can.
495  		 */
496  		if (node->rb_right) {
497  			node = node->rb_right;
498  			while (node->rb_left)
499  				node = node->rb_left;
500  			return (struct rb_node *)node;
501  		}
502  	
503  		/*
504  		 * No right-hand children. Everything down and left is smaller than us,
505  		 * so any 'next' node must be in the general direction of our parent.
506  		 * Go up the tree; any time the ancestor is a right-hand child of its
507  		 * parent, keep going up. First time it's a left-hand child of its
508  		 * parent, said parent is our 'next' node.
509  		 */
510  		while ((parent = rb_parent(node)) && node == parent->rb_right)
511  			node = parent;
512  	
513  		return parent;
514  	}
515  	
516  	struct rb_node *rb_prev(const struct rb_node *node)
517  	{
518  		struct rb_node *parent;
519  	
520  		if (RB_EMPTY_NODE(node))
521  			return NULL;
522  	
523  		/*
524  		 * If we have a left-hand child, go down and then right as far
525  		 * as we can.
526  		 */
527  		if (node->rb_left) {
528  			node = node->rb_left;
529  			while (node->rb_right)
530  				node = node->rb_right;
531  			return (struct rb_node *)node;
532  		}
533  	
534  		/*
535  		 * No left-hand children. Go up till we find an ancestor which
536  		 * is a right-hand child of its parent.
537  		 */
538  		while ((parent = rb_parent(node)) && node == parent->rb_left)
539  			node = parent;
540  	
541  		return parent;
542  	}
543  	
544  	void rb_replace_node(struct rb_node *victim, struct rb_node *new,
545  			     struct rb_root *root)
546  	{
547  		struct rb_node *parent = rb_parent(victim);
548  	
549  		/* Copy the pointers/colour from the victim to the replacement */
550  		*new = *victim;
551  	
552  		/* Set the surrounding nodes to point to the replacement */
553  		if (victim->rb_left)
554  			rb_set_parent(victim->rb_left, new);
555  		if (victim->rb_right)
556  			rb_set_parent(victim->rb_right, new);
557  		__rb_change_child(victim, new, parent, root);
558  	}
559  	
560  	static struct rb_node *rb_left_deepest_node(const struct rb_node *node)
561  	{
562  		for (;;) {
563  			if (node->rb_left)
564  				node = node->rb_left;
565  			else if (node->rb_right)
566  				node = node->rb_right;
567  			else
568  				return (struct rb_node *)node;
569  		}
570  	}
571  	
572  	struct rb_node *rb_next_postorder(const struct rb_node *node)
573  	{
574  		const struct rb_node *parent;
575  		if (!node)
576  			return NULL;
577  		parent = rb_parent(node);
578  	
579  		/* If we're sitting on node, we've already seen our children */
580  		if (parent && node == parent->rb_left && parent->rb_right) {
581  			/* If we are the parent's left node, go to the parent's right
582  			 * node then all the way down to the left */
583  			return rb_left_deepest_node(parent->rb_right);
584  		} else
585  			/* Otherwise we are the parent's right node, and the parent
586  			 * should be next */
587  			return (struct rb_node *)parent;
588  	}
589  	
590  	struct rb_node *rb_first_postorder(const struct rb_root *root)
591  	{
592  		if (!root->rb_node)
593  			return NULL;
594  	
595  		return rb_left_deepest_node(root->rb_node);
596  	}
597