]> mj.ucw.cz Git - libucw.git/blob - lib/sorter/govern.c
087720e125e17d6adc267c5017989fa41ac4494f
[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   ctx->start_time = get_timestamp();
26 }
27
28 static uns
29 sorter_speed(struct sort_context *ctx, u64 size, uns *account_to)
30 {
31   timestamp_t stop_time = get_timestamp();
32   if (!size)
33     return 0;
34   if (stop_time <= ctx->start_time)
35     return -1;
36   *account_to += stop_time - ctx->start_time;
37   return (uns)((double)size / (1<<20) * 1000 / (stop_time-ctx->start_time));
38 }
39
40 static int
41 sorter_presort(struct sort_context *ctx, struct sort_bucket *in, struct sort_bucket *out, struct sort_bucket *out_only)
42 {
43   sorter_alloc_buf(ctx);
44   if (in->flags & SBF_CUSTOM_PRESORT)
45     {
46       struct fastbuf *f = sbuck_write(out);
47       out->runs++;
48       return ctx->custom_presort(f, ctx->big_buf, ctx->big_buf_size);   // FIXME: out_only optimization?
49     }
50   return ctx->internal_sort(ctx, in, out, out_only);
51 }
52
53 static inline struct sort_bucket *
54 sbuck_join_to(struct sort_bucket *b)
55 {
56   if (sorter_debug & SORT_DEBUG_NO_JOIN)
57     return NULL;
58
59   struct sort_bucket *out = (struct sort_bucket *) b->n.prev;   // Such bucket is guaranteed to exist
60   return (out->flags & SBF_FINAL) ? out : NULL;
61 }
62
63 static void
64 sorter_join(struct sort_bucket *b)
65 {
66   struct sort_bucket *join = (struct sort_bucket *) b->n.prev;
67   ASSERT(join->flags & SBF_FINAL);
68   ASSERT(b->runs == 1);
69
70   if (!sbuck_has_file(join))
71     {
72       // The final bucket doesn't have any file associated yet, so replace
73       // it with the new bucket.
74       SORT_XTRACE(2, "Replaced final bucket");
75       b->flags |= SBF_FINAL;
76       sbuck_drop(join);
77     }
78   else
79     {
80       SORT_TRACE("Copying to output file: %s", F_BSIZE(b));
81       struct fastbuf *src = sbuck_read(b);
82       struct fastbuf *dest = sbuck_write(join);
83       bbcopy(src, dest, ~0U);
84       sbuck_drop(b);
85     }
86 }
87
88 static void
89 sorter_twoway(struct sort_context *ctx, struct sort_bucket *b)
90 {
91   struct sort_bucket *ins[3] = { NULL }, *outs[3] = { NULL };
92   cnode *list_pos = b->n.prev;
93   struct sort_bucket *join = sbuck_join_to(b);
94
95   if (!(sorter_debug & SORT_DEBUG_NO_PRESORT) || (b->flags & SBF_CUSTOM_PRESORT))
96     {
97       SORT_XTRACE(3, "%s", ((b->flags & SBF_CUSTOM_PRESORT) ? "Custom presorting" : "Presorting"));
98       sorter_start_timer(ctx);
99       ins[0] = sbuck_new(ctx);
100       if (!sorter_presort(ctx, b, ins[0], join ? : ins[0]))
101         {
102           SORT_XTRACE(((b->flags & SBF_SOURCE) ? 1 : 2), "Sorted in memory");
103           if (join)
104             sbuck_drop(ins[0]);
105           else
106             clist_insert_after(&ins[0]->n, list_pos);
107           sbuck_drop(b);
108           return;
109         }
110
111       ins[1] = sbuck_new(ctx);
112       int i = 1;
113       while (sorter_presort(ctx, b, ins[i], ins[i]))
114         i = 1-i;
115       sbuck_drop(b);
116       SORT_TRACE("Presorting pass (%d+%d runs, %s+%s, %dMB/s)",
117                  ins[0]->runs, ins[1]->runs,
118                  F_BSIZE(ins[0]), F_BSIZE(ins[1]),
119                  sorter_speed(ctx, sbuck_size(ins[0]) + sbuck_size(ins[1]), &ctx->total_pre_time));
120     }
121   else
122     {
123       SORT_XTRACE(2, "Presorting disabled");
124       ins[0] = b;
125     }
126
127   SORT_XTRACE(3, "Main sorting");
128   uns pass = 0;
129   do {
130     ++pass;
131     sorter_start_timer(ctx);
132     if (ins[0]->runs == 1 && ins[1]->runs == 1 && join)
133       {
134         // This is guaranteed to produce a single run, so join if possible
135         sh_off_t join_size = sbuck_size(join);
136         outs[0] = join;
137         outs[1] = NULL;
138         ctx->twoway_merge(ctx, ins, outs);
139         ASSERT(join->runs == 2);
140         join->runs--;
141         join_size = sbuck_size(join) - join_size;
142         SORT_TRACE("Mergesort pass %d (final run, %s, %dMB/s)", pass, stk_fsize(join_size), sorter_speed(ctx, join_size, &ctx->total_ext_time));
143         sbuck_drop(ins[0]);
144         sbuck_drop(ins[1]);
145         return;
146       }
147     outs[0] = sbuck_new(ctx);
148     outs[1] = sbuck_new(ctx);
149     outs[2] = NULL;
150     ctx->twoway_merge(ctx, ins, outs);
151     SORT_TRACE("Mergesort pass %d (%d+%d runs, %s+%s, %dMB/s)", pass,
152                outs[0]->runs, outs[1]->runs,
153                F_BSIZE(outs[0]), F_BSIZE(outs[1]),
154                sorter_speed(ctx, sbuck_size(outs[0]) + sbuck_size(outs[1]), &ctx->total_ext_time));
155     sbuck_drop(ins[0]);
156     sbuck_drop(ins[1]);
157     memcpy(ins, outs, 3*sizeof(struct sort_bucket *));
158   } while (sbuck_have(ins[1]));
159
160   sbuck_drop(ins[1]);
161   clist_insert_after(&ins[0]->n, list_pos);
162 }
163
164 static uns
165 sorter_radix_bits(struct sort_context *ctx, struct sort_bucket *b)
166 {
167   if (!b->hash_bits || !ctx->radix_split ||
168       (b->flags & SBF_CUSTOM_PRESORT) ||
169       (sorter_debug & SORT_DEBUG_NO_RADIX))
170     return 0;
171
172   u64 in = sbuck_size(b);
173   u64 mem = ctx->internal_estimate(ctx, b) * 0.8;       // FIXME: Magical factor for hash non-uniformity
174   if (in <= mem)
175     return 0;
176
177   uns n = sorter_min_radix_bits;
178   while (n < sorter_max_radix_bits && n < b->hash_bits && (in >> n) > mem)
179     n++;
180   return n;
181 }
182
183 static void
184 sorter_radix(struct sort_context *ctx, struct sort_bucket *b, uns bits)
185 {
186   uns nbuck = 1 << bits;
187   SORT_XTRACE(2, "Running radix split on %s with hash %d bits of %d (expecting %s buckets)",
188               F_BSIZE(b), bits, b->hash_bits, stk_fsize(sbuck_size(b) / nbuck));
189   sorter_free_buf(ctx);
190   sorter_start_timer(ctx);
191
192   struct sort_bucket **outs = alloca(nbuck * sizeof(struct sort_bucket *));
193   for (uns i=nbuck; i--; )
194     {
195       outs[i] = sbuck_new(ctx);
196       outs[i]->hash_bits = b->hash_bits - bits;
197       clist_insert_after(&outs[i]->n, &b->n);
198     }
199
200   ctx->radix_split(ctx, b, outs, b->hash_bits - bits, bits);
201
202   u64 min = ~(u64)0, max = 0, sum = 0;
203   for (uns i=0; i<nbuck; i++)
204     {
205       u64 s = sbuck_size(outs[i]);
206       min = MIN(min, s);
207       max = MAX(max, s);
208       sum += s;
209       if (nbuck > 4)
210         sbuck_swap_out(outs[i]);
211     }
212
213   SORT_TRACE("Radix split (%d buckets, %s min, %s max, %s avg, %dMB/s)", nbuck,
214              stk_fsize(min), stk_fsize(max), stk_fsize(sum / nbuck), sorter_speed(ctx, sum, &ctx->total_ext_time));
215   sbuck_drop(b);
216 }
217
218 void
219 sorter_run(struct sort_context *ctx)
220 {
221   ctx->pool = mp_new(4096);
222   clist_init(&ctx->bucket_list);
223   sorter_prepare_buf(ctx);
224
225   // Create bucket containing the source
226   struct sort_bucket *bin = sbuck_new(ctx);
227   bin->flags = SBF_SOURCE | SBF_OPEN_READ;
228   if (ctx->custom_presort)
229     bin->flags |= SBF_CUSTOM_PRESORT;
230   else
231     bin->fb = ctx->in_fb;
232   bin->ident = "in";
233   bin->size = ctx->in_size;
234   bin->hash_bits = ctx->hash_bits;
235   clist_add_tail(&ctx->bucket_list, &bin->n);
236   SORT_XTRACE(2, "Input size: %s", F_BSIZE(bin));
237
238   // Create bucket for the output
239   struct sort_bucket *bout = sbuck_new(ctx);
240   bout->flags = SBF_FINAL;
241   if (bout->fb = ctx->out_fb)
242     bout->flags |= SBF_OPEN_WRITE;
243   bout->ident = "out";
244   bout->runs = 1;
245   clist_add_head(&ctx->bucket_list, &bout->n);
246
247   struct sort_bucket *b;
248   uns bits;
249   while (bout = clist_head(&ctx->bucket_list), b = clist_next(&ctx->bucket_list, &bout->n))
250     {
251       SORT_XTRACE(2, "Next block: %s, %d hash bits", F_BSIZE(b), b->hash_bits);
252       if (!sbuck_have(b))
253         sbuck_drop(b);
254       else if (b->runs == 1)
255         sorter_join(b);
256       else if (bits = sorter_radix_bits(ctx, b))
257         sorter_radix(ctx, b, bits);
258       else
259         sorter_twoway(ctx, b);
260     }
261
262   sorter_free_buf(ctx);
263   sbuck_write(bout);            // Force empty bucket to a file
264   SORT_XTRACE(2, "Final size: %s", F_BSIZE(bout));
265   SORT_XTRACE(2, "Final timings: %.3fs external sorting, %.3fs presorting, %.3fs internal sorting",
266               ctx->total_ext_time/1000., ctx->total_pre_time/1000., ctx->total_int_time/1000.);
267   ctx->out_fb = sbuck_read(bout);
268 }