xref: /linux/lib/list_sort.c (revision b50ecc5aca4d18f1f0c4942f5c797bc85edef144)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/compiler.h>
3 #include <linux/export.h>
4 #include <linux/list_sort.h>
5 #include <linux/list.h>
6 
7 /*
8  * Returns a list organized in an intermediate format suited
9  * to chaining of merge() calls: null-terminated, no reserved or
10  * sentinel head node, "prev" links not maintained.
11  */
12 __attribute__((nonnull(2,3,4)))
13 static struct list_head *merge(void *priv, list_cmp_func_t cmp,
14 				struct list_head *a, struct list_head *b)
15 {
16 	struct list_head *head, **tail = &head;
17 
18 	for (;;) {
19 		/* if equal, take 'a' -- important for sort stability */
20 		if (cmp(priv, a, b) <= 0) {
21 			*tail = a;
22 			tail = &a->next;
23 			a = a->next;
24 			if (!a) {
25 				*tail = b;
26 				break;
27 			}
28 		} else {
29 			*tail = b;
30 			tail = &b->next;
31 			b = b->next;
32 			if (!b) {
33 				*tail = a;
34 				break;
35 			}
36 		}
37 	}
38 	return head;
39 }
40 
41 /*
42  * Combine final list merge with restoration of standard doubly-linked
43  * list structure.  This approach duplicates code from merge(), but
44  * runs faster than the tidier alternatives of either a separate final
45  * prev-link restoration pass, or maintaining the prev links
46  * throughout.
47  */
48 __attribute__((nonnull(2,3,4,5)))
49 static void merge_final(void *priv, list_cmp_func_t cmp, struct list_head *head,
50 			struct list_head *a, struct list_head *b)
51 {
52 	struct list_head *tail = head;
53 	u8 count = 0;
54 
55 	for (;;) {
56 		/* if equal, take 'a' -- important for sort stability */
57 		if (cmp(priv, a, b) <= 0) {
58 			tail->next = a;
59 			a->prev = tail;
60 			tail = a;
61 			a = a->next;
62 			if (!a)
63 				break;
64 		} else {
65 			tail->next = b;
66 			b->prev = tail;
67 			tail = b;
68 			b = b->next;
69 			if (!b) {
70 				b = a;
71 				break;
72 			}
73 		}
74 	}
75 
76 	/* Finish linking remainder of list b on to tail */
77 	tail->next = b;
78 	do {
79 		/*
80 		 * If the merge is highly unbalanced (e.g. the input is
81 		 * already sorted), this loop may run many iterations.
82 		 * Continue callbacks to the client even though no
83 		 * element comparison is needed, so the client's cmp()
84 		 * routine can invoke cond_resched() periodically.
85 		 */
86 		if (unlikely(!++count))
87 			cmp(priv, b, b);
88 		b->prev = tail;
89 		tail = b;
90 		b = b->next;
91 	} while (b);
92 
93 	/* And the final links to make a circular doubly-linked list */
94 	tail->next = head;
95 	head->prev = tail;
96 }
97 
98 /**
99  * list_sort - sort a list
100  * @priv: private data, opaque to list_sort(), passed to @cmp
101  * @head: the list to sort
102  * @cmp: the elements comparison function
103  *
104  * The comparison function @cmp must return > 0 if @a should sort after
105  * @b ("@a > @b" if you want an ascending sort), and <= 0 if @a should
106  * sort before @b *or* their original order should be preserved.  It is
107  * always called with the element that came first in the input in @a,
108  * and list_sort is a stable sort, so it is not necessary to distinguish
109  * the @a < @b and @a == @b cases.
110  *
111  * This is compatible with two styles of @cmp function:
112  * - The traditional style which returns <0 / =0 / >0, or
113  * - Returning a boolean 0/1.
114  * The latter offers a chance to save a few cycles in the comparison
115  * (which is used by e.g. plug_ctx_cmp() in block/blk-mq.c).
116  *
117  * A good way to write a multi-word comparison is::
118  *
119  *	if (a->high != b->high)
120  *		return a->high > b->high;
121  *	if (a->middle != b->middle)
122  *		return a->middle > b->middle;
123  *	return a->low > b->low;
124  *
125  *
126  * This mergesort is as eager as possible while always performing at least
127  * 2:1 balanced merges.  Given two pending sublists of size 2^k, they are
128  * merged to a size-2^(k+1) list as soon as we have 2^k following elements.
129  *
130  * Thus, it will avoid cache thrashing as long as 3*2^k elements can
131  * fit into the cache.  Not quite as good as a fully-eager bottom-up
132  * mergesort, but it does use 0.2*n fewer comparisons, so is faster in
133  * the common case that everything fits into L1.
134  *
135  *
136  * The merging is controlled by "count", the number of elements in the
137  * pending lists.  This is beautifully simple code, but rather subtle.
138  *
139  * Each time we increment "count", we set one bit (bit k) and clear
140  * bits k-1 .. 0.  Each time this happens (except the very first time
141  * for each bit, when count increments to 2^k), we merge two lists of
142  * size 2^k into one list of size 2^(k+1).
143  *
144  * This merge happens exactly when the count reaches an odd multiple of
145  * 2^k, which is when we have 2^k elements pending in smaller lists,
146  * so it's safe to merge away two lists of size 2^k.
147  *
148  * After this happens twice, we have created two lists of size 2^(k+1),
149  * which will be merged into a list of size 2^(k+2) before we create
150  * a third list of size 2^(k+1), so there are never more than two pending.
151  *
152  * The number of pending lists of size 2^k is determined by the
153  * state of bit k of "count" plus two extra pieces of information:
154  *
155  * - The state of bit k-1 (when k == 0, consider bit -1 always set), and
156  * - Whether the higher-order bits are zero or non-zero (i.e.
157  *   is count >= 2^(k+1)).
158  *
159  * There are six states we distinguish.  "x" represents some arbitrary
160  * bits, and "y" represents some arbitrary non-zero bits:
161  * 0:  00x: 0 pending of size 2^k;           x pending of sizes < 2^k
162  * 1:  01x: 0 pending of size 2^k; 2^(k-1) + x pending of sizes < 2^k
163  * 2: x10x: 0 pending of size 2^k; 2^k     + x pending of sizes < 2^k
164  * 3: x11x: 1 pending of size 2^k; 2^(k-1) + x pending of sizes < 2^k
165  * 4: y00x: 1 pending of size 2^k; 2^k     + x pending of sizes < 2^k
166  * 5: y01x: 2 pending of size 2^k; 2^(k-1) + x pending of sizes < 2^k
167  * (merge and loop back to state 2)
168  *
169  * We gain lists of size 2^k in the 2->3 and 4->5 transitions (because
170  * bit k-1 is set while the more significant bits are non-zero) and
171  * merge them away in the 5->2 transition.  Note in particular that just
172  * before the 5->2 transition, all lower-order bits are 11 (state 3),
173  * so there is one list of each smaller size.
174  *
175  * When we reach the end of the input, we merge all the pending
176  * lists, from smallest to largest.  If you work through cases 2 to
177  * 5 above, you can see that the number of elements we merge with a list
178  * of size 2^k varies from 2^(k-1) (cases 3 and 5 when x == 0) to
179  * 2^(k+1) - 1 (second merge of case 5 when x == 2^(k-1) - 1).
180  */
181 __attribute__((nonnull(2,3)))
182 void list_sort(void *priv, struct list_head *head, list_cmp_func_t cmp)
183 {
184 	struct list_head *list = head->next, *pending = NULL;
185 	size_t count = 0;	/* Count of pending */
186 
187 	if (list == head->prev)	/* Zero or one elements */
188 		return;
189 
190 	/* Convert to a null-terminated singly-linked list. */
191 	head->prev->next = NULL;
192 
193 	/*
194 	 * Data structure invariants:
195 	 * - All lists are singly linked and null-terminated; prev
196 	 *   pointers are not maintained.
197 	 * - pending is a prev-linked "list of lists" of sorted
198 	 *   sublists awaiting further merging.
199 	 * - Each of the sorted sublists is power-of-two in size.
200 	 * - Sublists are sorted by size and age, smallest & newest at front.
201 	 * - There are zero to two sublists of each size.
202 	 * - A pair of pending sublists are merged as soon as the number
203 	 *   of following pending elements equals their size (i.e.
204 	 *   each time count reaches an odd multiple of that size).
205 	 *   That ensures each later final merge will be at worst 2:1.
206 	 * - Each round consists of:
207 	 *   - Merging the two sublists selected by the highest bit
208 	 *     which flips when count is incremented, and
209 	 *   - Adding an element from the input as a size-1 sublist.
210 	 */
211 	do {
212 		size_t bits;
213 		struct list_head **tail = &pending;
214 
215 		/* Find the least-significant clear bit in count */
216 		for (bits = count; bits & 1; bits >>= 1)
217 			tail = &(*tail)->prev;
218 		/* Do the indicated merge */
219 		if (likely(bits)) {
220 			struct list_head *a = *tail, *b = a->prev;
221 
222 			a = merge(priv, cmp, b, a);
223 			/* Install the merged result in place of the inputs */
224 			a->prev = b->prev;
225 			*tail = a;
226 		}
227 
228 		/* Move one element from input list to pending */
229 		list->prev = pending;
230 		pending = list;
231 		list = list->next;
232 		pending->next = NULL;
233 		count++;
234 	} while (list);
235 
236 	/* End of input; merge together all the pending lists. */
237 	list = pending;
238 	pending = pending->prev;
239 	for (;;) {
240 		struct list_head *next = pending->prev;
241 
242 		if (!next)
243 			break;
244 		list = merge(priv, cmp, pending, list);
245 		pending = next;
246 	}
247 	/* The final merge, rebuilding prev links */
248 	merge_final(priv, cmp, head, pending, list);
249 }
250 EXPORT_SYMBOL(list_sort);
251