]> mj.ucw.cz Git - libucw.git/blob - lib/sorter/govern.c
format_size() no longer exists.
[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);   // FIXME: out_only optimization?
54     }
55   return ctx->internal_sort(ctx, in, out, out_only);
56 }
57
58 static inline struct sort_bucket *
59 sbuck_join_to(struct sort_bucket *b)
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   return out;
69 }
70
71 static void
72 sorter_join(struct sort_bucket *b)
73 {
74   struct sort_bucket *join = (struct sort_bucket *) b->n.prev;
75   ASSERT(join->flags & SBF_FINAL);
76   ASSERT(b->runs == 1);
77
78   if (!sbuck_has_file(join))
79     {
80       // The final bucket doesn't have any file associated yet, so replace
81       // it with the new bucket.
82       SORT_XTRACE(2, "Replaced final bucket");
83       b->flags |= SBF_FINAL;
84       sbuck_drop(join);
85     }
86   else
87     {
88       SORT_TRACE("Copying to output file: %s", F_BSIZE(b));
89       struct fastbuf *src = sbuck_read(b);
90       struct fastbuf *dest = sbuck_write(join);
91       bbcopy(src, dest, ~0U);
92       sbuck_drop(b);
93     }
94 }
95
96 static void
97 sorter_twoway(struct sort_context *ctx, struct sort_bucket *b)
98 {
99   struct sort_bucket *ins[3] = { NULL }, *outs[3] = { NULL };
100   cnode *list_pos = b->n.prev;
101   struct sort_bucket *join = sbuck_join_to(b);
102
103   if (!(sorter_debug & SORT_DEBUG_NO_PRESORT) || (b->flags & SBF_CUSTOM_PRESORT))
104     {
105       SORT_XTRACE(3, "%s", ((b->flags & SBF_CUSTOM_PRESORT) ? "Custom presorting" : "Presorting"));
106       sorter_start_timer(ctx);
107       ins[0] = sbuck_new(ctx);
108       if (!sorter_presort(ctx, b, ins[0], join ? : ins[0]))
109         {
110           sorter_stop_timer(ctx, &ctx->total_pre_time);
111           SORT_XTRACE(((b->flags & SBF_SOURCE) ? 1 : 2), "Sorted in memory");
112           if (join)
113             {
114               ASSERT(join->runs == 2);
115               join->runs--;
116               sbuck_drop(ins[0]);
117             }
118           else
119             clist_insert_after(&ins[0]->n, list_pos);
120           sbuck_drop(b);
121           return;
122         }
123
124       ins[1] = sbuck_new(ctx);
125       int i = 1;
126       while (sorter_presort(ctx, b, ins[i], ins[i]))
127         i = 1-i;
128       sbuck_drop(b);
129       sorter_stop_timer(ctx, &ctx->total_pre_time);
130       SORT_TRACE("Presorting pass (%d+%d runs, %s+%s, %dMB/s)",
131                  ins[0]->runs, ins[1]->runs,
132                  F_BSIZE(ins[0]), F_BSIZE(ins[1]),
133                  sorter_speed(ctx, sbuck_size(ins[0]) + sbuck_size(ins[1])));
134     }
135   else
136     {
137       SORT_XTRACE(2, "Presorting disabled");
138       ins[0] = b;
139     }
140
141   SORT_XTRACE(3, "Main sorting");
142   uns pass = 0;
143   do {
144     ++pass;
145     sorter_start_timer(ctx);
146     if (ins[0]->runs == 1 && ins[1]->runs == 1 && join)
147       {
148         // This is guaranteed to produce a single run, so join if possible
149         sh_off_t join_size = sbuck_size(join);
150         outs[0] = join;
151         outs[1] = NULL;
152         ctx->twoway_merge(ctx, ins, outs);
153         ASSERT(join->runs == 2);
154         join->runs--;
155         join_size = sbuck_size(join) - join_size;
156         sorter_stop_timer(ctx, &ctx->total_ext_time);
157         SORT_TRACE("Mergesort pass %d (final run, %s, %dMB/s)", pass, stk_fsize(join_size), sorter_speed(ctx, join_size));
158         sbuck_drop(ins[0]);
159         sbuck_drop(ins[1]);
160         return;
161       }
162     outs[0] = sbuck_new(ctx);
163     outs[1] = sbuck_new(ctx);
164     outs[2] = NULL;
165     ctx->twoway_merge(ctx, ins, outs);
166     sorter_stop_timer(ctx, &ctx->total_ext_time);
167     SORT_TRACE("Mergesort pass %d (%d+%d runs, %s+%s, %dMB/s)", pass,
168                outs[0]->runs, outs[1]->runs,
169                F_BSIZE(outs[0]), F_BSIZE(outs[1]),
170                sorter_speed(ctx, sbuck_size(outs[0]) + sbuck_size(outs[1])));
171     sbuck_drop(ins[0]);
172     sbuck_drop(ins[1]);
173     memcpy(ins, outs, 3*sizeof(struct sort_bucket *));
174   } while (sbuck_have(ins[1]));
175
176   sbuck_drop(ins[1]);
177   clist_insert_after(&ins[0]->n, list_pos);
178 }
179
180 static void
181 sorter_multiway(struct sort_context *ctx, struct sort_bucket *b)
182 {
183   clist parts;
184   cnode *list_pos = b->n.prev;
185   struct sort_bucket *join = sbuck_join_to(b);
186
187   clist_init(&parts);
188   ASSERT(!(sorter_debug & SORT_DEBUG_NO_PRESORT));
189   // FIXME: What if the parts will be too small?
190   SORT_XTRACE(3, "%s", ((b->flags & SBF_CUSTOM_PRESORT) ? "Custom presorting" : "Presorting"));
191   uns cont;
192   uns part_cnt = 0;
193   u64 total_size = 0;
194   sorter_start_timer(ctx);
195   do
196     {
197       struct sort_bucket *p = sbuck_new(ctx);
198       clist_add_tail(&parts, &p->n);
199       cont = sorter_presort(ctx, b, p, (!part_cnt && join) ? join : p);
200       part_cnt++;
201       total_size += sbuck_size(p);
202     }
203   while (cont);
204   sorter_stop_timer(ctx, &ctx->total_pre_time);
205
206   // FIXME: This is way too similar to the two-way case.
207   if (part_cnt == 1)
208     {
209       struct sort_bucket *p = clist_head(&parts);
210       SORT_XTRACE(((b->flags & SBF_SOURCE) ? 1 : 2), "Sorted in memory");
211       if (join)
212         {
213           ASSERT(join->runs == 2);
214           join->runs--;
215           sbuck_drop(b);
216         }
217       else
218         clist_insert_after(&p->n, list_pos);
219       sbuck_drop(b);
220       return;
221     }
222
223   SORT_TRACE("Multi-way presorting pass (%d parts, %s, %dMB/s)", part_cnt, stk_fsize(total_size), sorter_speed(ctx, total_size));
224   sbuck_drop(b);
225
226   uns max_ways = 16;
227   struct sort_bucket *ways[max_ways+1];
228   SORT_XTRACE(2, "Starting up to %d-way merge", max_ways);
229   for (;;)
230     {
231       uns n = 0;
232       struct sort_bucket *p;
233       while (n < max_ways && (p = clist_head(&parts)))
234         {
235           clist_remove(&p->n);
236           ways[n++] = p;
237         }
238       ways[n] = NULL;
239       ASSERT(n > 1);
240
241       struct sort_bucket *out;
242       out = sbuck_new(ctx);             // FIXME: No joining so far
243       sorter_start_timer(ctx);
244       ctx->multiway_merge(ctx, ways, out);
245       sorter_stop_timer(ctx, &ctx->total_ext_time);
246
247       for (uns i=0; i<n; i++)
248         sbuck_drop(ways[i]);
249
250       if (clist_empty(&parts))
251         {
252           clist_insert_after(&out->n, list_pos);
253           SORT_TRACE("Multi-way merge completed (%s, %dMB/s)", F_BSIZE(out), sorter_speed(ctx, sbuck_size(out)));
254           return;
255         }
256       else
257         {
258           clist_add_tail(&parts, &out->n);
259           SORT_TRACE("Multi-way merge pass (%d ways, %s, %dMB/s)", n, F_BSIZE(out), sorter_speed(ctx, sbuck_size(out)));
260         }
261     }
262 }
263
264 static uns
265 sorter_radix_bits(struct sort_context *ctx, struct sort_bucket *b)
266 {
267   if (!b->hash_bits || b->hash_bits < sorter_min_radix_bits ||
268       !ctx->radix_split ||
269       (b->flags & SBF_CUSTOM_PRESORT) ||
270       (sorter_debug & SORT_DEBUG_NO_RADIX))
271     return 0;
272
273   u64 in = sbuck_size(b);
274   u64 mem = ctx->internal_estimate(ctx, b) * 0.8;       // FIXME: Magical factor for hash non-uniformity
275   if (in <= mem)
276     return 0;
277
278   uns n = sorter_min_radix_bits;
279   while (n < sorter_max_radix_bits && n < b->hash_bits && (in >> n) > mem)
280     n++;
281   return n;
282 }
283
284 static void
285 sorter_radix(struct sort_context *ctx, struct sort_bucket *b, uns bits)
286 {
287   uns nbuck = 1 << bits;
288   SORT_XTRACE(2, "Running radix split on %s with hash %d bits of %d (expecting %s buckets)",
289               F_BSIZE(b), bits, b->hash_bits, stk_fsize(sbuck_size(b) / nbuck));
290   sorter_free_buf(ctx);
291   sorter_start_timer(ctx);
292
293   struct sort_bucket **outs = alloca(nbuck * sizeof(struct sort_bucket *));
294   for (uns i=nbuck; i--; )
295     {
296       outs[i] = sbuck_new(ctx);
297       outs[i]->hash_bits = b->hash_bits - bits;
298       clist_insert_after(&outs[i]->n, &b->n);
299     }
300
301   ctx->radix_split(ctx, b, outs, b->hash_bits - bits, bits);
302
303   u64 min = ~(u64)0, max = 0, sum = 0;
304   for (uns i=0; i<nbuck; i++)
305     {
306       u64 s = sbuck_size(outs[i]);
307       min = MIN(min, s);
308       max = MAX(max, s);
309       sum += s;
310       if (nbuck > 4)
311         sbuck_swap_out(outs[i]);
312     }
313
314   sorter_stop_timer(ctx, &ctx->total_ext_time);
315   SORT_TRACE("Radix split (%d buckets, %s min, %s max, %s avg, %dMB/s)", nbuck,
316              stk_fsize(min), stk_fsize(max), stk_fsize(sum / nbuck), sorter_speed(ctx, sum));
317   sbuck_drop(b);
318 }
319
320 void
321 sorter_run(struct sort_context *ctx)
322 {
323   ctx->pool = mp_new(4096);
324   clist_init(&ctx->bucket_list);
325   sorter_prepare_buf(ctx);
326
327   // Create bucket containing the source
328   struct sort_bucket *bin = sbuck_new(ctx);
329   bin->flags = SBF_SOURCE | SBF_OPEN_READ;
330   if (ctx->custom_presort)
331     bin->flags |= SBF_CUSTOM_PRESORT;
332   else
333     bin->fb = ctx->in_fb;
334   bin->ident = "in";
335   bin->size = ctx->in_size;
336   bin->hash_bits = ctx->hash_bits;
337   clist_add_tail(&ctx->bucket_list, &bin->n);
338   SORT_XTRACE(2, "Input size: %s, %d hash bits", F_BSIZE(bin), bin->hash_bits);
339
340   // Create bucket for the output
341   struct sort_bucket *bout = sbuck_new(ctx);
342   bout->flags = SBF_FINAL;
343   if (bout->fb = ctx->out_fb)
344     bout->flags |= SBF_OPEN_WRITE;
345   bout->ident = "out";
346   bout->runs = 1;
347   clist_add_head(&ctx->bucket_list, &bout->n);
348
349   struct sort_bucket *b;
350   uns bits;
351   while (bout = clist_head(&ctx->bucket_list), b = clist_next(&ctx->bucket_list, &bout->n))
352     {
353       SORT_XTRACE(2, "Next block: %s, %d hash bits", F_BSIZE(b), b->hash_bits);
354       if (!sbuck_have(b))
355         sbuck_drop(b);
356       else if (b->runs == 1)
357         sorter_join(b);
358       else if (ctx->multiway_merge && !(sorter_debug & (SORT_DEBUG_NO_MULTIWAY | SORT_DEBUG_NO_PRESORT)))       // FIXME: Just kidding...
359         sorter_multiway(ctx, b);
360       else if (bits = sorter_radix_bits(ctx, b))
361         sorter_radix(ctx, b, bits);
362       else
363         sorter_twoway(ctx, b);
364     }
365
366   sorter_free_buf(ctx);
367   sbuck_write(bout);            // Force empty bucket to a file
368   SORT_XTRACE(2, "Final size: %s", F_BSIZE(bout));
369   SORT_XTRACE(2, "Final timings: %.3fs external sorting, %.3fs presorting, %.3fs internal sorting",
370               ctx->total_ext_time/1000., ctx->total_pre_time/1000., ctx->total_int_time/1000.);
371   ctx->out_fb = sbuck_read(bout);
372 }