6 #define MAX_LIST_LENGTH_BITS 20
9 * Returns a list organized in an intermediate format suited
10 * to chaining of merge() calls: null-terminated, no reserved or
11 * sentinel head node, "prev" links not maintained.
13 static struct flist_head *merge(void *priv,
14 int (*cmp)(void *priv, struct flist_head *a,
15 struct flist_head *b),
16 struct flist_head *a, struct flist_head *b)
18 struct flist_head head, *tail = &head;
21 /* if equal, take 'a' -- important for sort stability */
22 if ((*cmp)(priv, a, b) <= 0) {
36 * Combine final list merge with restoration of standard doubly-linked
37 * list structure. This approach duplicates code from merge(), but
38 * runs faster than the tidier alternatives of either a separate final
39 * prev-link restoration pass, or maintaining the prev links
42 static void merge_and_restore_back_links(void *priv,
43 int (*cmp)(void *priv, struct flist_head *a,
44 struct flist_head *b),
45 struct flist_head *head,
46 struct flist_head *a, struct flist_head *b)
48 struct flist_head *tail = head;
51 /* if equal, take 'a' -- important for sort stability */
52 if ((*cmp)(priv, a, b) <= 0) {
67 * In worst cases this loop may run many iterations.
68 * Continue callbacks to the client even though no
69 * element comparison is needed, so the client's cmp()
70 * routine can invoke cond_resched() periodically.
72 (*cmp)(priv, tail->next, tail->next);
74 tail->next->prev = tail;
83 * list_sort - sort a list
84 * @priv: private data, opaque to list_sort(), passed to @cmp
85 * @head: the list to sort
86 * @cmp: the elements comparison function
88 * This function implements "merge sort", which has O(nlog(n))
91 * The comparison function @cmp must return a negative value if @a
92 * should sort before @b, and a positive value if @a should sort after
93 * @b. If @a and @b are equivalent, and their original relative
94 * ordering is to be preserved, @cmp must return 0.
96 void flist_sort(void *priv, struct flist_head *head,
97 int (*cmp)(void *priv, struct flist_head *a,
98 struct flist_head *b))
100 struct flist_head *part[MAX_LIST_LENGTH_BITS+1]; /* sorted partial lists
101 -- last slot is a sentinel */
102 int lev; /* index into part[] */
104 struct flist_head *list;
106 if (flist_empty(head))
109 memset(part, 0, sizeof(part));
111 head->prev->next = NULL;
115 struct flist_head *cur = list;
119 for (lev = 0; part[lev]; lev++) {
120 cur = merge(priv, cmp, part[lev], cur);
124 if (lev >= MAX_LIST_LENGTH_BITS) {
125 log_err("fio: list passed to"
126 " list_sort() too long for"
135 for (lev = 0; lev < max_lev; lev++)
137 list = merge(priv, cmp, part[lev], list);
139 merge_and_restore_back_links(priv, cmp, head, part[max_lev], list);