]> mj.ucw.cz Git - moe.git/blob - lib/sorter/govern.c
Added libucw from Sherlock v3.12.2.
[moe.git] / lib / sorter / govern.c
1 /*
2  *      UCW Library -- Universal Sorter: Governing Routines
3  *
4  *      (c) 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 #include "lib/lib.h"
11 #include "lib/fastbuf.h"
12 #include "lib/mempool.h"
13 #include "lib/stkstring.h"
14 #include "lib/sorter/common.h"
15
16 #include <string.h>
17 #include <sys/time.h>
18 #include <time.h>
19
20 #define F_BSIZE(b) stk_fsize(sbuck_size(b))
21
22 static void
23 sorter_start_timer(struct sort_context *ctx)
24 {
25   init_timer(&ctx->start_time);
26 }
27
28 static void
29 sorter_stop_timer(struct sort_context *ctx, uns *account_to)
30 {
31   ctx->last_pass_time = get_timer(&ctx->start_time);
32   *account_to += ctx->last_pass_time;
33 }
34
35 static uns
36 sorter_speed(struct sort_context *ctx, u64 size)
37 {
38   if (!size)
39     return 0;
40   if (!ctx->last_pass_time)
41     return 0;
42   return (uns)((double)size / (1<<20) * 1000 / ctx->last_pass_time);
43 }
44
45 static int
46 sorter_presort(struct sort_context *ctx, struct sort_bucket *in, struct sort_bucket *out, struct sort_bucket *out_only)
47 {
48   sorter_alloc_buf(ctx);
49   if (in->flags & SBF_CUSTOM_PRESORT)
50     {
51       /*
52        *  The trick with automatic joining, which we use for the normal presorter,
53        *  is not necessary with the custom presorter, because the custom presorter
54        *  is never called in the middle of the sorted data.
55        */
56       struct fastbuf *f = sbuck_write(out);
57       out->runs++;
58       return ctx->custom_presort(f, ctx->big_buf, ctx->big_buf_size);
59     }
60   return ctx->internal_sort(ctx, in, out, out_only);
61 }
62
63 static struct sort_bucket *
64 sbuck_join_to(struct sort_bucket *b, sh_off_t *sizep)
65 {
66   if (sorter_debug & SORT_DEBUG_NO_JOIN)
67     return NULL;
68
69   struct sort_bucket *out = (struct sort_bucket *) b->n.prev;   // Such bucket is guaranteed to exist
70   if (!(out->flags & SBF_FINAL))
71     return NULL;
72   ASSERT(out->runs == 1);
73   *sizep = sbuck_size(out);
74   return out;
75 }
76
77 static sh_off_t
78 sbuck_ins_or_join(struct sort_bucket *b, cnode *list_pos, struct sort_bucket *join, sh_off_t join_size)
79 {
80   if (join && join->runs >= 2)
81     {
82       if (b)
83         sbuck_drop(b);
84       ASSERT(join->runs == 2);
85       join->runs--;
86       return sbuck_size(join) - join_size;
87     }
88   else if (b)
89     {
90       clist_insert_after(&b->n, list_pos);
91       return sbuck_size(b);
92     }
93   else
94     return 0;
95 }
96
97 static void
98 sorter_join(struct sort_bucket *b)
99 {
100   struct sort_bucket *join = (struct sort_bucket *) b->n.prev;
101   ASSERT(join->flags & SBF_FINAL);
102   ASSERT(b->runs == 1);
103
104   if (!sbuck_has_file(join))
105     {
106       // The final bucket doesn't have any file associated yet, so replace
107       // it with the new bucket.
108       SORT_XTRACE(3, "Replaced final bucket");
109       b->flags |= SBF_FINAL;
110       sbuck_drop(join);
111     }
112   else
113     {
114       SORT_TRACE("Copying to output file: %s", F_BSIZE(b));
115       struct fastbuf *src = sbuck_read(b);
116       struct fastbuf *dest = sbuck_write(join);
117       bbcopy(src, dest, ~0U);
118       sbuck_drop(b);
119     }
120 }
121
122 static void
123 sorter_twoway(struct sort_context *ctx, struct sort_bucket *b)
124 {
125   struct sort_bucket *ins[3] = { NULL }, *outs[3] = { NULL };
126   cnode *list_pos = b->n.prev;
127   sh_off_t join_size;
128   struct sort_bucket *join = sbuck_join_to(b, &join_size);
129
130   if (!(sorter_debug & SORT_DEBUG_NO_PRESORT) || (b->flags & SBF_CUSTOM_PRESORT))
131     {
132       SORT_XTRACE(3, "%s", ((b->flags & SBF_CUSTOM_PRESORT) ? "Custom presorting" : "Presorting"));
133       sorter_start_timer(ctx);
134       ins[0] = sbuck_new(ctx);
135       if (!sorter_presort(ctx, b, ins[0], join ? : ins[0]))
136         {
137           sorter_stop_timer(ctx, &ctx->total_pre_time);
138           sh_off_t size = sbuck_ins_or_join(ins[0], list_pos, join, join_size);
139           SORT_XTRACE(((b->flags & SBF_SOURCE) ? 1 : 3), "Sorted in memory (%s, %dMB/s)", stk_fsize(size), sorter_speed(ctx, size));
140           sbuck_drop(b);
141           return;
142         }
143
144       ins[1] = sbuck_new(ctx);
145       int i = 1;
146       while (sorter_presort(ctx, b, ins[i], ins[i]))
147         i = 1-i;
148       sbuck_drop(b);
149       sorter_stop_timer(ctx, &ctx->total_pre_time);
150       SORT_TRACE("Presorting pass (%d+%d runs, %s+%s, %dMB/s)",
151                  ins[0]->runs, ins[1]->runs,
152                  F_BSIZE(ins[0]), F_BSIZE(ins[1]),
153                  sorter_speed(ctx, sbuck_size(ins[0]) + sbuck_size(ins[1])));
154     }
155   else
156     {
157       SORT_XTRACE(2, "Presorting disabled");
158       ins[0] = b;
159     }
160
161   SORT_XTRACE(3, "Main sorting");
162   uns pass = 0;
163   do {
164     ++pass;
165     sorter_start_timer(ctx);
166     if (ins[0]->runs <= 1 && ins[1]->runs <= 1 && join)
167       {
168         // This is guaranteed to produce a single run, so join if possible
169         outs[0] = join;
170         outs[1] = NULL;
171         ctx->twoway_merge(ctx, ins, outs);
172         sh_off_t size = sbuck_ins_or_join(NULL, NULL, join, join_size);
173         sorter_stop_timer(ctx, &ctx->total_ext_time);
174         SORT_TRACE("Mergesort pass %d (final run, %s, %dMB/s)", pass, stk_fsize(size), sorter_speed(ctx, size));
175         sbuck_drop(ins[0]);
176         sbuck_drop(ins[1]);
177         return;
178       }
179     outs[0] = sbuck_new(ctx);
180     outs[1] = sbuck_new(ctx);
181     outs[2] = NULL;
182     ctx->twoway_merge(ctx, ins, outs);
183     sorter_stop_timer(ctx, &ctx->total_ext_time);
184     SORT_TRACE("Mergesort pass %d (%d+%d runs, %s+%s, %dMB/s)", pass,
185                outs[0]->runs, outs[1]->runs,
186                F_BSIZE(outs[0]), F_BSIZE(outs[1]),
187                sorter_speed(ctx, sbuck_size(outs[0]) + sbuck_size(outs[1])));
188     sbuck_drop(ins[0]);
189     sbuck_drop(ins[1]);
190     memcpy(ins, outs, 3*sizeof(struct sort_bucket *));
191   } while (sbuck_have(ins[1]));
192
193   sbuck_drop(ins[1]);
194   clist_insert_after(&ins[0]->n, list_pos);
195 }
196
197 static void
198 sorter_multiway(struct sort_context *ctx, struct sort_bucket *b)
199 {
200   clist parts;
201   cnode *list_pos = b->n.prev;
202   sh_off_t join_size;
203   struct sort_bucket *join = sbuck_join_to(b, &join_size);
204   uns trace_level = (b->flags & SBF_SOURCE) ? 1 : 3;
205
206   clist_init(&parts);
207   ASSERT(!(sorter_debug & SORT_DEBUG_NO_PRESORT));
208   SORT_XTRACE(3, "%s", ((b->flags & SBF_CUSTOM_PRESORT) ? "Custom presorting" : "Presorting"));
209   uns cont;
210   uns part_cnt = 0;
211   u64 total_size = 0;
212   sorter_start_timer(ctx);
213   do
214     {
215       struct sort_bucket *p = sbuck_new(ctx);
216       cont = sorter_presort(ctx, b, p, (!part_cnt && join) ? join : p);
217       if (sbuck_have(p))
218         {
219           part_cnt++;
220           clist_add_tail(&parts, &p->n);
221           total_size += sbuck_size(p);
222           sbuck_swap_out(p);
223         }
224       else
225         sbuck_drop(p);
226     }
227   while (cont);
228   sorter_stop_timer(ctx, &ctx->total_pre_time);
229   sorter_free_buf(ctx);
230   sbuck_drop(b);
231
232   if (part_cnt <= 1)
233     {
234       sh_off_t size = sbuck_ins_or_join(clist_head(&parts), list_pos, (part_cnt ? NULL : join), join_size);
235       SORT_XTRACE(trace_level, "Sorted in memory (%s, %dMB/s)", stk_fsize(size), sorter_speed(ctx, size));
236       return;
237     }
238
239   SORT_TRACE("Multi-way presorting pass (%d parts, %s, %dMB/s)", part_cnt, stk_fsize(total_size), sorter_speed(ctx, total_size));
240
241   uns max_ways = 1 << sorter_max_multiway_bits;
242   struct sort_bucket *ways[max_ways+1];
243   SORT_XTRACE(3, "Starting up to %d-way merge", max_ways);
244   for (;;)
245     {
246       uns n = 0;
247       struct sort_bucket *p;
248       while (n < max_ways && (p = clist_head(&parts)))
249         {
250           clist_remove(&p->n);
251           ways[n++] = p;
252         }
253       ways[n] = NULL;
254       ASSERT(n > 1);
255
256       struct sort_bucket *out;
257       if (clist_empty(&parts) && join)
258         out = join;
259       else
260         out = sbuck_new(ctx);
261       sorter_start_timer(ctx);
262       ctx->multiway_merge(ctx, ways, out);
263       sorter_stop_timer(ctx, &ctx->total_ext_time);
264
265       for (uns i=0; i<n; i++)
266         sbuck_drop(ways[i]);
267
268       if (clist_empty(&parts))
269         {
270           sh_off_t size = sbuck_ins_or_join((join ? NULL : out), list_pos, join, join_size);
271           SORT_TRACE("Multi-way merge completed (%d ways, %s, %dMB/s)", n, stk_fsize(size), sorter_speed(ctx, size));
272           return;
273         }
274       else
275         {
276           sbuck_swap_out(out);
277           clist_add_tail(&parts, &out->n);
278           SORT_TRACE("Multi-way merge pass (%d ways, %s, %dMB/s)", n, F_BSIZE(out), sorter_speed(ctx, sbuck_size(out)));
279         }
280     }
281 }
282
283 static void
284 sorter_radix(struct sort_context *ctx, struct sort_bucket *b, uns bits)
285 {
286   // Add more bits if requested and allowed.
287   bits = MIN(bits + sorter_add_radix_bits, sorter_max_radix_bits);
288
289   uns nbuck = 1 << bits;
290   SORT_XTRACE(3, "Running radix split on %s with hash %d bits of %d (expecting %s buckets)",
291               F_BSIZE(b), bits, b->hash_bits, stk_fsize(sbuck_size(b) / nbuck));
292   sorter_free_buf(ctx);
293   sorter_start_timer(ctx);
294
295   struct sort_bucket **outs = alloca(nbuck * sizeof(struct sort_bucket *));
296   for (uns i=nbuck; i--; )
297     {
298       outs[i] = sbuck_new(ctx);
299       outs[i]->hash_bits = b->hash_bits - bits;
300       clist_insert_after(&outs[i]->n, &b->n);
301     }
302
303   ctx->radix_split(ctx, b, outs, b->hash_bits - bits, bits);
304
305   u64 min = ~(u64)0, max = 0, sum = 0;
306   for (uns i=0; i<nbuck; i++)
307     {
308       u64 s = sbuck_size(outs[i]);
309       min = MIN(min, s);
310       max = MAX(max, s);
311       sum += s;
312       if (nbuck > 4)
313         sbuck_swap_out(outs[i]);
314     }
315
316   sorter_stop_timer(ctx, &ctx->total_ext_time);
317   SORT_TRACE("Radix split (%d buckets, %s min, %s max, %s avg, %dMB/s)", nbuck,
318              stk_fsize(min), stk_fsize(max), stk_fsize(sum / nbuck), sorter_speed(ctx, sum));
319   sbuck_drop(b);
320 }
321
322 static void
323 sorter_decide(struct sort_context *ctx, struct sort_bucket *b)
324 {
325   // Drop empty buckets
326   if (!sbuck_have(b))
327     {
328       SORT_XTRACE(4, "Dropping empty bucket");
329       sbuck_drop(b);
330       return;
331     }
332
333   // How many bits of bucket size we have to reduce before it fits in the RAM?
334   // (this is insanely large if the input size is unknown, but it serves our purpose)
335   u64 insize = sbuck_size(b);
336   u64 mem = ctx->internal_estimate(ctx, b) * 0.8;       // Magical factor accounting for various non-uniformities
337   uns bits = 0;
338   while ((insize >> bits) > mem)
339     bits++;
340
341   // Calculate the possibilities of radix splits
342   uns radix_bits;
343   if (!ctx->radix_split ||
344       (b->flags & SBF_CUSTOM_PRESORT) ||
345       (sorter_debug & SORT_DEBUG_NO_RADIX))
346     radix_bits = 0;
347   else
348     {
349       radix_bits = MIN(bits, b->hash_bits);
350       radix_bits = MIN(radix_bits, sorter_max_radix_bits);
351       if (radix_bits < sorter_min_radix_bits)
352         radix_bits = 0;
353     }
354
355   // The same for multi-way merges
356   uns multiway_bits;
357   if (!ctx->multiway_merge ||
358       (sorter_debug & SORT_DEBUG_NO_MULTIWAY) ||
359       (sorter_debug & SORT_DEBUG_NO_PRESORT))
360     multiway_bits = 0;
361   else
362     {
363       multiway_bits = MIN(bits, sorter_max_multiway_bits);
364       if (multiway_bits < sorter_min_multiway_bits)
365         multiway_bits = 0;
366     }
367
368   SORT_XTRACE(3, "Decisions: size=%s max=%s runs=%d bits=%d hash=%d -> radix=%d multi=%d",
369         stk_fsize(insize), stk_fsize(mem), b->runs, bits, b->hash_bits,
370         radix_bits, multiway_bits);
371
372   // If the input already consists of a single run, just join it
373   if (b->runs)
374     return sorter_join(b);
375
376   // If everything fits in memory, the 2-way strategy will sort it in memory
377   if (!bits)
378     return sorter_twoway(ctx, b);
379
380   // If we can reduce everything in one pass, do so and prefer radix splits
381   if (radix_bits == bits)
382     return sorter_radix(ctx, b, radix_bits);
383   if (multiway_bits == bits)
384     return sorter_multiway(ctx, b);
385
386   // Otherwise, reduce as much as possible and again prefer radix splits
387   if (radix_bits)
388     return sorter_radix(ctx, b, radix_bits);
389   if (multiway_bits)
390     return sorter_multiway(ctx, b);
391
392   // Fall back to 2-way strategy if nothing else applies
393   return sorter_twoway(ctx, b);
394 }
395
396 void
397 sorter_run(struct sort_context *ctx)
398 {
399   ctx->pool = mp_new(4096);
400   clist_init(&ctx->bucket_list);
401   sorter_prepare_buf(ctx);
402   asort_start_threads(0);
403
404   // Create bucket containing the source
405   struct sort_bucket *bin = sbuck_new(ctx);
406   bin->flags = SBF_SOURCE | SBF_OPEN_READ;
407   if (ctx->custom_presort)
408     bin->flags |= SBF_CUSTOM_PRESORT;
409   else
410     bin->fb = ctx->in_fb;
411   bin->ident = "in";
412   bin->size = ctx->in_size;
413   bin->hash_bits = ctx->hash_bits;
414   clist_add_tail(&ctx->bucket_list, &bin->n);
415   SORT_XTRACE(2, "Input size: %s, %d hash bits", F_BSIZE(bin), bin->hash_bits);
416   ctx->fb_params = (bin->size < sorter_small_input) ? &sorter_small_fb_params : &sorter_fb_params;
417
418   // Create bucket for the output
419   struct sort_bucket *bout = sbuck_new(ctx);
420   bout->flags = SBF_FINAL;
421   if (bout->fb = ctx->out_fb)
422     bout->flags |= SBF_OPEN_WRITE;
423   bout->ident = "out";
424   bout->runs = 1;
425   clist_add_head(&ctx->bucket_list, &bout->n);
426
427   // Repeatedly sort buckets
428   struct sort_bucket *b;
429   while (bout = clist_head(&ctx->bucket_list), b = clist_next(&ctx->bucket_list, &bout->n))
430     sorter_decide(ctx, b);
431
432   asort_stop_threads();
433   sorter_free_buf(ctx);
434   sbuck_write(bout);            // Force empty bucket to a file
435   SORT_XTRACE(2, "Final size: %s", F_BSIZE(bout));
436   SORT_XTRACE(2, "Final timings: %.3fs external sorting, %.3fs presorting, %.3fs internal sorting",
437               ctx->total_ext_time/1000., ctx->total_pre_time/1000., ctx->total_int_time/1000.);
438   ctx->out_fb = sbuck_read(bout);
439   mp_delete(ctx->pool);
440 }