xref: /linux-6.15/lib/list_sort.c (revision e420460b)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
27259fa04SRasmus Villemoes #include <linux/compiler.h>
37259fa04SRasmus Villemoes #include <linux/export.h>
42c761270SDave Chinner #include <linux/list_sort.h>
52c761270SDave Chinner #include <linux/list.h>
62c761270SDave Chinner 
7835cc0c8SDon Mullis /*
8835cc0c8SDon Mullis  * Returns a list organized in an intermediate format suited
9835cc0c8SDon Mullis  * to chaining of merge() calls: null-terminated, no reserved or
10835cc0c8SDon Mullis  * sentinel head node, "prev" links not maintained.
11835cc0c8SDon Mullis  */
12043b3f7bSGeorge Spelvin __attribute__((nonnull(2,3,4)))
merge(void * priv,list_cmp_func_t cmp,struct list_head * a,struct list_head * b)134f0f586bSSami Tolvanen static struct list_head *merge(void *priv, list_cmp_func_t cmp,
14835cc0c8SDon Mullis 				struct list_head *a, struct list_head *b)
15835cc0c8SDon Mullis {
16043b3f7bSGeorge Spelvin 	struct list_head *head, **tail = &head;
17835cc0c8SDon Mullis 
18043b3f7bSGeorge Spelvin 	for (;;) {
19835cc0c8SDon Mullis 		/* if equal, take 'a' -- important for sort stability */
20043b3f7bSGeorge Spelvin 		if (cmp(priv, a, b) <= 0) {
21043b3f7bSGeorge Spelvin 			*tail = a;
22043b3f7bSGeorge Spelvin 			tail = &a->next;
23835cc0c8SDon Mullis 			a = a->next;
24043b3f7bSGeorge Spelvin 			if (!a) {
25043b3f7bSGeorge Spelvin 				*tail = b;
26043b3f7bSGeorge Spelvin 				break;
27043b3f7bSGeorge Spelvin 			}
28835cc0c8SDon Mullis 		} else {
29043b3f7bSGeorge Spelvin 			*tail = b;
30043b3f7bSGeorge Spelvin 			tail = &b->next;
31835cc0c8SDon Mullis 			b = b->next;
32043b3f7bSGeorge Spelvin 			if (!b) {
33043b3f7bSGeorge Spelvin 				*tail = a;
34043b3f7bSGeorge Spelvin 				break;
35835cc0c8SDon Mullis 			}
36835cc0c8SDon Mullis 		}
37043b3f7bSGeorge Spelvin 	}
38043b3f7bSGeorge Spelvin 	return head;
39835cc0c8SDon Mullis }
40835cc0c8SDon Mullis 
41835cc0c8SDon Mullis /*
42835cc0c8SDon Mullis  * Combine final list merge with restoration of standard doubly-linked
43835cc0c8SDon Mullis  * list structure.  This approach duplicates code from merge(), but
44835cc0c8SDon Mullis  * runs faster than the tidier alternatives of either a separate final
45835cc0c8SDon Mullis  * prev-link restoration pass, or maintaining the prev links
46835cc0c8SDon Mullis  * throughout.
47835cc0c8SDon Mullis  */
48043b3f7bSGeorge Spelvin __attribute__((nonnull(2,3,4,5)))
merge_final(void * priv,list_cmp_func_t cmp,struct list_head * head,struct list_head * a,struct list_head * b)494f0f586bSSami Tolvanen static void merge_final(void *priv, list_cmp_func_t cmp, struct list_head *head,
50835cc0c8SDon Mullis 			struct list_head *a, struct list_head *b)
51835cc0c8SDon Mullis {
52835cc0c8SDon Mullis 	struct list_head *tail = head;
5361b3d6c4SRasmus Villemoes 	u8 count = 0;
54835cc0c8SDon Mullis 
55043b3f7bSGeorge Spelvin 	for (;;) {
56835cc0c8SDon Mullis 		/* if equal, take 'a' -- important for sort stability */
57043b3f7bSGeorge Spelvin 		if (cmp(priv, a, b) <= 0) {
58835cc0c8SDon Mullis 			tail->next = a;
59835cc0c8SDon Mullis 			a->prev = tail;
60043b3f7bSGeorge Spelvin 			tail = a;
61835cc0c8SDon Mullis 			a = a->next;
62043b3f7bSGeorge Spelvin 			if (!a)
63043b3f7bSGeorge Spelvin 				break;
64835cc0c8SDon Mullis 		} else {
65835cc0c8SDon Mullis 			tail->next = b;
66835cc0c8SDon Mullis 			b->prev = tail;
67043b3f7bSGeorge Spelvin 			tail = b;
68835cc0c8SDon Mullis 			b = b->next;
69043b3f7bSGeorge Spelvin 			if (!b) {
70043b3f7bSGeorge Spelvin 				b = a;
71043b3f7bSGeorge Spelvin 				break;
72835cc0c8SDon Mullis 			}
73835cc0c8SDon Mullis 		}
74043b3f7bSGeorge Spelvin 	}
75835cc0c8SDon Mullis 
76043b3f7bSGeorge Spelvin 	/* Finish linking remainder of list b on to tail */
77043b3f7bSGeorge Spelvin 	tail->next = b;
78835cc0c8SDon Mullis 	do {
79835cc0c8SDon Mullis 		/*
80043b3f7bSGeorge Spelvin 		 * If the merge is highly unbalanced (e.g. the input is
81043b3f7bSGeorge Spelvin 		 * already sorted), this loop may run many iterations.
82835cc0c8SDon Mullis 		 * Continue callbacks to the client even though no
83835cc0c8SDon Mullis 		 * element comparison is needed, so the client's cmp()
84835cc0c8SDon Mullis 		 * routine can invoke cond_resched() periodically.
85835cc0c8SDon Mullis 		 */
86043b3f7bSGeorge Spelvin 		if (unlikely(!++count))
87043b3f7bSGeorge Spelvin 			cmp(priv, b, b);
88043b3f7bSGeorge Spelvin 		b->prev = tail;
89043b3f7bSGeorge Spelvin 		tail = b;
90043b3f7bSGeorge Spelvin 		b = b->next;
91043b3f7bSGeorge Spelvin 	} while (b);
92835cc0c8SDon Mullis 
93043b3f7bSGeorge Spelvin 	/* And the final links to make a circular doubly-linked list */
94835cc0c8SDon Mullis 	tail->next = head;
95835cc0c8SDon Mullis 	head->prev = tail;
96835cc0c8SDon Mullis }
97835cc0c8SDon Mullis 
982c761270SDave Chinner /**
9902b12b7aSDon Mullis  * list_sort - sort a list
10002b12b7aSDon Mullis  * @priv: private data, opaque to list_sort(), passed to @cmp
1012c761270SDave Chinner  * @head: the list to sort
1022c761270SDave Chinner  * @cmp: the elements comparison function
1032c761270SDave Chinner  *
1049dbbc3b9SZhen Lei  * The comparison function @cmp must return > 0 if @a should sort after
105043b3f7bSGeorge Spelvin  * @b ("@a > @b" if you want an ascending sort), and <= 0 if @a should
106043b3f7bSGeorge Spelvin  * sort before @b *or* their original order should be preserved.  It is
107043b3f7bSGeorge Spelvin  * always called with the element that came first in the input in @a,
108043b3f7bSGeorge Spelvin  * and list_sort is a stable sort, so it is not necessary to distinguish
109043b3f7bSGeorge Spelvin  * the @a < @b and @a == @b cases.
110043b3f7bSGeorge Spelvin  *
111*e420460bSKuan-Wei Chiu  * The comparison function must adhere to specific mathematical properties
112*e420460bSKuan-Wei Chiu  * to ensure correct and stable sorting:
113*e420460bSKuan-Wei Chiu  * - Antisymmetry: cmp(@a, @b) must return the opposite sign of
114*e420460bSKuan-Wei Chiu  * cmp(@b, @a).
115*e420460bSKuan-Wei Chiu  * - Transitivity: if cmp(@a, @b) <= 0 and cmp(@b, @c) <= 0, then
116*e420460bSKuan-Wei Chiu  * cmp(@a, @c) <= 0.
117*e420460bSKuan-Wei Chiu  *
118043b3f7bSGeorge Spelvin  * This is compatible with two styles of @cmp function:
119043b3f7bSGeorge Spelvin  * - The traditional style which returns <0 / =0 / >0, or
120043b3f7bSGeorge Spelvin  * - Returning a boolean 0/1.
121043b3f7bSGeorge Spelvin  * The latter offers a chance to save a few cycles in the comparison
122043b3f7bSGeorge Spelvin  * (which is used by e.g. plug_ctx_cmp() in block/blk-mq.c).
123043b3f7bSGeorge Spelvin  *
124f35a1abdSJonathan Corbet  * A good way to write a multi-word comparison is::
125f35a1abdSJonathan Corbet  *
126043b3f7bSGeorge Spelvin  *	if (a->high != b->high)
127043b3f7bSGeorge Spelvin  *		return a->high > b->high;
128043b3f7bSGeorge Spelvin  *	if (a->middle != b->middle)
129043b3f7bSGeorge Spelvin  *		return a->middle > b->middle;
130043b3f7bSGeorge Spelvin  *	return a->low > b->low;
131b5c56e0cSGeorge Spelvin  *
132b5c56e0cSGeorge Spelvin  *
133b5c56e0cSGeorge Spelvin  * This mergesort is as eager as possible while always performing at least
134b5c56e0cSGeorge Spelvin  * 2:1 balanced merges.  Given two pending sublists of size 2^k, they are
135b5c56e0cSGeorge Spelvin  * merged to a size-2^(k+1) list as soon as we have 2^k following elements.
136b5c56e0cSGeorge Spelvin  *
137b5c56e0cSGeorge Spelvin  * Thus, it will avoid cache thrashing as long as 3*2^k elements can
138b5c56e0cSGeorge Spelvin  * fit into the cache.  Not quite as good as a fully-eager bottom-up
139b5c56e0cSGeorge Spelvin  * mergesort, but it does use 0.2*n fewer comparisons, so is faster in
140b5c56e0cSGeorge Spelvin  * the common case that everything fits into L1.
141b5c56e0cSGeorge Spelvin  *
142b5c56e0cSGeorge Spelvin  *
143b5c56e0cSGeorge Spelvin  * The merging is controlled by "count", the number of elements in the
144e89b6358SToastC  * pending lists.  This is beautifully simple code, but rather subtle.
145b5c56e0cSGeorge Spelvin  *
146b5c56e0cSGeorge Spelvin  * Each time we increment "count", we set one bit (bit k) and clear
147b5c56e0cSGeorge Spelvin  * bits k-1 .. 0.  Each time this happens (except the very first time
148b5c56e0cSGeorge Spelvin  * for each bit, when count increments to 2^k), we merge two lists of
149b5c56e0cSGeorge Spelvin  * size 2^k into one list of size 2^(k+1).
150b5c56e0cSGeorge Spelvin  *
151b5c56e0cSGeorge Spelvin  * This merge happens exactly when the count reaches an odd multiple of
152b5c56e0cSGeorge Spelvin  * 2^k, which is when we have 2^k elements pending in smaller lists,
153b5c56e0cSGeorge Spelvin  * so it's safe to merge away two lists of size 2^k.
154b5c56e0cSGeorge Spelvin  *
155b5c56e0cSGeorge Spelvin  * After this happens twice, we have created two lists of size 2^(k+1),
156b5c56e0cSGeorge Spelvin  * which will be merged into a list of size 2^(k+2) before we create
157b5c56e0cSGeorge Spelvin  * a third list of size 2^(k+1), so there are never more than two pending.
158b5c56e0cSGeorge Spelvin  *
159b5c56e0cSGeorge Spelvin  * The number of pending lists of size 2^k is determined by the
160b5c56e0cSGeorge Spelvin  * state of bit k of "count" plus two extra pieces of information:
1614ae5b8f2SMauro Carvalho Chehab  *
162b5c56e0cSGeorge Spelvin  * - The state of bit k-1 (when k == 0, consider bit -1 always set), and
163b5c56e0cSGeorge Spelvin  * - Whether the higher-order bits are zero or non-zero (i.e.
164b5c56e0cSGeorge Spelvin  *   is count >= 2^(k+1)).
1654ae5b8f2SMauro Carvalho Chehab  *
166b5c56e0cSGeorge Spelvin  * There are six states we distinguish.  "x" represents some arbitrary
167b5c56e0cSGeorge Spelvin  * bits, and "y" represents some arbitrary non-zero bits:
168b5c56e0cSGeorge Spelvin  * 0:  00x: 0 pending of size 2^k;           x pending of sizes < 2^k
169b5c56e0cSGeorge Spelvin  * 1:  01x: 0 pending of size 2^k; 2^(k-1) + x pending of sizes < 2^k
170b5c56e0cSGeorge Spelvin  * 2: x10x: 0 pending of size 2^k; 2^k     + x pending of sizes < 2^k
171b5c56e0cSGeorge Spelvin  * 3: x11x: 1 pending of size 2^k; 2^(k-1) + x pending of sizes < 2^k
172b5c56e0cSGeorge Spelvin  * 4: y00x: 1 pending of size 2^k; 2^k     + x pending of sizes < 2^k
173b5c56e0cSGeorge Spelvin  * 5: y01x: 2 pending of size 2^k; 2^(k-1) + x pending of sizes < 2^k
174b5c56e0cSGeorge Spelvin  * (merge and loop back to state 2)
175b5c56e0cSGeorge Spelvin  *
176b5c56e0cSGeorge Spelvin  * We gain lists of size 2^k in the 2->3 and 4->5 transitions (because
177b5c56e0cSGeorge Spelvin  * bit k-1 is set while the more significant bits are non-zero) and
178b5c56e0cSGeorge Spelvin  * merge them away in the 5->2 transition.  Note in particular that just
179b5c56e0cSGeorge Spelvin  * before the 5->2 transition, all lower-order bits are 11 (state 3),
180b5c56e0cSGeorge Spelvin  * so there is one list of each smaller size.
181b5c56e0cSGeorge Spelvin  *
182b5c56e0cSGeorge Spelvin  * When we reach the end of the input, we merge all the pending
183b5c56e0cSGeorge Spelvin  * lists, from smallest to largest.  If you work through cases 2 to
184b5c56e0cSGeorge Spelvin  * 5 above, you can see that the number of elements we merge with a list
185b5c56e0cSGeorge Spelvin  * of size 2^k varies from 2^(k-1) (cases 3 and 5 when x == 0) to
186b5c56e0cSGeorge Spelvin  * 2^(k+1) - 1 (second merge of case 5 when x == 2^(k-1) - 1).
1872c761270SDave Chinner  */
188043b3f7bSGeorge Spelvin __attribute__((nonnull(2,3)))
list_sort(void * priv,struct list_head * head,list_cmp_func_t cmp)1894f0f586bSSami Tolvanen void list_sort(void *priv, struct list_head *head, list_cmp_func_t cmp)
1902c761270SDave Chinner {
191043b3f7bSGeorge Spelvin 	struct list_head *list = head->next, *pending = NULL;
192043b3f7bSGeorge Spelvin 	size_t count = 0;	/* Count of pending */
1932c761270SDave Chinner 
194043b3f7bSGeorge Spelvin 	if (list == head->prev)	/* Zero or one elements */
1952c761270SDave Chinner 		return;
1962c761270SDave Chinner 
197043b3f7bSGeorge Spelvin 	/* Convert to a null-terminated singly-linked list. */
198835cc0c8SDon Mullis 	head->prev->next = NULL;
1992c761270SDave Chinner 
200043b3f7bSGeorge Spelvin 	/*
201043b3f7bSGeorge Spelvin 	 * Data structure invariants:
202043b3f7bSGeorge Spelvin 	 * - All lists are singly linked and null-terminated; prev
203043b3f7bSGeorge Spelvin 	 *   pointers are not maintained.
204043b3f7bSGeorge Spelvin 	 * - pending is a prev-linked "list of lists" of sorted
205043b3f7bSGeorge Spelvin 	 *   sublists awaiting further merging.
206b5c56e0cSGeorge Spelvin 	 * - Each of the sorted sublists is power-of-two in size.
207043b3f7bSGeorge Spelvin 	 * - Sublists are sorted by size and age, smallest & newest at front.
208b5c56e0cSGeorge Spelvin 	 * - There are zero to two sublists of each size.
209b5c56e0cSGeorge Spelvin 	 * - A pair of pending sublists are merged as soon as the number
210b5c56e0cSGeorge Spelvin 	 *   of following pending elements equals their size (i.e.
211b5c56e0cSGeorge Spelvin 	 *   each time count reaches an odd multiple of that size).
212b5c56e0cSGeorge Spelvin 	 *   That ensures each later final merge will be at worst 2:1.
213b5c56e0cSGeorge Spelvin 	 * - Each round consists of:
214b5c56e0cSGeorge Spelvin 	 *   - Merging the two sublists selected by the highest bit
215b5c56e0cSGeorge Spelvin 	 *     which flips when count is incremented, and
216b5c56e0cSGeorge Spelvin 	 *   - Adding an element from the input as a size-1 sublist.
217043b3f7bSGeorge Spelvin 	 */
218043b3f7bSGeorge Spelvin 	do {
219043b3f7bSGeorge Spelvin 		size_t bits;
220b5c56e0cSGeorge Spelvin 		struct list_head **tail = &pending;
221043b3f7bSGeorge Spelvin 
222b5c56e0cSGeorge Spelvin 		/* Find the least-significant clear bit in count */
223b5c56e0cSGeorge Spelvin 		for (bits = count; bits & 1; bits >>= 1)
224b5c56e0cSGeorge Spelvin 			tail = &(*tail)->prev;
225b5c56e0cSGeorge Spelvin 		/* Do the indicated merge */
226b5c56e0cSGeorge Spelvin 		if (likely(bits)) {
227b5c56e0cSGeorge Spelvin 			struct list_head *a = *tail, *b = a->prev;
228835cc0c8SDon Mullis 
2294f0f586bSSami Tolvanen 			a = merge(priv, cmp, b, a);
230b5c56e0cSGeorge Spelvin 			/* Install the merged result in place of the inputs */
231b5c56e0cSGeorge Spelvin 			a->prev = b->prev;
232b5c56e0cSGeorge Spelvin 			*tail = a;
233835cc0c8SDon Mullis 		}
2342c761270SDave Chinner 
235b5c56e0cSGeorge Spelvin 		/* Move one element from input list to pending */
236b5c56e0cSGeorge Spelvin 		list->prev = pending;
237b5c56e0cSGeorge Spelvin 		pending = list;
238b5c56e0cSGeorge Spelvin 		list = list->next;
239b5c56e0cSGeorge Spelvin 		pending->next = NULL;
240b5c56e0cSGeorge Spelvin 		count++;
241b5c56e0cSGeorge Spelvin 	} while (list);
242b5c56e0cSGeorge Spelvin 
243b5c56e0cSGeorge Spelvin 	/* End of input; merge together all the pending lists. */
244b5c56e0cSGeorge Spelvin 	list = pending;
245043b3f7bSGeorge Spelvin 	pending = pending->prev;
246b5c56e0cSGeorge Spelvin 	for (;;) {
247b5c56e0cSGeorge Spelvin 		struct list_head *next = pending->prev;
248b5c56e0cSGeorge Spelvin 
249b5c56e0cSGeorge Spelvin 		if (!next)
250b5c56e0cSGeorge Spelvin 			break;
2514f0f586bSSami Tolvanen 		list = merge(priv, cmp, pending, list);
252b5c56e0cSGeorge Spelvin 		pending = next;
253043b3f7bSGeorge Spelvin 	}
254043b3f7bSGeorge Spelvin 	/* The final merge, rebuilding prev links */
2554f0f586bSSami Tolvanen 	merge_final(priv, cmp, head, pending, list);
2562c761270SDave Chinner }
2572c761270SDave Chinner EXPORT_SYMBOL(list_sort);
258