1 #include <linux/kernel.h>
3 #include <linux/compiler.h>
4 #include <linux/export.h>
5 #include <linux/string.h>
6 #include <linux/list_sort.h>
7 #include <linux/list.h>
9 #define MAX_LIST_LENGTH_BITS 20
12 * Returns a list organized in an intermediate format suited
13 * to chaining of merge() calls: null-terminated, no reserved or
14 * sentinel head node, "prev" links not maintained.
16 static struct list_head
*merge(void *priv
,
17 int (*cmp
)(void *priv
, struct list_head
*a
,
19 struct list_head
*a
, struct list_head
*b
)
21 struct list_head head
, *tail
= &head
;
24 /* if equal, take 'a' -- important for sort stability */
25 if ((*cmp
)(priv
, a
, b
) <= 0) {
39 * Combine final list merge with restoration of standard doubly-linked
40 * list structure. This approach duplicates code from merge(), but
41 * runs faster than the tidier alternatives of either a separate final
42 * prev-link restoration pass, or maintaining the prev links
45 static void merge_and_restore_back_links(void *priv
,
46 int (*cmp
)(void *priv
, struct list_head
*a
,
48 struct list_head
*head
,
49 struct list_head
*a
, struct list_head
*b
)
51 struct list_head
*tail
= head
;
55 /* if equal, take 'a' -- important for sort stability */
56 if ((*cmp
)(priv
, a
, b
) <= 0) {
71 * In worst cases this loop may run many iterations.
72 * Continue callbacks to the client even though no
73 * element comparison is needed, so the client's cmp()
74 * routine can invoke cond_resched() periodically.
76 if (unlikely(!(++count
)))
77 (*cmp
)(priv
, tail
->next
, tail
->next
);
79 tail
->next
->prev
= tail
;
88 * list_sort - sort a list
89 * @priv: private data, opaque to list_sort(), passed to @cmp
90 * @head: the list to sort
91 * @cmp: the elements comparison function
93 * This function implements "merge sort", which has O(nlog(n))
96 * The comparison function @cmp must return a negative value if @a
97 * should sort before @b, and a positive value if @a should sort after
98 * @b. If @a and @b are equivalent, and their original relative
99 * ordering is to be preserved, @cmp must return 0.
101 void list_sort(void *priv
, struct list_head
*head
,
102 int (*cmp
)(void *priv
, struct list_head
*a
,
103 struct list_head
*b
))
105 struct list_head
*part
[MAX_LIST_LENGTH_BITS
+1]; /* sorted partial lists
106 -- last slot is a sentinel */
107 int lev
; /* index into part[] */
109 struct list_head
*list
;
111 if (list_empty(head
))
114 memset(part
, 0, sizeof(part
));
116 head
->prev
->next
= NULL
;
120 struct list_head
*cur
= list
;
124 for (lev
= 0; part
[lev
]; lev
++) {
125 cur
= merge(priv
, cmp
, part
[lev
], cur
);
129 if (unlikely(lev
>= ARRAY_SIZE(part
)-1)) {
130 printk_once(KERN_DEBUG
"list too long for efficiency\n");
138 for (lev
= 0; lev
< max_lev
; lev
++)
140 list
= merge(priv
, cmp
, part
[lev
], list
);
142 merge_and_restore_back_links(priv
, cmp
, head
, part
[max_lev
], list
);
144 EXPORT_SYMBOL(list_sort
);