chiark / gitweb /
15a752d507eae8892e92ae7931dd3d562347a28c
[elogind.git] / src / journal / journal-file.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2011 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <sys/mman.h>
23 #include <errno.h>
24 #include <sys/uio.h>
25 #include <unistd.h>
26 #include <sys/statvfs.h>
27 #include <fcntl.h>
28 #include <stddef.h>
29
30 #include "journal-def.h"
31 #include "journal-file.h"
32 #include "lookup3.h"
33 #include "compress.h"
34
35 #define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*16ULL)
36 #define DEFAULT_FIELD_HASH_TABLE_SIZE (2047ULL*16ULL)
37
38 #define DEFAULT_WINDOW_SIZE (128ULL*1024ULL*1024ULL)
39
40 #define COMPRESSION_SIZE_THRESHOLD (64ULL)
41
42 /* This is the minimum journal file size */
43 #define JOURNAL_FILE_SIZE_MIN (64ULL*1024ULL)
44
45 /* These are the lower and upper bounds if we deduce the max_use value
46  * from the file system size */
47 #define DEFAULT_MAX_USE_LOWER (1ULL*1024ULL*1024ULL)           /* 1 MiB */
48 #define DEFAULT_MAX_USE_UPPER (4ULL*1024ULL*1024ULL*1024ULL)   /* 4 GiB */
49
50 /* This is the upper bound if we deduce max_size from max_use */
51 #define DEFAULT_MAX_SIZE_UPPER (16ULL*1024ULL*1024ULL)         /* 16 MiB */
52
53 /* This is the upper bound if we deduce the keep_free value from the
54  * file system size */
55 #define DEFAULT_KEEP_FREE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
56
57 /* This is the keep_free value when we can't determine the system
58  * size */
59 #define DEFAULT_KEEP_FREE (1024ULL*1024ULL)                    /* 1 MB */
60
61 static const char signature[] = { 'L', 'P', 'K', 'S', 'H', 'H', 'R', 'H' };
62
63 #define ALIGN64(x) (((x) + 7ULL) & ~7ULL)
64
65 void journal_file_close(JournalFile *f) {
66         int t;
67
68         assert(f);
69
70         if (f->header && f->writable)
71                 f->header->state = STATE_OFFLINE;
72
73
74         for (t = 0; t < _WINDOW_MAX; t++)
75                 if (f->windows[t].ptr)
76                         munmap(f->windows[t].ptr, f->windows[t].size);
77
78         if (f->fd >= 0)
79                 close_nointr_nofail(f->fd);
80
81         free(f->path);
82
83 #ifdef HAVE_XZ
84         free(f->compress_buffer);
85 #endif
86
87         free(f);
88 }
89
90 static int journal_file_init_header(JournalFile *f, JournalFile *template) {
91         Header h;
92         ssize_t k;
93         int r;
94
95         assert(f);
96
97         zero(h);
98         memcpy(h.signature, signature, 8);
99         h.arena_offset = htole64(ALIGN64(sizeof(h)));
100
101         r = sd_id128_randomize(&h.file_id);
102         if (r < 0)
103                 return r;
104
105         if (template) {
106                 h.seqnum_id = template->header->seqnum_id;
107                 h.seqnum = template->header->seqnum;
108         } else
109                 h.seqnum_id = h.file_id;
110
111         k = pwrite(f->fd, &h, sizeof(h), 0);
112         if (k < 0)
113                 return -errno;
114
115         if (k != sizeof(h))
116                 return -EIO;
117
118         return 0;
119 }
120
121 static int journal_file_refresh_header(JournalFile *f) {
122         int r;
123         sd_id128_t boot_id;
124
125         assert(f);
126
127         r = sd_id128_get_machine(&f->header->machine_id);
128         if (r < 0)
129                 return r;
130
131         r = sd_id128_get_boot(&boot_id);
132         if (r < 0)
133                 return r;
134
135         if (sd_id128_equal(boot_id, f->header->boot_id))
136                 f->tail_entry_monotonic_valid = true;
137
138         f->header->boot_id = boot_id;
139
140         f->header->state = STATE_ONLINE;
141
142         __sync_synchronize();
143
144         return 0;
145 }
146
147 static int journal_file_verify_header(JournalFile *f) {
148         assert(f);
149
150         if (memcmp(f->header, signature, 8))
151                 return -EBADMSG;
152
153 #ifdef HAVE_XZ
154         if ((le64toh(f->header->incompatible_flags) & ~HEADER_INCOMPATIBLE_COMPRESSED) != 0)
155                 return -EPROTONOSUPPORT;
156 #else
157         if (f->header->incompatible_flags != 0)
158                 return -EPROTONOSUPPORT;
159 #endif
160
161         if ((uint64_t) f->last_stat.st_size < (le64toh(f->header->arena_offset) + le64toh(f->header->arena_size)))
162                 return -ENODATA;
163
164         if (f->writable) {
165                 uint32_t state;
166                 sd_id128_t machine_id;
167                 int r;
168
169                 r = sd_id128_get_machine(&machine_id);
170                 if (r < 0)
171                         return r;
172
173                 if (!sd_id128_equal(machine_id, f->header->machine_id))
174                         return -EHOSTDOWN;
175
176                 state = f->header->state;
177
178                 if (state == STATE_ONLINE)
179                         log_debug("Journal file %s is already online. Assuming unclean closing. Ignoring.", f->path);
180                 else if (state == STATE_ARCHIVED)
181                         return -ESHUTDOWN;
182                 else if (state != STATE_OFFLINE)
183                         log_debug("Journal file %s has unknown state %u. Ignoring.", f->path, state);
184         }
185
186         return 0;
187 }
188
189 static int journal_file_allocate(JournalFile *f, uint64_t offset, uint64_t size) {
190         uint64_t old_size, new_size;
191
192         assert(f);
193
194         /* We assume that this file is not sparse, and we know that
195          * for sure, since we always call posix_fallocate()
196          * ourselves */
197
198         old_size =
199                 le64toh(f->header->arena_offset) +
200                 le64toh(f->header->arena_size);
201
202         new_size = PAGE_ALIGN(offset + size);
203         if (new_size < le64toh(f->header->arena_offset))
204                 new_size = le64toh(f->header->arena_offset);
205
206         if (new_size <= old_size)
207                 return 0;
208
209         if (f->metrics.max_size > 0 &&
210             new_size > f->metrics.max_size)
211                 return -E2BIG;
212
213         if (new_size > f->metrics.min_size &&
214             f->metrics.keep_free > 0) {
215                 struct statvfs svfs;
216
217                 if (fstatvfs(f->fd, &svfs) >= 0) {
218                         uint64_t available;
219
220                         available = svfs.f_bfree * svfs.f_bsize;
221
222                         if (available >= f->metrics.keep_free)
223                                 available -= f->metrics.keep_free;
224                         else
225                                 available = 0;
226
227                         if (new_size - old_size > available)
228                                 return -E2BIG;
229                 }
230         }
231
232         /* Note that the glibc fallocate() fallback is very
233            inefficient, hence we try to minimize the allocation area
234            as we can. */
235         if (posix_fallocate(f->fd, old_size, new_size - old_size) < 0)
236                 return -errno;
237
238         if (fstat(f->fd, &f->last_stat) < 0)
239                 return -errno;
240
241         f->header->arena_size = new_size - htole64(f->header->arena_offset);
242
243         return 0;
244 }
245
246 static int journal_file_map(
247                 JournalFile *f,
248                 uint64_t offset,
249                 uint64_t size,
250                 void **_window,
251                 uint64_t *_woffset,
252                 uint64_t *_wsize,
253                 void **ret) {
254
255         uint64_t woffset, wsize;
256         void *window;
257
258         assert(f);
259         assert(size > 0);
260         assert(ret);
261
262         woffset = offset & ~((uint64_t) page_size() - 1ULL);
263         wsize = size + (offset - woffset);
264         wsize = PAGE_ALIGN(wsize);
265
266         /* Avoid SIGBUS on invalid accesses */
267         if (woffset + wsize > (uint64_t) PAGE_ALIGN(f->last_stat.st_size))
268                 return -EADDRNOTAVAIL;
269
270         window = mmap(NULL, wsize, f->prot, MAP_SHARED, f->fd, woffset);
271         if (window == MAP_FAILED)
272                 return -errno;
273
274         if (_window)
275                 *_window = window;
276
277         if (_woffset)
278                 *_woffset = woffset;
279
280         if (_wsize)
281                 *_wsize = wsize;
282
283         *ret = (uint8_t*) window + (offset - woffset);
284
285         return 0;
286 }
287
288 static int journal_file_move_to(JournalFile *f, int wt, uint64_t offset, uint64_t size, void **ret) {
289         void *p = NULL;
290         uint64_t delta;
291         int r;
292         Window *w;
293
294         assert(f);
295         assert(ret);
296         assert(wt >= 0);
297         assert(wt < _WINDOW_MAX);
298
299         w = f->windows + wt;
300
301         if (_likely_(w->ptr &&
302                      w->offset <= offset &&
303                      w->offset + w->size >= offset + size)) {
304
305                 *ret = (uint8_t*) w->ptr + (offset - w->offset);
306                 return 0;
307         }
308
309         if (w->ptr) {
310                 if (munmap(w->ptr, w->size) < 0)
311                         return -errno;
312
313                 w->ptr = NULL;
314                 w->size = w->offset = 0;
315         }
316
317         if (size < DEFAULT_WINDOW_SIZE) {
318                 /* If the default window size is larger then what was
319                  * asked for extend the mapping a bit in the hope to
320                  * minimize needed remappings later on. We add half
321                  * the window space before and half behind the
322                  * requested mapping */
323
324                 delta = PAGE_ALIGN((DEFAULT_WINDOW_SIZE - size) / 2);
325
326                 if (offset < delta)
327                         delta = offset;
328
329                 offset -= delta;
330                 size += (DEFAULT_WINDOW_SIZE - delta);
331         } else
332                 delta = 0;
333
334         if (offset > (uint64_t) f->last_stat.st_size)
335                 return -EADDRNOTAVAIL;
336
337         if (offset + size > (uint64_t) f->last_stat.st_size)
338                 size = PAGE_ALIGN((uint64_t) f->last_stat.st_size - offset);
339
340         if (size <= 0)
341                 return -EADDRNOTAVAIL;
342
343         r = journal_file_map(f,
344                              offset, size,
345                              &w->ptr, &w->offset, &w->size,
346                              &p);
347
348         if (r < 0)
349                 return r;
350
351         *ret = (uint8_t*) p + delta;
352         return 0;
353 }
354
355 static bool verify_hash(Object *o) {
356         uint64_t h1, h2;
357
358         assert(o);
359
360         if (o->object.type == OBJECT_DATA && !(o->object.flags & OBJECT_COMPRESSED)) {
361                 h1 = le64toh(o->data.hash);
362                 h2 = hash64(o->data.payload, le64toh(o->object.size) - offsetof(Object, data.payload));
363         } else if (o->object.type == OBJECT_FIELD) {
364                 h1 = le64toh(o->field.hash);
365                 h2 = hash64(o->field.payload, le64toh(o->object.size) - offsetof(Object, field.payload));
366         } else
367                 return true;
368
369         return h1 == h2;
370 }
371
372 int journal_file_move_to_object(JournalFile *f, int type, uint64_t offset, Object **ret) {
373         int r;
374         void *t;
375         Object *o;
376         uint64_t s;
377
378         assert(f);
379         assert(ret);
380         assert(type < _OBJECT_TYPE_MAX);
381
382         r = journal_file_move_to(f, type >= 0 ? type : WINDOW_UNKNOWN, offset, sizeof(ObjectHeader), &t);
383         if (r < 0)
384                 return r;
385
386         o = (Object*) t;
387         s = le64toh(o->object.size);
388
389         if (s < sizeof(ObjectHeader))
390                 return -EBADMSG;
391
392         if (type >= 0 && o->object.type != type)
393                 return -EBADMSG;
394
395         if (s > sizeof(ObjectHeader)) {
396                 r = journal_file_move_to(f, o->object.type, offset, s, &t);
397                 if (r < 0)
398                         return r;
399
400                 o = (Object*) t;
401         }
402
403         if (!verify_hash(o))
404                 return -EBADMSG;
405
406         *ret = o;
407         return 0;
408 }
409
410 static uint64_t journal_file_seqnum(JournalFile *f, uint64_t *seqnum) {
411         uint64_t r;
412
413         assert(f);
414
415         r = le64toh(f->header->seqnum) + 1;
416
417         if (seqnum) {
418                 /* If an external seqnum counter was passed, we update
419                  * both the local and the external one, and set it to
420                  * the maximum of both */
421
422                 if (*seqnum + 1 > r)
423                         r = *seqnum + 1;
424
425                 *seqnum = r;
426         }
427
428         f->header->seqnum = htole64(r);
429
430         if (f->header->first_seqnum == 0)
431                 f->header->first_seqnum = htole64(r);
432
433         return r;
434 }
435
436 static int journal_file_append_object(JournalFile *f, int type, uint64_t size, Object **ret, uint64_t *offset) {
437         int r;
438         uint64_t p;
439         Object *tail, *o;
440         void *t;
441
442         assert(f);
443         assert(size >= sizeof(ObjectHeader));
444         assert(offset);
445         assert(ret);
446
447         p = le64toh(f->header->tail_object_offset);
448         if (p == 0)
449                 p = le64toh(f->header->arena_offset);
450         else {
451                 r = journal_file_move_to_object(f, -1, p, &tail);
452                 if (r < 0)
453                         return r;
454
455                 p += ALIGN64(le64toh(tail->object.size));
456         }
457
458         r = journal_file_allocate(f, p, size);
459         if (r < 0)
460                 return r;
461
462         r = journal_file_move_to(f, type, p, size, &t);
463         if (r < 0)
464                 return r;
465
466         o = (Object*) t;
467
468         zero(o->object);
469         o->object.type = type;
470         o->object.size = htole64(size);
471
472         f->header->tail_object_offset = htole64(p);
473         f->header->n_objects = htole64(le64toh(f->header->n_objects) + 1);
474
475         *ret = o;
476         *offset = p;
477
478         return 0;
479 }
480
481 static int journal_file_setup_data_hash_table(JournalFile *f) {
482         uint64_t s, p;
483         Object *o;
484         int r;
485
486         assert(f);
487
488         s = DEFAULT_DATA_HASH_TABLE_SIZE;
489         r = journal_file_append_object(f,
490                                        OBJECT_DATA_HASH_TABLE,
491                                        offsetof(Object, hash_table.items) + s,
492                                        &o, &p);
493         if (r < 0)
494                 return r;
495
496         memset(o->hash_table.items, 0, s);
497
498         f->header->data_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
499         f->header->data_hash_table_size = htole64(s);
500
501         return 0;
502 }
503
504 static int journal_file_setup_field_hash_table(JournalFile *f) {
505         uint64_t s, p;
506         Object *o;
507         int r;
508
509         assert(f);
510
511         s = DEFAULT_FIELD_HASH_TABLE_SIZE;
512         r = journal_file_append_object(f,
513                                        OBJECT_FIELD_HASH_TABLE,
514                                        offsetof(Object, hash_table.items) + s,
515                                        &o, &p);
516         if (r < 0)
517                 return r;
518
519         memset(o->hash_table.items, 0, s);
520
521         f->header->field_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
522         f->header->field_hash_table_size = htole64(s);
523
524         return 0;
525 }
526
527 static int journal_file_map_data_hash_table(JournalFile *f) {
528         uint64_t s, p;
529         void *t;
530         int r;
531
532         assert(f);
533
534         p = le64toh(f->header->data_hash_table_offset);
535         s = le64toh(f->header->data_hash_table_size);
536
537         r = journal_file_move_to(f,
538                                  WINDOW_DATA_HASH_TABLE,
539                                  p, s,
540                                  &t);
541         if (r < 0)
542                 return r;
543
544         f->data_hash_table = t;
545         return 0;
546 }
547
548 static int journal_file_map_field_hash_table(JournalFile *f) {
549         uint64_t s, p;
550         void *t;
551         int r;
552
553         assert(f);
554
555         p = le64toh(f->header->field_hash_table_offset);
556         s = le64toh(f->header->field_hash_table_size);
557
558         r = journal_file_move_to(f,
559                                  WINDOW_FIELD_HASH_TABLE,
560                                  p, s,
561                                  &t);
562         if (r < 0)
563                 return r;
564
565         f->field_hash_table = t;
566         return 0;
567 }
568
569 static int journal_file_link_data(JournalFile *f, Object *o, uint64_t offset, uint64_t hash) {
570         uint64_t p, h;
571         int r;
572
573         assert(f);
574         assert(o);
575         assert(offset > 0);
576         assert(o->object.type == OBJECT_DATA);
577
578         o->data.next_hash_offset = o->data.next_field_offset = 0;
579         o->data.entry_offset = o->data.entry_array_offset = 0;
580         o->data.n_entries = 0;
581
582         h = hash % (le64toh(f->header->data_hash_table_size) / sizeof(HashItem));
583         p = le64toh(f->data_hash_table[h].head_hash_offset);
584         if (p == 0) {
585                 /* Only entry in the hash table is easy */
586                 f->data_hash_table[h].head_hash_offset = htole64(offset);
587         } else {
588                 /* Temporarily move back to the previous data object,
589                  * to patch in pointer */
590
591                 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
592                 if (r < 0)
593                         return r;
594
595                 o->data.next_hash_offset = htole64(offset);
596
597                 r = journal_file_move_to_object(f, OBJECT_DATA, offset, &o);
598                 if (r < 0)
599                         return r;
600         }
601
602         f->data_hash_table[h].tail_hash_offset = htole64(offset);
603
604         return 0;
605 }
606
607 int journal_file_find_data_object_with_hash(
608                 JournalFile *f,
609                 const void *data, uint64_t size, uint64_t hash,
610                 Object **ret, uint64_t *offset) {
611         uint64_t p, osize, h;
612         int r;
613
614         assert(f);
615         assert(data || size == 0);
616
617         osize = offsetof(Object, data.payload) + size;
618
619         if (f->header->data_hash_table_size == 0)
620                 return -EBADMSG;
621
622         h = hash % (le64toh(f->header->data_hash_table_size) / sizeof(HashItem));
623         p = le64toh(f->data_hash_table[h].head_hash_offset);
624
625         while (p > 0) {
626                 Object *o;
627
628                 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
629                 if (r < 0)
630                         return r;
631
632                 if (le64toh(o->data.hash) != hash)
633                         goto next;
634
635                 if (o->object.flags & OBJECT_COMPRESSED) {
636 #ifdef HAVE_XZ
637                         uint64_t l, rsize;
638
639                         l = le64toh(o->object.size);
640                         if (l <= offsetof(Object, data.payload))
641                                 return -EBADMSG;
642
643                         l -= offsetof(Object, data.payload);
644
645                         if (!uncompress_blob(o->data.payload, l, &f->compress_buffer, &f->compress_buffer_size, &rsize))
646                                 return -EBADMSG;
647
648                         if (rsize == size &&
649                             memcmp(f->compress_buffer, data, size) == 0) {
650
651                                 if (ret)
652                                         *ret = o;
653
654                                 if (offset)
655                                         *offset = p;
656
657                                 return 1;
658                         }
659 #else
660                         return -EPROTONOSUPPORT;
661 #endif
662
663                 } else if (le64toh(o->object.size) == osize &&
664                            memcmp(o->data.payload, data, size) == 0) {
665
666                         if (ret)
667                                 *ret = o;
668
669                         if (offset)
670                                 *offset = p;
671
672                         return 1;
673                 }
674
675         next:
676                 p = le64toh(o->data.next_hash_offset);
677         }
678
679         return 0;
680 }
681
682 int journal_file_find_data_object(
683                 JournalFile *f,
684                 const void *data, uint64_t size,
685                 Object **ret, uint64_t *offset) {
686
687         uint64_t hash;
688
689         assert(f);
690         assert(data || size == 0);
691
692         hash = hash64(data, size);
693
694         return journal_file_find_data_object_with_hash(f,
695                                                        data, size, hash,
696                                                        ret, offset);
697 }
698
699 static int journal_file_append_data(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset) {
700         uint64_t hash, p;
701         uint64_t osize;
702         Object *o;
703         int r;
704         bool compressed = false;
705
706         assert(f);
707         assert(data || size == 0);
708
709         hash = hash64(data, size);
710
711         r = journal_file_find_data_object_with_hash(f, data, size, hash, &o, &p);
712         if (r < 0)
713                 return r;
714         else if (r > 0) {
715
716                 if (ret)
717                         *ret = o;
718
719                 if (offset)
720                         *offset = p;
721
722                 return 0;
723         }
724
725         osize = offsetof(Object, data.payload) + size;
726         r = journal_file_append_object(f, OBJECT_DATA, osize, &o, &p);
727         if (r < 0)
728                 return r;
729
730         o->data.hash = htole64(hash);
731
732 #ifdef HAVE_XZ
733         if (f->compress &&
734             size >= COMPRESSION_SIZE_THRESHOLD) {
735                 uint64_t rsize;
736
737                 compressed = compress_blob(data, size, o->data.payload, &rsize);
738
739                 if (compressed) {
740                         o->object.size = htole64(offsetof(Object, data.payload) + rsize);
741                         o->object.flags |= OBJECT_COMPRESSED;
742
743                         f->header->incompatible_flags = htole32(le32toh(f->header->incompatible_flags) | HEADER_INCOMPATIBLE_COMPRESSED);
744
745                         log_debug("Compressed data object %lu -> %lu", (unsigned long) size, (unsigned long) rsize);
746                 }
747         }
748 #endif
749
750         if (!compressed)
751                 memcpy(o->data.payload, data, size);
752
753         r = journal_file_link_data(f, o, p, hash);
754         if (r < 0)
755                 return r;
756
757         if (ret)
758                 *ret = o;
759
760         if (offset)
761                 *offset = p;
762
763         return 0;
764 }
765
766 uint64_t journal_file_entry_n_items(Object *o) {
767         assert(o);
768         assert(o->object.type == htole64(OBJECT_ENTRY));
769
770         return (le64toh(o->object.size) - offsetof(Object, entry.items)) / sizeof(EntryItem);
771 }
772
773 static uint64_t journal_file_entry_array_n_items(Object *o) {
774         assert(o);
775         assert(o->object.type == htole64(OBJECT_ENTRY_ARRAY));
776
777         return (le64toh(o->object.size) - offsetof(Object, entry_array.items)) / sizeof(uint64_t);
778 }
779
780 static int link_entry_into_array(JournalFile *f,
781                                  uint64_t *first,
782                                  uint64_t *idx,
783                                  uint64_t p) {
784         int r;
785         uint64_t n = 0, ap = 0, q, i, a, hidx;
786         Object *o;
787
788         assert(f);
789         assert(first);
790         assert(idx);
791         assert(p > 0);
792
793         a = le64toh(*first);
794         i = hidx = le64toh(*idx);
795         while (a > 0) {
796
797                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
798                 if (r < 0)
799                         return r;
800
801                 n = journal_file_entry_array_n_items(o);
802                 if (i < n) {
803                         o->entry_array.items[i] = htole64(p);
804                         *idx = htole64(hidx + 1);
805                         return 0;
806                 }
807
808                 i -= n;
809                 ap = a;
810                 a = le64toh(o->entry_array.next_entry_array_offset);
811         }
812
813         if (hidx > n)
814                 n = (hidx+1) * 2;
815         else
816                 n = n * 2;
817
818         if (n < 4)
819                 n = 4;
820
821         r = journal_file_append_object(f, OBJECT_ENTRY_ARRAY,
822                                        offsetof(Object, entry_array.items) + n * sizeof(uint64_t),
823                                        &o, &q);
824         if (r < 0)
825                 return r;
826
827         o->entry_array.items[i] = htole64(p);
828
829         if (ap == 0)
830                 *first = q;
831         else {
832                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, ap, &o);
833                 if (r < 0)
834                         return r;
835
836                 o->entry_array.next_entry_array_offset = htole64(q);
837         }
838
839         *idx = htole64(hidx + 1);
840
841         return 0;
842 }
843
844 static int link_entry_into_array_plus_one(JournalFile *f,
845                                           uint64_t *extra,
846                                           uint64_t *first,
847                                           uint64_t *idx,
848                                           uint64_t p) {
849
850         int r;
851
852         assert(f);
853         assert(extra);
854         assert(first);
855         assert(idx);
856         assert(p > 0);
857
858         if (*idx == 0)
859                 *extra = htole64(p);
860         else {
861                 uint64_t i;
862
863                 i = le64toh(*idx) - 1;
864                 r = link_entry_into_array(f, first, &i, p);
865                 if (r < 0)
866                         return r;
867         }
868
869         *idx = htole64(le64toh(*idx) + 1);
870         return 0;
871 }
872
873 static int journal_file_link_entry_item(JournalFile *f, Object *o, uint64_t offset, uint64_t i) {
874         uint64_t p;
875         int r;
876         assert(f);
877         assert(o);
878         assert(offset > 0);
879
880         p = le64toh(o->entry.items[i].object_offset);
881         if (p == 0)
882                 return -EINVAL;
883
884         r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
885         if (r < 0)
886                 return r;
887
888         return link_entry_into_array_plus_one(f,
889                                               &o->data.entry_offset,
890                                               &o->data.entry_array_offset,
891                                               &o->data.n_entries,
892                                               offset);
893 }
894
895 static int journal_file_link_entry(JournalFile *f, Object *o, uint64_t offset) {
896         uint64_t n, i;
897         int r;
898
899         assert(f);
900         assert(o);
901         assert(offset > 0);
902         assert(o->object.type == OBJECT_ENTRY);
903
904         __sync_synchronize();
905
906         /* Link up the entry itself */
907         r = link_entry_into_array(f,
908                                   &f->header->entry_array_offset,
909                                   &f->header->n_entries,
910                                   offset);
911         if (r < 0)
912                 return r;
913
914         log_error("=> %s seqnr=%lu n_entries=%lu", f->path, (unsigned long) o->entry.seqnum, (unsigned long) f->header->n_entries);
915
916         if (f->header->head_entry_realtime == 0)
917                 f->header->head_entry_realtime = o->entry.realtime;
918
919         f->header->tail_entry_realtime = o->entry.realtime;
920         f->header->tail_entry_monotonic = o->entry.monotonic;
921
922         f->tail_entry_monotonic_valid = true;
923
924         /* Link up the items */
925         n = journal_file_entry_n_items(o);
926         for (i = 0; i < n; i++) {
927                 r = journal_file_link_entry_item(f, o, offset, i);
928                 if (r < 0)
929                         return r;
930         }
931
932         return 0;
933 }
934
935 static int journal_file_append_entry_internal(
936                 JournalFile *f,
937                 const dual_timestamp *ts,
938                 uint64_t xor_hash,
939                 const EntryItem items[], unsigned n_items,
940                 uint64_t *seqnum,
941                 Object **ret, uint64_t *offset) {
942         uint64_t np;
943         uint64_t osize;
944         Object *o;
945         int r;
946
947         assert(f);
948         assert(items || n_items == 0);
949         assert(ts);
950
951         osize = offsetof(Object, entry.items) + (n_items * sizeof(EntryItem));
952
953         r = journal_file_append_object(f, OBJECT_ENTRY, osize, &o, &np);
954         if (r < 0)
955                 return r;
956
957         o->entry.seqnum = htole64(journal_file_seqnum(f, seqnum));
958         memcpy(o->entry.items, items, n_items * sizeof(EntryItem));
959         o->entry.realtime = htole64(ts->realtime);
960         o->entry.monotonic = htole64(ts->monotonic);
961         o->entry.xor_hash = htole64(xor_hash);
962         o->entry.boot_id = f->header->boot_id;
963
964         r = journal_file_link_entry(f, o, np);
965         if (r < 0)
966                 return r;
967
968         if (ret)
969                 *ret = o;
970
971         if (offset)
972                 *offset = np;
973
974         return 0;
975 }
976
977 void journal_file_post_change(JournalFile *f) {
978         assert(f);
979
980         /* inotify() does not receive IN_MODIFY events from file
981          * accesses done via mmap(). After each access we hence
982          * trigger IN_MODIFY by truncating the journal file to its
983          * current size which triggers IN_MODIFY. */
984
985         __sync_synchronize();
986
987         if (ftruncate(f->fd, f->last_stat.st_size) < 0)
988                 log_error("Failed to to truncate file to its own size: %m");
989 }
990
991 int journal_file_append_entry(JournalFile *f, const dual_timestamp *ts, const struct iovec iovec[], unsigned n_iovec, uint64_t *seqnum, Object **ret, uint64_t *offset) {
992         unsigned i;
993         EntryItem *items;
994         int r;
995         uint64_t xor_hash = 0;
996         struct dual_timestamp _ts;
997
998         assert(f);
999         assert(iovec || n_iovec == 0);
1000
1001         if (!f->writable)
1002                 return -EPERM;
1003
1004         if (!ts) {
1005                 dual_timestamp_get(&_ts);
1006                 ts = &_ts;
1007         }
1008
1009         if (f->tail_entry_monotonic_valid &&
1010             ts->monotonic < le64toh(f->header->tail_entry_monotonic))
1011                 return -EINVAL;
1012
1013         if (ts->realtime < le64toh(f->header->tail_entry_realtime))
1014                 return -EINVAL;
1015
1016         items = alloca(sizeof(EntryItem) * n_iovec);
1017
1018         for (i = 0; i < n_iovec; i++) {
1019                 uint64_t p;
1020                 Object *o;
1021
1022                 r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p);
1023                 if (r < 0)
1024                         return r;
1025
1026                 xor_hash ^= le64toh(o->data.hash);
1027                 items[i].object_offset = htole64(p);
1028                 items[i].hash = o->data.hash;
1029         }
1030
1031         r = journal_file_append_entry_internal(f, ts, xor_hash, items, n_iovec, seqnum, ret, offset);
1032
1033         journal_file_post_change(f);
1034
1035         return r;
1036 }
1037
1038 static int generic_array_get(JournalFile *f,
1039                              uint64_t first,
1040                              uint64_t i,
1041                              Object **ret, uint64_t *offset) {
1042
1043         Object *o;
1044         uint64_t p = 0, a;
1045         int r;
1046
1047         assert(f);
1048
1049         a = first;
1050         while (a > 0) {
1051                 uint64_t n;
1052
1053                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
1054                 if (r < 0)
1055                         return r;
1056
1057                 n = journal_file_entry_array_n_items(o);
1058                 if (i < n) {
1059                         p = le64toh(o->entry_array.items[i]);
1060                         break;
1061                 }
1062
1063                 i -= n;
1064                 a = le64toh(o->entry_array.next_entry_array_offset);
1065         }
1066
1067         if (a <= 0 || p <= 0)
1068                 return 0;
1069
1070         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1071         if (r < 0)
1072                 return r;
1073
1074         if (ret)
1075                 *ret = o;
1076
1077         if (offset)
1078                 *offset = p;
1079
1080         return 1;
1081 }
1082
1083 static int generic_array_get_plus_one(JournalFile *f,
1084                                       uint64_t extra,
1085                                       uint64_t first,
1086                                       uint64_t i,
1087                                       Object **ret, uint64_t *offset) {
1088
1089         Object *o;
1090
1091         assert(f);
1092
1093         if (i == 0) {
1094                 int r;
1095
1096                 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
1097                 if (r < 0)
1098                         return r;
1099
1100                 if (ret)
1101                         *ret = o;
1102
1103                 if (offset)
1104                         *offset = extra;
1105
1106                 return 1;
1107         }
1108
1109         return generic_array_get(f, first, i-1, ret, offset);
1110 }
1111
1112 enum {
1113         TEST_FOUND,
1114         TEST_LEFT,
1115         TEST_RIGHT
1116 };
1117
1118 static int generic_array_bisect(JournalFile *f,
1119                                 uint64_t first,
1120                                 uint64_t n,
1121                                 uint64_t needle,
1122                                 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
1123                                 direction_t direction,
1124                                 Object **ret,
1125                                 uint64_t *offset,
1126                                 uint64_t *idx) {
1127
1128         uint64_t a, p, t = 0, i = 0, last_p = 0;
1129         bool subtract_one = false;
1130         Object *o, *array = NULL;
1131         int r;
1132
1133         assert(f);
1134         assert(test_object);
1135
1136         a = first;
1137         while (a > 0) {
1138                 uint64_t left, right, k, lp;
1139
1140                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
1141                 if (r < 0)
1142                         return r;
1143
1144                 k = journal_file_entry_array_n_items(array);
1145                 right = MIN(k, n);
1146                 if (right <= 0)
1147                         return 0;
1148
1149                 i = right - 1;
1150                 lp = p = le64toh(array->entry_array.items[i]);
1151                 if (p <= 0)
1152                         return -EBADMSG;
1153
1154                 r = test_object(f, p, needle);
1155                 if (r < 0)
1156                         return r;
1157
1158                 if (r == TEST_FOUND)
1159                         r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
1160
1161                 if (r == TEST_RIGHT) {
1162                         left = 0;
1163                         right -= 1;
1164                         for (;;) {
1165                                 if (left == right) {
1166                                         if (direction == DIRECTION_UP)
1167                                                 subtract_one = true;
1168
1169                                         i = left;
1170                                         goto found;
1171                                 }
1172
1173                                 assert(left < right);
1174
1175                                 i = (left + right) / 2;
1176                                 p = le64toh(array->entry_array.items[i]);
1177                                 if (p <= 0)
1178                                         return -EBADMSG;
1179
1180                                 r = test_object(f, p, needle);
1181                                 if (r < 0)
1182                                         return r;
1183
1184                                 if (r == TEST_FOUND)
1185                                         r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
1186
1187                                 if (r == TEST_RIGHT)
1188                                         right = i;
1189                                 else
1190                                         left = i + 1;
1191                         }
1192                 }
1193
1194                 if (k > n)
1195                         return 0;
1196
1197                 last_p = lp;
1198
1199                 n -= k;
1200                 t += k;
1201                 a = le64toh(array->entry_array.next_entry_array_offset);
1202         }
1203
1204         return 0;
1205
1206 found:
1207         if (subtract_one && t == 0 && i == 0)
1208                 return 0;
1209
1210         if (subtract_one && i == 0)
1211                 p = last_p;
1212         else if (subtract_one)
1213                 p = le64toh(array->entry_array.items[i-1]);
1214         else
1215                 p = le64toh(array->entry_array.items[i]);
1216
1217         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1218         if (r < 0)
1219                 return r;
1220
1221         if (ret)
1222                 *ret = o;
1223
1224         if (offset)
1225                 *offset = p;
1226
1227         if (idx)
1228                 *idx = t + i - (subtract_one ? 1 : 0);
1229
1230         return 1;
1231 }
1232
1233 static int generic_array_bisect_plus_one(JournalFile *f,
1234                                          uint64_t extra,
1235                                          uint64_t first,
1236                                          uint64_t n,
1237                                          uint64_t needle,
1238                                          int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
1239                                          direction_t direction,
1240                                          Object **ret,
1241                                          uint64_t *offset,
1242                                          uint64_t *idx) {
1243
1244         int r;
1245
1246         assert(f);
1247         assert(test_object);
1248
1249         if (n <= 0)
1250                 return 0;
1251
1252         /* This bisects the array in object 'first', but first checks
1253          * an extra  */
1254         r = test_object(f, extra, needle);
1255         if (r < 0)
1256                 return r;
1257         else if (r == TEST_FOUND) {
1258                 Object *o;
1259
1260                 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
1261                 if (r < 0)
1262                         return r;
1263
1264                 if (ret)
1265                         *ret = o;
1266
1267                 if (offset)
1268                         *offset = extra;
1269
1270                 if (idx)
1271                         *idx = 0;
1272
1273                 return 1;
1274         } else if (r == TEST_RIGHT)
1275                 return 0;
1276
1277         r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret, offset, idx);
1278
1279         if (r > 0)
1280                 (*idx) ++;
1281
1282         return r;
1283 }
1284
1285 static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) {
1286         Object *o;
1287         int r;
1288
1289         assert(f);
1290         assert(p > 0);
1291
1292         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1293         if (r < 0)
1294                 return r;
1295
1296         if (le64toh(o->entry.seqnum) == needle)
1297                 return TEST_FOUND;
1298         else if (le64toh(o->entry.seqnum) < needle)
1299                 return TEST_LEFT;
1300         else
1301                 return TEST_RIGHT;
1302 }
1303
1304 int journal_file_move_to_entry_by_seqnum(
1305                 JournalFile *f,
1306                 uint64_t seqnum,
1307                 direction_t direction,
1308                 Object **ret,
1309                 uint64_t *offset) {
1310
1311         return generic_array_bisect(f,
1312                                     le64toh(f->header->entry_array_offset),
1313                                     le64toh(f->header->n_entries),
1314                                     seqnum,
1315                                     test_object_seqnum,
1316                                     direction,
1317                                     ret, offset, NULL);
1318 }
1319
1320 static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) {
1321         Object *o;
1322         int r;
1323
1324         assert(f);
1325         assert(p > 0);
1326
1327         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1328         if (r < 0)
1329                 return r;
1330
1331         if (le64toh(o->entry.realtime) == needle)
1332                 return TEST_FOUND;
1333         else if (le64toh(o->entry.realtime) < needle)
1334                 return TEST_LEFT;
1335         else
1336                 return TEST_RIGHT;
1337 }
1338
1339 int journal_file_move_to_entry_by_realtime(
1340                 JournalFile *f,
1341                 uint64_t realtime,
1342                 direction_t direction,
1343                 Object **ret,
1344                 uint64_t *offset) {
1345
1346         return generic_array_bisect(f,
1347                                     le64toh(f->header->entry_array_offset),
1348                                     le64toh(f->header->n_entries),
1349                                     realtime,
1350                                     test_object_realtime,
1351                                     direction,
1352                                     ret, offset, NULL);
1353 }
1354
1355 static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) {
1356         Object *o;
1357         int r;
1358
1359         assert(f);
1360         assert(p > 0);
1361
1362         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1363         if (r < 0)
1364                 return r;
1365
1366         if (le64toh(o->entry.monotonic) == needle)
1367                 return TEST_FOUND;
1368         else if (le64toh(o->entry.monotonic) < needle)
1369                 return TEST_LEFT;
1370         else
1371                 return TEST_RIGHT;
1372 }
1373
1374 int journal_file_move_to_entry_by_monotonic(
1375                 JournalFile *f,
1376                 sd_id128_t boot_id,
1377                 uint64_t monotonic,
1378                 direction_t direction,
1379                 Object **ret,
1380                 uint64_t *offset) {
1381
1382         char t[8+32+1] = "_BOOT_ID=";
1383         Object *o;
1384         int r;
1385
1386         sd_id128_to_string(boot_id, t + 8);
1387
1388         r = journal_file_find_data_object(f, t, strlen(t), &o, NULL);
1389         if (r < 0)
1390                 return r;
1391         else if (r == 0)
1392                 return -ENOENT;
1393
1394         return generic_array_bisect_plus_one(f,
1395                                              le64toh(o->data.entry_offset),
1396                                              le64toh(o->data.entry_array_offset),
1397                                              le64toh(o->data.n_entries),
1398                                              monotonic,
1399                                              test_object_monotonic,
1400                                              direction,
1401                                              ret, offset, NULL);
1402 }
1403
1404 static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) {
1405         assert(f);
1406         assert(p > 0);
1407
1408         if (p == needle)
1409                 return TEST_FOUND;
1410         else if (p < needle)
1411                 return TEST_LEFT;
1412         else
1413                 return TEST_RIGHT;
1414 }
1415
1416 int journal_file_next_entry(
1417                 JournalFile *f,
1418                 Object *o, uint64_t p,
1419                 direction_t direction,
1420                 Object **ret, uint64_t *offset) {
1421
1422         uint64_t i, n;
1423         int r;
1424
1425         assert(f);
1426         assert(p > 0 || !o);
1427
1428         n = le64toh(f->header->n_entries);
1429         if (n <= 0)
1430                 return 0;
1431
1432         if (!o)
1433                 i = direction == DIRECTION_DOWN ? 0 : n - 1;
1434         else {
1435                 if (o->object.type != OBJECT_ENTRY)
1436                         return -EINVAL;
1437
1438                 r = generic_array_bisect(f,
1439                                          le64toh(f->header->entry_array_offset),
1440                                          le64toh(f->header->n_entries),
1441                                          p,
1442                                          test_object_offset,
1443                                          DIRECTION_DOWN,
1444                                          NULL, NULL,
1445                                          &i);
1446                 if (r <= 0)
1447                         return r;
1448
1449                 if (direction == DIRECTION_DOWN) {
1450                         if (i >= n - 1)
1451                                 return 0;
1452
1453                         i++;
1454                 } else {
1455                         if (i <= 0)
1456                                 return 0;
1457
1458                         i--;
1459                 }
1460         }
1461
1462         /* And jump to it */
1463         return generic_array_get(f,
1464                                  le64toh(f->header->entry_array_offset),
1465                                  i,
1466                                  ret, offset);
1467 }
1468
1469 int journal_file_skip_entry(
1470                 JournalFile *f,
1471                 Object *o, uint64_t p,
1472                 int64_t skip,
1473                 Object **ret, uint64_t *offset) {
1474
1475         uint64_t i, n;
1476         int r;
1477
1478         assert(f);
1479         assert(o);
1480         assert(p > 0);
1481
1482         if (o->object.type != OBJECT_ENTRY)
1483                 return -EINVAL;
1484
1485         r = generic_array_bisect(f,
1486                                  le64toh(f->header->entry_array_offset),
1487                                  le64toh(f->header->n_entries),
1488                                  p,
1489                                  test_object_offset,
1490                                  DIRECTION_DOWN,
1491                                  NULL, NULL,
1492                                  &i);
1493         if (r <= 0)
1494                 return r;
1495
1496         /* Calculate new index */
1497         if (skip < 0) {
1498                 if ((uint64_t) -skip >= i)
1499                         i = 0;
1500                 else
1501                         i = i - (uint64_t) -skip;
1502         } else
1503                 i  += (uint64_t) skip;
1504
1505         n = le64toh(f->header->n_entries);
1506         if (n <= 0)
1507                 return -EBADMSG;
1508
1509         if (i >= n)
1510                 i = n-1;
1511
1512         return generic_array_get(f,
1513                                  le64toh(f->header->entry_array_offset),
1514                                  i,
1515                                  ret, offset);
1516 }
1517
1518 int journal_file_next_entry_for_data(
1519                 JournalFile *f,
1520                 Object *o, uint64_t p,
1521                 uint64_t data_offset,
1522                 direction_t direction,
1523                 Object **ret, uint64_t *offset) {
1524
1525         uint64_t n, i;
1526         int r;
1527         Object *d;
1528
1529         assert(f);
1530         assert(p > 0 || !o);
1531
1532         r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
1533         if (r < 0)
1534                 return r;
1535
1536         n = le64toh(d->data.n_entries);
1537         if (n <= 0)
1538                 return n;
1539
1540         if (!o)
1541                 i = direction == DIRECTION_DOWN ? 0 : n - 1;
1542         else {
1543                 if (o->object.type != OBJECT_ENTRY)
1544                         return -EINVAL;
1545
1546                 r = generic_array_bisect_plus_one(f,
1547                                                   le64toh(d->data.entry_offset),
1548                                                   le64toh(d->data.entry_array_offset),
1549                                                   le64toh(d->data.n_entries),
1550                                                   p,
1551                                                   test_object_offset,
1552                                                   DIRECTION_DOWN,
1553                                                   NULL, NULL,
1554                                                   &i);
1555
1556                 if (r <= 0)
1557                         return r;
1558
1559                 if (direction == DIRECTION_DOWN) {
1560                         if (i >= n - 1)
1561                                 return 0;
1562
1563                         i++;
1564                 } else {
1565                         if (i <= 0)
1566                                 return 0;
1567
1568                         i--;
1569                 }
1570
1571         }
1572
1573         return generic_array_get_plus_one(f,
1574                                           le64toh(d->data.entry_offset),
1575                                           le64toh(d->data.entry_array_offset),
1576                                           i,
1577                                           ret, offset);
1578 }
1579
1580 int journal_file_move_to_entry_by_seqnum_for_data(
1581                 JournalFile *f,
1582                 uint64_t data_offset,
1583                 uint64_t seqnum,
1584                 direction_t direction,
1585                 Object **ret, uint64_t *offset) {
1586
1587         Object *d;
1588         int r;
1589
1590         r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
1591         if (r <= 0)
1592                 return r;
1593
1594         return generic_array_bisect_plus_one(f,
1595                                              le64toh(d->data.entry_offset),
1596                                              le64toh(d->data.entry_array_offset),
1597                                              le64toh(d->data.n_entries),
1598                                              seqnum,
1599                                              test_object_seqnum,
1600                                              direction,
1601                                              ret, offset, NULL);
1602 }
1603
1604 int journal_file_move_to_entry_by_realtime_for_data(
1605                 JournalFile *f,
1606                 uint64_t data_offset,
1607                 uint64_t realtime,
1608                 direction_t direction,
1609                 Object **ret, uint64_t *offset) {
1610
1611         Object *d;
1612         int r;
1613
1614         r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
1615         if (r <= 0)
1616                 return r;
1617
1618         return generic_array_bisect_plus_one(f,
1619                                              le64toh(d->data.entry_offset),
1620                                              le64toh(d->data.entry_array_offset),
1621                                              le64toh(d->data.n_entries),
1622                                              realtime,
1623                                              test_object_realtime,
1624                                              direction,
1625                                              ret, offset, NULL);
1626 }
1627
1628 void journal_file_dump(JournalFile *f) {
1629         char a[33], b[33], c[33];
1630         Object *o;
1631         int r;
1632         uint64_t p;
1633
1634         assert(f);
1635
1636         printf("File Path: %s\n"
1637                "File ID: %s\n"
1638                "Machine ID: %s\n"
1639                "Boot ID: %s\n"
1640                "Arena size: %llu\n"
1641                "Objects: %lu\n"
1642                "Entries: %lu\n",
1643                f->path,
1644                sd_id128_to_string(f->header->file_id, a),
1645                sd_id128_to_string(f->header->machine_id, b),
1646                sd_id128_to_string(f->header->boot_id, c),
1647                (unsigned long long) le64toh(f->header->arena_size),
1648                (unsigned long) le64toh(f->header->n_objects),
1649                (unsigned long) le64toh(f->header->n_entries));
1650
1651         p = le64toh(f->header->arena_offset);
1652         while (p != 0) {
1653                 r = journal_file_move_to_object(f, -1, p, &o);
1654                 if (r < 0)
1655                         goto fail;
1656
1657                 switch (o->object.type) {
1658
1659                 case OBJECT_UNUSED:
1660                         printf("Type: OBJECT_UNUSED\n");
1661                         break;
1662
1663                 case OBJECT_DATA:
1664                         printf("Type: OBJECT_DATA\n");
1665                         break;
1666
1667                 case OBJECT_ENTRY:
1668                         printf("Type: OBJECT_ENTRY %llu %llu %llu\n",
1669                                (unsigned long long) le64toh(o->entry.seqnum),
1670                                (unsigned long long) le64toh(o->entry.monotonic),
1671                                (unsigned long long) le64toh(o->entry.realtime));
1672                         break;
1673
1674                 case OBJECT_FIELD_HASH_TABLE:
1675                         printf("Type: OBJECT_FIELD_HASH_TABLE\n");
1676                         break;
1677
1678                 case OBJECT_DATA_HASH_TABLE:
1679                         printf("Type: OBJECT_DATA_HASH_TABLE\n");
1680                         break;
1681
1682                 case OBJECT_ENTRY_ARRAY:
1683                         printf("Type: OBJECT_ENTRY_ARRAY\n");
1684                         break;
1685                 }
1686
1687                 if (o->object.flags & OBJECT_COMPRESSED)
1688                         printf("Flags: COMPRESSED\n");
1689
1690                 if (p == le64toh(f->header->tail_object_offset))
1691                         p = 0;
1692                 else
1693                         p = p + ALIGN64(le64toh(o->object.size));
1694         }
1695
1696         return;
1697 fail:
1698         log_error("File corrupt");
1699 }
1700
1701 int journal_file_open(
1702                 const char *fname,
1703                 int flags,
1704                 mode_t mode,
1705                 JournalFile *template,
1706                 JournalFile **ret) {
1707
1708         JournalFile *f;
1709         int r;
1710         bool newly_created = false;
1711
1712         assert(fname);
1713
1714         if ((flags & O_ACCMODE) != O_RDONLY &&
1715             (flags & O_ACCMODE) != O_RDWR)
1716                 return -EINVAL;
1717
1718         f = new0(JournalFile, 1);
1719         if (!f)
1720                 return -ENOMEM;
1721
1722         f->fd = -1;
1723         f->flags = flags;
1724         f->mode = mode;
1725         f->writable = (flags & O_ACCMODE) != O_RDONLY;
1726         f->prot = prot_from_flags(flags);
1727
1728         f->path = strdup(fname);
1729         if (!f->path) {
1730                 r = -ENOMEM;
1731                 goto fail;
1732         }
1733
1734         f->fd = open(f->path, f->flags|O_CLOEXEC, f->mode);
1735         if (f->fd < 0) {
1736                 r = -errno;
1737                 goto fail;
1738         }
1739
1740         if (fstat(f->fd, &f->last_stat) < 0) {
1741                 r = -errno;
1742                 goto fail;
1743         }
1744
1745         if (f->last_stat.st_size == 0 && f->writable) {
1746                 newly_created = true;
1747
1748                 r = journal_file_init_header(f, template);
1749                 if (r < 0)
1750                         goto fail;
1751
1752                 if (fstat(f->fd, &f->last_stat) < 0) {
1753                         r = -errno;
1754                         goto fail;
1755                 }
1756         }
1757
1758         if (f->last_stat.st_size < (off_t) sizeof(Header)) {
1759                 r = -EIO;
1760                 goto fail;
1761         }
1762
1763         f->header = mmap(NULL, PAGE_ALIGN(sizeof(Header)), prot_from_flags(flags), MAP_SHARED, f->fd, 0);
1764         if (f->header == MAP_FAILED) {
1765                 f->header = NULL;
1766                 r = -errno;
1767                 goto fail;
1768         }
1769
1770         if (!newly_created) {
1771                 r = journal_file_verify_header(f);
1772                 if (r < 0)
1773                         goto fail;
1774         }
1775
1776         if (f->writable) {
1777                 r = journal_file_refresh_header(f);
1778                 if (r < 0)
1779                         goto fail;
1780         }
1781
1782         if (newly_created) {
1783
1784                 r = journal_file_setup_field_hash_table(f);
1785                 if (r < 0)
1786                         goto fail;
1787
1788                 r = journal_file_setup_data_hash_table(f);
1789                 if (r < 0)
1790                         goto fail;
1791         }
1792
1793         r = journal_file_map_field_hash_table(f);
1794         if (r < 0)
1795                 goto fail;
1796
1797         r = journal_file_map_data_hash_table(f);
1798         if (r < 0)
1799                 goto fail;
1800
1801         if (ret)
1802                 *ret = f;
1803
1804         return 0;
1805
1806 fail:
1807         journal_file_close(f);
1808
1809         return r;
1810 }
1811
1812 int journal_file_rotate(JournalFile **f) {
1813         char *p;
1814         size_t l;
1815         JournalFile *old_file, *new_file = NULL;
1816         int r;
1817
1818         assert(f);
1819         assert(*f);
1820
1821         old_file = *f;
1822
1823         if (!old_file->writable)
1824                 return -EINVAL;
1825
1826         if (!endswith(old_file->path, ".journal"))
1827                 return -EINVAL;
1828
1829         l = strlen(old_file->path);
1830
1831         p = new(char, l + 1 + 16 + 1 + 32 + 1 + 16 + 1);
1832         if (!p)
1833                 return -ENOMEM;
1834
1835         memcpy(p, old_file->path, l - 8);
1836         p[l-8] = '@';
1837         sd_id128_to_string(old_file->header->seqnum_id, p + l - 8 + 1);
1838         snprintf(p + l - 8 + 1 + 32, 1 + 16 + 1 + 16 + 8 + 1,
1839                  "-%016llx-%016llx.journal",
1840                  (unsigned long long) le64toh((*f)->header->seqnum),
1841                  (unsigned long long) le64toh((*f)->header->tail_entry_realtime));
1842
1843         r = rename(old_file->path, p);
1844         free(p);
1845
1846         if (r < 0)
1847                 return -errno;
1848
1849         old_file->header->state = le32toh(STATE_ARCHIVED);
1850
1851         r = journal_file_open(old_file->path, old_file->flags, old_file->mode, old_file, &new_file);
1852         journal_file_close(old_file);
1853
1854         *f = new_file;
1855         return r;
1856 }
1857
1858 struct vacuum_info {
1859         off_t usage;
1860         char *filename;
1861
1862         uint64_t realtime;
1863         sd_id128_t seqnum_id;
1864         uint64_t seqnum;
1865 };
1866
1867 static int vacuum_compare(const void *_a, const void *_b) {
1868         const struct vacuum_info *a, *b;
1869
1870         a = _a;
1871         b = _b;
1872
1873         if (sd_id128_equal(a->seqnum_id, b->seqnum_id)) {
1874                 if (a->seqnum < b->seqnum)
1875                         return -1;
1876                 else if (a->seqnum > b->seqnum)
1877                         return 1;
1878                 else
1879                         return 0;
1880         }
1881
1882         if (a->realtime < b->realtime)
1883                 return -1;
1884         else if (a->realtime > b->realtime)
1885                 return 1;
1886         else
1887                 return memcmp(&a->seqnum_id, &b->seqnum_id, 16);
1888 }
1889
1890 int journal_directory_vacuum(const char *directory, uint64_t max_use, uint64_t min_free) {
1891         DIR *d;
1892         int r = 0;
1893         struct vacuum_info *list = NULL;
1894         unsigned n_list = 0, n_allocated = 0, i;
1895         uint64_t sum = 0;
1896
1897         assert(directory);
1898
1899         if (max_use <= 0)
1900                 return 0;
1901
1902         d = opendir(directory);
1903         if (!d)
1904                 return -errno;
1905
1906         for (;;) {
1907                 int k;
1908                 struct dirent buf, *de;
1909                 size_t q;
1910                 struct stat st;
1911                 char *p;
1912                 unsigned long long seqnum, realtime;
1913                 sd_id128_t seqnum_id;
1914
1915                 k = readdir_r(d, &buf, &de);
1916                 if (k != 0) {
1917                         r = -k;
1918                         goto finish;
1919                 }
1920
1921                 if (!de)
1922                         break;
1923
1924                 if (!dirent_is_file_with_suffix(de, ".journal"))
1925                         continue;
1926
1927                 q = strlen(de->d_name);
1928
1929                 if (q < 1 + 32 + 1 + 16 + 1 + 16 + 8)
1930                         continue;
1931
1932                 if (de->d_name[q-8-16-1] != '-' ||
1933                     de->d_name[q-8-16-1-16-1] != '-' ||
1934                     de->d_name[q-8-16-1-16-1-32-1] != '@')
1935                         continue;
1936
1937                 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
1938                         continue;
1939
1940                 if (!S_ISREG(st.st_mode))
1941                         continue;
1942
1943                 p = strdup(de->d_name);
1944                 if (!p) {
1945                         r = -ENOMEM;
1946                         goto finish;
1947                 }
1948
1949                 de->d_name[q-8-16-1-16-1] = 0;
1950                 if (sd_id128_from_string(de->d_name + q-8-16-1-16-1-32, &seqnum_id) < 0) {
1951                         free(p);
1952                         continue;
1953                 }
1954
1955                 if (sscanf(de->d_name + q-8-16-1-16, "%16llx-%16llx.journal", &seqnum, &realtime) != 2) {
1956                         free(p);
1957                         continue;
1958                 }
1959
1960                 if (n_list >= n_allocated) {
1961                         struct vacuum_info *j;
1962
1963                         n_allocated = MAX(n_allocated * 2U, 8U);
1964                         j = realloc(list, n_allocated * sizeof(struct vacuum_info));
1965                         if (!j) {
1966                                 free(p);
1967                                 r = -ENOMEM;
1968                                 goto finish;
1969                         }
1970
1971                         list = j;
1972                 }
1973
1974                 list[n_list].filename = p;
1975                 list[n_list].usage = (uint64_t) st.st_blksize * (uint64_t) st.st_blocks;
1976                 list[n_list].seqnum = seqnum;
1977                 list[n_list].realtime = realtime;
1978                 list[n_list].seqnum_id = seqnum_id;
1979
1980                 sum += list[n_list].usage;
1981
1982                 n_list ++;
1983         }
1984
1985         qsort(list, n_list, sizeof(struct vacuum_info), vacuum_compare);
1986
1987         for(i = 0; i < n_list; i++) {
1988                 struct statvfs ss;
1989
1990                 if (fstatvfs(dirfd(d), &ss) < 0) {
1991                         r = -errno;
1992                         goto finish;
1993                 }
1994
1995                 if (sum <= max_use &&
1996                     (uint64_t) ss.f_bavail * (uint64_t) ss.f_bsize >= min_free)
1997                         break;
1998
1999                 if (unlinkat(dirfd(d), list[i].filename, 0) >= 0) {
2000                         log_debug("Deleted archived journal %s/%s.", directory, list[i].filename);
2001                         sum -= list[i].usage;
2002                 } else if (errno != ENOENT)
2003                         log_warning("Failed to delete %s/%s: %m", directory, list[i].filename);
2004         }
2005
2006 finish:
2007         for (i = 0; i < n_list; i++)
2008                 free(list[i].filename);
2009
2010         free(list);
2011
2012         if (d)
2013                 closedir(d);
2014
2015         return r;
2016 }
2017
2018 int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset) {
2019         uint64_t i, n;
2020         uint64_t q, xor_hash = 0;
2021         int r;
2022         EntryItem *items;
2023         dual_timestamp ts;
2024
2025         assert(from);
2026         assert(to);
2027         assert(o);
2028         assert(p);
2029
2030         if (!to->writable)
2031                 return -EPERM;
2032
2033         ts.monotonic = le64toh(o->entry.monotonic);
2034         ts.realtime = le64toh(o->entry.realtime);
2035
2036         if (to->tail_entry_monotonic_valid &&
2037             ts.monotonic < le64toh(to->header->tail_entry_monotonic))
2038                 return -EINVAL;
2039
2040         if (ts.realtime < le64toh(to->header->tail_entry_realtime))
2041                 return -EINVAL;
2042
2043         n = journal_file_entry_n_items(o);
2044         items = alloca(sizeof(EntryItem) * n);
2045
2046         for (i = 0; i < n; i++) {
2047                 uint64_t le_hash, l, h;
2048                 size_t t;
2049                 void *data;
2050                 Object *u;
2051
2052                 q = le64toh(o->entry.items[i].object_offset);
2053                 le_hash = o->entry.items[i].hash;
2054
2055                 r = journal_file_move_to_object(from, OBJECT_DATA, q, &o);
2056                 if (r < 0)
2057                         return r;
2058
2059                 if (le_hash != o->data.hash)
2060                         return -EBADMSG;
2061
2062                 l = le64toh(o->object.size) - offsetof(Object, data.payload);
2063                 t = (size_t) l;
2064
2065                 /* We hit the limit on 32bit machines */
2066                 if ((uint64_t) t != l)
2067                         return -E2BIG;
2068
2069                 if (o->object.flags & OBJECT_COMPRESSED) {
2070 #ifdef HAVE_XZ
2071                         uint64_t rsize;
2072
2073                         if (!uncompress_blob(o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize))
2074                                 return -EBADMSG;
2075
2076                         data = from->compress_buffer;
2077                         l = rsize;
2078 #else
2079                         return -EPROTONOSUPPORT;
2080 #endif
2081                 } else
2082                         data = o->data.payload;
2083
2084                 r = journal_file_append_data(to, data, l, &u, &h);
2085                 if (r < 0)
2086                         return r;
2087
2088                 xor_hash ^= le64toh(u->data.hash);
2089                 items[i].object_offset = htole64(h);
2090                 items[i].hash = u->data.hash;
2091
2092                 r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
2093                 if (r < 0)
2094                         return r;
2095         }
2096
2097         return journal_file_append_entry_internal(to, &ts, xor_hash, items, n, seqnum, ret, offset);
2098 }
2099
2100 void journal_default_metrics(JournalMetrics *m, int fd) {
2101         uint64_t fs_size = 0;
2102         struct statvfs ss;
2103         char a[64], b[64], c[64], d[64];
2104
2105         assert(m);
2106         assert(fd >= 0);
2107
2108         if (fstatvfs(fd, &ss) >= 0)
2109                 fs_size = ss.f_frsize * ss.f_blocks;
2110
2111         if (m->max_use == (uint64_t) -1) {
2112
2113                 if (fs_size > 0) {
2114                         m->max_use = PAGE_ALIGN(fs_size / 10); /* 10% of file system size */
2115
2116                         if (m->max_use > DEFAULT_MAX_USE_UPPER)
2117                                 m->max_use = DEFAULT_MAX_USE_UPPER;
2118
2119                         if (m->max_use < DEFAULT_MAX_USE_LOWER)
2120                                 m->max_use = DEFAULT_MAX_USE_LOWER;
2121                 } else
2122                         m->max_use = DEFAULT_MAX_USE_LOWER;
2123         } else {
2124                 m->max_use = PAGE_ALIGN(m->max_use);
2125
2126                 if (m->max_use < JOURNAL_FILE_SIZE_MIN*2)
2127                         m->max_use = JOURNAL_FILE_SIZE_MIN*2;
2128         }
2129
2130         if (m->max_size == (uint64_t) -1) {
2131                 m->max_size = PAGE_ALIGN(m->max_use / 8); /* 8 chunks */
2132
2133                 if (m->max_size > DEFAULT_MAX_SIZE_UPPER)
2134                         m->max_size = DEFAULT_MAX_SIZE_UPPER;
2135         } else
2136                 m->max_size = PAGE_ALIGN(m->max_size);
2137
2138         if (m->max_size < JOURNAL_FILE_SIZE_MIN)
2139                 m->max_size = JOURNAL_FILE_SIZE_MIN;
2140
2141         if (m->max_size*2 > m->max_use)
2142                 m->max_use = m->max_size*2;
2143
2144         if (m->min_size == (uint64_t) -1)
2145                 m->min_size = JOURNAL_FILE_SIZE_MIN;
2146         else {
2147                 m->min_size = PAGE_ALIGN(m->min_size);
2148
2149                 if (m->min_size < JOURNAL_FILE_SIZE_MIN)
2150                         m->min_size = JOURNAL_FILE_SIZE_MIN;
2151
2152                 if (m->min_size > m->max_size)
2153                         m->max_size = m->min_size;
2154         }
2155
2156         if (m->keep_free == (uint64_t) -1) {
2157
2158                 if (fs_size > 0) {
2159                         m->keep_free = PAGE_ALIGN(fs_size / 20); /* 5% of file system size */
2160
2161                         if (m->keep_free > DEFAULT_KEEP_FREE_UPPER)
2162                                 m->keep_free = DEFAULT_KEEP_FREE_UPPER;
2163
2164                 } else
2165                         m->keep_free = DEFAULT_KEEP_FREE;
2166         }
2167
2168         log_debug("Fixed max_use=%s max_size=%s min_size=%s keep_free=%s",
2169                   format_bytes(a, sizeof(a), m->max_use),
2170                   format_bytes(b, sizeof(b), m->max_size),
2171                   format_bytes(c, sizeof(c), m->min_size),
2172                   format_bytes(d, sizeof(d), m->keep_free));
2173 }