]> mj.ucw.cz Git - libucw.git/blob - lib/bucket.c
BCONFIG_CAN_OVERWRITE is a read/write parameter, i.e. the used can
[libucw.git] / lib / bucket.c
1 /*
2  *      Sherlock Library -- Object Buckets
3  *
4  *      (c) 2001--2004 Martin Mares <mj@ucw.cz>
5  *      (c) 2004 Robert Spalek <robert@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #undef LOCAL_DEBUG
12
13 #include "lib/lib.h"
14 #include "lib/bucket.h"
15 #include "lib/fastbuf.h"
16 #include "lib/lfs.h"
17 #include "lib/conf.h"
18
19 #include <string.h>
20 #include <stdlib.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <sys/file.h>
24 #include <alloca.h>
25
26 static int obuck_fd;
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;
30
31 /*** Configuration ***/
32
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;
38
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 }
47 };
48
49 static void CONSTRUCTOR obuck_init_config(void)
50 {
51   cf_register(obuck_config);
52 }
53
54 /*** Internal operations ***/
55
56 static void
57 obuck_broken(char *msg, sh_off_t pos)
58 {
59   die("Object pool corrupted: %s (pos=%Lx)", msg, (long long) pos);
60 }
61
62 /*
63  *  We need several types of locks:
64  *
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
69  *
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.
73  *
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.]
79  *
80  *                      byte0           byte1
81  *      Read            <read>          <read>
82  *      Write           <write>         <write>
83  *      Append          <write>         -
84  *      Scan            -               <read>
85  */
86
87 static inline void
88 obuck_do_lock(int type, int start, int len)
89 {
90   struct flock fl;
91
92   fl.l_type = type;
93   fl.l_whence = SEEK_SET;
94   fl.l_start = start;
95   fl.l_len = len;
96   if (fcntl(obuck_fd, F_SETLKW, &fl) < 0)
97     die("fcntl lock: %m");
98 }
99
100 inline void
101 obuck_lock_read(void)
102 {
103   obuck_do_lock(F_RDLCK, 0, 2);
104 }
105
106 inline void
107 obuck_lock_write(void)
108 {
109   obuck_do_lock(F_WRLCK, 0, 2);
110 }
111
112 static inline void
113 obuck_lock_append(void)
114 {
115   obuck_do_lock(F_WRLCK, 0, 1);
116 }
117
118 static inline void
119 obuck_lock_read_to_scan(void)
120 {
121   obuck_do_lock(F_UNLCK, 0, 1);
122 }
123
124 inline void
125 obuck_unlock(void)
126 {
127   obuck_do_lock(F_UNLCK, 0, 2);
128 }
129
130 /*** FastIO emulation ***/
131
132 struct fb_bucket {
133   struct fastbuf fb;
134   int can_overwrite;
135   sh_off_t start_pos;
136   uns bucket_size;
137   byte buffer[0];
138 };
139 #define FB_BUCKET(f) ((struct fb_bucket *)(f)->is_fastbuf)
140
141 static int obuck_fb_count;
142
143 static void
144 obuck_fb_close(struct fastbuf *f)
145 {
146   obuck_fb_count--;
147   xfree(f);
148 }
149
150 /* We need to use pread/pwrite since we work on fd's shared between processes */
151
152 static int
153 obuck_fb_refill(struct fastbuf *f)
154 {
155   uns remains, bufsize, size, datasize;
156
157   remains = FB_BUCKET(f)->bucket_size - (uns)f->pos;
158   bufsize = f->bufend - f->buffer;
159   if (!remains)
160     return 0;
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)
164     {
165       datasize = remains;
166       size = start + obuck_bucket_size(FB_BUCKET(f)->bucket_size) - pos;
167     }
168   else
169     size = datasize = bufsize;
170   int l = sh_pread(obuck_fd, f->buffer, size, pos);
171   if (l < 0)
172     die("Error reading bucket: %m");
173   if ((unsigned) l != size)
174     obuck_broken("Short read", FB_BUCKET(f)->start_pos);
175   f->bptr = f->buffer;
176   f->bstop = f->buffer + datasize;
177   f->pos += datasize;
178   if (datasize < size)
179     {
180       if (GET_U32(f->buffer + size - 4) != OBUCK_TRAILER)
181         obuck_broken("Missing trailer", FB_BUCKET(f)->start_pos);
182     }
183   return datasize;
184 }
185
186 static void
187 obuck_fb_spout(struct fastbuf *f)
188 {
189   int l = f->bptr - f->buffer;
190   char *c = f->buffer;
191
192   while (l)
193     {
194       int z = sh_pwrite(obuck_fd, c, l, FB_BUCKET(f)->start_pos + sizeof(struct obuck_header) + f->pos);
195       if (z <= 0)
196         die("Error writing bucket: %m");
197       f->pos += z;
198       l -= z;
199       c += z;
200     }
201   f->bptr = f->buffer;
202 }
203
204 /*** Exported functions ***/
205
206 void
207 obuck_init(int writeable)
208 {
209   sh_off_t size;
210
211   obuck_fd = sh_open(obuck_name, (writeable ? O_RDWR | O_CREAT : O_RDONLY), 0666);
212   if (obuck_fd < 0)
213     die("Unable to open bucket file %s: %m", obuck_name);
214   obuck_lock_read();
215   size = sh_seek(obuck_fd, 0, SEEK_END);
216   if (size)
217     {
218       /* If the bucket pool is not empty, check consistency of its end */
219       u32 check;
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);
223     }
224   obuck_unlock();
225 }
226
227 void
228 obuck_cleanup(void)
229 {
230   close(obuck_fd);
231   if (obuck_fb_count)
232     log(L_ERROR, "Bug: Unbalanced bucket opens/closes: %d streams remain", obuck_fb_count);
233   if (obuck_write_fb)
234     log(L_ERROR, "Bug: Forgot to close bucket write stream");
235 }
236
237 void
238 obuck_sync(void)
239 {
240   if (obuck_write_fb)
241     bflush(obuck_write_fb);
242   fsync(obuck_fd);
243 }
244
245 static void
246 obuck_get(oid_t oid)
247 {
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);
257 }
258
259 void
260 obuck_find_by_oid(struct obuck_header *hdrp)
261 {
262   oid_t oid = hdrp->oid;
263
264   ASSERT(oid < OBUCK_OID_FIRST_SPECIAL);
265   obuck_lock_read();
266   obuck_get(oid);
267   obuck_unlock();
268   memcpy(hdrp, &obuck_hdr, sizeof(obuck_hdr));
269 }
270
271 int
272 obuck_find_first(struct obuck_header *hdrp, int full)
273 {
274   bucket_find_pos = 0;
275   obuck_hdr.magic = 0;
276   return obuck_find_next(hdrp, full);
277 }
278
279 int
280 obuck_find_next(struct obuck_header *hdrp, int full)
281 {
282   int c;
283
284   for(;;)
285     {
286       if (obuck_hdr.magic)
287         bucket_find_pos += obuck_bucket_size(obuck_hdr.length);
288       obuck_lock_read();
289       c = sh_pread(obuck_fd, &obuck_hdr, sizeof(obuck_hdr), bucket_find_pos);
290       obuck_unlock();
291       if (!c)
292         return 0;
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)
298         {
299           memcpy(hdrp, &obuck_hdr, sizeof(obuck_hdr));
300           return 1;
301         }
302     }
303 }
304
305 static int
306 obuck_bconfig(struct fastbuf *f, uns item, int value)
307 {
308   switch (item)
309     {
310     case BCONFIG_CAN_OVERWRITE: ;
311       int old_value = FB_BUCKET(f)->can_overwrite;
312       if (value >= 0 && value <= 2)
313         FB_BUCKET(f)->can_overwrite = value;
314       return old_value;
315     default:
316       return -1;
317     }
318 }
319
320 struct fastbuf *
321 obuck_fetch(void)
322 {
323   struct fastbuf *b;
324   uns official_buflen = ALIGN(MIN(obuck_hdr.length, obuck_io_buflen), OBUCK_ALIGN);
325   uns real_buflen = official_buflen + OBUCK_ALIGN;
326
327   b = xmalloc(sizeof(struct fb_bucket) + real_buflen);
328   b->buffer = b->bptr = b->bstop = FB_BUCKET(b)->buffer;
329   b->bufend = b->buffer + official_buflen;
330   b->name = "bucket-read";
331   b->pos = 0;
332   b->refill = obuck_fb_refill;
333   b->spout = NULL;
334   b->seek = NULL;
335   b->close = obuck_fb_close;
336   b->config = obuck_bconfig;
337   FB_BUCKET(b)->start_pos = bucket_find_pos;
338   FB_BUCKET(b)->bucket_size = obuck_hdr.length;
339   obuck_fb_count++;
340   return b;
341 }
342
343 oid_t
344 obuck_predict_last_oid(void)
345 {
346   sh_off_t size = sh_seek(obuck_fd, 0, SEEK_END);
347   return (oid_t)(size >> OBUCK_SHIFT);
348 }
349
350 struct fastbuf *
351 obuck_create(u32 type)
352 {
353   ASSERT(!obuck_write_fb);
354
355   obuck_lock_append();
356   sh_off_t start = sh_seek(obuck_fd, 0, SEEK_END);
357   if (start & (OBUCK_ALIGN - 1))
358     obuck_broken("Misaligned file", start);
359   obuck_create_hdr.magic = OBUCK_INCOMPLETE_MAGIC;
360   obuck_create_hdr.oid = start >> OBUCK_SHIFT;
361   obuck_create_hdr.length = 0;
362   obuck_create_hdr.type = type;
363
364   struct fastbuf *b = xmalloc(sizeof(struct fb_bucket) + obuck_io_buflen);
365   obuck_write_fb = b;
366   b->buffer = FB_BUCKET(b)->buffer;
367   b->bptr = b->bstop = b->buffer;
368   b->bufend = b->buffer + obuck_io_buflen;
369   b->pos = -(int)sizeof(obuck_create_hdr);
370   b->name = "bucket-write";
371   b->refill = NULL;
372   b->spout = obuck_fb_spout;
373   b->seek = NULL;
374   b->close = NULL;
375   b->config = NULL;
376   FB_BUCKET(b)->start_pos = start;
377   FB_BUCKET(b)->bucket_size = 0;
378   FB_BUCKET(b)->can_overwrite = 2;
379   bwrite(b, &obuck_create_hdr, sizeof(obuck_create_hdr));
380
381   return b;
382 }
383
384 void
385 obuck_create_end(struct fastbuf *b, struct obuck_header *hdrp)
386 {
387   ASSERT(b == obuck_write_fb);
388   obuck_write_fb = NULL;
389
390   obuck_create_hdr.magic = OBUCK_MAGIC;
391   obuck_create_hdr.length = btell(b);
392   int pad = (OBUCK_ALIGN - sizeof(obuck_create_hdr) - obuck_create_hdr.length - 4) & (OBUCK_ALIGN - 1);
393   while (pad--)
394     bputc(b, 0);
395   bputl(b, OBUCK_TRAILER);
396   bflush(b);
397   ASSERT(!((FB_BUCKET(b)->start_pos + sizeof(obuck_create_hdr) + b->pos) & (OBUCK_ALIGN - 1)));
398   if (sh_pwrite(obuck_fd, &obuck_create_hdr, sizeof(obuck_create_hdr), FB_BUCKET(b)->start_pos) != sizeof(obuck_create_hdr))
399     die("Bucket header update failed: %m");
400   obuck_unlock();
401   memcpy(hdrp, &obuck_create_hdr, sizeof(obuck_create_hdr));
402   xfree(b);
403 }
404
405 void
406 obuck_delete(oid_t oid)
407 {
408   obuck_lock_write();
409   obuck_get(oid);
410   obuck_hdr.oid = OBUCK_OID_DELETED;
411   sh_pwrite(obuck_fd, &obuck_hdr, sizeof(obuck_hdr), bucket_find_pos);
412   obuck_unlock();
413 }
414
415 /*** Fast reading of the whole pool ***/
416
417 static struct fastbuf *obuck_rpf;
418 static uns slurp_remains;
419 static sh_off_t slurp_start, slurp_current, slurp_end;
420
421 static int
422 obuck_slurp_refill(struct fastbuf *f)
423 {
424   uns l;
425
426   if (!slurp_remains)
427     return 0;
428   l = bdirect_read_prepare(obuck_rpf, &f->buffer);
429   if (!l)
430     obuck_broken("Incomplete object", slurp_start);
431   l = MIN(l, slurp_remains);
432   bdirect_read_commit(obuck_rpf, f->buffer + l);
433   slurp_remains -= l;
434   f->bptr = f->buffer;
435   f->bufend = f->bstop = f->buffer + l;
436   return 1;
437 }
438
439 struct fastbuf *
440 obuck_slurp_pool(struct obuck_header *hdrp)
441 {
442   static struct fastbuf limiter;
443   uns l;
444
445   do
446     {
447       if (!obuck_rpf)
448         {
449           obuck_lock_read();
450           obuck_rpf = bopen(obuck_name, O_RDONLY, obuck_slurp_buflen);
451           bseek(obuck_rpf, 0, SEEK_END);
452           slurp_end = btell(obuck_rpf);
453           bsetpos(obuck_rpf, 0);
454           obuck_lock_read_to_scan();
455         }
456       else
457         {
458           bsetpos(obuck_rpf, slurp_current - 4);
459           if (bgetl(obuck_rpf) != OBUCK_TRAILER)
460             obuck_broken("Missing trailer", slurp_start);
461         }
462       slurp_start = btell(obuck_rpf);
463       if (slurp_start < slurp_end)
464         l = bread(obuck_rpf, hdrp, sizeof(struct obuck_header));
465       else
466         l = 0;
467       if (!l)
468         {
469           bclose(obuck_rpf);
470           obuck_rpf = NULL;
471           obuck_unlock();
472           return NULL;
473         }
474       if (l != sizeof(struct obuck_header))
475         obuck_broken("Short header read", slurp_start);
476       if (hdrp->magic != OBUCK_MAGIC)
477         obuck_broken("Missing magic number", slurp_start);
478       slurp_current = slurp_start + obuck_bucket_size(hdrp->length);
479     }
480   while (hdrp->oid == OBUCK_OID_DELETED);
481   if (obuck_get_pos(hdrp->oid) != slurp_start)
482     obuck_broken("Invalid backlink", slurp_start);
483   slurp_remains = hdrp->length;
484   limiter.bptr = limiter.bstop = limiter.buffer = limiter.bufend = NULL;
485   limiter.name = "Bucket";
486   limiter.pos = 0;
487   limiter.refill = obuck_slurp_refill;
488   return &limiter;
489 }
490
491 /*** Shakedown ***/
492
493 static inline void
494 shake_write(void *addr, int len, sh_off_t pos)
495 {
496   int l = sh_pwrite(obuck_fd, addr, len, pos);
497   if (l != len)
498     {
499       if (l < 0)
500         die("obuck_shakedown write error: %m");
501       else
502         die("obuck_shakedown write error: disk full");
503     }
504 }
505
506 static inline void
507 shake_sync(void)
508 {
509   if (obuck_shake_security > 1)
510     fdatasync(obuck_fd);
511 }
512
513 static void
514 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)
515 {
516   struct obuck_header *bhdr;
517   int boff = 0;
518   int l;
519   oid_t old_oid;
520
521   /* First of all, the "normal" part -- everything that will be written in this pass */
522   DBG("Backing up first round of changes at position %Lx + %x", (long long) bpos, norm_size);
523   while (boff < norm_size)
524     {
525       /* This needn't be optimized for speed. */
526       bhdr = (struct obuck_header *) (norm_buf + boff);
527       ASSERT(bhdr->magic == OBUCK_MAGIC);
528       l = obuck_bucket_size(bhdr->length);
529       old_oid = bhdr->oid;
530       bhdr->oid = bpos >> OBUCK_SHIFT;
531       shake_write(bhdr, l, bpos);
532       bhdr->oid = old_oid;
533       boff += l;
534       bpos += l;
535     }
536
537   /* If we have an incomplete bucket at the end of the buffer, we must copy it as well. */
538   if (more_size)
539     {
540       DBG("Backing up fragment of size %x and %x more", frag_size, more_size);
541
542       /* First the part we already have in the buffer */
543       bhdr = (struct obuck_header *) fragment;
544       ASSERT(bhdr->magic == OBUCK_MAGIC);
545       old_oid = bhdr->oid;
546       bhdr->oid = bpos >> OBUCK_SHIFT;
547       shake_write(bhdr, frag_size, bpos);
548       bhdr->oid = old_oid;
549       bpos += frag_size;
550
551       /* And then the rest, using a small 64K buffer */
552       byte *auxbuf = alloca(65536);
553       l = 0;
554       while (l < more_size)
555         {
556           int j = MIN(more_size-l, 65536);
557           if (sh_pread(obuck_fd, auxbuf, j, frag_pos + frag_size + l) != j)
558             die("obuck_shakedown read error: %m");
559           shake_write(auxbuf, j, bpos);
560           bpos += j;
561           l += j;
562         }
563     }
564 }
565
566 static void
567 shake_erase(sh_off_t start, sh_off_t end)
568 {
569   if (start > end)
570     die("shake_erase called with negative length, that's a bug");
571   ASSERT(!(start & (OBUCK_ALIGN-1)) && !(end & (OBUCK_ALIGN-1)));
572   while (start < end)
573     {
574       u32 check = OBUCK_TRAILER;
575       obuck_hdr.magic = OBUCK_MAGIC;
576       obuck_hdr.oid = OBUCK_OID_DELETED;
577       uns len = MIN(0x40000000, end-start);
578       obuck_hdr.length = len - sizeof(obuck_hdr) - 4;
579       DBG("Erasing %08x bytes at %Lx", len, (long long) start);
580       shake_write(&obuck_hdr, sizeof(obuck_hdr), start);
581       start += len;
582       shake_write(&check, 4, start-4);
583     }
584 }
585
586 void
587 obuck_shakedown(int (*kibitz)(struct obuck_header *old, oid_t new, byte *buck))
588 {
589   byte *buf;                                            /* Shakedown buffer and its size */
590   int buflen = ALIGN(obuck_shake_buflen, OBUCK_ALIGN);
591   byte *msg;                                            /* Error message we will print */
592   sh_off_t rstart, wstart;                              /* Original and new position of buffer start */
593   sh_off_t r_bucket_start, w_bucket_start;              /* Original and new position of the current bucket */
594   int roff, woff;                                       /* Orig/new position of the current bucket relative to buffer start */
595   int rsize;                                            /* Number of original bytes in the buffer */
596   int l;                                                /* Raw size of the current bucket */
597   int changed = 0;                                      /* "Something has been altered" flag */
598   int wrote_anything = 0;                               /* We already did a write to the bucket file */
599   struct obuck_header *rhdr, *whdr;                     /* Original and new address of header of the current bucket */
600   sh_off_t r_file_size;                                 /* Original size of the bucket file */
601   int more;                                             /* How much does the last bucket overlap the buffer */
602
603   buf = xmalloc(buflen);
604   rstart = wstart = 0;
605   roff = woff = rsize = 0;
606
607   /* We need to be the only accessor, all the object ID's are becoming invalid */
608   obuck_lock_write();
609   r_file_size = sh_seek(obuck_fd, 0, SEEK_END);
610   ASSERT(!(r_file_size & (OBUCK_ALIGN - 1)));
611   if (r_file_size >= (0x100000000 << OBUCK_SHIFT) - buflen)
612     die("Bucket file is too large for safe shakedown. Shaking down with Bucket.ShakeSecurity=0 will still work.");
613
614   DBG("Starting shakedown. Buffer size is %d, original length %Lx", buflen, (long long) r_file_size);
615
616   for(;;)
617     {
618       r_bucket_start = rstart + roff;
619       w_bucket_start = wstart + woff;
620       rhdr = (struct obuck_header *)(buf + roff);
621       whdr = (struct obuck_header *)(buf + woff);
622       if (roff == rsize)
623         {
624           more = 0;
625           goto next;
626         }
627       if (rhdr->magic != OBUCK_MAGIC ||
628           rhdr->oid != OBUCK_OID_DELETED && rhdr->oid != (oid_t)(r_bucket_start >> OBUCK_SHIFT))
629         {
630           msg = "header mismatch";
631           goto broken;
632         }
633       l = obuck_bucket_size(rhdr->length);
634       if (l > buflen)
635         {
636           if (rhdr->oid != OBUCK_OID_DELETED)
637             {
638               msg = "bucket longer than ShakeBufSize";
639               goto broken;
640             }
641           /* Empty buckets are allowed to be large, but we need to handle them extra */
642           DBG("Tricking around an extra-large empty bucket at %Lx + %x", (long long)r_bucket_start, l);
643           rsize = roff + l;
644         }
645       else
646         {
647           if (rsize - roff < l)
648             {
649               more = l - (rsize - roff);
650               goto next;
651             }
652           if (GET_U32((byte *)rhdr + l - 4) != OBUCK_TRAILER)
653             {
654               msg = "missing trailer";
655               goto broken;
656             }
657         }
658       if (rhdr->oid != OBUCK_OID_DELETED)
659         {
660           int status = kibitz(rhdr, w_bucket_start >> OBUCK_SHIFT, (byte *)(rhdr+1));
661           if (status)
662             {
663               int lnew = l;
664               if (status > 1)
665                 {
666                   /* Changed! Reconstruct the trailer. */
667                   lnew = obuck_bucket_size(rhdr->length);
668                   ASSERT(lnew <= l);
669                   PUT_U32((byte *)rhdr + lnew - 4, OBUCK_TRAILER);
670                   changed = 1;
671                 }
672               whdr = (struct obuck_header *)(buf+woff);
673               if (rhdr != whdr)
674                 memmove(whdr, rhdr, lnew);
675               whdr->oid = w_bucket_start >> OBUCK_SHIFT;
676               woff += lnew;
677             }
678           else
679             changed = 1;
680         }
681       else
682         {
683           kibitz(rhdr, OBUCK_OID_DELETED, NULL);
684           changed = 1;
685         }
686       roff += l;
687       continue;
688
689     next:
690       if (changed)
691         {
692           /* Write the new contents of the bucket file */
693           if (!wrote_anything)
694             {
695               if (obuck_shake_security)
696                 {
697                   /* But first write a backup at the end of the file to ensure nothing can be lost. */
698                   shake_write_backup(r_file_size, buf, woff, buf+roff, rsize-roff, rstart+roff, more);
699                   shake_sync();
700                 }
701               wrote_anything = 1;
702             }
703           if (woff)
704             {
705               DBG("Write %Lx %x", wstart, woff);
706               shake_write(buf, woff, wstart);
707               shake_sync();
708             }
709         }
710       else
711         ASSERT(wstart == rstart);
712
713       /* In any case, update the write position */
714       wstart += woff;
715       woff = 0;
716
717       /* Skip what's been read and if there is any fragment at the end of the buffer, move it to the start */
718       rstart += roff;
719       if (more)
720         {
721           memmove(buf, buf+roff, rsize-roff);
722           rsize = rsize-roff;
723         }
724       else
725         rsize = 0;
726
727       /* And refill the buffer */
728       r_bucket_start = rstart+rsize;    /* Also needed for error messages */
729       l = sh_pread(obuck_fd, buf+rsize, MIN(buflen-rsize, r_file_size - r_bucket_start), r_bucket_start);
730       DBG("Read  %Lx %x (%x inherited)", (long long)r_bucket_start, l, rsize);
731       if (l < 0)
732         die("obuck_shakedown read error: %m");
733       if (!l)
734         {
735           if (!more)
736             break;
737           msg = "unexpected EOF";
738           goto broken;
739         }
740       if (l & (OBUCK_ALIGN-1))
741         {
742           msg = "garbage at the end of file";
743           goto broken;
744         }
745       rsize += l;
746       roff = 0;
747     }
748
749   DBG("Finished at position %Lx", (long long) wstart);
750   sh_ftruncate(obuck_fd, wstart);
751   shake_sync();
752
753   obuck_unlock();
754   xfree(buf);
755   return;
756
757  broken:
758   log(L_ERROR, "Error during object pool shakedown: %s (pos=%Ld, id=%x), gathering debris",
759       msg, (long long) r_bucket_start, (uns)(r_bucket_start >> OBUCK_SHIFT));
760   /*
761    * We can attempt to clean up the bucket file by erasing everything between the last
762    * byte written and the next byte to be read. If the secure mode is switched on, we can
763    * guarantee that no data are lost, only some might be duplicated.
764    */
765   shake_erase(wstart, rstart);
766   die("Fatal error during object pool shakedown");
767 }
768
769 /*** Testing ***/
770
771 #ifdef TEST
772
773 #define COUNT 5000
774 #define MAXLEN 10000
775 #define KILLPERC 13
776 #define LEN(i) ((259309*(i))%MAXLEN)
777
778 static int test_kibitz(struct obuck_header *h, oid_t new, byte *buck)
779 {
780   return 1;
781 }
782
783 int main(int argc, char **argv)
784 {
785   int ids[COUNT];
786   unsigned int i, j, cnt;
787   struct obuck_header h;
788   struct fastbuf *b;
789
790   log_init(NULL);
791   if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0 ||
792       optind < argc)
793   {
794     fputs("This program supports only the following command-line arguments:\n" CF_USAGE, stderr);
795     exit(1);
796   }
797
798   unlink(obuck_name);
799   obuck_init(1);
800   for(j=0; j<COUNT; j++)
801     {
802       b = obuck_create(BUCKET_TYPE_PLAIN);
803       for(i=0; i<LEN(j); i++)
804         bputc(b, (i+j) % 256);
805       obuck_create_end(b, &h);
806       printf("Writing %08x %d\n", h.oid, h.length);
807       ids[j] = h.oid;
808     }
809   for(j=0; j<COUNT; j++)
810     if (j % 100 < KILLPERC)
811       {
812         printf("Deleting %08x\n", ids[j]);
813         obuck_delete(ids[j]);
814       }
815   cnt = 0;
816   for(j=0; j<COUNT; j++)
817     if (j % 100 >= KILLPERC)
818       {
819         cnt++;
820         h.oid = ids[j];
821         obuck_find_by_oid(&h);
822         b = obuck_fetch();
823         printf("Reading %08x %d\n", h.oid, h.length);
824         if (h.length != LEN(j))
825           die("Invalid length");
826         for(i=0; i<h.length; i++)
827           if ((unsigned) bgetc(b) != (i+j) % 256)
828             die("Contents mismatch");
829         if (bgetc(b) != EOF)
830           die("EOF mismatch");
831         bclose(b);
832       }
833   obuck_shakedown(test_kibitz);
834   if (obuck_find_first(&h, 0))
835     do
836       {
837         printf("<<< %08x\t%d\n", h.oid, h.length);
838         cnt--;
839       }
840     while (obuck_find_next(&h, 0));
841   if (cnt)
842     die("Walk mismatch");
843   obuck_cleanup();
844   return 0;
845 }
846
847 #endif