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