// SPDX-License-Identifier: GPL-2.0-or-later1/*2Red Black Trees3(C) 1999 Andrea Arcangeli <[email protected]>4(C) 2002 David Woodhouse <[email protected]>5(C) 2012 Michel Lespinasse <[email protected]>678linux/lib/rbtree.c9*/1011#include <linux/rbtree_augmented.h>12#include <linux/export.h>1314/*15* red-black trees properties: https://en.wikipedia.org/wiki/Rbtree16*17* 1) A node is either red or black18* 2) The root is black19* 3) All leaves (NULL) are black20* 4) Both children of every red node are black21* 5) Every simple path from root to leaves contains the same number22* of black nodes.23*24* 4 and 5 give the O(log n) guarantee, since 4 implies you cannot have two25* consecutive red nodes in a path and every red node is therefore followed by26* a black. So if B is the number of black nodes on every simple path (as per27* 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 red30* nodes will be lowercase. Unknown color nodes shall be drawn as red within31* parentheses and have some accompanying text comment.32*/3334/*35* Notes on lockless lookups:36*37* All stores to the tree structure (rb_left and rb_right) must be done using38* WRITE_ONCE(). And we must not inadvertently cause (temporary) loops in the39* tree structure as seen in program order.40*41* These two requirements will allow lockless iteration of the tree -- not42* correct iteration mind you, tree rotations are not atomic so a lookup might43* miss entire subtrees.44*45* But they do guarantee that any such traversal will only see valid elements46* 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 those54* are left undone as of now. Nor did I check for loops involving parent55* pointers.56*/5758static inline void rb_set_black(struct rb_node *rb)59{60rb->__rb_parent_color += RB_BLACK;61}6263static inline struct rb_node *rb_red_parent(struct rb_node *red)64{65return (struct rb_node *)red->__rb_parent_color;66}6768/*69* Helper function for rotations:70* - old's parent and color get assigned to new71* - old gets assigned new as a parent and 'color' as a color.72*/73static inline void74__rb_rotate_set_parents(struct rb_node *old, struct rb_node *new,75struct rb_root *root, int color)76{77struct rb_node *parent = rb_parent(old);78new->__rb_parent_color = old->__rb_parent_color;79rb_set_parent_color(old, new, color);80__rb_change_child(old, new, parent, root);81}8283static __always_inline void84__rb_insert(struct rb_node *node, struct rb_root *root,85void (*augment_rotate)(struct rb_node *old, struct rb_node *new))86{87struct rb_node *parent = rb_red_parent(node), *gparent, *tmp;8889while (true) {90/*91* Loop invariant: node is red.92*/93if (unlikely(!parent)) {94/*95* The inserted node is root. Either this is the96* first node, or we recursed at Case 1 below and97* are no longer violating 4).98*/99rb_set_parent_color(node, NULL, RB_BLACK);100break;101}102103/*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 two107* consecutive red nodes.108*/109if(rb_is_black(parent))110break;111112gparent = rb_red_parent(parent);113114tmp = gparent->rb_right;115if (parent != tmp) { /* parent == gparent->rb_left */116if (tmp && rb_is_red(tmp)) {117/*118* Case 1 - node's uncle is red (color flips).119*120* G g121* / \ / \122* p u --> P U123* / /124* n n125*126* However, since g's parent might be red, and127* 4) does not allow this, we need to recurse128* at g.129*/130rb_set_parent_color(tmp, gparent, RB_BLACK);131rb_set_parent_color(parent, gparent, RB_BLACK);132node = gparent;133parent = rb_parent(node);134rb_set_parent_color(node, parent, RB_RED);135continue;136}137138tmp = parent->rb_right;139if (node == tmp) {140/*141* Case 2 - node's uncle is black and node is142* the parent's right child (left rotate at parent).143*144* G G145* / \ / \146* p U --> n U147* \ /148* n p149*150* This still leaves us in violation of 4), the151* continuation into Case 3 will fix that.152*/153tmp = node->rb_left;154WRITE_ONCE(parent->rb_right, tmp);155WRITE_ONCE(node->rb_left, parent);156if (tmp)157rb_set_parent_color(tmp, parent,158RB_BLACK);159rb_set_parent_color(parent, node, RB_RED);160augment_rotate(parent, node);161parent = node;162tmp = node->rb_right;163}164165/*166* Case 3 - node's uncle is black and node is167* the parent's left child (right rotate at gparent).168*169* G P170* / \ / \171* p U --> n g172* / \173* n U174*/175WRITE_ONCE(gparent->rb_left, tmp); /* == parent->rb_right */176WRITE_ONCE(parent->rb_right, gparent);177if (tmp)178rb_set_parent_color(tmp, gparent, RB_BLACK);179__rb_rotate_set_parents(gparent, parent, root, RB_RED);180augment_rotate(gparent, parent);181break;182} else {183tmp = gparent->rb_left;184if (tmp && rb_is_red(tmp)) {185/* Case 1 - color flips */186rb_set_parent_color(tmp, gparent, RB_BLACK);187rb_set_parent_color(parent, gparent, RB_BLACK);188node = gparent;189parent = rb_parent(node);190rb_set_parent_color(node, parent, RB_RED);191continue;192}193194tmp = parent->rb_left;195if (node == tmp) {196/* Case 2 - right rotate at parent */197tmp = node->rb_right;198WRITE_ONCE(parent->rb_left, tmp);199WRITE_ONCE(node->rb_right, parent);200if (tmp)201rb_set_parent_color(tmp, parent,202RB_BLACK);203rb_set_parent_color(parent, node, RB_RED);204augment_rotate(parent, node);205parent = node;206tmp = node->rb_left;207}208209/* Case 3 - left rotate at gparent */210WRITE_ONCE(gparent->rb_right, tmp); /* == parent->rb_left */211WRITE_ONCE(parent->rb_left, gparent);212if (tmp)213rb_set_parent_color(tmp, gparent, RB_BLACK);214__rb_rotate_set_parents(gparent, parent, root, RB_RED);215augment_rotate(gparent, parent);216break;217}218}219}220221/*222* Inline version for rb_erase() use - we want to be able to inline223* and eliminate the dummy_rotate callback there224*/225static __always_inline void226____rb_erase_color(struct rb_node *parent, struct rb_root *root,227void (*augment_rotate)(struct rb_node *old, struct rb_node *new))228{229struct rb_node *node = NULL, *sibling, *tmp1, *tmp2;230231while (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 a237* black node count that is 1 lower than other leaf paths.238*/239sibling = parent->rb_right;240if (node != sibling) { /* node == parent->rb_left */241if (rb_is_red(sibling)) {242/*243* Case 1 - left rotate at parent244*245* P S246* / \ / \247* N s --> p Sr248* / \ / \249* Sl Sr N Sl250*/251tmp1 = sibling->rb_left;252WRITE_ONCE(parent->rb_right, tmp1);253WRITE_ONCE(sibling->rb_left, parent);254rb_set_parent_color(tmp1, parent, RB_BLACK);255__rb_rotate_set_parents(parent, sibling, root,256RB_RED);257augment_rotate(parent, sibling);258sibling = tmp1;259}260tmp1 = sibling->rb_right;261if (!tmp1 || rb_is_black(tmp1)) {262tmp2 = sibling->rb_left;263if (!tmp2 || rb_is_black(tmp2)) {264/*265* Case 2 - sibling color flip266* (p could be either color here)267*268* (p) (p)269* / \ / \270* N S --> N s271* / \ / \272* Sl Sr Sl Sr273*274* This leaves us violating 5) which275* can be fixed by flipping p to black276* if it was red, or by recursing at p.277* p is red when coming from Case 1.278*/279rb_set_parent_color(sibling, parent,280RB_RED);281if (rb_is_red(parent))282rb_set_black(parent);283else {284node = parent;285parent = rb_parent(node);286if (parent)287continue;288}289break;290}291/*292* Case 3 - right rotate at sibling293* (p could be either color here)294*295* (p) (p)296* / \ / \297* N S --> N sl298* / \ \299* sl Sr S300* \301* Sr302*303* Note: p might be red, and then both304* p and sl are red after rotation(which305* breaks property 4). This is fixed in306* Case 4 (in __rb_rotate_set_parents()307* which set sl the color of p308* and set p RB_BLACK)309*310* (p) (sl)311* / \ / \312* N sl --> P S313* \ / \314* S N Sr315* \316* Sr317*/318tmp1 = tmp2->rb_right;319WRITE_ONCE(sibling->rb_left, tmp1);320WRITE_ONCE(tmp2->rb_right, sibling);321WRITE_ONCE(parent->rb_right, tmp2);322if (tmp1)323rb_set_parent_color(tmp1, sibling,324RB_BLACK);325augment_rotate(sibling, tmp2);326tmp1 = sibling;327sibling = tmp2;328}329/*330* Case 4 - left rotate at parent + color flips331* (p and sl could be either color here.332* After rotation, p becomes black, s acquires333* p's color, and sl keeps its color)334*335* (p) (s)336* / \ / \337* N S --> P Sr338* / \ / \339* (sl) sr N (sl)340*/341tmp2 = sibling->rb_left;342WRITE_ONCE(parent->rb_right, tmp2);343WRITE_ONCE(sibling->rb_left, parent);344rb_set_parent_color(tmp1, sibling, RB_BLACK);345if (tmp2)346rb_set_parent(tmp2, parent);347__rb_rotate_set_parents(parent, sibling, root,348RB_BLACK);349augment_rotate(parent, sibling);350break;351} else {352sibling = parent->rb_left;353if (rb_is_red(sibling)) {354/* Case 1 - right rotate at parent */355tmp1 = sibling->rb_right;356WRITE_ONCE(parent->rb_left, tmp1);357WRITE_ONCE(sibling->rb_right, parent);358rb_set_parent_color(tmp1, parent, RB_BLACK);359__rb_rotate_set_parents(parent, sibling, root,360RB_RED);361augment_rotate(parent, sibling);362sibling = tmp1;363}364tmp1 = sibling->rb_left;365if (!tmp1 || rb_is_black(tmp1)) {366tmp2 = sibling->rb_right;367if (!tmp2 || rb_is_black(tmp2)) {368/* Case 2 - sibling color flip */369rb_set_parent_color(sibling, parent,370RB_RED);371if (rb_is_red(parent))372rb_set_black(parent);373else {374node = parent;375parent = rb_parent(node);376if (parent)377continue;378}379break;380}381/* Case 3 - left rotate at sibling */382tmp1 = tmp2->rb_left;383WRITE_ONCE(sibling->rb_right, tmp1);384WRITE_ONCE(tmp2->rb_left, sibling);385WRITE_ONCE(parent->rb_left, tmp2);386if (tmp1)387rb_set_parent_color(tmp1, sibling,388RB_BLACK);389augment_rotate(sibling, tmp2);390tmp1 = sibling;391sibling = tmp2;392}393/* Case 4 - right rotate at parent + color flips */394tmp2 = sibling->rb_right;395WRITE_ONCE(parent->rb_left, tmp2);396WRITE_ONCE(sibling->rb_right, parent);397rb_set_parent_color(tmp1, sibling, RB_BLACK);398if (tmp2)399rb_set_parent(tmp2, parent);400__rb_rotate_set_parents(parent, sibling, root,401RB_BLACK);402augment_rotate(parent, sibling);403break;404}405}406}407408/* Non-inline version for rb_erase_augmented() use */409void __rb_erase_color(struct rb_node *parent, struct rb_root *root,410void (*augment_rotate)(struct rb_node *old, struct rb_node *new))411{412____rb_erase_color(parent, root, augment_rotate);413}414415/*416* Non-augmented rbtree manipulation functions.417*418* We use dummy augmented callbacks here, and have the compiler optimize them419* out of the rb_insert_color() and rb_erase() function definitions.420*/421422static inline void dummy_propagate(struct rb_node *node, struct rb_node *stop) {}423static inline void dummy_copy(struct rb_node *old, struct rb_node *new) {}424static inline void dummy_rotate(struct rb_node *old, struct rb_node *new) {}425426static const struct rb_augment_callbacks dummy_callbacks = {427.propagate = dummy_propagate,428.copy = dummy_copy,429.rotate = dummy_rotate430};431432void rb_insert_color(struct rb_node *node, struct rb_root *root)433{434__rb_insert(node, root, dummy_rotate);435}436437void rb_erase(struct rb_node *node, struct rb_root *root)438{439struct rb_node *rebalance;440rebalance = __rb_erase_augmented(node, root, &dummy_callbacks);441if (rebalance)442____rb_erase_color(rebalance, root, dummy_rotate);443}444445/*446* Augmented rbtree manipulation functions.447*448* This instantiates the same __always_inline functions as in the non-augmented449* case, but this time with user-defined callbacks.450*/451452void __rb_insert_augmented(struct rb_node *node, struct rb_root *root,453void (*augment_rotate)(struct rb_node *old, struct rb_node *new))454{455__rb_insert(node, root, augment_rotate);456}457458/*459* This function returns the first node (in sort order) of the tree.460*/461struct rb_node *rb_first(const struct rb_root *root)462{463struct rb_node *n;464465n = root->rb_node;466if (!n)467return NULL;468while (n->rb_left)469n = n->rb_left;470return n;471}472473struct rb_node *rb_last(const struct rb_root *root)474{475struct rb_node *n;476477n = root->rb_node;478if (!n)479return NULL;480while (n->rb_right)481n = n->rb_right;482return n;483}484485struct rb_node *rb_next(const struct rb_node *node)486{487struct rb_node *parent;488489if (RB_EMPTY_NODE(node))490return NULL;491492/*493* If we have a right-hand child, go down and then left as far494* as we can.495*/496if (node->rb_right) {497node = node->rb_right;498while (node->rb_left)499node = node->rb_left;500return (struct rb_node *)node;501}502503/*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 its507* parent, keep going up. First time it's a left-hand child of its508* parent, said parent is our 'next' node.509*/510while ((parent = rb_parent(node)) && node == parent->rb_right)511node = parent;512513return parent;514}515516struct rb_node *rb_prev(const struct rb_node *node)517{518struct rb_node *parent;519520if (RB_EMPTY_NODE(node))521return NULL;522523/*524* If we have a left-hand child, go down and then right as far525* as we can.526*/527if (node->rb_left) {528node = node->rb_left;529while (node->rb_right)530node = node->rb_right;531return (struct rb_node *)node;532}533534/*535* No left-hand children. Go up till we find an ancestor which536* is a right-hand child of its parent.537*/538while ((parent = rb_parent(node)) && node == parent->rb_left)539node = parent;540541return parent;542}543544void rb_replace_node(struct rb_node *victim, struct rb_node *new,545struct rb_root *root)546{547struct rb_node *parent = rb_parent(victim);548549/* Copy the pointers/colour from the victim to the replacement */550*new = *victim;551552/* Set the surrounding nodes to point to the replacement */553if (victim->rb_left)554rb_set_parent(victim->rb_left, new);555if (victim->rb_right)556rb_set_parent(victim->rb_right, new);557__rb_change_child(victim, new, parent, root);558}559560static struct rb_node *rb_left_deepest_node(const struct rb_node *node)561{562for (;;) {563if (node->rb_left)564node = node->rb_left;565else if (node->rb_right)566node = node->rb_right;567else568return (struct rb_node *)node;569}570}571572struct rb_node *rb_next_postorder(const struct rb_node *node)573{574const struct rb_node *parent;575if (!node)576return NULL;577parent = rb_parent(node);578579/* If we're sitting on node, we've already seen our children */580if (parent && node == parent->rb_left && parent->rb_right) {581/* If we are the parent's left node, go to the parent's right582* node then all the way down to the left */583return rb_left_deepest_node(parent->rb_right);584} else585/* Otherwise we are the parent's right node, and the parent586* should be next */587return (struct rb_node *)parent;588}589590struct rb_node *rb_first_postorder(const struct rb_root *root)591{592if (!root->rb_node)593return NULL;594595return rb_left_deepest_node(root->rb_node);596}597598599