2 * UCW Library -- Universal Sorter: Operations on Contexts, Buffers and Buckets
4 * (c) 2007 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 #include "lib/fastbuf.h"
12 #include "lib/mempool.h"
13 #include "lib/stkstring.h"
14 #include "lib/sorter/common.h"
19 sorter_alloc(struct sort_context *ctx, uns size)
21 return mp_alloc_zero(ctx->pool, size);
25 sbuck_new(struct sort_context *ctx)
27 struct sort_bucket *b = sorter_alloc(ctx, sizeof(struct sort_bucket));
33 sbuck_drop(struct sort_bucket *b)
37 ASSERT(!(b->flags & SBF_DESTROYED));
42 b->flags = SBF_DESTROYED;
47 sbuck_size(struct sort_bucket *b)
49 if ((b->flags & SBF_OPEN_WRITE) && !(b->flags & SBF_SWAPPED_OUT))
56 sbuck_have(struct sort_bucket *b)
58 return b && sbuck_size(b);
62 sbuck_has_file(struct sort_bucket *b)
64 return (b->fb || (b->flags & SBF_SWAPPED_OUT));
68 sbuck_swap_in(struct sort_bucket *b)
70 if (b->flags & SBF_SWAPPED_OUT)
72 b->fb = bopen_file(b->filename, O_RDWR, &sorter_fb_params); /* FIXME: Something different for small buckets? */
73 if (b->flags & SBF_OPEN_WRITE)
74 bseek(b->fb, 0, SEEK_END);
75 bconfig(b->fb, BCONFIG_IS_TEMP_FILE, 1);
76 b->flags &= ~SBF_SWAPPED_OUT;
77 SORT_XTRACE(3, "Swapped in %s", b->filename);
82 sbuck_read(struct sort_bucket *b)
85 if (b->flags & SBF_OPEN_READ)
87 else if (b->flags & SBF_OPEN_WRITE)
89 b->size = btell(b->fb);
90 b->flags = (b->flags & ~SBF_OPEN_WRITE) | SBF_OPEN_READ;
99 sbuck_write(struct sort_bucket *b)
102 if (b->flags & SBF_OPEN_WRITE)
106 ASSERT(!(b->flags & (SBF_OPEN_READ | SBF_DESTROYED)));
107 b->fb = bopen_tmp_file(&sorter_fb_params);
108 if (sorter_debug & SORT_DEBUG_KEEP_BUCKETS)
109 bconfig(b->fb, BCONFIG_IS_TEMP_FILE, 0);
110 b->flags |= SBF_OPEN_WRITE;
111 b->filename = mp_strdup(b->ctx->pool, b->fb->name);
117 sbuck_swap_out(struct sort_bucket *b)
119 if ((b->flags & (SBF_OPEN_READ | SBF_OPEN_WRITE)) && b->fb && !(b->flags & SBF_SOURCE))
121 if (b->flags & SBF_OPEN_WRITE)
122 b->size = btell(b->fb);
123 bconfig(b->fb, BCONFIG_IS_TEMP_FILE, 0);
126 b->flags |= SBF_SWAPPED_OUT;
127 SORT_XTRACE(3, "Swapped out %s", b->filename);
132 sorter_prepare_buf(struct sort_context *ctx)
134 u64 bs = sorter_bufsize;
135 bs = ALIGN_TO(bs, (u64)CPU_PAGE_SIZE);
136 bs = MAX(bs, 2*(u64)CPU_PAGE_SIZE);
137 ctx->big_buf_size = bs;
141 sorter_alloc_buf(struct sort_context *ctx)
145 ctx->big_buf = big_alloc(ctx->big_buf_size);
146 SORT_XTRACE(2, "Allocated sorting buffer (%s)", stk_fsize(ctx->big_buf_size));
150 sorter_free_buf(struct sort_context *ctx)
154 big_free(ctx->big_buf, ctx->big_buf_size);
156 SORT_XTRACE(2, "Freed sorting buffer");