Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  *  Generic Timer-queue
0004  *
0005  *  Manages a simple queue of timers, ordered by expiration time.
0006  *  Uses rbtrees for quick list adds and expiration.
0007  *
0008  *  NOTE: All of the following functions need to be serialized
0009  *  to avoid races. No locking is done by this library code.
0010  */
0011 
0012 #include <linux/bug.h>
0013 #include <linux/timerqueue.h>
0014 #include <linux/rbtree.h>
0015 #include <linux/export.h>
0016 
0017 #define __node_2_tq(_n) \
0018     rb_entry((_n), struct timerqueue_node, node)
0019 
0020 static inline bool __timerqueue_less(struct rb_node *a, const struct rb_node *b)
0021 {
0022     return __node_2_tq(a)->expires < __node_2_tq(b)->expires;
0023 }
0024 
0025 /**
0026  * timerqueue_add - Adds timer to timerqueue.
0027  *
0028  * @head: head of timerqueue
0029  * @node: timer node to be added
0030  *
0031  * Adds the timer node to the timerqueue, sorted by the node's expires
0032  * value. Returns true if the newly added timer is the first expiring timer in
0033  * the queue.
0034  */
0035 bool timerqueue_add(struct timerqueue_head *head, struct timerqueue_node *node)
0036 {
0037     /* Make sure we don't add nodes that are already added */
0038     WARN_ON_ONCE(!RB_EMPTY_NODE(&node->node));
0039 
0040     return rb_add_cached(&node->node, &head->rb_root, __timerqueue_less);
0041 }
0042 EXPORT_SYMBOL_GPL(timerqueue_add);
0043 
0044 /**
0045  * timerqueue_del - Removes a timer from the timerqueue.
0046  *
0047  * @head: head of timerqueue
0048  * @node: timer node to be removed
0049  *
0050  * Removes the timer node from the timerqueue. Returns true if the queue is
0051  * not empty after the remove.
0052  */
0053 bool timerqueue_del(struct timerqueue_head *head, struct timerqueue_node *node)
0054 {
0055     WARN_ON_ONCE(RB_EMPTY_NODE(&node->node));
0056 
0057     rb_erase_cached(&node->node, &head->rb_root);
0058     RB_CLEAR_NODE(&node->node);
0059 
0060     return !RB_EMPTY_ROOT(&head->rb_root.rb_root);
0061 }
0062 EXPORT_SYMBOL_GPL(timerqueue_del);
0063 
0064 /**
0065  * timerqueue_iterate_next - Returns the timer after the provided timer
0066  *
0067  * @node: Pointer to a timer.
0068  *
0069  * Provides the timer that is after the given node. This is used, when
0070  * necessary, to iterate through the list of timers in a timer list
0071  * without modifying the list.
0072  */
0073 struct timerqueue_node *timerqueue_iterate_next(struct timerqueue_node *node)
0074 {
0075     struct rb_node *next;
0076 
0077     if (!node)
0078         return NULL;
0079     next = rb_next(&node->node);
0080     if (!next)
0081         return NULL;
0082     return container_of(next, struct timerqueue_node, node);
0083 }
0084 EXPORT_SYMBOL_GPL(timerqueue_iterate_next);