xref: /linux/include/linux/rbtree_augmented.h (revision cb95904b470d2d347012d5e360303cf478ca5362)
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
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/include/linux/rbtree_augmented.h
10 */
11 
12 #ifndef _LINUX_RBTREE_AUGMENTED_H
13 #define _LINUX_RBTREE_AUGMENTED_H
14 
15 #include <linux/compiler.h>
16 #include <linux/rbtree.h>
17 #include <linux/rcupdate.h>
18 #include <linux/args.h>
19 #include <linux/minmax.h>
20 
21 /*
22  * Please note - only struct rb_augment_callbacks and the prototypes for
23  * rb_insert_augmented() and rb_erase_augmented() are intended to be public.
24  * The rest are implementation details you are not expected to depend on.
25  *
26  * See Documentation/core-api/rbtree.rst for documentation and samples.
27  */
28 
29 struct rb_augment_callbacks {
30 	void (*propagate)(struct rb_node *node, struct rb_node *stop);
31 	void (*copy)(struct rb_node *old, struct rb_node *new);
32 	void (*rotate)(struct rb_node *old, struct rb_node *new);
33 	void (*merge)(struct rb_node *node, struct rb_node *new);
34 };
35 
36 extern void __rb_insert_augmented(struct rb_node *node, struct rb_root *root,
37 	void (*augment_rotate)(struct rb_node *old, struct rb_node *new));
38 
39 /*
40  * Fixup the rbtree and update the augmented information when rebalancing.
41  *
42  * On insertion, the user must update the augmented information on the path
43  * leading to the inserted node, then call rb_link_node() as usual and
44  * rb_insert_augmented() instead of the usual rb_insert_color() call.
45  * If rb_insert_augmented() rebalances the rbtree, it will callback into
46  * a user provided function to update the augmented information on the
47  * affected subtrees.
48  */
49 static inline void
rb_insert_augmented(struct rb_node * node,struct rb_root * root,const struct rb_augment_callbacks * augment)50 rb_insert_augmented(struct rb_node *node, struct rb_root *root,
51 		    const struct rb_augment_callbacks *augment)
52 {
53 	__rb_insert_augmented(node, root, augment->rotate);
54 }
55 
56 static inline void
rb_insert_augmented_cached(struct rb_node * node,struct rb_root_cached * root,bool newleft,const struct rb_augment_callbacks * augment)57 rb_insert_augmented_cached(struct rb_node *node,
58 			   struct rb_root_cached *root, bool newleft,
59 			   const struct rb_augment_callbacks *augment)
60 {
61 	if (newleft)
62 		root->rb_leftmost = node;
63 	rb_insert_augmented(node, &root->rb_root, augment);
64 }
65 
66 /*
67  * Insert @node into the leftmost cached augmented tree @tree.
68  *
69  * The augmented data of @node must already describe @node alone; it is
70  * merged into every ancestor on the way down through augment->merge().
71  */
72 static __always_inline struct rb_node *
rb_add_augmented_cached(struct rb_node * node,struct rb_root_cached * tree,bool (* less)(struct rb_node *,const struct rb_node *),const struct rb_augment_callbacks * augment)73 rb_add_augmented_cached(struct rb_node *node, struct rb_root_cached *tree,
74 			bool (*less)(struct rb_node *, const struct rb_node *),
75 			const struct rb_augment_callbacks *augment)
76 {
77 	struct rb_node **link = &tree->rb_root.rb_node;
78 	struct rb_node *parent = NULL;
79 	bool leftmost = true;
80 
81 	while (*link) {
82 		parent = *link;
83 		augment->merge(parent, node);
84 		if (less(node, parent)) {
85 			link = &parent->rb_left;
86 		} else {
87 			link = &parent->rb_right;
88 			leftmost = false;
89 		}
90 	}
91 
92 	rb_link_node(node, parent, link);
93 	rb_insert_augmented_cached(node, tree, leftmost, augment);
94 
95 	return leftmost ? node : NULL;
96 }
97 
98 #define RB_FOR_EACH_1(what, RBNAME, RBSTRUCT, RBFIELD, x)		\
99 	what(1, RBNAME, RBSTRUCT, RBFIELD, x)
100 
101 #define RB_FOR_EACH_2(what, RBNAME, RBSTRUCT, RBFIELD, x, ...)		\
102 	what(2, RBNAME, RBSTRUCT, RBFIELD, x)				\
103 	RB_FOR_EACH_1(what, RBNAME, RBSTRUCT, RBFIELD, __VA_ARGS__)
104 
105 #define RB_FOR_EACH_3(what, RBNAME, RBSTRUCT, RBFIELD, x, ...)		\
106 	what(3, RBNAME, RBSTRUCT, RBFIELD, x)				\
107 	RB_FOR_EACH_2(what, RBNAME, RBSTRUCT, RBFIELD, __VA_ARGS__)
108 
109 #define RB_FOR_EACH_4(what, RBNAME, RBSTRUCT, RBFIELD, x, ...)		\
110 	what(4, RBNAME, RBSTRUCT, RBFIELD, x)				\
111 	RB_FOR_EACH_3(what, RBNAME, RBSTRUCT, RBFIELD, __VA_ARGS__)
112 
113 #define RB_FOR_EACH_5(what, RBNAME, RBSTRUCT, RBFIELD, x, ...)		\
114 	what(5, RBNAME, RBSTRUCT, RBFIELD, x)				\
115 	RB_FOR_EACH_4(what, RBNAME, RBSTRUCT, RBFIELD, __VA_ARGS__)
116 
117 #define RB_FOR_EACH_6(what, RBNAME, RBSTRUCT, RBFIELD, x, ...)		\
118 	what(6, RBNAME, RBSTRUCT, RBFIELD, x)				\
119 	RB_FOR_EACH_5(what, RBNAME, RBSTRUCT, RBFIELD, __VA_ARGS__)
120 
121 #define RB_FOR_EACH_7(what, RBNAME, RBSTRUCT, RBFIELD, x, ...)		\
122 	what(7, RBNAME, RBSTRUCT, RBFIELD, x)				\
123 	RB_FOR_EACH_6(what, RBNAME, RBSTRUCT, RBFIELD, __VA_ARGS__)
124 
125 #define RB_FOR_EACH_8(what, RBNAME, RBSTRUCT, RBFIELD, x, ...)		\
126 	what(8, RBNAME, RBSTRUCT, RBFIELD, x)				\
127 	RB_FOR_EACH_7(what, RBNAME, RBSTRUCT, RBFIELD, __VA_ARGS__)
128 
129 #define RB_FOR_EACH(action, RBNAME, RBSTRUCT, RBFIELD, ...)		\
130 	CONCATENATE(RB_FOR_EACH_, COUNT_ARGS(__VA_ARGS__))		\
131 		(action, RBNAME, RBSTRUCT, RBFIELD, __VA_ARGS__)
132 
133 /*
134  * One augmented field: @val is the node's own contribution (a member for
135  * RB_AUG(), a function of the node for RB_AUG_FUNC()), @aug the member
136  * holding the aggregate over the subtree, and @fold(a, b) combines two
137  * aggregates: min, max, a sum, ...  It must be commutative and associative.
138  */
139 #define RB_AUG_FUNC(val, aug, fold) (val(s), aug, fold)
140 #define RB_AUG(val, aug, fold) (s->val, aug, fold)
141 #define RB_UNPACK(...) __VA_ARGS__
142 
143 #define __RB_INST(n, RBNAME, RBSTRUCT, RBFIELD, val, aug, fold)		\
144 static inline void							\
145 RBNAME ## _copy_ ## n(RBSTRUCT *old, RBSTRUCT *new)			\
146 {									\
147 	new->aug = old->aug;						\
148 }									\
149 static inline bool							\
150 RBNAME ## _compute_ ## n(RBSTRUCT *s, bool exit)			\
151 {									\
152 	TYPEOF_UNQUAL(s->aug) _old_aug = s->aug;			\
153 	TYPEOF_UNQUAL(s->aug) _val = val;				\
154 	struct rb_node *_node = &s->RBFIELD;				\
155 	if (_node->rb_right) {						\
156 		RBSTRUCT *_c = container_of(_node->rb_right, typeof(*s), RBFIELD); \
157 		_val = fold(_val, _c->aug);				\
158 	}								\
159 	if (_node->rb_left) {						\
160 		RBSTRUCT *_c = container_of(_node->rb_left, typeof(*s), RBFIELD); \
161 		_val = fold(_val, _c->aug);				\
162 	}								\
163 	if (exit && _old_aug == _val)					\
164 		return true;						\
165 	s->aug = _val;							\
166 	return false;							\
167 }
168 #define _RB_INST(n, RBNAME, RBSTRUCT, RBFIELD, args)			\
169 	__RB_INST(n, RBNAME, RBSTRUCT, RBFIELD, args)
170 #define RB_INST(n, RBNAME, RBSTRUCT, RBFIELD, x)			\
171 	_RB_INST(n, RBNAME, RBSTRUCT, RBFIELD, RB_UNPACK x)
172 
173 #define __RB_COPY(n, RBNAME, RBSTRUCT, RBFIELD, val, aug, fold)		\
174 	RBNAME ## _copy_ ## n(old, new);
175 #define _RB_COPY(n, RBNAME, RBSTRUCT, RBFIELD, args)			\
176 	__RB_COPY(n, RBNAME, RBSTRUCT, RBFIELD, args)
177 #define RB_COPY(n, RBNAME, RBSTRUCT, RBFIELD, x)			\
178 	_RB_COPY(n, RBNAME, RBSTRUCT, RBFIELD, RB_UNPACK x)
179 
180 #define __RB_COMPUTE(n, RBNAME, RBSTRUCT, RBFIELD, val, aug, fold)	\
181 	ret &= RBNAME ## _compute_ ## n(node, exit);
182 #define _RB_COMPUTE(n, RBNAME, RBSTRUCT, RBFIELD, args)			\
183 	__RB_COMPUTE(n, RBNAME, RBSTRUCT, RBFIELD, args)
184 #define RB_COMPUTE(n, RBNAME, RBSTRUCT, RBFIELD, x)			\
185 	_RB_COMPUTE(n, RBNAME, RBSTRUCT, RBFIELD, RB_UNPACK x)
186 
187 /* fold @new, about to become a descendant of @node, into @node */
188 #define __RB_MERGE(n, RBNAME, RBSTRUCT, RBFIELD, val, aug, fold)	\
189 	node->aug = fold(node->aug, new->aug);
190 #define _RB_MERGE(n, RBNAME, RBSTRUCT, RBFIELD, args)			\
191 	__RB_MERGE(n, RBNAME, RBSTRUCT, RBFIELD, args)
192 #define RB_MERGE(n, RBNAME, RBSTRUCT, RBFIELD, x)			\
193 	_RB_MERGE(n, RBNAME, RBSTRUCT, RBFIELD, RB_UNPACK x)
194 
195 /*
196  * Template for declaring augmented rbtree callbacks (generic multi fields)
197  *
198  * RBSTATIC:    'static' or empty
199  * RBNAME:      name of the rb_augment_callbacks structure
200  * RBSTRUCT:    struct type of the tree nodes
201  * RBFIELD:     name of struct rb_node field within RBSTRUCT
202  * RBAUG...:	list of RB_AUG() describing the augmented data
203  */
204 #define RB_DECLARE_CALLBACKS(RBSTATIC, RBNAME,				\
205 			     RBSTRUCT, RBFIELD, RBAUG...)		\
206 RB_FOR_EACH(RB_INST, RBNAME, RBSTRUCT, RBFIELD, RBAUG)			\
207 static inline void							\
208 RBNAME ## __copy(RBSTRUCT *old, RBSTRUCT *new)				\
209 {									\
210 	RB_FOR_EACH(RB_COPY, RBNAME, RBSTRUCT, RBFIELD, RBAUG);		\
211 }									\
212 static inline bool							\
213 RBNAME ## __compute(RBSTRUCT *node, bool exit)				\
214 {									\
215 	bool ret = true;						\
216 	RB_FOR_EACH(RB_COMPUTE, RBNAME, RBSTRUCT, RBFIELD, RBAUG);	\
217 	return ret;							\
218 }									\
219 static inline void							\
220 RBNAME ## _propagate(struct rb_node *rb, struct rb_node *stop)		\
221 {									\
222 	while (rb != stop) {						\
223 		RBSTRUCT *node = rb_entry(rb, RBSTRUCT, RBFIELD);	\
224 		if (RBNAME ## __compute(node, true))			\
225 			break;						\
226 		rb = rb_parent(&node->RBFIELD);				\
227 	}								\
228 }									\
229 static inline void							\
230 RBNAME ## _copy(struct rb_node *rb_old, struct rb_node *rb_new)		\
231 {									\
232 	RBSTRUCT *old = rb_entry(rb_old, RBSTRUCT, RBFIELD);		\
233 	RBSTRUCT *new = rb_entry(rb_new, RBSTRUCT, RBFIELD);		\
234 	RBNAME ## __copy(old, new);					\
235 }									\
236 static void								\
237 RBNAME ## _rotate(struct rb_node *rb_old, struct rb_node *rb_new)	\
238 {									\
239 	RBSTRUCT *old = rb_entry(rb_old, RBSTRUCT, RBFIELD);		\
240 	RBSTRUCT *new = rb_entry(rb_new, RBSTRUCT, RBFIELD);		\
241 	RBNAME ## __copy(old, new);					\
242 	RBNAME ## __compute(old, false);				\
243 }									\
244 static inline void							\
245 RBNAME ## _merge(struct rb_node *rb, struct rb_node *rb_new)		\
246 {									\
247 	RBSTRUCT *node = rb_entry(rb, RBSTRUCT, RBFIELD);		\
248 	RBSTRUCT *new = rb_entry(rb_new, RBSTRUCT, RBFIELD);		\
249 	RB_FOR_EACH(RB_MERGE, RBNAME, RBSTRUCT, RBFIELD, RBAUG);	\
250 }									\
251 RBSTATIC const struct rb_augment_callbacks RBNAME = {			\
252 	.propagate = RBNAME ## _propagate,				\
253 	.copy = RBNAME ## _copy,					\
254 	.rotate = RBNAME ## _rotate,					\
255 	.merge = RBNAME ## _merge					\
256 };
257 
258 /*
259  * Template for declaring augmented rbtree callbacks,
260  * computing RBAUGMENTED scalar as max(RBCOMPUTE(node)) for all subtree nodes.
261  *
262  * RBSTATIC:    'static' or empty
263  * RBNAME:      name of the rb_augment_callbacks structure
264  * RBSTRUCT:    struct type of the tree nodes
265  * RBFIELD:     name of struct rb_node field within RBSTRUCT
266  * RBTYPE:      type of the RBAUGMENTED field -- unused, assumed typeof(RBAUGMENTED)
267  * RBAUGMENTED: name of field within RBSTRUCT holding data for subtree
268  * RBVALUE:     name of function that returns the per-node RBTYPE scalar
269  */
270 
271 #define RB_DECLARE_CALLBACKS_MAX(RBSTATIC, RBNAME, RBSTRUCT, RBFIELD,		\
272 				 RBTYPE, RBAUGMENTED, RBVALUE)			\
273 RB_DECLARE_CALLBACKS(RBSTATIC, RBNAME, RBSTRUCT, RBFIELD,			\
274 		     RB_AUG_FUNC(RBVALUE, RBAUGMENTED, max))
275 
276 
277 #define	RB_RED		0
278 #define	RB_BLACK	1
279 
280 #define __rb_parent(pc)    ((struct rb_node *)(pc & ~3))
281 
282 #define __rb_color(pc)     ((pc) & 1)
283 #define __rb_is_black(pc)  __rb_color(pc)
284 #define __rb_is_red(pc)    (!__rb_color(pc))
285 #define rb_color(rb)       __rb_color((rb)->__rb_parent_color)
286 #define rb_is_red(rb)      __rb_is_red((rb)->__rb_parent_color)
287 #define rb_is_black(rb)    __rb_is_black((rb)->__rb_parent_color)
288 
rb_set_parent(struct rb_node * rb,struct rb_node * p)289 static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p)
290 {
291 	rb->__rb_parent_color = rb_color(rb) + (unsigned long)p;
292 }
293 
rb_set_parent_color(struct rb_node * rb,struct rb_node * p,int color)294 static inline void rb_set_parent_color(struct rb_node *rb,
295 				       struct rb_node *p, int color)
296 {
297 	rb->__rb_parent_color = (unsigned long)p + color;
298 }
299 
300 static inline void
__rb_change_child(struct rb_node * old,struct rb_node * new,struct rb_node * parent,struct rb_root * root)301 __rb_change_child(struct rb_node *old, struct rb_node *new,
302 		  struct rb_node *parent, struct rb_root *root)
303 {
304 	if (parent) {
305 		if (parent->rb_left == old)
306 			WRITE_ONCE(parent->rb_left, new);
307 		else
308 			WRITE_ONCE(parent->rb_right, new);
309 	} else
310 		WRITE_ONCE(root->rb_node, new);
311 }
312 
313 static inline void
__rb_change_child_rcu(struct rb_node * old,struct rb_node * new,struct rb_node * parent,struct rb_root * root)314 __rb_change_child_rcu(struct rb_node *old, struct rb_node *new,
315 		      struct rb_node *parent, struct rb_root *root)
316 {
317 	if (parent) {
318 		if (parent->rb_left == old)
319 			rcu_assign_pointer(parent->rb_left, new);
320 		else
321 			rcu_assign_pointer(parent->rb_right, new);
322 	} else
323 		rcu_assign_pointer(root->rb_node, new);
324 }
325 
326 extern void __rb_erase_color(struct rb_node *parent, struct rb_root *root,
327 	void (*augment_rotate)(struct rb_node *old, struct rb_node *new));
328 
329 static __always_inline struct rb_node *
__rb_erase_augmented(struct rb_node * node,struct rb_root * root,const struct rb_augment_callbacks * augment)330 __rb_erase_augmented(struct rb_node *node, struct rb_root *root,
331 		     const struct rb_augment_callbacks *augment)
332 {
333 	struct rb_node *child = node->rb_right;
334 	struct rb_node *tmp = node->rb_left;
335 	struct rb_node *parent, *rebalance;
336 	unsigned long pc;
337 
338 	if (!tmp) {
339 		/*
340 		 * Case 1: node to erase has no more than 1 child (easy!)
341 		 *
342 		 * Note that if there is one child it must be red due to 5)
343 		 * and node must be black due to 4). We adjust colors locally
344 		 * so as to bypass __rb_erase_color() later on.
345 		 */
346 		pc = node->__rb_parent_color;
347 		parent = __rb_parent(pc);
348 		__rb_change_child(node, child, parent, root);
349 		if (child) {
350 			child->__rb_parent_color = pc;
351 			rebalance = NULL;
352 		} else
353 			rebalance = __rb_is_black(pc) ? parent : NULL;
354 		tmp = parent;
355 	} else if (!child) {
356 		/* Still case 1, but this time the child is node->rb_left */
357 		tmp->__rb_parent_color = pc = node->__rb_parent_color;
358 		parent = __rb_parent(pc);
359 		__rb_change_child(node, tmp, parent, root);
360 		rebalance = NULL;
361 		tmp = parent;
362 	} else {
363 		struct rb_node *successor = child, *child2;
364 
365 		tmp = child->rb_left;
366 		if (!tmp) {
367 			/*
368 			 * Case 2: node's successor is its right child
369 			 *
370 			 *    (n)          (s)
371 			 *    / \          / \
372 			 *  (x) (s)  ->  (x) (c)
373 			 *        \
374 			 *        (c)
375 			 */
376 			parent = successor;
377 			child2 = successor->rb_right;
378 
379 			augment->copy(node, successor);
380 		} else {
381 			/*
382 			 * Case 3: node's successor is leftmost under
383 			 * node's right child subtree
384 			 *
385 			 *    (n)          (s)
386 			 *    / \          / \
387 			 *  (x) (y)  ->  (x) (y)
388 			 *      /            /
389 			 *    (p)          (p)
390 			 *    /            /
391 			 *  (s)          (c)
392 			 *    \
393 			 *    (c)
394 			 */
395 			do {
396 				parent = successor;
397 				successor = tmp;
398 				tmp = tmp->rb_left;
399 			} while (tmp);
400 			child2 = successor->rb_right;
401 			WRITE_ONCE(parent->rb_left, child2);
402 			WRITE_ONCE(successor->rb_right, child);
403 			rb_set_parent(child, successor);
404 
405 			augment->copy(node, successor);
406 			augment->propagate(parent, successor);
407 		}
408 
409 		tmp = node->rb_left;
410 		WRITE_ONCE(successor->rb_left, tmp);
411 		rb_set_parent(tmp, successor);
412 
413 		pc = node->__rb_parent_color;
414 		tmp = __rb_parent(pc);
415 		__rb_change_child(node, successor, tmp, root);
416 
417 		if (child2) {
418 			rb_set_parent_color(child2, parent, RB_BLACK);
419 			rebalance = NULL;
420 		} else {
421 			rebalance = rb_is_black(successor) ? parent : NULL;
422 		}
423 		successor->__rb_parent_color = pc;
424 		tmp = successor;
425 	}
426 
427 	augment->propagate(tmp, NULL);
428 	return rebalance;
429 }
430 
431 static __always_inline void
rb_erase_augmented(struct rb_node * node,struct rb_root * root,const struct rb_augment_callbacks * augment)432 rb_erase_augmented(struct rb_node *node, struct rb_root *root,
433 		   const struct rb_augment_callbacks *augment)
434 {
435 	struct rb_node *rebalance = __rb_erase_augmented(node, root, augment);
436 	if (rebalance)
437 		__rb_erase_color(rebalance, root, augment->rotate);
438 }
439 
440 static __always_inline void
rb_erase_augmented_cached(struct rb_node * node,struct rb_root_cached * root,const struct rb_augment_callbacks * augment)441 rb_erase_augmented_cached(struct rb_node *node, struct rb_root_cached *root,
442 			  const struct rb_augment_callbacks *augment)
443 {
444 	if (root->rb_leftmost == node)
445 		root->rb_leftmost = rb_next(node);
446 	rb_erase_augmented(node, &root->rb_root, augment);
447 }
448 
449 #endif	/* _LINUX_RBTREE_AUGMENTED_H */
450