2 * Sherlock Library -- Object Buckets
4 * (c) 2001--2004 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.
13 #include "lib/bucket.h"
14 #include "lib/fastbuf.h"
26 static struct obuck_header obuck_hdr, obuck_create_hdr;
27 static sh_off_t bucket_find_pos;
28 static struct fastbuf *obuck_write_fb;
30 /*** Configuration ***/
32 byte *obuck_name = "not/configured";
33 static uns obuck_io_buflen = 65536;
34 static int obuck_shake_buflen = 1048576;
35 static uns obuck_shake_security;
36 static uns obuck_slurp_buflen = 65536;
38 static struct cfitem obuck_config[] = {
39 { "Buckets", CT_SECTION, NULL },
40 { "BucketFile", CT_STRING, &obuck_name },
41 { "BufSize", CT_INT, &obuck_io_buflen },
42 { "ShakeBufSize", CT_INT, &obuck_shake_buflen },
43 { "ShakeSecurity", CT_INT, &obuck_shake_security },
44 { "SlurpBufSize", CT_INT, &obuck_slurp_buflen },
45 { NULL, CT_STOP, NULL }
48 static void CONSTRUCTOR obuck_init_config(void)
50 cf_register(obuck_config);
53 /*** Internal operations ***/
56 obuck_broken(char *msg, sh_off_t pos)
58 die("Object pool corrupted: %s (pos=%Lx)", msg, (long long) pos);
62 * We need several types of locks:
64 * Read lock reading parts of bucket file
65 * Write lock any write operations
66 * Append lock appending to the end of the file
67 * Scan lock reading parts which we are certain they exist
69 * Multiple read and scan locks can co-exist together.
70 * Scan locks can co-exist with an append lock.
71 * There can be at most one write/append lock at a time.
73 * These lock types map to a pair of normal read-write locks which
74 * we represent as fcntl() locks on the first and second byte of the
75 * bucket file. [We cannot use flock() since it happily permits
76 * locking a shared fd (e.g., after fork()) multiple times at it also
77 * doesn't offer multiple locks on a single file.]
81 * Write <write> <write>
87 obuck_do_lock(int type, int start, int len)
92 fl.l_whence = SEEK_SET;
95 if (fcntl(obuck_fd, F_SETLKW, &fl) < 0)
96 die("fcntl lock: %m");
100 obuck_lock_read(void)
102 obuck_do_lock(F_RDLCK, 0, 2);
106 obuck_lock_write(void)
108 obuck_do_lock(F_WRLCK, 0, 2);
112 obuck_lock_append(void)
114 obuck_do_lock(F_WRLCK, 0, 1);
118 obuck_lock_read_to_scan(void)
120 obuck_do_lock(F_UNLCK, 0, 1);
126 obuck_do_lock(F_UNLCK, 0, 2);
129 /*** FastIO emulation ***/
137 #define FB_BUCKET(f) ((struct fb_bucket *)(f)->is_fastbuf)
139 static int obuck_fb_count;
142 obuck_fb_close(struct fastbuf *f)
148 /* We need to use pread/pwrite since we work on fd's shared between processes */
151 obuck_fb_refill(struct fastbuf *f)
153 uns remains, bufsize, size, datasize;
155 remains = FB_BUCKET(f)->bucket_size - (uns)f->pos;
156 bufsize = f->bufend - f->buffer;
159 sh_off_t start = FB_BUCKET(f)->start_pos;
160 sh_off_t pos = start + sizeof(struct obuck_header) + f->pos;
161 if (remains <= bufsize)
164 size = start + obuck_bucket_size(FB_BUCKET(f)->bucket_size) - pos;
167 size = datasize = bufsize;
168 int l = sh_pread(obuck_fd, f->buffer, size, pos);
170 die("Error reading bucket: %m");
171 if ((unsigned) l != size)
172 obuck_broken("Short read", FB_BUCKET(f)->start_pos);
174 f->bstop = f->buffer + datasize;
178 if (GET_U32(f->buffer + size - 4) != OBUCK_TRAILER)
179 obuck_broken("Missing trailer", FB_BUCKET(f)->start_pos);
185 obuck_fb_spout(struct fastbuf *f)
187 int l = f->bptr - f->buffer;
192 int z = sh_pwrite(obuck_fd, c, l, FB_BUCKET(f)->start_pos + sizeof(struct obuck_header) + f->pos);
194 die("Error writing bucket: %m");
202 /*** Exported functions ***/
205 obuck_init(int writeable)
209 obuck_fd = sh_open(obuck_name, (writeable ? O_RDWR | O_CREAT : O_RDONLY), 0666);
211 die("Unable to open bucket file %s: %m", obuck_name);
213 size = sh_seek(obuck_fd, 0, SEEK_END);
216 /* If the bucket pool is not empty, check consistency of its end */
218 if (sh_pread(obuck_fd, &check, 4, size-4) != 4 ||
219 check != OBUCK_TRAILER)
220 obuck_broken("Missing trailer of last object", size - 4);
230 log(L_ERROR, "Bug: Unbalanced bucket opens/closes: %d streams remain", obuck_fb_count);
232 log(L_ERROR, "Bug: Forgot to close bucket write stream");
239 bflush(obuck_write_fb);
246 bucket_find_pos = obuck_get_pos(oid);
247 if (sh_pread(obuck_fd, &obuck_hdr, sizeof(obuck_hdr), bucket_find_pos) != sizeof(obuck_hdr))
248 obuck_broken("Short header read", bucket_find_pos);
249 if (obuck_hdr.magic != OBUCK_MAGIC)
250 obuck_broken("Missing magic number", bucket_find_pos);
251 if (obuck_hdr.oid == OBUCK_OID_DELETED)
252 obuck_broken("Access to deleted bucket", bucket_find_pos);
253 if (obuck_hdr.oid != oid)
254 obuck_broken("Invalid backlink", bucket_find_pos);
258 obuck_find_by_oid(struct obuck_header *hdrp)
260 oid_t oid = hdrp->oid;
262 ASSERT(oid < OBUCK_OID_FIRST_SPECIAL);
266 memcpy(hdrp, &obuck_hdr, sizeof(obuck_hdr));
270 obuck_find_first(struct obuck_header *hdrp, int full)
274 return obuck_find_next(hdrp, full);
278 obuck_find_next(struct obuck_header *hdrp, int full)
285 bucket_find_pos += obuck_bucket_size(obuck_hdr.length);
287 c = sh_pread(obuck_fd, &obuck_hdr, sizeof(obuck_hdr), bucket_find_pos);
291 if (c != sizeof(obuck_hdr))
292 obuck_broken("Short header read", bucket_find_pos);
293 if (obuck_hdr.magic != OBUCK_MAGIC)
294 obuck_broken("Missing magic number", bucket_find_pos);
295 if (obuck_hdr.oid != OBUCK_OID_DELETED || full)
297 memcpy(hdrp, &obuck_hdr, sizeof(obuck_hdr));
307 uns official_buflen = ALIGN(MIN(obuck_hdr.length, obuck_io_buflen), OBUCK_ALIGN);
308 uns real_buflen = official_buflen + OBUCK_ALIGN;
310 b = xmalloc(sizeof(struct fb_bucket) + real_buflen);
311 b->buffer = b->bptr = b->bstop = FB_BUCKET(b)->buffer;
312 b->bufend = b->buffer + official_buflen;
313 b->name = "bucket-read";
315 b->refill = obuck_fb_refill;
318 b->close = obuck_fb_close;
320 FB_BUCKET(b)->start_pos = bucket_find_pos;
321 FB_BUCKET(b)->bucket_size = obuck_hdr.length;
327 obuck_predict_last_oid(void)
329 sh_off_t size = sh_seek(obuck_fd, 0, SEEK_END);
330 return (oid_t)(size >> OBUCK_SHIFT);
334 obuck_create(u32 type)
336 ASSERT(!obuck_write_fb);
339 sh_off_t start = sh_seek(obuck_fd, 0, SEEK_END);
340 if (start & (OBUCK_ALIGN - 1))
341 obuck_broken("Misaligned file", start);
342 obuck_create_hdr.magic = OBUCK_INCOMPLETE_MAGIC;
343 obuck_create_hdr.oid = start >> OBUCK_SHIFT;
344 obuck_create_hdr.length = 0;
345 obuck_create_hdr.type = type;
347 struct fastbuf *b = xmalloc(sizeof(struct fb_bucket) + obuck_io_buflen);
349 b->buffer = FB_BUCKET(b)->buffer;
350 b->bptr = b->bstop = b->buffer;
351 b->bufend = b->buffer + obuck_io_buflen;
352 b->pos = -(int)sizeof(obuck_create_hdr);
353 b->name = "bucket-write";
355 b->spout = obuck_fb_spout;
359 FB_BUCKET(b)->start_pos = start;
360 FB_BUCKET(b)->bucket_size = 0;
361 bwrite(b, &obuck_create_hdr, sizeof(obuck_create_hdr));
367 obuck_create_end(struct fastbuf *b, struct obuck_header *hdrp)
369 ASSERT(b == obuck_write_fb);
370 obuck_write_fb = NULL;
372 obuck_create_hdr.magic = OBUCK_MAGIC;
373 obuck_create_hdr.length = btell(b);
374 int pad = (OBUCK_ALIGN - sizeof(obuck_create_hdr) - obuck_create_hdr.length - 4) & (OBUCK_ALIGN - 1);
377 bputl(b, OBUCK_TRAILER);
379 ASSERT(!((FB_BUCKET(b)->start_pos + sizeof(obuck_create_hdr) + b->pos) & (OBUCK_ALIGN - 1)));
380 if (sh_pwrite(obuck_fd, &obuck_create_hdr, sizeof(obuck_create_hdr), FB_BUCKET(b)->start_pos) != sizeof(obuck_create_hdr))
381 die("Bucket header update failed: %m");
383 memcpy(hdrp, &obuck_create_hdr, sizeof(obuck_create_hdr));
388 obuck_delete(oid_t oid)
392 obuck_hdr.oid = OBUCK_OID_DELETED;
393 sh_pwrite(obuck_fd, &obuck_hdr, sizeof(obuck_hdr), bucket_find_pos);
397 /*** Fast reading of the whole pool ***/
399 static struct fastbuf *obuck_rpf;
400 static uns slurp_remains;
401 static sh_off_t slurp_start, slurp_current, slurp_end;
404 obuck_slurp_refill(struct fastbuf *f)
410 l = bdirect_read_prepare(obuck_rpf, &f->buffer);
412 obuck_broken("Incomplete object", slurp_start);
413 l = MIN(l, slurp_remains);
414 bdirect_read_commit(obuck_rpf, f->buffer + l);
417 f->bufend = f->bstop = f->buffer + l;
422 obuck_slurp_pool(struct obuck_header *hdrp)
424 static struct fastbuf limiter;
432 obuck_rpf = bopen(obuck_name, O_RDONLY, obuck_slurp_buflen);
433 bseek(obuck_rpf, 0, SEEK_END);
434 slurp_end = btell(obuck_rpf);
435 bsetpos(obuck_rpf, 0);
436 obuck_lock_read_to_scan();
440 bsetpos(obuck_rpf, slurp_current - 4);
441 if (bgetl(obuck_rpf) != OBUCK_TRAILER)
442 obuck_broken("Missing trailer", slurp_start);
444 slurp_start = btell(obuck_rpf);
445 if (slurp_start < slurp_end)
446 l = bread(obuck_rpf, hdrp, sizeof(struct obuck_header));
456 if (l != sizeof(struct obuck_header))
457 obuck_broken("Short header read", slurp_start);
458 if (hdrp->magic != OBUCK_MAGIC)
459 obuck_broken("Missing magic number", slurp_start);
460 slurp_current = slurp_start + obuck_bucket_size(hdrp->length);
462 while (hdrp->oid == OBUCK_OID_DELETED);
463 if (obuck_get_pos(hdrp->oid) != slurp_start)
464 obuck_broken("Invalid backlink", slurp_start);
465 slurp_remains = hdrp->length;
466 limiter.bptr = limiter.bstop = limiter.buffer = limiter.bufend = NULL;
467 limiter.name = "Bucket";
469 limiter.refill = obuck_slurp_refill;
476 shake_write(void *addr, int len, sh_off_t pos)
478 int l = sh_pwrite(obuck_fd, addr, len, pos);
482 die("obuck_shakedown write error: %m");
484 die("obuck_shakedown write error: disk full");
491 if (obuck_shake_security > 1)
496 shake_write_backup(sh_off_t bpos, byte *norm_buf, int norm_size, byte *fragment, int frag_size, sh_off_t frag_pos, int more_size)
498 struct obuck_header *bhdr;
503 /* First of all, the "normal" part -- everything that will be written in this pass */
504 DBG("Backing up first round of changes at position %Lx + %x", (long long) bpos, norm_size);
505 while (boff < norm_size)
507 /* This needn't be optimized for speed. */
508 bhdr = (struct obuck_header *) (norm_buf + boff);
509 ASSERT(bhdr->magic == OBUCK_MAGIC);
510 l = obuck_bucket_size(bhdr->length);
512 bhdr->oid = bpos >> OBUCK_SHIFT;
513 shake_write(bhdr, l, bpos);
519 /* If we have an incomplete bucket at the end of the buffer, we must copy it as well. */
522 DBG("Backing up fragment of size %x and %x more", frag_size, more_size);
524 /* First the part we already have in the buffer */
525 bhdr = (struct obuck_header *) fragment;
526 ASSERT(bhdr->magic == OBUCK_MAGIC);
528 bhdr->oid = bpos >> OBUCK_SHIFT;
529 shake_write(bhdr, frag_size, bpos);
533 /* And then the rest, using a small 64K buffer */
534 byte *auxbuf = alloca(65536);
536 while (l < more_size)
538 int j = MIN(more_size-l, 65536);
539 if (sh_pread(obuck_fd, auxbuf, j, frag_pos + frag_size + l) != j)
540 die("obuck_shakedown read error: %m");
541 shake_write(auxbuf, j, bpos);
549 shake_erase(sh_off_t start, sh_off_t end)
552 die("shake_erase called with negative length, that's a bug");
553 ASSERT(!(start & (OBUCK_ALIGN-1)) && !(end & (OBUCK_ALIGN-1)));
556 u32 check = OBUCK_TRAILER;
557 obuck_hdr.magic = OBUCK_MAGIC;
558 obuck_hdr.oid = OBUCK_OID_DELETED;
559 uns len = MIN(0x40000000, end-start);
560 obuck_hdr.length = len - sizeof(obuck_hdr) - 4;
561 DBG("Erasing %08x bytes at %Lx", len, (long long) start);
562 shake_write(&obuck_hdr, sizeof(obuck_hdr), start);
564 shake_write(&check, 4, start-4);
569 obuck_shakedown(int (*kibitz)(struct obuck_header *old, oid_t new, byte *buck))
571 byte *buf; /* Shakedown buffer and its size */
572 int buflen = ALIGN(obuck_shake_buflen, OBUCK_ALIGN);
573 byte *msg; /* Error message we will print */
574 sh_off_t rstart, wstart; /* Original and new position of buffer start */
575 sh_off_t r_bucket_start, w_bucket_start; /* Original and new position of the current bucket */
576 int roff, woff; /* Orig/new position of the current bucket relative to buffer start */
577 int rsize; /* Number of original bytes in the buffer */
578 int l; /* Raw size of the current bucket */
579 int changed = 0; /* "Something has been altered" flag */
580 int wrote_anything = 0; /* We already did a write to the bucket file */
581 struct obuck_header *rhdr, *whdr; /* Original and new address of header of the current bucket */
582 sh_off_t r_file_size; /* Original size of the bucket file */
583 int more; /* How much does the last bucket overlap the buffer */
585 buf = xmalloc(buflen);
587 roff = woff = rsize = 0;
589 /* We need to be the only accessor, all the object ID's are becoming invalid */
591 r_file_size = sh_seek(obuck_fd, 0, SEEK_END);
592 ASSERT(!(r_file_size & (OBUCK_ALIGN - 1)));
593 if (r_file_size >= (0x100000000 << OBUCK_SHIFT) - buflen)
594 die("Bucket file is too large for safe shakedown. Shaking down with Bucket.ShakeSecurity=0 will still work.");
596 DBG("Starting shakedown. Buffer size is %d, original length %Lx", buflen, (long long) r_file_size);
600 r_bucket_start = rstart + roff;
601 w_bucket_start = wstart + woff;
602 rhdr = (struct obuck_header *)(buf + roff);
603 whdr = (struct obuck_header *)(buf + woff);
609 if (rhdr->magic != OBUCK_MAGIC ||
610 rhdr->oid != OBUCK_OID_DELETED && rhdr->oid != (oid_t)(r_bucket_start >> OBUCK_SHIFT))
612 msg = "header mismatch";
615 l = obuck_bucket_size(rhdr->length);
618 if (rhdr->oid != OBUCK_OID_DELETED)
620 msg = "bucket longer than ShakeBufSize";
623 /* Empty buckets are allowed to be large, but we need to handle them extra */
624 DBG("Tricking around an extra-large empty bucket at %Lx + %x", (long long)r_bucket_start, l);
629 if (rsize - roff < l)
631 more = l - (rsize - roff);
634 if (GET_U32((byte *)rhdr + l - 4) != OBUCK_TRAILER)
636 msg = "missing trailer";
640 if (rhdr->oid != OBUCK_OID_DELETED)
642 int status = kibitz(rhdr, w_bucket_start >> OBUCK_SHIFT, (byte *)(rhdr+1));
648 /* Changed! Reconstruct the trailer. */
649 lnew = obuck_bucket_size(rhdr->length);
651 PUT_U32((byte *)rhdr + lnew - 4, OBUCK_TRAILER);
654 whdr = (struct obuck_header *)(buf+woff);
656 memmove(whdr, rhdr, lnew);
657 whdr->oid = w_bucket_start >> OBUCK_SHIFT;
665 kibitz(rhdr, OBUCK_OID_DELETED, NULL);
674 /* Write the new contents of the bucket file */
677 if (obuck_shake_security)
679 /* But first write a backup at the end of the file to ensure nothing can be lost. */
680 shake_write_backup(r_file_size, buf, woff, buf+roff, rsize-roff, rstart+roff, more);
687 DBG("Write %Lx %x", wstart, woff);
688 shake_write(buf, woff, wstart);
693 ASSERT(wstart == rstart);
695 /* In any case, update the write position */
699 /* Skip what's been read and if there is any fragment at the end of the buffer, move it to the start */
703 memmove(buf, buf+roff, rsize-roff);
709 /* And refill the buffer */
710 r_bucket_start = rstart+rsize; /* Also needed for error messages */
711 l = sh_pread(obuck_fd, buf+rsize, MIN(buflen-rsize, r_file_size - r_bucket_start), r_bucket_start);
712 DBG("Read %Lx %x (%x inherited)", (long long)r_bucket_start, l, rsize);
714 die("obuck_shakedown read error: %m");
719 msg = "unexpected EOF";
722 if (l & (OBUCK_ALIGN-1))
724 msg = "garbage at the end of file";
731 DBG("Finished at position %Lx", (long long) wstart);
732 sh_ftruncate(obuck_fd, wstart);
740 log(L_ERROR, "Error during object pool shakedown: %s (pos=%Ld, id=%x), gathering debris",
741 msg, (long long) r_bucket_start, (uns)(r_bucket_start >> OBUCK_SHIFT));
743 * We can attempt to clean up the bucket file by erasing everything between the last
744 * byte written and the next byte to be read. If the secure mode is switched on, we can
745 * guarantee that no data are lost, only some might be duplicated.
747 shake_erase(wstart, rstart);
748 die("Fatal error during object pool shakedown");
758 #define LEN(i) ((259309*(i))%MAXLEN)
760 static int test_kibitz(struct obuck_header *h, oid_t new, byte *buck)
765 int main(int argc, char **argv)
768 unsigned int i, j, cnt;
769 struct obuck_header h;
773 if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0 ||
776 fputs("This program supports only the following command-line arguments:\n" CF_USAGE, stderr);
782 for(j=0; j<COUNT; j++)
784 b = obuck_create(BUCKET_TYPE_PLAIN);
785 for(i=0; i<LEN(j); i++)
786 bputc(b, (i+j) % 256);
787 obuck_create_end(b, &h);
788 printf("Writing %08x %d\n", h.oid, h.length);
791 for(j=0; j<COUNT; j++)
792 if (j % 100 < KILLPERC)
794 printf("Deleting %08x\n", ids[j]);
795 obuck_delete(ids[j]);
798 for(j=0; j<COUNT; j++)
799 if (j % 100 >= KILLPERC)
803 obuck_find_by_oid(&h);
805 printf("Reading %08x %d\n", h.oid, h.length);
806 if (h.length != LEN(j))
807 die("Invalid length");
808 for(i=0; i<h.length; i++)
809 if ((unsigned) bgetc(b) != (i+j) % 256)
810 die("Contents mismatch");
815 obuck_shakedown(test_kibitz);
816 if (obuck_find_first(&h, 0))
819 printf("<<< %08x\t%d\n", h.oid, h.length);
822 while (obuck_find_next(&h, 0));
824 die("Walk mismatch");