list_sort.c 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/kernel.h>
  3. #include <linux/bug.h>
  4. #include <linux/compiler.h>
  5. #include <linux/export.h>
  6. #include <linux/string.h>
  7. #include <linux/list_sort.h>
  8. #include <linux/list.h>
  9. typedef int __attribute__((nonnull(2,3))) (*cmp_func)(void *,
  10. struct list_head *, struct list_head *);
  11. /*
  12. * Returns a list organized in an intermediate format suited
  13. * to chaining of merge() calls: null-terminated, no reserved or
  14. * sentinel head node, "prev" links not maintained.
  15. */
  16. __attribute__((nonnull(2,3,4)))
  17. static struct list_head *merge(void *priv, cmp_func cmp,
  18. struct list_head *a, struct list_head *b)
  19. {
  20. struct list_head *head, **tail = &head;
  21. for (;;) {
  22. /* if equal, take 'a' -- important for sort stability */
  23. if (cmp(priv, a, b) <= 0) {
  24. *tail = a;
  25. tail = &a->next;
  26. a = a->next;
  27. if (!a) {
  28. *tail = b;
  29. break;
  30. }
  31. } else {
  32. *tail = b;
  33. tail = &b->next;
  34. b = b->next;
  35. if (!b) {
  36. *tail = a;
  37. break;
  38. }
  39. }
  40. }
  41. return head;
  42. }
  43. /*
  44. * Combine final list merge with restoration of standard doubly-linked
  45. * list structure. This approach duplicates code from merge(), but
  46. * runs faster than the tidier alternatives of either a separate final
  47. * prev-link restoration pass, or maintaining the prev links
  48. * throughout.
  49. */
  50. __attribute__((nonnull(2,3,4,5)))
  51. static void merge_final(void *priv, cmp_func cmp, struct list_head *head,
  52. struct list_head *a, struct list_head *b)
  53. {
  54. struct list_head *tail = head;
  55. u8 count = 0;
  56. for (;;) {
  57. /* if equal, take 'a' -- important for sort stability */
  58. if (cmp(priv, a, b) <= 0) {
  59. tail->next = a;
  60. a->prev = tail;
  61. tail = a;
  62. a = a->next;
  63. if (!a)
  64. break;
  65. } else {
  66. tail->next = b;
  67. b->prev = tail;
  68. tail = b;
  69. b = b->next;
  70. if (!b) {
  71. b = a;
  72. break;
  73. }
  74. }
  75. }
  76. /* Finish linking remainder of list b on to tail */
  77. tail->next = b;
  78. do {
  79. /*
  80. * If the merge is highly unbalanced (e.g. the input is
  81. * already sorted), this loop may run many iterations.
  82. * Continue callbacks to the client even though no
  83. * element comparison is needed, so the client's cmp()
  84. * routine can invoke cond_resched() periodically.
  85. */
  86. if (unlikely(!++count))
  87. cmp(priv, b, b);
  88. b->prev = tail;
  89. tail = b;
  90. b = b->next;
  91. } while (b);
  92. /* And the final links to make a circular doubly-linked list */
  93. tail->next = head;
  94. head->prev = tail;
  95. }
  96. /**
  97. * list_sort - sort a list
  98. * @priv: private data, opaque to list_sort(), passed to @cmp
  99. * @head: the list to sort
  100. * @cmp: the elements comparison function
  101. *
  102. * The comparison funtion @cmp must return > 0 if @a should sort after
  103. * @b ("@a > @b" if you want an ascending sort), and <= 0 if @a should
  104. * sort before @b *or* their original order should be preserved. It is
  105. * always called with the element that came first in the input in @a,
  106. * and list_sort is a stable sort, so it is not necessary to distinguish
  107. * the @a < @b and @a == @b cases.
  108. *
  109. * This is compatible with two styles of @cmp function:
  110. * - The traditional style which returns <0 / =0 / >0, or
  111. * - Returning a boolean 0/1.
  112. * The latter offers a chance to save a few cycles in the comparison
  113. * (which is used by e.g. plug_ctx_cmp() in block/blk-mq.c).
  114. *
  115. * A good way to write a multi-word comparison is::
  116. *
  117. * if (a->high != b->high)
  118. * return a->high > b->high;
  119. * if (a->middle != b->middle)
  120. * return a->middle > b->middle;
  121. * return a->low > b->low;
  122. *
  123. *
  124. * This mergesort is as eager as possible while always performing at least
  125. * 2:1 balanced merges. Given two pending sublists of size 2^k, they are
  126. * merged to a size-2^(k+1) list as soon as we have 2^k following elements.
  127. *
  128. * Thus, it will avoid cache thrashing as long as 3*2^k elements can
  129. * fit into the cache. Not quite as good as a fully-eager bottom-up
  130. * mergesort, but it does use 0.2*n fewer comparisons, so is faster in
  131. * the common case that everything fits into L1.
  132. *
  133. *
  134. * The merging is controlled by "count", the number of elements in the
  135. * pending lists. This is beautiully simple code, but rather subtle.
  136. *
  137. * Each time we increment "count", we set one bit (bit k) and clear
  138. * bits k-1 .. 0. Each time this happens (except the very first time
  139. * for each bit, when count increments to 2^k), we merge two lists of
  140. * size 2^k into one list of size 2^(k+1).
  141. *
  142. * This merge happens exactly when the count reaches an odd multiple of
  143. * 2^k, which is when we have 2^k elements pending in smaller lists,
  144. * so it's safe to merge away two lists of size 2^k.
  145. *
  146. * After this happens twice, we have created two lists of size 2^(k+1),
  147. * which will be merged into a list of size 2^(k+2) before we create
  148. * a third list of size 2^(k+1), so there are never more than two pending.
  149. *
  150. * The number of pending lists of size 2^k is determined by the
  151. * state of bit k of "count" plus two extra pieces of information:
  152. *
  153. * - The state of bit k-1 (when k == 0, consider bit -1 always set), and
  154. * - Whether the higher-order bits are zero or non-zero (i.e.
  155. * is count >= 2^(k+1)).
  156. *
  157. * There are six states we distinguish. "x" represents some arbitrary
  158. * bits, and "y" represents some arbitrary non-zero bits:
  159. * 0: 00x: 0 pending of size 2^k; x pending of sizes < 2^k
  160. * 1: 01x: 0 pending of size 2^k; 2^(k-1) + x pending of sizes < 2^k
  161. * 2: x10x: 0 pending of size 2^k; 2^k + x pending of sizes < 2^k
  162. * 3: x11x: 1 pending of size 2^k; 2^(k-1) + x pending of sizes < 2^k
  163. * 4: y00x: 1 pending of size 2^k; 2^k + x pending of sizes < 2^k
  164. * 5: y01x: 2 pending of size 2^k; 2^(k-1) + x pending of sizes < 2^k
  165. * (merge and loop back to state 2)
  166. *
  167. * We gain lists of size 2^k in the 2->3 and 4->5 transitions (because
  168. * bit k-1 is set while the more significant bits are non-zero) and
  169. * merge them away in the 5->2 transition. Note in particular that just
  170. * before the 5->2 transition, all lower-order bits are 11 (state 3),
  171. * so there is one list of each smaller size.
  172. *
  173. * When we reach the end of the input, we merge all the pending
  174. * lists, from smallest to largest. If you work through cases 2 to
  175. * 5 above, you can see that the number of elements we merge with a list
  176. * of size 2^k varies from 2^(k-1) (cases 3 and 5 when x == 0) to
  177. * 2^(k+1) - 1 (second merge of case 5 when x == 2^(k-1) - 1).
  178. */
  179. __attribute__((nonnull(2,3)))
  180. void list_sort(void *priv, struct list_head *head,
  181. int (*cmp)(void *priv, struct list_head *a,
  182. struct list_head *b))
  183. {
  184. struct list_head *list = head->next, *pending = NULL;
  185. size_t count = 0; /* Count of pending */
  186. if (list == head->prev) /* Zero or one elements */
  187. return;
  188. /* Convert to a null-terminated singly-linked list. */
  189. head->prev->next = NULL;
  190. /*
  191. * Data structure invariants:
  192. * - All lists are singly linked and null-terminated; prev
  193. * pointers are not maintained.
  194. * - pending is a prev-linked "list of lists" of sorted
  195. * sublists awaiting further merging.
  196. * - Each of the sorted sublists is power-of-two in size.
  197. * - Sublists are sorted by size and age, smallest & newest at front.
  198. * - There are zero to two sublists of each size.
  199. * - A pair of pending sublists are merged as soon as the number
  200. * of following pending elements equals their size (i.e.
  201. * each time count reaches an odd multiple of that size).
  202. * That ensures each later final merge will be at worst 2:1.
  203. * - Each round consists of:
  204. * - Merging the two sublists selected by the highest bit
  205. * which flips when count is incremented, and
  206. * - Adding an element from the input as a size-1 sublist.
  207. */
  208. do {
  209. size_t bits;
  210. struct list_head **tail = &pending;
  211. /* Find the least-significant clear bit in count */
  212. for (bits = count; bits & 1; bits >>= 1)
  213. tail = &(*tail)->prev;
  214. /* Do the indicated merge */
  215. if (likely(bits)) {
  216. struct list_head *a = *tail, *b = a->prev;
  217. a = merge(priv, cmp, b, a);
  218. /* Install the merged result in place of the inputs */
  219. a->prev = b->prev;
  220. *tail = a;
  221. }
  222. /* Move one element from input list to pending */
  223. list->prev = pending;
  224. pending = list;
  225. list = list->next;
  226. pending->next = NULL;
  227. count++;
  228. } while (list);
  229. /* End of input; merge together all the pending lists. */
  230. list = pending;
  231. pending = pending->prev;
  232. for (;;) {
  233. struct list_head *next = pending->prev;
  234. if (!next)
  235. break;
  236. list = merge(priv, cmp, pending, list);
  237. pending = next;
  238. }
  239. /* The final merge, rebuilding prev links */
  240. merge_final(priv, cmp, head, pending, list);
  241. }
  242. EXPORT_SYMBOL(list_sort);