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