Debian Codegraph @

buffer.c

raw symbols SCIP
1 /*
2 * buffer.c
3 * Manages data reading and caching.
4 *
5 * Copyright (c) 2003 Christoph Pfisterer
6 *
7 * Permission is hereby granted, free of charge, to any person
8 * obtaining a copy of this software and associated documentation
9 * files (the "Software"), to deal in the Software without
10 * restriction, including without limitation the rights to use, copy,
11 * modify, merge, publish, distribute, sublicense, and/or sell copies
12 * of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be
16 * included in all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
22 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
23 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 * SOFTWARE.
26 */
27
28 #include "global.h"
29
30 #define PROFILE 0
31
32 /*
33 * constants
34 */
35
36 /* this defines 4K chunks, should only be changed upwards */
37 #define CHUNKBITS (12)
38 #define CHUNKSIZE (1<<CHUNKBITS)
39 #define CHUNKMASK (CHUNKSIZE-1)
40
41 /* the minimum block size for block-oriented sources, maximum is the
42 chunk size */
43 #define MINBLOCKSIZE (256)
44
45 /* a simple hash function */
46 #define HASHSIZE (13)
47 #define HASHFUNC(start) (((start)>>CHUNKBITS) % HASHSIZE)
48
49 /* convenience */
50 #define MINIMUM(a,b) (((a) < (b)) ? (a) : (b))
51 #define MAXIMUM(a,b) (((a) > (b)) ? (a) : (b))
52
53 /*
54 * types
55 */
56
57 typedef struct chunk {
58 /* file positions
59 start never changes and is CHUNKSIZE-aligned, it identifies the chunk
60 len is between 0 and CHUNKSIZE
61 end is kept synchronized to (start + len)
62 */
63 u8 start, end, len;
64 void *buf;
65 /* links within a hash bucket, organized as a ring list */
66 struct chunk *next, *prev;
67 } CHUNK;
68
69 typedef struct cache {
70 /* chunks stored as a hash table of ring lists */
71 CHUNK *hashtab[HASHSIZE];
72 /* temporary buffer for requests involving several chunks */
73 void *tempbuf;
74 } CACHE;
75
76 /*
77 * helper functions
78 */
79
80 static CHUNK * ensure_chunk(SOURCE *s, CACHE *cache, u8 start);
81 static CHUNK * get_chunk_alloc(CACHE *cache, u8 start);
82
83 /*
84 * retrieve a piece of the source, entry point for detection
85 */
86
87 u8 get_buffer(SECTION *section, u8 pos, u8 len, void **buf)
88 {
89 SOURCE *s;
90
91 /* get source info */
92 s = section->source;
93 pos += section->pos;
94
95 return get_buffer_real(s, pos, len, NULL, buf);
96 }
97
98 /*
99 * actual retrieval, entry point for layering
100 */
101
102 u8 get_buffer_real(SOURCE *s, u8 pos, u8 len, void *inbuf, void **outbuf)
103 {
104 CACHE *cache;
105 CHUNK *c;
106 u8 end, first_chunk, last_chunk, curr_chunk, got, tocopy;
107 void *mybuf;
108
109 /* sanity check */
110 if (len == 0 || (inbuf == NULL && outbuf == NULL))
111 return 0;
112
113 /* get source info */
114 if (s->size_known && pos >= s->size) {
115 /* error("Request for data beyond end of file (pos %llu)", pos); */
116 return 0;
117 }
118 end = pos + len;
119 if (s->size_known && end > s->size) {
120 /* truncate to known end of file */
121 end = s->size;
122 len = end - pos;
123 }
124
125 /* get cache head */
126 cache = (CACHE *)s->cache_head;
127 if (cache == NULL) {
128 /* allocate and initialize new cache head */
129 cache = (CACHE *)malloc(sizeof(CACHE));
130 if (cache == NULL)
131 bailout("Out of memory");
132 memset(cache, 0, sizeof(CACHE));
133 s->cache_head = (void *)cache;
134 }
135 /* free old temp buffer if present */
136 if (cache->tempbuf != NULL) {
137 free(cache->tempbuf);
138 cache->tempbuf = NULL;
139 }
140
141 /* calculate involved chunks */
142 first_chunk = pos & ~CHUNKMASK;
143 last_chunk = (end - 1) & ~CHUNKMASK;
144
145 if (last_chunk == first_chunk) {
146 /* just get the matching chunk */
147 c = ensure_chunk(s, cache, first_chunk);
148 /* NOTE: first_chunk == c->start */
149
150 if (pos >= c->end) /* chunk is incomplete and doesn't have our data */
151 return 0;
152
153 /* calculate return data */
154 len = MINIMUM(len, c->end - pos); /* guaranteed to be > 0 */
155 mybuf = c->buf + (pos - c->start);
156 if (inbuf)
157 memcpy(inbuf, mybuf, len);
158 if (outbuf)
159 *outbuf = mybuf;
160
161 return len;
162
163 } else {
164
165 /* prepare a buffer for concatenation */
166 if (inbuf) {
167 mybuf = inbuf;
168 } else {
169
170 #if PROFILE
171 printf("Temporary buffer for request %llu:%llu\n", pos, len);
172 #endif
173
174 /* allocate one temporarily, will be free()'d at the next call */
175 cache->tempbuf = malloc(len);
176 if (cache->tempbuf == NULL) {
177 error("Out of memory, still going");
178 return 0;
179 }
180 mybuf = cache->tempbuf;
181 }
182
183 /* draw data from all covered chunks */
184 got = 0;
185 for (curr_chunk = first_chunk; curr_chunk <= last_chunk;
186 curr_chunk += CHUNKSIZE) {
187 /* get that chunk */
188 c = ensure_chunk(s, cache, curr_chunk);
189 /* NOTE: curr_chunk == c->start */
190
191 if (pos > curr_chunk) {
192 /* copy from middle of chunk */
193 /* NOTE:
194 - we're in the first chunk, i.e. pos < curr_chunk + CHUNKSIZE
195 - pos >= curr_chunk
196 - got == 0
197 - we must read to the end (else it would be the one-chunk case),
198 i.e. pos + len > curr_chunk + CHUNKSIZE
199 BUT: the chunk may be only partially filled
200 */
201 if (c->end > pos) {
202 tocopy = c->end - pos;
203 memcpy(mybuf, c->buf + (pos & CHUNKMASK), tocopy);
204 } else
205 tocopy = 0;
206 } else {
207 /* copy from start of chunk */
208 tocopy = MINIMUM(c->len, len - got); /* c->len can be zero */
209 if (tocopy)
210 memcpy(mybuf + got, c->buf, tocopy);
211 }
212 got += tocopy;
213
214 /* stop after an incomplete chunk (possibly-okay for the last one,
215 not-so-nice for earlier ones, but treated all the same) */
216 if (c->len < CHUNKSIZE)
217 break;
218 }
219
220 /* calculate return data */
221 len = MINIMUM(len, got); /* may be zero */
222 if (outbuf)
223 *outbuf = mybuf;
224 return len;
225
226 }
227 }
228
229 static CHUNK * ensure_chunk(SOURCE *s, CACHE *cache, u8 start)
230 {
231 CHUNK *c;
232 u8 pos, rel_start, rel_end;
233 u8 toread, result, curr_chunk;
234
235 c = get_chunk_alloc(cache, start);
236 if (c->len >= CHUNKSIZE || (s->size_known && c->end >= s->size)) {
237 /* chunk is complete or complete until EOF */
238 return c;
239 }
240
241 if (s->sequential) {
242 /* sequential source: ensure all data before this chunk was read */
243
244 if (s->seq_pos < start) {
245 /* try to read data between seq_pos and start */
246 curr_chunk = s->seq_pos & ~CHUNKMASK;
247 while (curr_chunk < start) { /* runs at least once, due to the if()
248 and the formula of curr_chunk */
249 ensure_chunk(s, cache, curr_chunk);
250 curr_chunk += CHUNKSIZE;
251 if (s->seq_pos < curr_chunk)
252 break; /* it didn't work out... */
253 }
254
255 /* re-check precondition since s->size may have changed */
256 if (s->size_known && c->end >= s->size)
257 return c; /* there is no more data to read */
258 }
259
260 if (s->seq_pos != c->end) /* c->end is where we'll continue reading */
261 return c; /* we're not in a sane state, give up */
262 }
263
264 /* try to read the missing piece */
265 if (s->read_block != NULL) {
266 /* use block-oriented read_block() method */
267
268 if (s->blocksize < MINBLOCKSIZE ||
269 s->blocksize > CHUNKSIZE ||
270 ((s->blocksize & (s->blocksize - 1)) != 0)) {
271 bailout("Internal error: Invalid block size %d", s->blocksize);
272 }
273
274 for (rel_start = 0; rel_start < CHUNKSIZE; rel_start = rel_end) {
275 rel_end = rel_start + s->blocksize;
276 if (c->len >= rel_end)
277 continue; /* already read */
278 pos = c->start + rel_start;
279 if (s->size_known && pos >= s->size)
280 break; /* whole block is past end of file */
281
282 /* read it */
283 if (s->read_block(s, pos, c->buf + rel_start)) {
284 /* success */
285 c->len = rel_end;
286 c->end = c->start + c->len;
287 } else {
288 /* failure */
289 c->len = rel_start; /* this is safe as it can only mean a shrink */
290 c->end = c->start + c->len;
291 /* note the new end of file if necessary */
292 if (!s->size_known || s->size > c->end) {
293 s->size_known = 1;
294 s->size = c->end;
295 }
296 break;
297 }
298 }
299
300 } else {
301 /* use byte-oriented read_bytes() method */
302
303 if (s->size_known && s->size < c->start + CHUNKSIZE) {
304 /* do not try to read beyond known end of file */
305 toread = s->size - c->end;
306 /* toread cannot be zero or negative due to the preconditions */
307 } else {
308 toread = CHUNKSIZE - c->len;
309 }
310 result = s->read_bytes(s, c->start + c->len, toread,
311 c->buf + c->len);
312 if (result > 0) {
313 /* adjust offsets */
314 c->len += result;
315 c->end = c->start + c->len;
316 if (s->sequential)
317 s->seq_pos += result;
318 }
319 if (result < toread) {
320 /* we fell short, so it must have been an error or end-of-file */
321 /* make sure we don't try again */
322 if (!s->size_known || s->size > c->end) {
323 s->size_known = 1;
324 s->size = c->end;
325 }
326 }
327 }
328
329 return c;
330 }
331
332 static CHUNK * get_chunk_alloc(CACHE *cache, u8 start)
333 {
334 int hpos;
335 CHUNK *chain, *trav, *c;
336
337 /* get hash bucket (chain) */
338 hpos = HASHFUNC(start);
339 chain = cache->hashtab[hpos];
340
341 if (chain == NULL) {
342 /* bucket is empty, allocate new chunk */
343 c = (CHUNK *)malloc(sizeof(CHUNK));
344 if (c == NULL)
345 bailout("Out of memory");
346 c->buf = malloc(CHUNKSIZE);
347 if (c->buf == NULL)
348 bailout("Out of memory");
349 c->start = start;
350 c->end = start;
351 c->len = 0;
352 /* create a new ring list */
353 c->prev = c->next = c;
354 cache->hashtab[hpos] = c;
355 return c;
356 }
357
358 /* travel the ring list, looking for the wanted chunk */
359 trav = chain;
360 do {
361 if (trav->start == start) /* found existing chunk */
362 return trav;
363 trav = trav->next;
364 } while (trav != chain);
365
366 /* not found, allocate new chunk */
367 c = (CHUNK *)malloc(sizeof(CHUNK));
368 if (c == NULL)
369 bailout("Out of memory");
370 c->buf = malloc(CHUNKSIZE);
371 if (c->buf == NULL)
372 bailout("Out of memory");
373 c->start = start;
374 c->end = start;
375 c->len = 0;
376 /* add to ring list before chain, becomes new head */
377 c->prev = chain->prev;
378 c->next = chain;
379 c->prev->next = c;
380 c->next->prev = c;
381 cache->hashtab[hpos] = c;
382 return c;
383 }
384
385 /*
386 * dispose of a source
387 */
388
389 void close_source(SOURCE *s)
390 {
391 CACHE *cache;
392 int hpos;
393 CHUNK *chain, *trav, *nexttrav;
394
395 /* drop the cache */
396 cache = (CACHE *)s->cache_head;
397 if (cache != NULL) {
398 #if PROFILE
399 printf("Cache profile:\n");
400 #endif
401 if (cache->tempbuf != NULL)
402 free(cache->tempbuf);
403 for (hpos = 0; hpos < HASHSIZE; hpos++) {
404 #if PROFILE
405 printf(" hash position %d:", hpos);
406 #endif
407 chain = cache->hashtab[hpos];
408 if (chain != NULL) {
409 trav = chain;
410 do {
411 #if PROFILE
412 printf(" %lluK", trav->start >> 10);
413 if (trav->len != CHUNKSIZE)
414 printf(":%llu", trav->len);
415 #endif
416 nexttrav = trav->next;
417 free(trav->buf);
418 free(trav);
419 trav = nexttrav;
420 } while (trav != chain);
421 #if PROFILE
422 printf("\n");
423 #endif
424 }
425 #if PROFILE
426 else
427 printf(" empty\n");
428 #endif
429 }
430 }
431
432 /* type-specific cleanup */
433 if (s->close != NULL)
434 (*s->close)(s);
435
436 /* release memory for the structure */
437 free(s);
438 }
439
440 /* EOF */