timerqueue.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Generic Timer-queue
  4. *
  5. * Manages a simple queue of timers, ordered by expiration time.
  6. * Uses rbtrees for quick list adds and expiration.
  7. *
  8. * NOTE: All of the following functions need to be serialized
  9. * to avoid races. No locking is done by this library code.
  10. */
  11. #include <linux/bug.h>
  12. #include <linux/timerqueue.h>
  13. #include <linux/rbtree.h>
  14. #include <linux/export.h>
  15. #define __node_2_tq(_n) \
  16. rb_entry((_n), struct timerqueue_node, node)
  17. static inline bool __timerqueue_less(struct rb_node *a, const struct rb_node *b)
  18. {
  19. return __node_2_tq(a)->expires < __node_2_tq(b)->expires;
  20. }
  21. /**
  22. * timerqueue_add - Adds timer to timerqueue.
  23. *
  24. * @head: head of timerqueue
  25. * @node: timer node to be added
  26. *
  27. * Adds the timer node to the timerqueue, sorted by the node's expires
  28. * value. Returns true if the newly added timer is the first expiring timer in
  29. * the queue.
  30. */
  31. bool timerqueue_add(struct timerqueue_head *head, struct timerqueue_node *node)
  32. {
  33. /* Make sure we don't add nodes that are already added */
  34. WARN_ON_ONCE(!RB_EMPTY_NODE(&node->node));
  35. return rb_add_cached(&node->node, &head->rb_root, __timerqueue_less);
  36. }
  37. EXPORT_SYMBOL_GPL(timerqueue_add);
  38. /**
  39. * timerqueue_del - Removes a timer from the timerqueue.
  40. *
  41. * @head: head of timerqueue
  42. * @node: timer node to be removed
  43. *
  44. * Removes the timer node from the timerqueue. Returns true if the queue is
  45. * not empty after the remove.
  46. */
  47. bool timerqueue_del(struct timerqueue_head *head, struct timerqueue_node *node)
  48. {
  49. WARN_ON_ONCE(RB_EMPTY_NODE(&node->node));
  50. rb_erase_cached(&node->node, &head->rb_root);
  51. RB_CLEAR_NODE(&node->node);
  52. return !RB_EMPTY_ROOT(&head->rb_root.rb_root);
  53. }
  54. EXPORT_SYMBOL_GPL(timerqueue_del);
  55. /**
  56. * timerqueue_iterate_next - Returns the timer after the provided timer
  57. *
  58. * @node: Pointer to a timer.
  59. *
  60. * Provides the timer that is after the given node. This is used, when
  61. * necessary, to iterate through the list of timers in a timer list
  62. * without modifying the list.
  63. */
  64. struct timerqueue_node *timerqueue_iterate_next(struct timerqueue_node *node)
  65. {
  66. struct rb_node *next;
  67. if (!node)
  68. return NULL;
  69. next = rb_next(&node->node);
  70. if (!next)
  71. return NULL;
  72. return container_of(next, struct timerqueue_node, node);
  73. }
  74. EXPORT_SYMBOL_GPL(timerqueue_iterate_next);