sort.c 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 stil 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_func_t)0
  117. #define SWAP_WORDS_32 (swap_func_t)1
  118. #define SWAP_BYTES (swap_func_t)2
  119. /*
  120. * The function pointer is last to make tail calls most efficient if the
  121. * compiler decides not to inline this function.
  122. */
  123. static void do_swap(void *a, void *b, size_t size, swap_func_t swap_func)
  124. {
  125. if (swap_func == SWAP_WORDS_64)
  126. swap_words_64(a, b, size);
  127. else if (swap_func == SWAP_WORDS_32)
  128. swap_words_32(a, b, size);
  129. else if (swap_func == SWAP_BYTES)
  130. swap_bytes(a, b, size);
  131. else
  132. swap_func(a, b, (int)size);
  133. }
  134. #define _CMP_WRAPPER ((cmp_r_func_t)0L)
  135. static int do_cmp(const void *a, const void *b, cmp_r_func_t cmp, const void *priv)
  136. {
  137. if (cmp == _CMP_WRAPPER)
  138. return ((cmp_func_t)(priv))(a, b);
  139. return cmp(a, b, priv);
  140. }
  141. /**
  142. * parent - given the offset of the child, find the offset of the parent.
  143. * @i: the offset of the heap element whose parent is sought. Non-zero.
  144. * @lsbit: a precomputed 1-bit mask, equal to "size & -size"
  145. * @size: size of each element
  146. *
  147. * In terms of array indexes, the parent of element j = @i/@size is simply
  148. * (j-1)/2. But when working in byte offsets, we can't use implicit
  149. * truncation of integer divides.
  150. *
  151. * Fortunately, we only need one bit of the quotient, not the full divide.
  152. * @size has a least significant bit. That bit will be clear if @i is
  153. * an even multiple of @size, and set if it's an odd multiple.
  154. *
  155. * Logically, we're doing "if (i & lsbit) i -= size;", but since the
  156. * branch is unpredictable, it's done with a bit of clever branch-free
  157. * code instead.
  158. */
  159. __attribute_const__ __always_inline
  160. static size_t parent(size_t i, unsigned int lsbit, size_t size)
  161. {
  162. i -= size;
  163. i -= size & -(i & lsbit);
  164. return i / 2;
  165. }
  166. /**
  167. * sort_r - sort an array of elements
  168. * @base: pointer to data to sort
  169. * @num: number of elements
  170. * @size: size of each element
  171. * @cmp_func: pointer to comparison function
  172. * @swap_func: pointer to swap function or NULL
  173. * @priv: third argument passed to comparison function
  174. *
  175. * This function does a heapsort on the given array. You may provide
  176. * a swap_func function if you need to do something more than a memory
  177. * copy (e.g. fix up pointers or auxiliary data), but the built-in swap
  178. * avoids a slow retpoline and so is significantly faster.
  179. *
  180. * Sorting time is O(n log n) both on average and worst-case. While
  181. * quicksort is slightly faster on average, it suffers from exploitable
  182. * O(n*n) worst-case behavior and extra memory requirements that make
  183. * it less suitable for kernel use.
  184. */
  185. void sort_r(void *base, size_t num, size_t size,
  186. cmp_r_func_t cmp_func,
  187. swap_func_t swap_func,
  188. const void *priv)
  189. {
  190. /* pre-scale counters for performance */
  191. size_t n = num * size, a = (num/2) * size;
  192. const unsigned int lsbit = size & -size; /* Used to find parent */
  193. if (!a) /* num < 2 || size == 0 */
  194. return;
  195. if (!swap_func) {
  196. if (is_aligned(base, size, 8))
  197. swap_func = SWAP_WORDS_64;
  198. else if (is_aligned(base, size, 4))
  199. swap_func = SWAP_WORDS_32;
  200. else
  201. swap_func = SWAP_BYTES;
  202. }
  203. /*
  204. * Loop invariants:
  205. * 1. elements [a,n) satisfy the heap property (compare greater than
  206. * all of their children),
  207. * 2. elements [n,num*size) are sorted, and
  208. * 3. a <= b <= c <= d <= n (whenever they are valid).
  209. */
  210. for (;;) {
  211. size_t b, c, d;
  212. if (a) /* Building heap: sift down --a */
  213. a -= size;
  214. else if (n -= size) /* Sorting: Extract root to --n */
  215. do_swap(base, base + n, size, swap_func);
  216. else /* Sort complete */
  217. break;
  218. /*
  219. * Sift element at "a" down into heap. This is the
  220. * "bottom-up" variant, which significantly reduces
  221. * calls to cmp_func(): we find the sift-down path all
  222. * the way to the leaves (one compare per level), then
  223. * backtrack to find where to insert the target element.
  224. *
  225. * Because elements tend to sift down close to the leaves,
  226. * this uses fewer compares than doing two per level
  227. * on the way down. (A bit more than half as many on
  228. * average, 3/4 worst-case.)
  229. */
  230. for (b = a; c = 2*b + size, (d = c + size) < n;)
  231. b = do_cmp(base + c, base + d, cmp_func, priv) >= 0 ? c : d;
  232. if (d == n) /* Special case last leaf with no sibling */
  233. b = c;
  234. /* Now backtrack from "b" to the correct location for "a" */
  235. while (b != a && do_cmp(base + a, base + b, cmp_func, priv) >= 0)
  236. b = parent(b, lsbit, size);
  237. c = b; /* Where "a" belongs */
  238. while (b != a) { /* Shift it into place */
  239. b = parent(b, lsbit, size);
  240. do_swap(base + b, base + c, size, swap_func);
  241. }
  242. }
  243. }
  244. EXPORT_SYMBOL(sort_r);
  245. void sort(void *base, size_t num, size_t size,
  246. cmp_func_t cmp_func,
  247. swap_func_t swap_func)
  248. {
  249. return sort_r(base, num, size, _CMP_WRAPPER, swap_func, cmp_func);
  250. }
  251. EXPORT_SYMBOL(sort);