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