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