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