]> mj.ucw.cz Git - libucw.git/blob - lib/sorter/govern.c
b6dea908ee3ebc0686bd53ad5f0f1a67982fdebd
[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/sorter/common.h"
14
15 #include <string.h>
16 #include <sys/time.h>
17 #include <time.h>
18 #include <alloca.h>
19
20 #define F_SIZE(x) ({ byte *buf = alloca(16); format_size(buf, x); buf; })
21 #define F_BSIZE(b) F_SIZE(sbuck_size(b))
22
23 static u64
24 sorter_clock(void)
25 {
26   struct timeval tv;
27   gettimeofday(&tv, NULL);
28   return (u64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
29 }
30
31 static void
32 sorter_start_timer(struct sort_context *ctx)
33 {
34   ctx->start_time = sorter_clock();
35 }
36
37 static uns
38 sorter_speed(struct sort_context *ctx, u64 size)
39 {
40   u64 stop_time = sorter_clock();
41   if (!size)
42     return 0;
43   if (stop_time <= ctx->start_time)
44     return -1;
45   return (uns)((double)size / (1<<20) * 1000 / (stop_time-ctx->start_time));
46 }
47
48 static int
49 sorter_presort(struct sort_context *ctx, struct sort_bucket *in, struct sort_bucket *out, struct sort_bucket *out_only)
50 {
51   sorter_alloc_buf(ctx);
52   if (in->flags & SBF_CUSTOM_PRESORT)
53     {
54       struct fastbuf *f = sbuck_write(out);
55       out->runs++;
56       return ctx->custom_presort(f, ctx->big_buf, ctx->big_buf_size);   // FIXME: out_only optimization?
57     }
58   return ctx->internal_sort(ctx, in, out, out_only);
59 }
60
61 static inline struct sort_bucket *
62 sbuck_join_to(struct sort_bucket *b)
63 {
64   if (sorter_debug & SORT_DEBUG_NO_JOIN)
65     return NULL;
66
67   struct sort_bucket *out = (struct sort_bucket *) b->n.prev;   // Such bucket is guaranteed to exist
68   return (out->flags & SBF_FINAL) ? out : NULL;
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           SORT_XTRACE(((b->flags & SBF_SOURCE) ? 1 : 2), "Sorted in memory");
111           if (join)
112             sbuck_drop(ins[0]);
113           else
114             clist_insert_after(&ins[0]->n, list_pos);
115           sbuck_drop(b);
116           return;
117         }
118
119       ins[1] = sbuck_new(ctx);
120       int i = 1;
121       while (sorter_presort(ctx, b, ins[i], ins[i]))
122         i = 1-i;
123       sbuck_drop(b);
124       SORT_TRACE("Presorting pass (%d+%d runs, %s+%s, %dMB/s)",
125                  ins[0]->runs, ins[1]->runs,
126                  F_BSIZE(ins[0]), F_BSIZE(ins[1]),
127                  sorter_speed(ctx, sbuck_size(ins[0]) + sbuck_size(ins[1])));
128     }
129   else
130     {
131       SORT_XTRACE(2, "Presorting disabled");
132       ins[0] = b;
133     }
134
135   SORT_XTRACE(3, "Main sorting");
136   uns pass = 0;
137   do {
138     ++pass;
139     sorter_start_timer(ctx);
140     if (ins[0]->runs == 1 && ins[1]->runs == 1 && join)
141       {
142         // This is guaranteed to produce a single run, so join if possible
143         sh_off_t join_size = sbuck_size(join);
144         outs[0] = join;
145         outs[1] = NULL;
146         ctx->twoway_merge(ctx, ins, outs);
147         ASSERT(join->runs == 2);
148         join->runs--;
149         join_size = sbuck_size(join) - join_size;
150         SORT_TRACE("Mergesort pass %d (final run, %s, %dMB/s)", pass, F_SIZE(join_size), sorter_speed(ctx, join_size));
151         sbuck_drop(ins[0]);
152         sbuck_drop(ins[1]);
153         return;
154       }
155     outs[0] = sbuck_new(ctx);
156     outs[1] = sbuck_new(ctx);
157     outs[2] = NULL;
158     ctx->twoway_merge(ctx, ins, outs);
159     SORT_TRACE("Mergesort pass %d (%d+%d runs, %s+%s, %dMB/s)", pass,
160                outs[0]->runs, outs[1]->runs,
161                F_BSIZE(outs[0]), F_BSIZE(outs[1]),
162                sorter_speed(ctx, sbuck_size(outs[0]) + sbuck_size(outs[1])));
163     sbuck_drop(ins[0]);
164     sbuck_drop(ins[1]);
165     memcpy(ins, outs, 3*sizeof(struct sort_bucket *));
166   } while (sbuck_have(ins[1]));
167
168   sbuck_drop(ins[1]);
169   clist_insert_after(&ins[0]->n, list_pos);
170 }
171
172 static int
173 sorter_radix_p(struct sort_context *ctx, struct sort_bucket *b)
174 {
175   return b->hash_bits && ctx->radix_split &&
176     !(sorter_debug & SORT_DEBUG_NO_RADIX) &&
177     sbuck_size(b) > (sh_off_t)sorter_bufsize;
178 }
179
180 static void
181 sorter_radix(struct sort_context *ctx, struct sort_bucket *b)
182 {
183   uns bits = MIN(b->hash_bits, 4);      /* FIXME */
184   uns nbuck = 1 << bits;
185   SORT_XTRACE(2, "Running radix sort on %s with %d bits of %d", F_BSIZE(b), bits, b->hash_bits);
186   sorter_start_timer(ctx);
187
188   struct sort_bucket **outs = alloca(nbuck * sizeof(struct sort_bucket *));
189   for (uns i=nbuck; i--; )
190     {
191       outs[i] = sbuck_new(ctx);
192       outs[i]->hash_bits = b->hash_bits - bits;
193       clist_insert_after(&outs[i]->n, &b->n);
194     }
195
196   ctx->radix_split(ctx, b, outs, b->hash_bits - bits, bits);
197
198   u64 min = ~(u64)0, max = 0, sum = 0;
199   for (uns i=0; i<nbuck; i++)
200     {
201       u64 s = sbuck_size(outs[i]);
202       min = MIN(min, s);
203       max = MAX(max, s);
204       sum += s;
205     }
206
207   SORT_TRACE("Radix split (%d buckets, %s min, %s max, %s avg, %dMB/s)", nbuck,
208              F_SIZE(min), F_SIZE(max), F_SIZE(sum / nbuck), sorter_speed(ctx, sum));
209   sbuck_drop(b);
210 }
211
212 void
213 sorter_run(struct sort_context *ctx)
214 {
215   ctx->pool = mp_new(4096);
216   clist_init(&ctx->bucket_list);
217
218   /* FIXME: Remember to test sorting of empty files */
219
220   // Create bucket containing the source
221   struct sort_bucket *bin = sbuck_new(ctx);
222   bin->flags = SBF_SOURCE | SBF_OPEN_READ;
223   if (ctx->custom_presort)
224     bin->flags |= SBF_CUSTOM_PRESORT;
225   else
226     bin->fb = ctx->in_fb;
227   bin->ident = "in";
228   bin->size = ctx->in_size;             /* FIXME: Sizes should be either sh_off_t or u64, not both; beware of ~0U */
229   bin->hash_bits = ctx->hash_bits;
230   clist_add_tail(&ctx->bucket_list, &bin->n);
231   SORT_XTRACE(2, "Input size: %s", F_BSIZE(bin));
232
233   // Create bucket for the output
234   struct sort_bucket *bout = sbuck_new(ctx);
235   bout->flags = SBF_FINAL;
236   if (bout->fb = ctx->out_fb)
237     bout->flags |= SBF_OPEN_WRITE;
238   bout->ident = "out";
239   bout->runs = 1;
240   clist_add_head(&ctx->bucket_list, &bout->n);
241
242   struct sort_bucket *b;
243   while (bout = clist_head(&ctx->bucket_list), b = clist_next(&ctx->bucket_list, &bout->n))
244     {
245       SORT_XTRACE(2, "Next block: %s, %d hash bits", F_BSIZE(b), b->hash_bits);
246       if (!sbuck_have(b))
247         sbuck_drop(b);
248       else if (b->runs == 1)
249         sorter_join(b);
250       else if (sorter_radix_p(ctx, b))
251         sorter_radix(ctx, b);
252       else
253         sorter_twoway(ctx, b);
254     }
255
256   sorter_free_buf(ctx);
257   sbuck_write(bout);            // Force empty bucket to a file
258   SORT_XTRACE(2, "Final size: %s", F_BSIZE(bout));
259   ctx->out_fb = sbuck_read(bout);
260 }