2 * Sherlock Library -- Object Buckets
4 * (c) 2001--2004 Martin Mares <mj@ucw.cz>
5 * (c) 2004 Robert Spalek <robert@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
14 #include "lib/bucket.h"
15 #include "lib/fastbuf.h"
27 static struct obuck_header obuck_hdr, obuck_create_hdr;
28 static sh_off_t bucket_find_pos;
29 static struct fastbuf *obuck_write_fb;
31 /*** Configuration ***/
33 byte *obuck_name = "not/configured";
34 static uns obuck_io_buflen = 65536;
35 static int obuck_shake_buflen = 1048576;
36 static uns obuck_shake_security;
37 static uns obuck_slurp_buflen = 65536;
39 static struct cfitem obuck_config[] = {
40 { "Buckets", CT_SECTION, NULL },
41 { "BucketFile", CT_STRING, &obuck_name },
42 { "BufSize", CT_INT, &obuck_io_buflen },
43 { "ShakeBufSize", CT_INT, &obuck_shake_buflen },
44 { "ShakeSecurity", CT_INT, &obuck_shake_security },
45 { "SlurpBufSize", CT_INT, &obuck_slurp_buflen },
46 { NULL, CT_STOP, NULL }
49 static void CONSTRUCTOR obuck_init_config(void)
51 cf_register(obuck_config);
54 /*** Internal operations ***/
57 obuck_broken(char *msg, sh_off_t pos)
59 die("Object pool corrupted: %s (pos=%Lx)", msg, (long long) pos);
63 * We need several types of locks:
65 * Read lock reading parts of bucket file
66 * Write lock any write operations
67 * Append lock appending to the end of the file
68 * Scan lock reading parts which we are certain they exist
70 * Multiple read and scan locks can co-exist together.
71 * Scan locks can co-exist with an append lock.
72 * There can be at most one write/append lock at a time.
74 * These lock types map to a pair of normal read-write locks which
75 * we represent as fcntl() locks on the first and second byte of the
76 * bucket file. [We cannot use flock() since it happily permits
77 * locking a shared fd (e.g., after fork()) multiple times at it also
78 * doesn't offer multiple locks on a single file.]
82 * Write <write> <write>
88 obuck_do_lock(int type, int start, int len)
93 fl.l_whence = SEEK_SET;
96 if (fcntl(obuck_fd, F_SETLKW, &fl) < 0)
97 die("fcntl lock: %m");
101 obuck_lock_read(void)
103 obuck_do_lock(F_RDLCK, 0, 2);
107 obuck_lock_write(void)
109 obuck_do_lock(F_WRLCK, 0, 2);
113 obuck_lock_append(void)
115 obuck_do_lock(F_WRLCK, 0, 1);
119 obuck_lock_read_to_scan(void)
121 obuck_do_lock(F_UNLCK, 0, 1);
127 obuck_do_lock(F_UNLCK, 0, 2);
130 /*** FastIO emulation ***/
138 #define FB_BUCKET(f) ((struct fb_bucket *)(f)->is_fastbuf)
140 static int obuck_fb_count;
143 obuck_fb_close(struct fastbuf *f)
149 /* We need to use pread/pwrite since we work on fd's shared between processes */
152 obuck_fb_refill(struct fastbuf *f)
154 uns remains, bufsize, size, datasize;
156 remains = FB_BUCKET(f)->bucket_size - (uns)f->pos;
159 f->buffer = FB_BUCKET(f)->buffer; /* Could have been trimmed by bdirect_read_commit_modified() */
160 bufsize = f->bufend - f->buffer;
161 sh_off_t start = FB_BUCKET(f)->start_pos;
162 sh_off_t pos = start + sizeof(struct obuck_header) + f->pos;
163 if (remains <= bufsize)
166 size = start + obuck_bucket_size(FB_BUCKET(f)->bucket_size) - pos;
169 size = datasize = bufsize;
170 int l = sh_pread(obuck_fd, f->buffer, size, pos);
172 die("Error reading bucket: %m");
173 if ((unsigned) l != size)
174 obuck_broken("Short read", FB_BUCKET(f)->start_pos);
176 f->bstop = f->buffer + datasize;
180 if (GET_U32(f->buffer + size - 4) != OBUCK_TRAILER)
181 obuck_broken("Missing trailer", FB_BUCKET(f)->start_pos);
187 obuck_fb_spout(struct fastbuf *f)
189 int l = f->bptr - f->buffer;
194 int z = sh_pwrite(obuck_fd, c, l, FB_BUCKET(f)->start_pos + sizeof(struct obuck_header) + f->pos);
196 die("Error writing bucket: %m");
204 /*** Exported functions ***/
207 obuck_init(int writeable)
211 obuck_fd = sh_open(obuck_name, (writeable ? O_RDWR | O_CREAT : O_RDONLY), 0666);
213 die("Unable to open bucket file %s: %m", obuck_name);
215 size = sh_seek(obuck_fd, 0, SEEK_END);
218 /* If the bucket pool is not empty, check consistency of its end */
220 if (sh_pread(obuck_fd, &check, 4, size-4) != 4 ||
221 check != OBUCK_TRAILER)
222 obuck_broken("Missing trailer of last object", size - 4);
232 log(L_ERROR, "Bug: Unbalanced bucket opens/closes: %d streams remain", obuck_fb_count);
234 log(L_ERROR, "Bug: Forgot to close bucket write stream");
241 bflush(obuck_write_fb);
248 bucket_find_pos = obuck_get_pos(oid);
249 if (sh_pread(obuck_fd, &obuck_hdr, sizeof(obuck_hdr), bucket_find_pos) != sizeof(obuck_hdr))
250 obuck_broken("Short header read", bucket_find_pos);
251 if (obuck_hdr.magic != OBUCK_MAGIC)
252 obuck_broken("Missing magic number", bucket_find_pos);
253 if (obuck_hdr.oid == OBUCK_OID_DELETED)
254 obuck_broken("Access to deleted bucket", bucket_find_pos);
255 if (obuck_hdr.oid != oid)
256 obuck_broken("Invalid backlink", bucket_find_pos);
260 obuck_find_by_oid(struct obuck_header *hdrp)
262 oid_t oid = hdrp->oid;
264 ASSERT(oid < OBUCK_OID_FIRST_SPECIAL);
268 memcpy(hdrp, &obuck_hdr, sizeof(obuck_hdr));
272 obuck_find_first(struct obuck_header *hdrp, int full)
276 return obuck_find_next(hdrp, full);
280 obuck_find_next(struct obuck_header *hdrp, int full)
287 bucket_find_pos += obuck_bucket_size(obuck_hdr.length);
289 c = sh_pread(obuck_fd, &obuck_hdr, sizeof(obuck_hdr), bucket_find_pos);
293 if (c != sizeof(obuck_hdr))
294 obuck_broken("Short header read", bucket_find_pos);
295 if (obuck_hdr.magic != OBUCK_MAGIC)
296 obuck_broken("Missing magic number", bucket_find_pos);
297 if (obuck_hdr.oid != OBUCK_OID_DELETED || full)
299 memcpy(hdrp, &obuck_hdr, sizeof(obuck_hdr));
309 uns official_buflen = ALIGN(MIN(obuck_hdr.length, obuck_io_buflen), OBUCK_ALIGN);
310 uns real_buflen = official_buflen + OBUCK_ALIGN;
312 b = xmalloc(sizeof(struct fb_bucket) + real_buflen);
313 b->buffer = b->bptr = b->bstop = FB_BUCKET(b)->buffer;
314 b->bufend = b->buffer + official_buflen;
315 b->name = "bucket-read";
317 b->refill = obuck_fb_refill;
320 b->close = obuck_fb_close;
322 b->can_overwrite_buffer = 2;
323 FB_BUCKET(b)->start_pos = bucket_find_pos;
324 FB_BUCKET(b)->bucket_size = obuck_hdr.length;
330 obuck_predict_last_oid(void)
332 sh_off_t size = sh_seek(obuck_fd, 0, SEEK_END);
333 return (oid_t)(size >> OBUCK_SHIFT);
337 obuck_create(u32 type)
339 ASSERT(!obuck_write_fb);
342 sh_off_t start = sh_seek(obuck_fd, 0, SEEK_END);
343 if (start & (OBUCK_ALIGN - 1))
344 obuck_broken("Misaligned file", start);
345 obuck_create_hdr.magic = OBUCK_INCOMPLETE_MAGIC;
346 obuck_create_hdr.oid = start >> OBUCK_SHIFT;
347 obuck_create_hdr.length = 0;
348 obuck_create_hdr.type = type;
350 struct fastbuf *b = xmalloc(sizeof(struct fb_bucket) + obuck_io_buflen);
352 b->buffer = FB_BUCKET(b)->buffer;
353 b->bptr = b->bstop = b->buffer;
354 b->bufend = b->buffer + obuck_io_buflen;
355 b->pos = -(int)sizeof(obuck_create_hdr);
356 b->name = "bucket-write";
358 b->spout = obuck_fb_spout;
362 b->can_overwrite_buffer = 0;
363 FB_BUCKET(b)->start_pos = start;
364 FB_BUCKET(b)->bucket_size = 0;
365 bwrite(b, &obuck_create_hdr, sizeof(obuck_create_hdr));
371 obuck_create_end(struct fastbuf *b, struct obuck_header *hdrp)
373 ASSERT(b == obuck_write_fb);
374 obuck_write_fb = NULL;
376 obuck_create_hdr.magic = OBUCK_MAGIC;
377 obuck_create_hdr.length = btell(b);
378 int pad = (OBUCK_ALIGN - sizeof(obuck_create_hdr) - obuck_create_hdr.length - 4) & (OBUCK_ALIGN - 1);
381 bputl(b, OBUCK_TRAILER);
383 ASSERT(!((FB_BUCKET(b)->start_pos + sizeof(obuck_create_hdr) + b->pos) & (OBUCK_ALIGN - 1)));
384 if (sh_pwrite(obuck_fd, &obuck_create_hdr, sizeof(obuck_create_hdr), FB_BUCKET(b)->start_pos) != sizeof(obuck_create_hdr))
385 die("Bucket header update failed: %m");
387 memcpy(hdrp, &obuck_create_hdr, sizeof(obuck_create_hdr));
392 obuck_delete(oid_t oid)
396 obuck_hdr.oid = OBUCK_OID_DELETED;
397 sh_pwrite(obuck_fd, &obuck_hdr, sizeof(obuck_hdr), bucket_find_pos);
401 /*** Fast reading of the whole pool ***/
403 static struct fastbuf *obuck_rpf;
404 static uns slurp_remains;
405 static sh_off_t slurp_start, slurp_current, slurp_end;
408 obuck_slurp_refill(struct fastbuf *f)
412 uns l = bdirect_read_prepare(obuck_rpf, &f->buffer);
414 obuck_broken("Incomplete object", slurp_start);
415 l = MIN(l, slurp_remains);
416 /* XXX: This probably should be bdirect_read_commit_modified() in some cases,
417 * but it doesn't hurt since we aren't going to seek.
419 bdirect_read_commit(obuck_rpf, f->buffer + l);
422 f->bufend = f->bstop = f->buffer + l;
427 obuck_slurp_pool(struct obuck_header *hdrp)
429 static struct fastbuf limiter;
437 obuck_rpf = bopen(obuck_name, O_RDONLY, obuck_slurp_buflen);
438 bseek(obuck_rpf, 0, SEEK_END);
439 slurp_end = btell(obuck_rpf);
440 bsetpos(obuck_rpf, 0);
441 obuck_lock_read_to_scan();
445 bsetpos(obuck_rpf, slurp_current - 4);
446 if (bgetl(obuck_rpf) != OBUCK_TRAILER)
447 obuck_broken("Missing trailer", slurp_start);
449 slurp_start = btell(obuck_rpf);
450 if (slurp_start < slurp_end)
451 l = bread(obuck_rpf, hdrp, sizeof(struct obuck_header));
461 if (l != sizeof(struct obuck_header))
462 obuck_broken("Short header read", slurp_start);
463 if (hdrp->magic != OBUCK_MAGIC)
464 obuck_broken("Missing magic number", slurp_start);
465 slurp_current = slurp_start + obuck_bucket_size(hdrp->length);
467 while (hdrp->oid == OBUCK_OID_DELETED);
468 if (obuck_get_pos(hdrp->oid) != slurp_start)
469 obuck_broken("Invalid backlink", slurp_start);
470 slurp_remains = hdrp->length;
471 limiter.bptr = limiter.bstop = limiter.buffer = limiter.bufend = NULL;
472 limiter.name = "Bucket";
474 limiter.refill = obuck_slurp_refill;
475 limiter.can_overwrite_buffer = obuck_rpf->can_overwrite_buffer;
482 shake_write(void *addr, int len, sh_off_t pos)
484 int l = sh_pwrite(obuck_fd, addr, len, pos);
488 die("obuck_shakedown write error: %m");
490 die("obuck_shakedown write error: disk full");
497 if (obuck_shake_security > 1)
502 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)
504 struct obuck_header *bhdr;
509 /* First of all, the "normal" part -- everything that will be written in this pass */
510 DBG("Backing up first round of changes at position %Lx + %x", (long long) bpos, norm_size);
511 while (boff < norm_size)
513 /* This needn't be optimized for speed. */
514 bhdr = (struct obuck_header *) (norm_buf + boff);
515 ASSERT(bhdr->magic == OBUCK_MAGIC);
516 l = obuck_bucket_size(bhdr->length);
518 bhdr->oid = bpos >> OBUCK_SHIFT;
519 shake_write(bhdr, l, bpos);
525 /* If we have an incomplete bucket at the end of the buffer, we must copy it as well. */
528 DBG("Backing up fragment of size %x and %x more", frag_size, more_size);
530 /* First the part we already have in the buffer */
531 bhdr = (struct obuck_header *) fragment;
532 ASSERT(bhdr->magic == OBUCK_MAGIC);
534 bhdr->oid = bpos >> OBUCK_SHIFT;
535 shake_write(bhdr, frag_size, bpos);
539 /* And then the rest, using a small 64K buffer */
540 byte *auxbuf = alloca(65536);
542 while (l < more_size)
544 int j = MIN(more_size-l, 65536);
545 if (sh_pread(obuck_fd, auxbuf, j, frag_pos + frag_size + l) != j)
546 die("obuck_shakedown read error: %m");
547 shake_write(auxbuf, j, bpos);
555 shake_erase(sh_off_t start, sh_off_t end)
558 die("shake_erase called with negative length, that's a bug");
559 ASSERT(!(start & (OBUCK_ALIGN-1)) && !(end & (OBUCK_ALIGN-1)));
562 u32 check = OBUCK_TRAILER;
563 obuck_hdr.magic = OBUCK_MAGIC;
564 obuck_hdr.oid = OBUCK_OID_DELETED;
565 uns len = MIN(0x40000000, end-start);
566 obuck_hdr.length = len - sizeof(obuck_hdr) - 4;
567 DBG("Erasing %08x bytes at %Lx", len, (long long) start);
568 shake_write(&obuck_hdr, sizeof(obuck_hdr), start);
570 shake_write(&check, 4, start-4);
575 obuck_shakedown(int (*kibitz)(struct obuck_header *old, oid_t new, byte *buck))
577 byte *buf; /* Shakedown buffer and its size */
578 int buflen = ALIGN(obuck_shake_buflen, OBUCK_ALIGN);
579 byte *msg; /* Error message we will print */
580 sh_off_t rstart, wstart; /* Original and new position of buffer start */
581 sh_off_t r_bucket_start, w_bucket_start; /* Original and new position of the current bucket */
582 int roff, woff; /* Orig/new position of the current bucket relative to buffer start */
583 int rsize; /* Number of original bytes in the buffer */
584 int l; /* Raw size of the current bucket */
585 int changed = 0; /* "Something has been altered" flag */
586 int wrote_anything = 0; /* We already did a write to the bucket file */
587 struct obuck_header *rhdr, *whdr; /* Original and new address of header of the current bucket */
588 sh_off_t r_file_size; /* Original size of the bucket file */
589 int more; /* How much does the last bucket overlap the buffer */
591 buf = xmalloc(buflen);
593 roff = woff = rsize = 0;
595 /* We need to be the only accessor, all the object ID's are becoming invalid */
597 r_file_size = sh_seek(obuck_fd, 0, SEEK_END);
598 ASSERT(!(r_file_size & (OBUCK_ALIGN - 1)));
599 if (r_file_size >= (0x100000000 << OBUCK_SHIFT) - buflen)
600 die("Bucket file is too large for safe shakedown. Shaking down with Bucket.ShakeSecurity=0 will still work.");
602 DBG("Starting shakedown. Buffer size is %d, original length %Lx", buflen, (long long) r_file_size);
606 r_bucket_start = rstart + roff;
607 w_bucket_start = wstart + woff;
608 rhdr = (struct obuck_header *)(buf + roff);
609 whdr = (struct obuck_header *)(buf + woff);
615 if (rhdr->magic != OBUCK_MAGIC ||
616 rhdr->oid != OBUCK_OID_DELETED && rhdr->oid != (oid_t)(r_bucket_start >> OBUCK_SHIFT))
618 msg = "header mismatch";
621 l = obuck_bucket_size(rhdr->length);
624 if (rhdr->oid != OBUCK_OID_DELETED)
626 msg = "bucket longer than ShakeBufSize";
629 /* Empty buckets are allowed to be large, but we need to handle them extra */
630 DBG("Tricking around an extra-large empty bucket at %Lx + %x", (long long)r_bucket_start, l);
635 if (rsize - roff < l)
637 more = l - (rsize - roff);
640 if (GET_U32((byte *)rhdr + l - 4) != OBUCK_TRAILER)
642 msg = "missing trailer";
646 if (rhdr->oid != OBUCK_OID_DELETED)
648 int status = kibitz(rhdr, w_bucket_start >> OBUCK_SHIFT, (byte *)(rhdr+1));
654 /* Changed! Reconstruct the trailer. */
655 lnew = obuck_bucket_size(rhdr->length);
657 PUT_U32((byte *)rhdr + lnew - 4, OBUCK_TRAILER);
660 whdr = (struct obuck_header *)(buf+woff);
662 memmove(whdr, rhdr, lnew);
663 whdr->oid = w_bucket_start >> OBUCK_SHIFT;
671 kibitz(rhdr, OBUCK_OID_DELETED, NULL);
680 /* Write the new contents of the bucket file */
683 if (obuck_shake_security)
685 /* But first write a backup at the end of the file to ensure nothing can be lost. */
686 shake_write_backup(r_file_size, buf, woff, buf+roff, rsize-roff, rstart+roff, more);
693 DBG("Write %Lx %x", wstart, woff);
694 shake_write(buf, woff, wstart);
699 ASSERT(wstart == rstart);
701 /* In any case, update the write position */
705 /* Skip what's been read and if there is any fragment at the end of the buffer, move it to the start */
709 memmove(buf, buf+roff, rsize-roff);
715 /* And refill the buffer */
716 r_bucket_start = rstart+rsize; /* Also needed for error messages */
717 l = sh_pread(obuck_fd, buf+rsize, MIN(buflen-rsize, r_file_size - r_bucket_start), r_bucket_start);
718 DBG("Read %Lx %x (%x inherited)", (long long)r_bucket_start, l, rsize);
720 die("obuck_shakedown read error: %m");
725 msg = "unexpected EOF";
728 if (l & (OBUCK_ALIGN-1))
730 msg = "garbage at the end of file";
737 DBG("Finished at position %Lx", (long long) wstart);
738 sh_ftruncate(obuck_fd, wstart);
746 log(L_ERROR, "Error during object pool shakedown: %s (pos=%Ld, id=%x), gathering debris",
747 msg, (long long) r_bucket_start, (uns)(r_bucket_start >> OBUCK_SHIFT));
749 * We can attempt to clean up the bucket file by erasing everything between the last
750 * byte written and the next byte to be read. If the secure mode is switched on, we can
751 * guarantee that no data are lost, only some might be duplicated.
753 shake_erase(wstart, rstart);
754 die("Fatal error during object pool shakedown");
764 #define LEN(i) ((259309*(i))%MAXLEN)
766 static int test_kibitz(struct obuck_header *h, oid_t new, byte *buck)
771 int main(int argc, char **argv)
774 unsigned int i, j, cnt;
775 struct obuck_header h;
779 if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0 ||
782 fputs("This program supports only the following command-line arguments:\n" CF_USAGE, stderr);
788 for(j=0; j<COUNT; j++)
790 b = obuck_create(BUCKET_TYPE_PLAIN);
791 for(i=0; i<LEN(j); i++)
792 bputc(b, (i+j) % 256);
793 obuck_create_end(b, &h);
794 printf("Writing %08x %d\n", h.oid, h.length);
797 for(j=0; j<COUNT; j++)
798 if (j % 100 < KILLPERC)
800 printf("Deleting %08x\n", ids[j]);
801 obuck_delete(ids[j]);
804 for(j=0; j<COUNT; j++)
805 if (j % 100 >= KILLPERC)
809 obuck_find_by_oid(&h);
811 printf("Reading %08x %d\n", h.oid, h.length);
812 if (h.length != LEN(j))
813 die("Invalid length");
814 for(i=0; i<h.length; i++)
815 if ((unsigned) bgetc(b) != (i+j) % 256)
816 die("Contents mismatch");
821 obuck_shakedown(test_kibitz);
822 if (obuck_find_first(&h, 0))
825 printf("<<< %08x\t%d\n", h.oid, h.length);
828 while (obuck_find_next(&h, 0));
830 die("Walk mismatch");