min_heap.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. .. SPDX-License-Identifier: GPL-2.0
  2. ============
  3. Min Heap API
  4. ============
  5. :Author: Kuan-Wei Chiu <visitorckw@gmail.com>
  6. Introduction
  7. ============
  8. The Min Heap API provides a set of functions and macros for managing min-heaps
  9. in the Linux kernel. A min-heap is a binary tree structure where the value of
  10. each node is less than or equal to the values of its children, ensuring that
  11. the smallest element is always at the root.
  12. This document provides a guide to the Min Heap API, detailing how to define and
  13. use min-heaps. Users should not directly call functions with **__min_heap_*()**
  14. prefixes, but should instead use the provided macro wrappers.
  15. In addition to the standard version of the functions, the API also includes a
  16. set of inline versions for performance-critical scenarios. These inline
  17. functions have the same names as their non-inline counterparts but include an
  18. **_inline** suffix. For example, **__min_heap_init_inline** and its
  19. corresponding macro wrapper **min_heap_init_inline**. The inline versions allow
  20. custom comparison and swap functions to be called directly, rather than through
  21. indirect function calls. This can significantly reduce overhead, especially
  22. when CONFIG_MITIGATION_RETPOLINE is enabled, as indirect function calls become
  23. more expensive. As with the non-inline versions, it is important to use the
  24. macro wrappers for inline functions instead of directly calling the functions
  25. themselves.
  26. Data Structures
  27. ===============
  28. Min-Heap Definition
  29. -------------------
  30. The core data structure for representing a min-heap is defined using the
  31. **MIN_HEAP_PREALLOCATED** and **DEFINE_MIN_HEAP** macros. These macros allow
  32. you to define a min-heap with a preallocated buffer or dynamically allocated
  33. memory.
  34. Example:
  35. .. code-block:: c
  36. #define MIN_HEAP_PREALLOCATED(_type, _name, _nr)
  37. struct _name {
  38. size_t nr; /* Number of elements in the heap */
  39. size_t size; /* Maximum number of elements that can be held */
  40. _type *data; /* Pointer to the heap data */
  41. _type preallocated[_nr]; /* Static preallocated array */
  42. }
  43. #define DEFINE_MIN_HEAP(_type, _name) MIN_HEAP_PREALLOCATED(_type, _name, 0)
  44. A typical heap structure will include a counter for the number of elements
  45. (`nr`), the maximum capacity of the heap (`size`), and a pointer to an array of
  46. elements (`data`). Optionally, you can specify a static array for preallocated
  47. heap storage using **MIN_HEAP_PREALLOCATED**.
  48. Min Heap Callbacks
  49. ------------------
  50. The **struct min_heap_callbacks** provides customization options for ordering
  51. elements in the heap and swapping them. It contains two function pointers:
  52. .. code-block:: c
  53. struct min_heap_callbacks {
  54. bool (*less)(const void *lhs, const void *rhs, void *args);
  55. void (*swp)(void *lhs, void *rhs, void *args);
  56. };
  57. - **less** is the comparison function used to establish the order of elements.
  58. - **swp** is a function for swapping elements in the heap. If swp is set to
  59. NULL, the default swap function will be used, which swaps the elements based on their size
  60. Macro Wrappers
  61. ==============
  62. The following macro wrappers are provided for interacting with the heap in a
  63. user-friendly manner. Each macro corresponds to a function that operates on the
  64. heap, and they abstract away direct calls to internal functions.
  65. Each macro accepts various parameters that are detailed below.
  66. Heap Initialization
  67. --------------------
  68. .. code-block:: c
  69. min_heap_init(heap, data, size);
  70. - **heap**: A pointer to the min-heap structure to be initialized.
  71. - **data**: A pointer to the buffer where the heap elements will be stored. If
  72. `NULL`, the preallocated buffer within the heap structure will be used.
  73. - **size**: The maximum number of elements the heap can hold.
  74. This macro initializes the heap, setting its initial state. If `data` is
  75. `NULL`, the preallocated memory inside the heap structure will be used for
  76. storage. Otherwise, the user-provided buffer is used. The operation is **O(1)**.
  77. **Inline Version:** min_heap_init_inline(heap, data, size)
  78. Accessing the Top Element
  79. -------------------------
  80. .. code-block:: c
  81. element = min_heap_peek(heap);
  82. - **heap**: A pointer to the min-heap from which to retrieve the smallest
  83. element.
  84. This macro returns a pointer to the smallest element (the root) of the heap, or
  85. `NULL` if the heap is empty. The operation is **O(1)**.
  86. **Inline Version:** min_heap_peek_inline(heap)
  87. Heap Insertion
  88. --------------
  89. .. code-block:: c
  90. success = min_heap_push(heap, element, callbacks, args);
  91. - **heap**: A pointer to the min-heap into which the element should be inserted.
  92. - **element**: A pointer to the element to be inserted into the heap.
  93. - **callbacks**: A pointer to a `struct min_heap_callbacks` providing the
  94. `less` and `swp` functions.
  95. - **args**: Optional arguments passed to the `less` and `swp` functions.
  96. This macro inserts an element into the heap. It returns `true` if the insertion
  97. was successful and `false` if the heap is full. The operation is **O(log n)**.
  98. **Inline Version:** min_heap_push_inline(heap, element, callbacks, args)
  99. Heap Removal
  100. ------------
  101. .. code-block:: c
  102. success = min_heap_pop(heap, callbacks, args);
  103. - **heap**: A pointer to the min-heap from which to remove the smallest element.
  104. - **callbacks**: A pointer to a `struct min_heap_callbacks` providing the
  105. `less` and `swp` functions.
  106. - **args**: Optional arguments passed to the `less` and `swp` functions.
  107. This macro removes the smallest element (the root) from the heap. It returns
  108. `true` if the element was successfully removed, or `false` if the heap is
  109. empty. The operation is **O(log n)**.
  110. **Inline Version:** min_heap_pop_inline(heap, callbacks, args)
  111. Heap Maintenance
  112. ----------------
  113. You can use the following macros to maintain the heap's structure:
  114. .. code-block:: c
  115. min_heap_sift_down(heap, pos, callbacks, args);
  116. - **heap**: A pointer to the min-heap.
  117. - **pos**: The index from which to start sifting down.
  118. - **callbacks**: A pointer to a `struct min_heap_callbacks` providing the
  119. `less` and `swp` functions.
  120. - **args**: Optional arguments passed to the `less` and `swp` functions.
  121. This macro restores the heap property by moving the element at the specified
  122. index (`pos`) down the heap until it is in the correct position. The operation
  123. is **O(log n)**.
  124. **Inline Version:** min_heap_sift_down_inline(heap, pos, callbacks, args)
  125. .. code-block:: c
  126. min_heap_sift_up(heap, idx, callbacks, args);
  127. - **heap**: A pointer to the min-heap.
  128. - **idx**: The index of the element to sift up.
  129. - **callbacks**: A pointer to a `struct min_heap_callbacks` providing the
  130. `less` and `swp` functions.
  131. - **args**: Optional arguments passed to the `less` and `swp` functions.
  132. This macro restores the heap property by moving the element at the specified
  133. index (`idx`) up the heap. The operation is **O(log n)**.
  134. **Inline Version:** min_heap_sift_up_inline(heap, idx, callbacks, args)
  135. .. code-block:: c
  136. min_heapify_all(heap, callbacks, args);
  137. - **heap**: A pointer to the min-heap.
  138. - **callbacks**: A pointer to a `struct min_heap_callbacks` providing the
  139. `less` and `swp` functions.
  140. - **args**: Optional arguments passed to the `less` and `swp` functions.
  141. This macro ensures that the entire heap satisfies the heap property. It is
  142. called when the heap is built from scratch or after many modifications. The
  143. operation is **O(n)**.
  144. **Inline Version:** min_heapify_all_inline(heap, callbacks, args)
  145. Removing Specific Elements
  146. --------------------------
  147. .. code-block:: c
  148. success = min_heap_del(heap, idx, callbacks, args);
  149. - **heap**: A pointer to the min-heap.
  150. - **idx**: The index of the element to delete.
  151. - **callbacks**: A pointer to a `struct min_heap_callbacks` providing the
  152. `less` and `swp` functions.
  153. - **args**: Optional arguments passed to the `less` and `swp` functions.
  154. This macro removes an element at the specified index (`idx`) from the heap and
  155. restores the heap property. The operation is **O(log n)**.
  156. **Inline Version:** min_heap_del_inline(heap, idx, callbacks, args)
  157. Other Utilities
  158. ===============
  159. - **min_heap_full(heap)**: Checks whether the heap is full.
  160. Complexity: **O(1)**.
  161. .. code-block:: c
  162. bool full = min_heap_full(heap);
  163. - `heap`: A pointer to the min-heap to check.
  164. This macro returns `true` if the heap is full, otherwise `false`.
  165. **Inline Version:** min_heap_full_inline(heap)
  166. - **min_heap_empty(heap)**: Checks whether the heap is empty.
  167. Complexity: **O(1)**.
  168. .. code-block:: c
  169. bool empty = min_heap_empty(heap);
  170. - `heap`: A pointer to the min-heap to check.
  171. This macro returns `true` if the heap is empty, otherwise `false`.
  172. **Inline Version:** min_heap_empty_inline(heap)
  173. Example Usage
  174. =============
  175. An example usage of the min-heap API would involve defining a heap structure,
  176. initializing it, and inserting and removing elements as needed.
  177. .. code-block:: c
  178. #include <linux/min_heap.h>
  179. int my_less_function(const void *lhs, const void *rhs, void *args) {
  180. return (*(int *)lhs < *(int *)rhs);
  181. }
  182. struct min_heap_callbacks heap_cb = {
  183. .less = my_less_function, /* Comparison function for heap order */
  184. .swp = NULL, /* Use default swap function */
  185. };
  186. void example_usage(void) {
  187. /* Pre-populate the buffer with elements */
  188. int buffer[5] = {5, 2, 8, 1, 3};
  189. /* Declare a min-heap */
  190. DEFINE_MIN_HEAP(int, my_heap);
  191. /* Initialize the heap with preallocated buffer and size */
  192. min_heap_init(&my_heap, buffer, 5);
  193. /* Build the heap using min_heapify_all */
  194. my_heap.nr = 5; /* Set the number of elements in the heap */
  195. min_heapify_all(&my_heap, &heap_cb, NULL);
  196. /* Peek at the top element (should be 1 in this case) */
  197. int *top = min_heap_peek(&my_heap);
  198. pr_info("Top element: %d\n", *top);
  199. /* Pop the top element (1) and get the new top (2) */
  200. min_heap_pop(&my_heap, &heap_cb, NULL);
  201. top = min_heap_peek(&my_heap);
  202. pr_info("New top element: %d\n", *top);
  203. /* Insert a new element (0) and recheck the top */
  204. int new_element = 0;
  205. min_heap_push(&my_heap, &new_element, &heap_cb, NULL);
  206. top = min_heap_peek(&my_heap);
  207. pr_info("Top element after insertion: %d\n", *top);
  208. }