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