xref: /openbmc/linux/lib/sort.c (revision a0019cd7)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * A fast, small, non-recursive O(n log n) sort for the Linux kernel
41da177e4SLinus Torvalds  *
522a241ccSGeorge Spelvin  * This performs n*log2(n) + 0.37*n + o(n) comparisons on average,
622a241ccSGeorge Spelvin  * and 1.5*n*log2(n) + O(n) in the (very contrived) worst case.
722a241ccSGeorge Spelvin  *
822a241ccSGeorge Spelvin  * Glibc qsort() manages n*log2(n) - 1.26*n for random inputs (1.63*n
922a241ccSGeorge Spelvin  * better) at the expense of stack usage and much larger code to avoid
1022a241ccSGeorge Spelvin  * quicksort's O(n^2) worst case.
111da177e4SLinus Torvalds  */
121da177e4SLinus Torvalds 
13c5adae95SKostenzer Felix #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14c5adae95SKostenzer Felix 
1542cf8096SRasmus Villemoes #include <linux/types.h>
1642cf8096SRasmus Villemoes #include <linux/export.h>
17ecec4cb7SAdrian Bunk #include <linux/sort.h>
181da177e4SLinus Torvalds 
1937d0ec34SGeorge Spelvin /**
2037d0ec34SGeorge Spelvin  * is_aligned - is this pointer & size okay for word-wide copying?
2137d0ec34SGeorge Spelvin  * @base: pointer to data
2237d0ec34SGeorge Spelvin  * @size: size of each element
2322a241ccSGeorge Spelvin  * @align: required alignment (typically 4 or 8)
2437d0ec34SGeorge Spelvin  *
2537d0ec34SGeorge Spelvin  * Returns true if elements can be copied using word loads and stores.
2637d0ec34SGeorge Spelvin  * The size must be a multiple of the alignment, and the base address must
2737d0ec34SGeorge Spelvin  * be if we do not have CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS.
2837d0ec34SGeorge Spelvin  *
2937d0ec34SGeorge Spelvin  * For some reason, gcc doesn't know to optimize "if (a & mask || b & mask)"
3037d0ec34SGeorge Spelvin  * to "if ((a | b) & mask)", so we do that by hand.
3137d0ec34SGeorge Spelvin  */
3237d0ec34SGeorge Spelvin __attribute_const__ __always_inline
is_aligned(const void * base,size_t size,unsigned char align)3337d0ec34SGeorge Spelvin static bool is_aligned(const void *base, size_t size, unsigned char align)
34ca96ab85SDaniel Wagner {
3537d0ec34SGeorge Spelvin 	unsigned char lsbits = (unsigned char)size;
3637d0ec34SGeorge Spelvin 
3737d0ec34SGeorge Spelvin 	(void)base;
3837d0ec34SGeorge Spelvin #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
3937d0ec34SGeorge Spelvin 	lsbits |= (unsigned char)(uintptr_t)base;
4037d0ec34SGeorge Spelvin #endif
4137d0ec34SGeorge Spelvin 	return (lsbits & (align - 1)) == 0;
42ca96ab85SDaniel Wagner }
43ca96ab85SDaniel Wagner 
4437d0ec34SGeorge Spelvin /**
4537d0ec34SGeorge Spelvin  * swap_words_32 - swap two elements in 32-bit chunks
46aa52619cSRandy Dunlap  * @a: pointer to the first element to swap
47aa52619cSRandy Dunlap  * @b: pointer to the second element to swap
48aa52619cSRandy Dunlap  * @n: element size (must be a multiple of 4)
4937d0ec34SGeorge Spelvin  *
5037d0ec34SGeorge Spelvin  * Exchange the two objects in memory.  This exploits base+index addressing,
5137d0ec34SGeorge Spelvin  * which basically all CPUs have, to minimize loop overhead computations.
5237d0ec34SGeorge Spelvin  *
5337d0ec34SGeorge Spelvin  * For some reason, on x86 gcc 7.3.0 adds a redundant test of n at the
549dbbc3b9SZhen Lei  * bottom of the loop, even though the zero flag is still valid from the
5537d0ec34SGeorge Spelvin  * subtract (since the intervening mov instructions don't alter the flags).
5637d0ec34SGeorge Spelvin  * Gcc 8.1.0 doesn't have that problem.
5737d0ec34SGeorge Spelvin  */
swap_words_32(void * a,void * b,size_t n)588fb583c4SGeorge Spelvin static void swap_words_32(void *a, void *b, size_t n)
591da177e4SLinus Torvalds {
601da177e4SLinus Torvalds 	do {
6137d0ec34SGeorge Spelvin 		u32 t = *(u32 *)(a + (n -= 4));
6237d0ec34SGeorge Spelvin 		*(u32 *)(a + n) = *(u32 *)(b + n);
6337d0ec34SGeorge Spelvin 		*(u32 *)(b + n) = t;
6437d0ec34SGeorge Spelvin 	} while (n);
6537d0ec34SGeorge Spelvin }
6637d0ec34SGeorge Spelvin 
6737d0ec34SGeorge Spelvin /**
6837d0ec34SGeorge Spelvin  * swap_words_64 - swap two elements in 64-bit chunks
69aa52619cSRandy Dunlap  * @a: pointer to the first element to swap
70aa52619cSRandy Dunlap  * @b: pointer to the second element to swap
71aa52619cSRandy Dunlap  * @n: element size (must be a multiple of 8)
7237d0ec34SGeorge Spelvin  *
7337d0ec34SGeorge Spelvin  * Exchange the two objects in memory.  This exploits base+index
7437d0ec34SGeorge Spelvin  * addressing, which basically all CPUs have, to minimize loop overhead
7537d0ec34SGeorge Spelvin  * computations.
7637d0ec34SGeorge Spelvin  *
7737d0ec34SGeorge Spelvin  * We'd like to use 64-bit loads if possible.  If they're not, emulating
7837d0ec34SGeorge Spelvin  * one requires base+index+4 addressing which x86 has but most other
7937d0ec34SGeorge Spelvin  * processors do not.  If CONFIG_64BIT, we definitely have 64-bit loads,
8037d0ec34SGeorge Spelvin  * but it's possible to have 64-bit loads without 64-bit pointers (e.g.
8137d0ec34SGeorge Spelvin  * x32 ABI).  Are there any cases the kernel needs to worry about?
8237d0ec34SGeorge Spelvin  */
swap_words_64(void * a,void * b,size_t n)838fb583c4SGeorge Spelvin static void swap_words_64(void *a, void *b, size_t n)
8437d0ec34SGeorge Spelvin {
8537d0ec34SGeorge Spelvin 	do {
8637d0ec34SGeorge Spelvin #ifdef CONFIG_64BIT
8737d0ec34SGeorge Spelvin 		u64 t = *(u64 *)(a + (n -= 8));
8837d0ec34SGeorge Spelvin 		*(u64 *)(a + n) = *(u64 *)(b + n);
8937d0ec34SGeorge Spelvin 		*(u64 *)(b + n) = t;
9037d0ec34SGeorge Spelvin #else
9137d0ec34SGeorge Spelvin 		/* Use two 32-bit transfers to avoid base+index+4 addressing */
9237d0ec34SGeorge Spelvin 		u32 t = *(u32 *)(a + (n -= 4));
9337d0ec34SGeorge Spelvin 		*(u32 *)(a + n) = *(u32 *)(b + n);
9437d0ec34SGeorge Spelvin 		*(u32 *)(b + n) = t;
9537d0ec34SGeorge Spelvin 
9637d0ec34SGeorge Spelvin 		t = *(u32 *)(a + (n -= 4));
9737d0ec34SGeorge Spelvin 		*(u32 *)(a + n) = *(u32 *)(b + n);
9837d0ec34SGeorge Spelvin 		*(u32 *)(b + n) = t;
9937d0ec34SGeorge Spelvin #endif
10037d0ec34SGeorge Spelvin 	} while (n);
10137d0ec34SGeorge Spelvin }
10237d0ec34SGeorge Spelvin 
10337d0ec34SGeorge Spelvin /**
10437d0ec34SGeorge Spelvin  * swap_bytes - swap two elements a byte at a time
105aa52619cSRandy Dunlap  * @a: pointer to the first element to swap
106aa52619cSRandy Dunlap  * @b: pointer to the second element to swap
107aa52619cSRandy Dunlap  * @n: element size
10837d0ec34SGeorge Spelvin  *
10937d0ec34SGeorge Spelvin  * This is the fallback if alignment doesn't allow using larger chunks.
11037d0ec34SGeorge Spelvin  */
swap_bytes(void * a,void * b,size_t n)1118fb583c4SGeorge Spelvin static void swap_bytes(void *a, void *b, size_t n)
11237d0ec34SGeorge Spelvin {
11337d0ec34SGeorge Spelvin 	do {
11437d0ec34SGeorge Spelvin 		char t = ((char *)a)[--n];
11537d0ec34SGeorge Spelvin 		((char *)a)[n] = ((char *)b)[n];
11637d0ec34SGeorge Spelvin 		((char *)b)[n] = t;
11737d0ec34SGeorge Spelvin 	} while (n);
1181da177e4SLinus Torvalds }
1191da177e4SLinus Torvalds 
1208fb583c4SGeorge Spelvin /*
1218fb583c4SGeorge Spelvin  * The values are arbitrary as long as they can't be confused with
1228fb583c4SGeorge Spelvin  * a pointer, but small integers make for the smallest compare
1238fb583c4SGeorge Spelvin  * instructions.
1248fb583c4SGeorge Spelvin  */
125*a0019cd7SJiri Olsa #define SWAP_WORDS_64 (swap_r_func_t)0
126*a0019cd7SJiri Olsa #define SWAP_WORDS_32 (swap_r_func_t)1
127*a0019cd7SJiri Olsa #define SWAP_BYTES    (swap_r_func_t)2
128*a0019cd7SJiri Olsa #define SWAP_WRAPPER  (swap_r_func_t)3
129*a0019cd7SJiri Olsa 
130*a0019cd7SJiri Olsa struct wrapper {
131*a0019cd7SJiri Olsa 	cmp_func_t cmp;
132*a0019cd7SJiri Olsa 	swap_func_t swap;
133*a0019cd7SJiri Olsa };
1348fb583c4SGeorge Spelvin 
1358fb583c4SGeorge Spelvin /*
1368fb583c4SGeorge Spelvin  * The function pointer is last to make tail calls most efficient if the
1378fb583c4SGeorge Spelvin  * compiler decides not to inline this function.
1388fb583c4SGeorge Spelvin  */
do_swap(void * a,void * b,size_t size,swap_r_func_t swap_func,const void * priv)139*a0019cd7SJiri Olsa static void do_swap(void *a, void *b, size_t size, swap_r_func_t swap_func, const void *priv)
1408fb583c4SGeorge Spelvin {
141*a0019cd7SJiri Olsa 	if (swap_func == SWAP_WRAPPER) {
142*a0019cd7SJiri Olsa 		((const struct wrapper *)priv)->swap(a, b, (int)size);
143*a0019cd7SJiri Olsa 		return;
144*a0019cd7SJiri Olsa 	}
145*a0019cd7SJiri Olsa 
1468fb583c4SGeorge Spelvin 	if (swap_func == SWAP_WORDS_64)
1478fb583c4SGeorge Spelvin 		swap_words_64(a, b, size);
1488fb583c4SGeorge Spelvin 	else if (swap_func == SWAP_WORDS_32)
1498fb583c4SGeorge Spelvin 		swap_words_32(a, b, size);
1508fb583c4SGeorge Spelvin 	else if (swap_func == SWAP_BYTES)
1518fb583c4SGeorge Spelvin 		swap_bytes(a, b, size);
1528fb583c4SGeorge Spelvin 	else
153*a0019cd7SJiri Olsa 		swap_func(a, b, (int)size, priv);
1548fb583c4SGeorge Spelvin }
1558fb583c4SGeorge Spelvin 
1564333fb96SRasmus Villemoes #define _CMP_WRAPPER ((cmp_r_func_t)0L)
1574333fb96SRasmus Villemoes 
do_cmp(const void * a,const void * b,cmp_r_func_t cmp,const void * priv)15852ae533bSAndy Shevchenko static int do_cmp(const void *a, const void *b, cmp_r_func_t cmp, const void *priv)
1594333fb96SRasmus Villemoes {
1604333fb96SRasmus Villemoes 	if (cmp == _CMP_WRAPPER)
161*a0019cd7SJiri Olsa 		return ((const struct wrapper *)priv)->cmp(a, b);
1624333fb96SRasmus Villemoes 	return cmp(a, b, priv);
1634333fb96SRasmus Villemoes }
1644333fb96SRasmus Villemoes 
16572fd4a35SRobert P. J. Day /**
16622a241ccSGeorge Spelvin  * parent - given the offset of the child, find the offset of the parent.
16722a241ccSGeorge Spelvin  * @i: the offset of the heap element whose parent is sought.  Non-zero.
16822a241ccSGeorge Spelvin  * @lsbit: a precomputed 1-bit mask, equal to "size & -size"
16922a241ccSGeorge Spelvin  * @size: size of each element
17022a241ccSGeorge Spelvin  *
17122a241ccSGeorge Spelvin  * In terms of array indexes, the parent of element j = @i/@size is simply
17222a241ccSGeorge Spelvin  * (j-1)/2.  But when working in byte offsets, we can't use implicit
17322a241ccSGeorge Spelvin  * truncation of integer divides.
17422a241ccSGeorge Spelvin  *
17522a241ccSGeorge Spelvin  * Fortunately, we only need one bit of the quotient, not the full divide.
17622a241ccSGeorge Spelvin  * @size has a least significant bit.  That bit will be clear if @i is
17722a241ccSGeorge Spelvin  * an even multiple of @size, and set if it's an odd multiple.
17822a241ccSGeorge Spelvin  *
17922a241ccSGeorge Spelvin  * Logically, we're doing "if (i & lsbit) i -= size;", but since the
18022a241ccSGeorge Spelvin  * branch is unpredictable, it's done with a bit of clever branch-free
18122a241ccSGeorge Spelvin  * code instead.
18222a241ccSGeorge Spelvin  */
18322a241ccSGeorge Spelvin __attribute_const__ __always_inline
parent(size_t i,unsigned int lsbit,size_t size)18422a241ccSGeorge Spelvin static size_t parent(size_t i, unsigned int lsbit, size_t size)
18522a241ccSGeorge Spelvin {
18622a241ccSGeorge Spelvin 	i -= size;
18722a241ccSGeorge Spelvin 	i -= size & -(i & lsbit);
18822a241ccSGeorge Spelvin 	return i / 2;
18922a241ccSGeorge Spelvin }
19022a241ccSGeorge Spelvin 
19122a241ccSGeorge Spelvin /**
1924333fb96SRasmus Villemoes  * sort_r - sort an array of elements
1931da177e4SLinus Torvalds  * @base: pointer to data to sort
1941da177e4SLinus Torvalds  * @num: number of elements
1951da177e4SLinus Torvalds  * @size: size of each element
196b53907c0SWu Fengguang  * @cmp_func: pointer to comparison function
197b53907c0SWu Fengguang  * @swap_func: pointer to swap function or NULL
1984333fb96SRasmus Villemoes  * @priv: third argument passed to comparison function
1991da177e4SLinus Torvalds  *
20037d0ec34SGeorge Spelvin  * This function does a heapsort on the given array.  You may provide
20137d0ec34SGeorge Spelvin  * a swap_func function if you need to do something more than a memory
20237d0ec34SGeorge Spelvin  * copy (e.g. fix up pointers or auxiliary data), but the built-in swap
2038fb583c4SGeorge Spelvin  * avoids a slow retpoline and so is significantly faster.
2041da177e4SLinus Torvalds  *
2051da177e4SLinus Torvalds  * Sorting time is O(n log n) both on average and worst-case. While
20622a241ccSGeorge Spelvin  * quicksort is slightly faster on average, it suffers from exploitable
2071da177e4SLinus Torvalds  * O(n*n) worst-case behavior and extra memory requirements that make
2081da177e4SLinus Torvalds  * it less suitable for kernel use.
2091da177e4SLinus Torvalds  */
sort_r(void * base,size_t num,size_t size,cmp_r_func_t cmp_func,swap_r_func_t swap_func,const void * priv)2104333fb96SRasmus Villemoes void sort_r(void *base, size_t num, size_t size,
21152ae533bSAndy Shevchenko 	    cmp_r_func_t cmp_func,
212*a0019cd7SJiri Olsa 	    swap_r_func_t swap_func,
2134333fb96SRasmus Villemoes 	    const void *priv)
2141da177e4SLinus Torvalds {
2151da177e4SLinus Torvalds 	/* pre-scale counters for performance */
21622a241ccSGeorge Spelvin 	size_t n = num * size, a = (num/2) * size;
21722a241ccSGeorge Spelvin 	const unsigned int lsbit = size & -size;  /* Used to find parent */
21822a241ccSGeorge Spelvin 
21922a241ccSGeorge Spelvin 	if (!a)		/* num < 2 || size == 0 */
22022a241ccSGeorge Spelvin 		return;
2211da177e4SLinus Torvalds 
222*a0019cd7SJiri Olsa 	/* called from 'sort' without swap function, let's pick the default */
223*a0019cd7SJiri Olsa 	if (swap_func == SWAP_WRAPPER && !((struct wrapper *)priv)->swap)
224*a0019cd7SJiri Olsa 		swap_func = NULL;
225*a0019cd7SJiri Olsa 
226ca96ab85SDaniel Wagner 	if (!swap_func) {
22737d0ec34SGeorge Spelvin 		if (is_aligned(base, size, 8))
2288fb583c4SGeorge Spelvin 			swap_func = SWAP_WORDS_64;
22937d0ec34SGeorge Spelvin 		else if (is_aligned(base, size, 4))
2308fb583c4SGeorge Spelvin 			swap_func = SWAP_WORDS_32;
231ca96ab85SDaniel Wagner 		else
2328fb583c4SGeorge Spelvin 			swap_func = SWAP_BYTES;
233ca96ab85SDaniel Wagner 	}
2341da177e4SLinus Torvalds 
23522a241ccSGeorge Spelvin 	/*
23622a241ccSGeorge Spelvin 	 * Loop invariants:
23722a241ccSGeorge Spelvin 	 * 1. elements [a,n) satisfy the heap property (compare greater than
23822a241ccSGeorge Spelvin 	 *    all of their children),
23922a241ccSGeorge Spelvin 	 * 2. elements [n,num*size) are sorted, and
24022a241ccSGeorge Spelvin 	 * 3. a <= b <= c <= d <= n (whenever they are valid).
24122a241ccSGeorge Spelvin 	 */
24222a241ccSGeorge Spelvin 	for (;;) {
24322a241ccSGeorge Spelvin 		size_t b, c, d;
2441da177e4SLinus Torvalds 
24522a241ccSGeorge Spelvin 		if (a)			/* Building heap: sift down --a */
24622a241ccSGeorge Spelvin 			a -= size;
24722a241ccSGeorge Spelvin 		else if (n -= size)	/* Sorting: Extract root to --n */
248*a0019cd7SJiri Olsa 			do_swap(base, base + n, size, swap_func, priv);
24922a241ccSGeorge Spelvin 		else			/* Sort complete */
2501da177e4SLinus Torvalds 			break;
2511da177e4SLinus Torvalds 
25222a241ccSGeorge Spelvin 		/*
25322a241ccSGeorge Spelvin 		 * Sift element at "a" down into heap.  This is the
25422a241ccSGeorge Spelvin 		 * "bottom-up" variant, which significantly reduces
25522a241ccSGeorge Spelvin 		 * calls to cmp_func(): we find the sift-down path all
25622a241ccSGeorge Spelvin 		 * the way to the leaves (one compare per level), then
25722a241ccSGeorge Spelvin 		 * backtrack to find where to insert the target element.
25822a241ccSGeorge Spelvin 		 *
25922a241ccSGeorge Spelvin 		 * Because elements tend to sift down close to the leaves,
26022a241ccSGeorge Spelvin 		 * this uses fewer compares than doing two per level
26122a241ccSGeorge Spelvin 		 * on the way down.  (A bit more than half as many on
26222a241ccSGeorge Spelvin 		 * average, 3/4 worst-case.)
26322a241ccSGeorge Spelvin 		 */
26422a241ccSGeorge Spelvin 		for (b = a; c = 2*b + size, (d = c + size) < n;)
2654333fb96SRasmus Villemoes 			b = do_cmp(base + c, base + d, cmp_func, priv) >= 0 ? c : d;
26622a241ccSGeorge Spelvin 		if (d == n)	/* Special case last leaf with no sibling */
26722a241ccSGeorge Spelvin 			b = c;
26822a241ccSGeorge Spelvin 
26922a241ccSGeorge Spelvin 		/* Now backtrack from "b" to the correct location for "a" */
2704333fb96SRasmus Villemoes 		while (b != a && do_cmp(base + a, base + b, cmp_func, priv) >= 0)
27122a241ccSGeorge Spelvin 			b = parent(b, lsbit, size);
27222a241ccSGeorge Spelvin 		c = b;			/* Where "a" belongs */
27322a241ccSGeorge Spelvin 		while (b != a) {	/* Shift it into place */
27422a241ccSGeorge Spelvin 			b = parent(b, lsbit, size);
275*a0019cd7SJiri Olsa 			do_swap(base + b, base + c, size, swap_func, priv);
27622a241ccSGeorge Spelvin 		}
27722a241ccSGeorge Spelvin 	}
27822a241ccSGeorge Spelvin }
2794333fb96SRasmus Villemoes EXPORT_SYMBOL(sort_r);
2804333fb96SRasmus Villemoes 
sort(void * base,size_t num,size_t size,cmp_func_t cmp_func,swap_func_t swap_func)2814333fb96SRasmus Villemoes void sort(void *base, size_t num, size_t size,
28252ae533bSAndy Shevchenko 	  cmp_func_t cmp_func,
28352ae533bSAndy Shevchenko 	  swap_func_t swap_func)
2844333fb96SRasmus Villemoes {
285*a0019cd7SJiri Olsa 	struct wrapper w = {
286*a0019cd7SJiri Olsa 		.cmp  = cmp_func,
287*a0019cd7SJiri Olsa 		.swap = swap_func,
288*a0019cd7SJiri Olsa 	};
289*a0019cd7SJiri Olsa 
290*a0019cd7SJiri Olsa 	return sort_r(base, num, size, _CMP_WRAPPER, SWAP_WRAPPER, &w);
2914333fb96SRasmus Villemoes }
2921da177e4SLinus Torvalds EXPORT_SYMBOL(sort);
293