sort.c 11 KB

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