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