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