sort.c 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * A fast, small, non-recursive O(n log n) sort for the Linux kernel
  4. *
  5. * This performs n*log2(n) + 0.37*n + o(n) comparisons on average,
  6. * and 1.5*n*log2(n) + O(n) in the (very contrived) worst case.
  7. *
  8. * Glibc qsort() manages n*log2(n) - 1.26*n for random inputs (1.63*n
  9. * better) at the expense of stack usage and much larger code to avoid
  10. * quicksort's O(n^2) worst case.
  11. */
  12. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  13. #include <linux/types.h>
  14. #include <linux/export.h>
  15. #include <linux/sort.h>
  16. /**
  17. * is_aligned - is this pointer & size okay for word-wide copying?
  18. * @base: pointer to data
  19. * @size: size of each element
  20. * @align: required alignment (typically 4 or 8)
  21. *
  22. * Returns true if elements can be copied using word loads and stores.
  23. * The size must be a multiple of the alignment, and the base address must
  24. * be if we do not have CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS.
  25. *
  26. * For some reason, gcc doesn't know to optimize "if (a & mask || b & mask)"
  27. * to "if ((a | b) & mask)", so we do that by hand.
  28. */
  29. __attribute_const__ __always_inline
  30. static bool is_aligned(const void *base, size_t size, unsigned char align)
  31. {
  32. unsigned char lsbits = (unsigned char)size;
  33. (void)base;
  34. #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
  35. lsbits |= (unsigned char)(uintptr_t)base;
  36. #endif
  37. return (lsbits & (align - 1)) == 0;
  38. }
  39. /**
  40. * swap_words_32 - swap two elements in 32-bit chunks
  41. * @a: pointer to the first element to swap
  42. * @b: pointer to the second element to swap
  43. * @n: element size (must be a multiple of 4)
  44. *
  45. * Exchange the two objects in memory. This exploits base+index addressing,
  46. * which basically all CPUs have, to minimize loop overhead computations.
  47. *
  48. * For some reason, on x86 gcc 7.3.0 adds a redundant test of n at the
  49. * bottom of the loop, even though the zero flag is still valid from the
  50. * subtract (since the intervening mov instructions don't alter the flags).
  51. * Gcc 8.1.0 doesn't have that problem.
  52. */
  53. static void swap_words_32(void *a, void *b, size_t n)
  54. {
  55. do {
  56. u32 t = *(u32 *)(a + (n -= 4));
  57. *(u32 *)(a + n) = *(u32 *)(b + n);
  58. *(u32 *)(b + n) = t;
  59. } while (n);
  60. }
  61. /**
  62. * swap_words_64 - swap two elements in 64-bit chunks
  63. * @a: pointer to the first element to swap
  64. * @b: pointer to the second element to swap
  65. * @n: element size (must be a multiple of 8)
  66. *
  67. * Exchange the two objects in memory. This exploits base+index
  68. * addressing, which basically all CPUs have, to minimize loop overhead
  69. * computations.
  70. *
  71. * We'd like to use 64-bit loads if possible. If they're not, emulating
  72. * one requires base+index+4 addressing which x86 has but most other
  73. * processors do not. If CONFIG_64BIT, we definitely have 64-bit loads,
  74. * but it's possible to have 64-bit loads without 64-bit pointers (e.g.
  75. * x32 ABI). Are there any cases the kernel needs to worry about?
  76. */
  77. static void swap_words_64(void *a, void *b, size_t n)
  78. {
  79. do {
  80. #ifdef CONFIG_64BIT
  81. u64 t = *(u64 *)(a + (n -= 8));
  82. *(u64 *)(a + n) = *(u64 *)(b + n);
  83. *(u64 *)(b + n) = t;
  84. #else
  85. /* Use two 32-bit transfers to avoid base+index+4 addressing */
  86. u32 t = *(u32 *)(a + (n -= 4));
  87. *(u32 *)(a + n) = *(u32 *)(b + n);
  88. *(u32 *)(b + n) = t;
  89. t = *(u32 *)(a + (n -= 4));
  90. *(u32 *)(a + n) = *(u32 *)(b + n);
  91. *(u32 *)(b + n) = t;
  92. #endif
  93. } while (n);
  94. }
  95. /**
  96. * swap_bytes - swap two elements a byte at a time
  97. * @a: pointer to the first element to swap
  98. * @b: pointer to the second element to swap
  99. * @n: element size
  100. *
  101. * This is the fallback if alignment doesn't allow using larger chunks.
  102. */
  103. static void swap_bytes(void *a, void *b, size_t n)
  104. {
  105. do {
  106. char t = ((char *)a)[--n];
  107. ((char *)a)[n] = ((char *)b)[n];
  108. ((char *)b)[n] = t;
  109. } while (n);
  110. }
  111. /*
  112. * The values are arbitrary as long as they can't be confused with
  113. * a pointer, but small integers make for the smallest compare
  114. * instructions.
  115. */
  116. #define SWAP_WORDS_64 (swap_r_func_t)0
  117. #define SWAP_WORDS_32 (swap_r_func_t)1
  118. #define SWAP_BYTES (swap_r_func_t)2
  119. #define SWAP_WRAPPER (swap_r_func_t)3
  120. struct wrapper {
  121. cmp_func_t cmp;
  122. swap_func_t swap;
  123. };
  124. /*
  125. * The function pointer is last to make tail calls most efficient if the
  126. * compiler decides not to inline this function.
  127. */
  128. static void do_swap(void *a, void *b, size_t size, swap_r_func_t swap_func, const void *priv)
  129. {
  130. if (swap_func == SWAP_WRAPPER) {
  131. ((const struct wrapper *)priv)->swap(a, b, (int)size);
  132. return;
  133. }
  134. if (swap_func == SWAP_WORDS_64)
  135. swap_words_64(a, b, size);
  136. else if (swap_func == SWAP_WORDS_32)
  137. swap_words_32(a, b, size);
  138. else if (swap_func == SWAP_BYTES)
  139. swap_bytes(a, b, size);
  140. else
  141. swap_func(a, b, (int)size, priv);
  142. }
  143. #define _CMP_WRAPPER ((cmp_r_func_t)0L)
  144. static int do_cmp(const void *a, const void *b, cmp_r_func_t cmp, const void *priv)
  145. {
  146. if (cmp == _CMP_WRAPPER)
  147. return ((const struct wrapper *)priv)->cmp(a, b);
  148. return cmp(a, b, priv);
  149. }
  150. /**
  151. * parent - given the offset of the child, find the offset of the parent.
  152. * @i: the offset of the heap element whose parent is sought. Non-zero.
  153. * @lsbit: a precomputed 1-bit mask, equal to "size & -size"
  154. * @size: size of each element
  155. *
  156. * In terms of array indexes, the parent of element j = @i/@size is simply
  157. * (j-1)/2. But when working in byte offsets, we can't use implicit
  158. * truncation of integer divides.
  159. *
  160. * Fortunately, we only need one bit of the quotient, not the full divide.
  161. * @size has a least significant bit. That bit will be clear if @i is
  162. * an even multiple of @size, and set if it's an odd multiple.
  163. *
  164. * Logically, we're doing "if (i & lsbit) i -= size;", but since the
  165. * branch is unpredictable, it's done with a bit of clever branch-free
  166. * code instead.
  167. */
  168. __attribute_const__ __always_inline
  169. static size_t parent(size_t i, unsigned int lsbit, size_t size)
  170. {
  171. i -= size;
  172. i -= size & -(i & lsbit);
  173. return i / 2;
  174. }
  175. /**
  176. * sort_r - sort an array of elements
  177. * @base: pointer to data to sort
  178. * @num: number of elements
  179. * @size: size of each element
  180. * @cmp_func: pointer to comparison function
  181. * @swap_func: pointer to swap function or NULL
  182. * @priv: third argument passed to comparison function
  183. *
  184. * This function does a heapsort on the given array. You may provide
  185. * a swap_func function if you need to do something more than a memory
  186. * copy (e.g. fix up pointers or auxiliary data), but the built-in swap
  187. * avoids a slow retpoline and so is significantly faster.
  188. *
  189. * Sorting time is O(n log n) both on average and worst-case. While
  190. * quicksort is slightly faster on average, it suffers from exploitable
  191. * O(n*n) worst-case behavior and extra memory requirements that make
  192. * it less suitable for kernel use.
  193. */
  194. void sort_r(void *base, size_t num, size_t size,
  195. cmp_r_func_t cmp_func,
  196. swap_r_func_t swap_func,
  197. const void *priv)
  198. {
  199. /* pre-scale counters for performance */
  200. size_t n = num * size, a = (num/2) * size;
  201. const unsigned int lsbit = size & -size; /* Used to find parent */
  202. if (!a) /* num < 2 || size == 0 */
  203. return;
  204. /* called from 'sort' without swap function, let's pick the default */
  205. if (swap_func == SWAP_WRAPPER && !((struct wrapper *)priv)->swap)
  206. swap_func = NULL;
  207. if (!swap_func) {
  208. if (is_aligned(base, size, 8))
  209. swap_func = SWAP_WORDS_64;
  210. else if (is_aligned(base, size, 4))
  211. swap_func = SWAP_WORDS_32;
  212. else
  213. swap_func = SWAP_BYTES;
  214. }
  215. /*
  216. * Loop invariants:
  217. * 1. elements [a,n) satisfy the heap property (compare greater than
  218. * all of their children),
  219. * 2. elements [n,num*size) are sorted, and
  220. * 3. a <= b <= c <= d <= n (whenever they are valid).
  221. */
  222. for (;;) {
  223. size_t b, c, d;
  224. if (a) /* Building heap: sift down --a */
  225. a -= size;
  226. else if (n -= size) /* Sorting: Extract root to --n */
  227. do_swap(base, base + n, size, swap_func, priv);
  228. else /* Sort complete */
  229. break;
  230. /*
  231. * Sift element at "a" down into heap. This is the
  232. * "bottom-up" variant, which significantly reduces
  233. * calls to cmp_func(): we find the sift-down path all
  234. * the way to the leaves (one compare per level), then
  235. * backtrack to find where to insert the target element.
  236. *
  237. * Because elements tend to sift down close to the leaves,
  238. * this uses fewer compares than doing two per level
  239. * on the way down. (A bit more than half as many on
  240. * average, 3/4 worst-case.)
  241. */
  242. for (b = a; c = 2*b + size, (d = c + size) < n;)
  243. b = do_cmp(base + c, base + d, cmp_func, priv) >= 0 ? c : d;
  244. if (d == n) /* Special case last leaf with no sibling */
  245. b = c;
  246. /* Now backtrack from "b" to the correct location for "a" */
  247. while (b != a && do_cmp(base + a, base + b, cmp_func, priv) >= 0)
  248. b = parent(b, lsbit, size);
  249. c = b; /* Where "a" belongs */
  250. while (b != a) { /* Shift it into place */
  251. b = parent(b, lsbit, size);
  252. do_swap(base + b, base + c, size, swap_func, priv);
  253. }
  254. }
  255. }
  256. EXPORT_SYMBOL(sort_r);
  257. void sort(void *base, size_t num, size_t size,
  258. cmp_func_t cmp_func,
  259. swap_func_t swap_func)
  260. {
  261. struct wrapper w = {
  262. .cmp = cmp_func,
  263. .swap = swap_func,
  264. };
  265. return sort_r(base, num, size, _CMP_WRAPPER, SWAP_WRAPPER, &w);
  266. }
  267. EXPORT_SYMBOL(sort);