]> mj.ucw.cz Git - moe.git/blob - lib/sorter/array.c
Added libucw from Sherlock v3.12.2.
[moe.git] / lib / sorter / array.c
1 /*
2  *      UCW Library -- Optimized Array Sorter
3  *
4  *      (c) 2003--2007 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #undef LOCAL_DEBUG
11
12 #include "lib/lib.h"
13 #include "lib/sorter/common.h"
14
15 #include <string.h>
16 #include <alloca.h>
17
18 #define ASORT_MIN_SHIFT 2
19
20 #define ASORT_TRACE(x...) ASORT_XTRACE(1, x)
21 #define ASORT_XTRACE(level, x...) do { if (sorter_trace_array >= level) msg(L_DEBUG, x); } while(0)
22
23 static void
24 asort_radix(struct asort_context *ctx, void *array, void *buffer, uns num_elts, uns hash_bits, uns swapped_output)
25 {
26   // swap_output == 0 if result should be returned in `array', otherwise in `buffer'
27   uns buckets = (1 << ctx->radix_bits);
28   uns shift = (hash_bits > ctx->radix_bits) ? (hash_bits - ctx->radix_bits) : 0;
29   uns cnt[buckets];
30
31 #if 0
32   static int reported[64];
33   if (!reported[hash_bits]++)
34 #endif
35   DBG(">>> n=%u h=%d s=%d sw=%d", num_elts, hash_bits, shift, swapped_output);
36
37   bzero(cnt, sizeof(cnt));
38   ctx->radix_count(array, num_elts, cnt, shift);
39
40   uns pos = 0;
41   for (uns i=0; i<buckets; i++)
42     {
43       uns j = cnt[i];
44       cnt[i] = pos;
45       pos += j;
46     }
47   ASSERT(pos == num_elts);
48
49   ctx->radix_split(array, buffer, num_elts, cnt, shift);
50   pos = 0;
51   for (uns i=0; i<buckets; i++)
52     {
53       uns n = cnt[i] - pos;
54       if (n < ctx->radix_threshold || shift < ASORT_MIN_SHIFT)
55         {
56           ctx->quicksort(buffer, n);
57           if (!swapped_output)
58             memcpy(array, buffer, n * ctx->elt_size);
59         }
60       else
61         asort_radix(ctx, buffer, array, n, shift, !swapped_output);
62       array += n * ctx->elt_size;
63       buffer += n * ctx->elt_size;
64       pos = cnt[i];
65     }
66 }
67
68 #ifdef CONFIG_UCW_THREADS
69
70 #include "lib/threads.h"
71 #include "lib/workqueue.h"
72 #include "lib/eltpool.h"
73
74 static uns asort_threads_use_count;
75 static uns asort_threads_ready;
76 static struct worker_pool asort_thread_pool;
77
78 static uns
79 rs_estimate_stack(void)
80 {
81   // Stack space needed by the recursive radix-sorter
82   uns ctrsize = sizeof(uns) * (1 << CONFIG_UCW_RADIX_SORTER_BITS);
83   uns maxdepth = (64 / CONFIG_UCW_RADIX_SORTER_BITS) + 1;
84   return ctrsize * maxdepth;
85 }
86
87 void
88 asort_start_threads(uns run)
89 {
90   ucwlib_lock();
91   asort_threads_use_count++;
92   if (run && !asort_threads_ready)
93     {
94       // XXX: If somebody overrides the radix-sorter parameters to insane values,
95       // he also should override the stack size to insane values.
96       asort_thread_pool.stack_size = default_thread_stack_size + rs_estimate_stack();
97       asort_thread_pool.num_threads = sorter_threads;
98       ASORT_TRACE("Initializing thread pool (%d threads, %dK stack)", sorter_threads, asort_thread_pool.stack_size >> 10);
99       worker_pool_init(&asort_thread_pool);
100       asort_threads_ready = 1;
101     }
102   ucwlib_unlock();
103 }
104
105 void
106 asort_stop_threads(void)
107 {
108   ucwlib_lock();
109   if (!--asort_threads_use_count && asort_threads_ready)
110     {
111       ASORT_TRACE("Shutting down thread pool");
112       worker_pool_cleanup(&asort_thread_pool);
113       asort_threads_ready = 0;
114     }
115   ucwlib_unlock();
116 }
117
118 struct qs_work {
119   struct work w;
120   struct asort_context *ctx;
121   void *array;
122   uns num_elts;
123   int left, right;
124 #define LR_UNDEF -100
125 };
126
127 static void
128 qs_handle_work(struct worker_thread *thr UNUSED, struct work *ww)
129 {
130   struct qs_work *w = (struct qs_work *) ww;
131   struct asort_context *ctx = w->ctx;
132
133   DBG("Thread %d: got %u elts", thr->id, w->num_elts);
134   if (w->num_elts < ctx->thread_threshold)
135     {
136       ctx->quicksort(w->array, w->num_elts);
137       w->left = w->right = LR_UNDEF;
138     }
139   else
140     ctx->quicksplit(w->array, w->num_elts, &w->left, &w->right);
141   DBG("Thread %d: returning l=%u r=%u", thr->id, w->left, w->right);
142 }
143
144 static struct qs_work *
145 qs_alloc_work(struct asort_context *ctx)
146 {
147   struct qs_work *w = ep_alloc(ctx->eltpool);
148   w->w.priority = 0;
149   w->w.go = qs_handle_work;
150   w->ctx = ctx;
151   return w;
152 }
153
154 static void
155 threaded_quicksort(struct asort_context *ctx)
156 {
157   struct work_queue q;
158   struct qs_work *v, *w;
159
160   asort_start_threads(1);
161   work_queue_init(&asort_thread_pool, &q);
162   ctx->eltpool = ep_new(sizeof(struct qs_work), 1000);
163
164   w = qs_alloc_work(ctx);
165   w->array = ctx->array;
166   w->num_elts = ctx->num_elts;
167   work_submit(&q, &w->w);
168
169   while (v = (struct qs_work *) work_wait(&q))
170     {
171       if (v->left != LR_UNDEF)
172         {
173           if (v->right > 0)
174             {
175               w = qs_alloc_work(ctx);
176               w->array = v->array;
177               w->num_elts = v->right + 1;
178               w->w.priority = v->w.priority + 1;
179               work_submit(&q, &w->w);
180             }
181           if (v->left < (int)v->num_elts - 1)
182             {
183               w = qs_alloc_work(ctx);
184               w->array = v->array + v->left * ctx->elt_size;
185               w->num_elts = v->num_elts - v->left;
186               w->w.priority = v->w.priority + 1;
187               work_submit(&q, &w->w);
188             }
189         }
190       ep_free(ctx->eltpool, v);
191     }
192
193   ep_delete(ctx->eltpool);
194   work_queue_cleanup(&q);
195   asort_stop_threads();
196 }
197
198 struct rs_work {
199   struct work w;
200   struct asort_context *ctx;
201   void *array, *buffer;         // Like asort_radix().
202   uns num_elts;
203   uns shift;
204   uns swap_output;
205   uns cnt[0];
206 };
207
208 static void
209 rs_count(struct worker_thread *thr UNUSED, struct work *ww)
210 {
211   struct rs_work *w = (struct rs_work *) ww;
212
213   DBG("Thread %d: Counting %u items, shift=%d", thr->id, w->num_elts, w->shift);
214   w->ctx->radix_count(w->array, w->num_elts, w->cnt, w->shift);
215   DBG("Thread %d: Counting done", thr->id);
216 }
217
218 static void
219 rs_split(struct worker_thread *thr UNUSED, struct work *ww)
220 {
221   struct rs_work *w = (struct rs_work *) ww;
222
223   DBG("Thread %d: Splitting %u items, shift=%d", thr->id, w->num_elts, w->shift);
224   w->ctx->radix_split(w->array, w->buffer, w->num_elts, w->cnt, w->shift);
225   DBG("Thread %d: Splitting done", thr->id);
226 }
227
228 static void
229 rs_finish(struct worker_thread *thr UNUSED, struct work *ww)
230 {
231   struct rs_work *w = (struct rs_work *) ww;
232
233   if (thr)
234     DBG("Thread %d: Finishing %u items, shift=%d", thr->id, w->num_elts, w->shift);
235   if (w->shift < ASORT_MIN_SHIFT || w->num_elts < w->ctx->radix_threshold)
236     {
237       w->ctx->quicksort(w->array, w->num_elts);
238       if (w->swap_output)
239         memcpy(w->buffer, w->array, w->num_elts * w->ctx->elt_size);
240     }
241   else
242     asort_radix(w->ctx, w->array, w->buffer, w->num_elts, w->shift, w->swap_output);
243   if (thr)
244     DBG("Thread %d: Finishing done", thr->id);
245 }
246
247 static void
248 rs_wait_small(struct asort_context *ctx)
249 {
250   struct rs_work *w;
251
252   while (w = (struct rs_work *) work_wait(ctx->rs_work_queue))
253     {
254       DBG("Reaping small chunk of %u items", w->num_elts);
255       ep_free(ctx->eltpool, w);
256     }
257 }
258
259 static void
260 rs_radix(struct asort_context *ctx, void *array, void *buffer, uns num_elts, uns hash_bits, uns swapped_output)
261 {
262   uns buckets = (1 << ctx->radix_bits);
263   uns shift = (hash_bits > ctx->radix_bits) ? (hash_bits - ctx->radix_bits) : 0;
264   uns cnt[buckets];
265   uns blksize = num_elts / sorter_threads;
266   DBG(">>> n=%u h=%d s=%d blk=%u sw=%d", num_elts, hash_bits, shift, blksize, swapped_output);
267
268   // If there are any small chunks in progress, wait for them to finish
269   rs_wait_small(ctx);
270
271   // Start parallel counting
272   void *iptr = array;
273   for (uns i=0; i<sorter_threads; i++)
274     {
275       struct rs_work *w = ctx->rs_works[i];
276       w->w.priority = 0;
277       w->w.go = rs_count;
278       w->ctx = ctx;
279       w->array = iptr;
280       w->buffer = buffer;
281       w->num_elts = blksize;
282       if (i == sorter_threads-1)
283         w->num_elts += num_elts % sorter_threads;
284       w->shift = shift;
285       iptr += w->num_elts * ctx->elt_size;
286       bzero(w->cnt, sizeof(uns) * buckets);
287       work_submit(ctx->rs_work_queue, &w->w);
288     }
289
290   // Get bucket sizes from the counts
291   bzero(cnt, sizeof(cnt));
292   for (uns i=0; i<sorter_threads; i++)
293     {
294       struct rs_work *w = (struct rs_work *) work_wait(ctx->rs_work_queue);
295       ASSERT(w);
296       for (uns j=0; j<buckets; j++)
297         cnt[j] += w->cnt[j];
298     }
299
300   // Calculate bucket starts
301   uns pos = 0;
302   for (uns i=0; i<buckets; i++)
303     {
304       uns j = cnt[i];
305       cnt[i] = pos;
306       pos += j;
307     }
308   ASSERT(pos == num_elts);
309
310   // Start parallel splitting
311   for (uns i=0; i<sorter_threads; i++)
312     {
313       struct rs_work *w = ctx->rs_works[i];
314       w->w.go = rs_split;
315       for (uns j=0; j<buckets; j++)
316         {
317           uns k = w->cnt[j];
318           w->cnt[j] = cnt[j];
319           cnt[j] += k;
320         }
321       work_submit(ctx->rs_work_queue, &w->w);
322     }
323   ASSERT(cnt[buckets-1] == num_elts);
324
325   // Wait for splits to finish
326   while (work_wait(ctx->rs_work_queue))
327     ;
328
329   // Recurse on buckets
330   pos = 0;
331   for (uns i=0; i<buckets; i++)
332     {
333       uns n = cnt[i] - pos;
334       if (!n)
335         continue;
336       if (n < ctx->thread_threshold || shift < ASORT_MIN_SHIFT)
337         {
338           struct rs_work *w = ep_alloc(ctx->eltpool);
339           w->w.priority = 0;
340           w->w.go = rs_finish;
341           w->ctx = ctx;
342           w->array = buffer;
343           w->buffer = array;
344           w->num_elts = n;
345           w->shift = shift;
346           w->swap_output = !swapped_output;
347           if (n < ctx->thread_chunk)
348             {
349               DBG("Sorting block %u+%u inline", pos, n);
350               rs_finish(NULL, &w->w);
351               ep_free(ctx->eltpool, w);
352             }
353           else
354             {
355               DBG("Scheduling block %u+%u", pos, n);
356               work_submit(ctx->rs_work_queue, &w->w);
357             }
358         }
359       else
360         rs_radix(ctx, buffer, array, n, shift, !swapped_output);
361       pos = cnt[i];
362       array += n * ctx->elt_size;
363       buffer += n * ctx->elt_size;
364     }
365 }
366
367 static void
368 threaded_radixsort(struct asort_context *ctx, uns swap)
369 {
370   struct work_queue q;
371
372   asort_start_threads(1);
373   work_queue_init(&asort_thread_pool, &q);
374
375   // Prepare work structures for counting and splitting.
376   // We use big_alloc(), because we want to avoid cacheline aliasing between threads.
377   ctx->rs_work_queue = &q;
378   ctx->rs_works = alloca(sizeof(struct rs_work *) * sorter_threads);
379   for (uns i=0; i<sorter_threads; i++)
380     ctx->rs_works[i] = big_alloc(sizeof(struct rs_work) + sizeof(uns) * (1 << ctx->radix_bits));
381
382   // Prepare a pool for all remaining small bits which will be sorted on background.
383   ctx->eltpool = ep_new(sizeof(struct rs_work), 1000);
384
385   // Do the big splitting
386   rs_radix(ctx, ctx->array, ctx->buffer, ctx->num_elts, ctx->hash_bits, swap);
387   for (uns i=0; i<sorter_threads; i++)
388     big_free(ctx->rs_works[i], sizeof(struct rs_work) + sizeof(uns) * (1 << ctx->radix_bits));
389
390   // Finish the small blocks
391   rs_wait_small(ctx);
392
393   ASSERT(!ctx->eltpool->num_allocated);
394   ep_delete(ctx->eltpool);
395   work_queue_cleanup(&q);
396   asort_stop_threads();
397 }
398
399 #else
400
401 void asort_start_threads(uns run UNUSED) { }
402 void asort_stop_threads(void) { }
403
404 #endif
405
406 static uns
407 predict_swap(struct asort_context *ctx)
408 {
409   uns bits = ctx->radix_bits;
410   uns elts = ctx->num_elts;
411   uns swap = 0;
412
413   while (elts >= ctx->radix_threshold && bits >= ASORT_MIN_SHIFT)
414     {
415       DBG("Predicting pass: %u elts, %d bits", elts, bits);
416       swap = !swap;
417       elts >>= ctx->radix_bits;
418       bits = MAX(bits, ctx->radix_bits) - ctx->radix_bits;
419     }
420   return swap;
421 }
422
423 void
424 asort_run(struct asort_context *ctx)
425 {
426   ctx->thread_threshold = MIN(sorter_thread_threshold / ctx->elt_size, ~0U);
427   ctx->thread_chunk = MIN(sorter_thread_chunk / ctx->elt_size, ~0U);
428   ctx->radix_threshold = MIN(sorter_radix_threshold / ctx->elt_size, ~0U);
429
430   ASORT_TRACE("Array-sorting %u items per %u bytes, hash_bits=%d", ctx->num_elts, ctx->elt_size, ctx->hash_bits);
431   ASORT_XTRACE(2, "Limits: thread_threshold=%u, thread_chunk=%u, radix_threshold=%u",
432         ctx->thread_threshold, ctx->thread_chunk, ctx->radix_threshold);
433   uns allow_threads UNUSED = (sorter_threads > 1 &&
434                               ctx->num_elts >= ctx->thread_threshold &&
435                               !(sorter_debug & SORT_DEBUG_ASORT_NO_THREADS));
436
437   if (ctx->num_elts < ctx->radix_threshold ||
438       ctx->hash_bits <= ASORT_MIN_SHIFT ||
439       !ctx->radix_split ||
440       (sorter_debug & SORT_DEBUG_ASORT_NO_RADIX))
441     {
442 #ifdef CONFIG_UCW_THREADS
443       if (allow_threads)
444         {
445           ASORT_XTRACE(2, "Decided to use parallel quicksort");
446           threaded_quicksort(ctx);
447         }
448       else
449 #endif
450         {
451           ASORT_XTRACE(2, "Decided to use sequential quicksort");
452           ctx->quicksort(ctx->array, ctx->num_elts);
453         }
454     }
455   else
456     {
457       uns swap = predict_swap(ctx);
458 #ifdef CONFIG_UCW_THREADS
459       if (allow_threads)
460         {
461           ASORT_XTRACE(2, "Decided to use parallel radix-sort (swap=%d)", swap);
462           threaded_radixsort(ctx, swap);
463         }
464       else
465 #endif
466         {
467           ASORT_XTRACE(2, "Decided to use sequential radix-sort (swap=%d)", swap);
468           asort_radix(ctx, ctx->array, ctx->buffer, ctx->num_elts, ctx->hash_bits, swap);
469         }
470       if (swap)
471         ctx->array = ctx->buffer;
472     }
473
474   ASORT_XTRACE(2, "Array-sort finished");
475 }