chiark / gitweb /
journal: fix endianness errors
[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 (512ULL)
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 = htole64(new_size - le64toh(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 = (DEFAULT_WINDOW_SIZE - size) / 2;
334
335                 if (delta > offset)
336                         delta = offset;
337
338                 offset -= delta;
339                 size = DEFAULT_WINDOW_SIZE;
340         } else
341                 delta = 0;
342
343         if (offset + size > (uint64_t) f->last_stat.st_size)
344                 size = (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 == 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 == 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 = htole64(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 = htole64(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_debug("=> %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         items = alloca(sizeof(EntryItem) * n_iovec);
1020
1021         for (i = 0; i < n_iovec; i++) {
1022                 uint64_t p;
1023                 Object *o;
1024
1025                 r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p);
1026                 if (r < 0)
1027                         return r;
1028
1029                 xor_hash ^= le64toh(o->data.hash);
1030                 items[i].object_offset = htole64(p);
1031                 items[i].hash = o->data.hash;
1032         }
1033
1034         r = journal_file_append_entry_internal(f, ts, xor_hash, items, n_iovec, seqnum, ret, offset);
1035
1036         journal_file_post_change(f);
1037
1038         return r;
1039 }
1040
1041 static int generic_array_get(JournalFile *f,
1042                              uint64_t first,
1043                              uint64_t i,
1044                              Object **ret, uint64_t *offset) {
1045
1046         Object *o;
1047         uint64_t p = 0, a;
1048         int r;
1049
1050         assert(f);
1051
1052         a = first;
1053         while (a > 0) {
1054                 uint64_t n;
1055
1056                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
1057                 if (r < 0)
1058                         return r;
1059
1060                 n = journal_file_entry_array_n_items(o);
1061                 if (i < n) {
1062                         p = le64toh(o->entry_array.items[i]);
1063                         break;
1064                 }
1065
1066                 i -= n;
1067                 a = le64toh(o->entry_array.next_entry_array_offset);
1068         }
1069
1070         if (a <= 0 || p <= 0)
1071                 return 0;
1072
1073         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1074         if (r < 0)
1075                 return r;
1076
1077         if (ret)
1078                 *ret = o;
1079
1080         if (offset)
1081                 *offset = p;
1082
1083         return 1;
1084 }
1085
1086 static int generic_array_get_plus_one(JournalFile *f,
1087                                       uint64_t extra,
1088                                       uint64_t first,
1089                                       uint64_t i,
1090                                       Object **ret, uint64_t *offset) {
1091
1092         Object *o;
1093
1094         assert(f);
1095
1096         if (i == 0) {
1097                 int r;
1098
1099                 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
1100                 if (r < 0)
1101                         return r;
1102
1103                 if (ret)
1104                         *ret = o;
1105
1106                 if (offset)
1107                         *offset = extra;
1108
1109                 return 1;
1110         }
1111
1112         return generic_array_get(f, first, i-1, ret, offset);
1113 }
1114
1115 enum {
1116         TEST_FOUND,
1117         TEST_LEFT,
1118         TEST_RIGHT
1119 };
1120
1121 static int generic_array_bisect(JournalFile *f,
1122                                 uint64_t first,
1123                                 uint64_t n,
1124                                 uint64_t needle,
1125                                 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
1126                                 direction_t direction,
1127                                 Object **ret,
1128                                 uint64_t *offset,
1129                                 uint64_t *idx) {
1130
1131         uint64_t a, p, t = 0, i = 0, last_p = 0;
1132         bool subtract_one = false;
1133         Object *o, *array = NULL;
1134         int r;
1135
1136         assert(f);
1137         assert(test_object);
1138
1139         a = first;
1140         while (a > 0) {
1141                 uint64_t left, right, k, lp;
1142
1143                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
1144                 if (r < 0)
1145                         return r;
1146
1147                 k = journal_file_entry_array_n_items(array);
1148                 right = MIN(k, n);
1149                 if (right <= 0)
1150                         return 0;
1151
1152                 i = right - 1;
1153                 lp = p = le64toh(array->entry_array.items[i]);
1154                 if (p <= 0)
1155                         return -EBADMSG;
1156
1157                 r = test_object(f, p, needle);
1158                 if (r < 0)
1159                         return r;
1160
1161                 if (r == TEST_FOUND)
1162                         r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
1163
1164                 if (r == TEST_RIGHT) {
1165                         left = 0;
1166                         right -= 1;
1167                         for (;;) {
1168                                 if (left == right) {
1169                                         if (direction == DIRECTION_UP)
1170                                                 subtract_one = true;
1171
1172                                         i = left;
1173                                         goto found;
1174                                 }
1175
1176                                 assert(left < right);
1177
1178                                 i = (left + right) / 2;
1179                                 p = le64toh(array->entry_array.items[i]);
1180                                 if (p <= 0)
1181                                         return -EBADMSG;
1182
1183                                 r = test_object(f, p, needle);
1184                                 if (r < 0)
1185                                         return r;
1186
1187                                 if (r == TEST_FOUND)
1188                                         r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
1189
1190                                 if (r == TEST_RIGHT)
1191                                         right = i;
1192                                 else
1193                                         left = i + 1;
1194                         }
1195                 }
1196
1197                 if (k > n)
1198                         return 0;
1199
1200                 last_p = lp;
1201
1202                 n -= k;
1203                 t += k;
1204                 a = le64toh(array->entry_array.next_entry_array_offset);
1205         }
1206
1207         return 0;
1208
1209 found:
1210         if (subtract_one && t == 0 && i == 0)
1211                 return 0;
1212
1213         if (subtract_one && i == 0)
1214                 p = last_p;
1215         else if (subtract_one)
1216                 p = le64toh(array->entry_array.items[i-1]);
1217         else
1218                 p = le64toh(array->entry_array.items[i]);
1219
1220         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1221         if (r < 0)
1222                 return r;
1223
1224         if (ret)
1225                 *ret = o;
1226
1227         if (offset)
1228                 *offset = p;
1229
1230         if (idx)
1231                 *idx = t + i - (subtract_one ? 1 : 0);
1232
1233         return 1;
1234 }
1235
1236 static int generic_array_bisect_plus_one(JournalFile *f,
1237                                          uint64_t extra,
1238                                          uint64_t first,
1239                                          uint64_t n,
1240                                          uint64_t needle,
1241                                          int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
1242                                          direction_t direction,
1243                                          Object **ret,
1244                                          uint64_t *offset,
1245                                          uint64_t *idx) {
1246
1247         int r;
1248
1249         assert(f);
1250         assert(test_object);
1251
1252         if (n <= 0)
1253                 return 0;
1254
1255         /* This bisects the array in object 'first', but first checks
1256          * an extra  */
1257         r = test_object(f, extra, needle);
1258         if (r < 0)
1259                 return r;
1260         else if (r == TEST_FOUND) {
1261                 Object *o;
1262
1263                 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
1264                 if (r < 0)
1265                         return r;
1266
1267                 if (ret)
1268                         *ret = o;
1269
1270                 if (offset)
1271                         *offset = extra;
1272
1273                 if (idx)
1274                         *idx = 0;
1275
1276                 return 1;
1277         } else if (r == TEST_RIGHT)
1278                 return 0;
1279
1280         r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret, offset, idx);
1281
1282         if (r > 0)
1283                 (*idx) ++;
1284
1285         return r;
1286 }
1287
1288 static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) {
1289         Object *o;
1290         int r;
1291
1292         assert(f);
1293         assert(p > 0);
1294
1295         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1296         if (r < 0)
1297                 return r;
1298
1299         if (le64toh(o->entry.seqnum) == needle)
1300                 return TEST_FOUND;
1301         else if (le64toh(o->entry.seqnum) < needle)
1302                 return TEST_LEFT;
1303         else
1304                 return TEST_RIGHT;
1305 }
1306
1307 int journal_file_move_to_entry_by_seqnum(
1308                 JournalFile *f,
1309                 uint64_t seqnum,
1310                 direction_t direction,
1311                 Object **ret,
1312                 uint64_t *offset) {
1313
1314         return generic_array_bisect(f,
1315                                     le64toh(f->header->entry_array_offset),
1316                                     le64toh(f->header->n_entries),
1317                                     seqnum,
1318                                     test_object_seqnum,
1319                                     direction,
1320                                     ret, offset, NULL);
1321 }
1322
1323 static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) {
1324         Object *o;
1325         int r;
1326
1327         assert(f);
1328         assert(p > 0);
1329
1330         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1331         if (r < 0)
1332                 return r;
1333
1334         if (le64toh(o->entry.realtime) == needle)
1335                 return TEST_FOUND;
1336         else if (le64toh(o->entry.realtime) < needle)
1337                 return TEST_LEFT;
1338         else
1339                 return TEST_RIGHT;
1340 }
1341
1342 int journal_file_move_to_entry_by_realtime(
1343                 JournalFile *f,
1344                 uint64_t realtime,
1345                 direction_t direction,
1346                 Object **ret,
1347                 uint64_t *offset) {
1348
1349         return generic_array_bisect(f,
1350                                     le64toh(f->header->entry_array_offset),
1351                                     le64toh(f->header->n_entries),
1352                                     realtime,
1353                                     test_object_realtime,
1354                                     direction,
1355                                     ret, offset, NULL);
1356 }
1357
1358 static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) {
1359         Object *o;
1360         int r;
1361
1362         assert(f);
1363         assert(p > 0);
1364
1365         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1366         if (r < 0)
1367                 return r;
1368
1369         if (le64toh(o->entry.monotonic) == needle)
1370                 return TEST_FOUND;
1371         else if (le64toh(o->entry.monotonic) < needle)
1372                 return TEST_LEFT;
1373         else
1374                 return TEST_RIGHT;
1375 }
1376
1377 int journal_file_move_to_entry_by_monotonic(
1378                 JournalFile *f,
1379                 sd_id128_t boot_id,
1380                 uint64_t monotonic,
1381                 direction_t direction,
1382                 Object **ret,
1383                 uint64_t *offset) {
1384
1385         char t[8+32+1] = "_BOOT_ID=";
1386         Object *o;
1387         int r;
1388
1389         sd_id128_to_string(boot_id, t + 8);
1390
1391         r = journal_file_find_data_object(f, t, strlen(t), &o, NULL);
1392         if (r < 0)
1393                 return r;
1394         else if (r == 0)
1395                 return -ENOENT;
1396
1397         return generic_array_bisect_plus_one(f,
1398                                              le64toh(o->data.entry_offset),
1399                                              le64toh(o->data.entry_array_offset),
1400                                              le64toh(o->data.n_entries),
1401                                              monotonic,
1402                                              test_object_monotonic,
1403                                              direction,
1404                                              ret, offset, NULL);
1405 }
1406
1407 static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) {
1408         assert(f);
1409         assert(p > 0);
1410
1411         if (p == needle)
1412                 return TEST_FOUND;
1413         else if (p < needle)
1414                 return TEST_LEFT;
1415         else
1416                 return TEST_RIGHT;
1417 }
1418
1419 int journal_file_next_entry(
1420                 JournalFile *f,
1421                 Object *o, uint64_t p,
1422                 direction_t direction,
1423                 Object **ret, uint64_t *offset) {
1424
1425         uint64_t i, n;
1426         int r;
1427
1428         assert(f);
1429         assert(p > 0 || !o);
1430
1431         n = le64toh(f->header->n_entries);
1432         if (n <= 0)
1433                 return 0;
1434
1435         if (!o)
1436                 i = direction == DIRECTION_DOWN ? 0 : n - 1;
1437         else {
1438                 if (o->object.type != OBJECT_ENTRY)
1439                         return -EINVAL;
1440
1441                 r = generic_array_bisect(f,
1442                                          le64toh(f->header->entry_array_offset),
1443                                          le64toh(f->header->n_entries),
1444                                          p,
1445                                          test_object_offset,
1446                                          DIRECTION_DOWN,
1447                                          NULL, NULL,
1448                                          &i);
1449                 if (r <= 0)
1450                         return r;
1451
1452                 if (direction == DIRECTION_DOWN) {
1453                         if (i >= n - 1)
1454                                 return 0;
1455
1456                         i++;
1457                 } else {
1458                         if (i <= 0)
1459                                 return 0;
1460
1461                         i--;
1462                 }
1463         }
1464
1465         /* And jump to it */
1466         return generic_array_get(f,
1467                                  le64toh(f->header->entry_array_offset),
1468                                  i,
1469                                  ret, offset);
1470 }
1471
1472 int journal_file_skip_entry(
1473                 JournalFile *f,
1474                 Object *o, uint64_t p,
1475                 int64_t skip,
1476                 Object **ret, uint64_t *offset) {
1477
1478         uint64_t i, n;
1479         int r;
1480
1481         assert(f);
1482         assert(o);
1483         assert(p > 0);
1484
1485         if (o->object.type != OBJECT_ENTRY)
1486                 return -EINVAL;
1487
1488         r = generic_array_bisect(f,
1489                                  le64toh(f->header->entry_array_offset),
1490                                  le64toh(f->header->n_entries),
1491                                  p,
1492                                  test_object_offset,
1493                                  DIRECTION_DOWN,
1494                                  NULL, NULL,
1495                                  &i);
1496         if (r <= 0)
1497                 return r;
1498
1499         /* Calculate new index */
1500         if (skip < 0) {
1501                 if ((uint64_t) -skip >= i)
1502                         i = 0;
1503                 else
1504                         i = i - (uint64_t) -skip;
1505         } else
1506                 i  += (uint64_t) skip;
1507
1508         n = le64toh(f->header->n_entries);
1509         if (n <= 0)
1510                 return -EBADMSG;
1511
1512         if (i >= n)
1513                 i = n-1;
1514
1515         return generic_array_get(f,
1516                                  le64toh(f->header->entry_array_offset),
1517                                  i,
1518                                  ret, offset);
1519 }
1520
1521 int journal_file_next_entry_for_data(
1522                 JournalFile *f,
1523                 Object *o, uint64_t p,
1524                 uint64_t data_offset,
1525                 direction_t direction,
1526                 Object **ret, uint64_t *offset) {
1527
1528         uint64_t n, i;
1529         int r;
1530         Object *d;
1531
1532         assert(f);
1533         assert(p > 0 || !o);
1534
1535         r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
1536         if (r < 0)
1537                 return r;
1538
1539         n = le64toh(d->data.n_entries);
1540         if (n <= 0)
1541                 return n;
1542
1543         if (!o)
1544                 i = direction == DIRECTION_DOWN ? 0 : n - 1;
1545         else {
1546                 if (o->object.type != OBJECT_ENTRY)
1547                         return -EINVAL;
1548
1549                 r = generic_array_bisect_plus_one(f,
1550                                                   le64toh(d->data.entry_offset),
1551                                                   le64toh(d->data.entry_array_offset),
1552                                                   le64toh(d->data.n_entries),
1553                                                   p,
1554                                                   test_object_offset,
1555                                                   DIRECTION_DOWN,
1556                                                   NULL, NULL,
1557                                                   &i);
1558
1559                 if (r <= 0)
1560                         return r;
1561
1562                 if (direction == DIRECTION_DOWN) {
1563                         if (i >= n - 1)
1564                                 return 0;
1565
1566                         i++;
1567                 } else {
1568                         if (i <= 0)
1569                                 return 0;
1570
1571                         i--;
1572                 }
1573
1574         }
1575
1576         return generic_array_get_plus_one(f,
1577                                           le64toh(d->data.entry_offset),
1578                                           le64toh(d->data.entry_array_offset),
1579                                           i,
1580                                           ret, offset);
1581 }
1582
1583 int journal_file_move_to_entry_by_seqnum_for_data(
1584                 JournalFile *f,
1585                 uint64_t data_offset,
1586                 uint64_t seqnum,
1587                 direction_t direction,
1588                 Object **ret, uint64_t *offset) {
1589
1590         Object *d;
1591         int r;
1592
1593         r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
1594         if (r <= 0)
1595                 return r;
1596
1597         return generic_array_bisect_plus_one(f,
1598                                              le64toh(d->data.entry_offset),
1599                                              le64toh(d->data.entry_array_offset),
1600                                              le64toh(d->data.n_entries),
1601                                              seqnum,
1602                                              test_object_seqnum,
1603                                              direction,
1604                                              ret, offset, NULL);
1605 }
1606
1607 int journal_file_move_to_entry_by_realtime_for_data(
1608                 JournalFile *f,
1609                 uint64_t data_offset,
1610                 uint64_t realtime,
1611                 direction_t direction,
1612                 Object **ret, uint64_t *offset) {
1613
1614         Object *d;
1615         int r;
1616
1617         r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
1618         if (r <= 0)
1619                 return r;
1620
1621         return generic_array_bisect_plus_one(f,
1622                                              le64toh(d->data.entry_offset),
1623                                              le64toh(d->data.entry_array_offset),
1624                                              le64toh(d->data.n_entries),
1625                                              realtime,
1626                                              test_object_realtime,
1627                                              direction,
1628                                              ret, offset, NULL);
1629 }
1630
1631 void journal_file_dump(JournalFile *f) {
1632         char a[33], b[33], c[33];
1633         Object *o;
1634         int r;
1635         uint64_t p;
1636
1637         assert(f);
1638
1639         printf("File Path: %s\n"
1640                "File ID: %s\n"
1641                "Machine ID: %s\n"
1642                "Boot ID: %s\n"
1643                "Arena size: %llu\n"
1644                "Objects: %lu\n"
1645                "Entries: %lu\n",
1646                f->path,
1647                sd_id128_to_string(f->header->file_id, a),
1648                sd_id128_to_string(f->header->machine_id, b),
1649                sd_id128_to_string(f->header->boot_id, c),
1650                (unsigned long long) le64toh(f->header->arena_size),
1651                (unsigned long) le64toh(f->header->n_objects),
1652                (unsigned long) le64toh(f->header->n_entries));
1653
1654         p = le64toh(f->header->arena_offset);
1655         while (p != 0) {
1656                 r = journal_file_move_to_object(f, -1, p, &o);
1657                 if (r < 0)
1658                         goto fail;
1659
1660                 switch (o->object.type) {
1661
1662                 case OBJECT_UNUSED:
1663                         printf("Type: OBJECT_UNUSED\n");
1664                         break;
1665
1666                 case OBJECT_DATA:
1667                         printf("Type: OBJECT_DATA\n");
1668                         break;
1669
1670                 case OBJECT_ENTRY:
1671                         printf("Type: OBJECT_ENTRY %llu %llu %llu\n",
1672                                (unsigned long long) le64toh(o->entry.seqnum),
1673                                (unsigned long long) le64toh(o->entry.monotonic),
1674                                (unsigned long long) le64toh(o->entry.realtime));
1675                         break;
1676
1677                 case OBJECT_FIELD_HASH_TABLE:
1678                         printf("Type: OBJECT_FIELD_HASH_TABLE\n");
1679                         break;
1680
1681                 case OBJECT_DATA_HASH_TABLE:
1682                         printf("Type: OBJECT_DATA_HASH_TABLE\n");
1683                         break;
1684
1685                 case OBJECT_ENTRY_ARRAY:
1686                         printf("Type: OBJECT_ENTRY_ARRAY\n");
1687                         break;
1688                 }
1689
1690                 if (o->object.flags & OBJECT_COMPRESSED)
1691                         printf("Flags: COMPRESSED\n");
1692
1693                 if (p == le64toh(f->header->tail_object_offset))
1694                         p = 0;
1695                 else
1696                         p = p + ALIGN64(le64toh(o->object.size));
1697         }
1698
1699         return;
1700 fail:
1701         log_error("File corrupt");
1702 }
1703
1704 int journal_file_open(
1705                 const char *fname,
1706                 int flags,
1707                 mode_t mode,
1708                 JournalFile *template,
1709                 JournalFile **ret) {
1710
1711         JournalFile *f;
1712         int r;
1713         bool newly_created = false;
1714
1715         assert(fname);
1716
1717         if ((flags & O_ACCMODE) != O_RDONLY &&
1718             (flags & O_ACCMODE) != O_RDWR)
1719                 return -EINVAL;
1720
1721         f = new0(JournalFile, 1);
1722         if (!f)
1723                 return -ENOMEM;
1724
1725         f->fd = -1;
1726         f->flags = flags;
1727         f->mode = mode;
1728         f->writable = (flags & O_ACCMODE) != O_RDONLY;
1729         f->prot = prot_from_flags(flags);
1730
1731         f->path = strdup(fname);
1732         if (!f->path) {
1733                 r = -ENOMEM;
1734                 goto fail;
1735         }
1736
1737         f->fd = open(f->path, f->flags|O_CLOEXEC, f->mode);
1738         if (f->fd < 0) {
1739                 r = -errno;
1740                 goto fail;
1741         }
1742
1743         if (fstat(f->fd, &f->last_stat) < 0) {
1744                 r = -errno;
1745                 goto fail;
1746         }
1747
1748         if (f->last_stat.st_size == 0 && f->writable) {
1749                 newly_created = true;
1750
1751                 r = journal_file_init_header(f, template);
1752                 if (r < 0)
1753                         goto fail;
1754
1755                 if (fstat(f->fd, &f->last_stat) < 0) {
1756                         r = -errno;
1757                         goto fail;
1758                 }
1759         }
1760
1761         if (f->last_stat.st_size < (off_t) sizeof(Header)) {
1762                 r = -EIO;
1763                 goto fail;
1764         }
1765
1766         f->header = mmap(NULL, PAGE_ALIGN(sizeof(Header)), prot_from_flags(flags), MAP_SHARED, f->fd, 0);
1767         if (f->header == MAP_FAILED) {
1768                 f->header = NULL;
1769                 r = -errno;
1770                 goto fail;
1771         }
1772
1773         if (!newly_created) {
1774                 r = journal_file_verify_header(f);
1775                 if (r < 0)
1776                         goto fail;
1777         }
1778
1779         if (f->writable) {
1780                 r = journal_file_refresh_header(f);
1781                 if (r < 0)
1782                         goto fail;
1783         }
1784
1785         if (newly_created) {
1786
1787                 r = journal_file_setup_field_hash_table(f);
1788                 if (r < 0)
1789                         goto fail;
1790
1791                 r = journal_file_setup_data_hash_table(f);
1792                 if (r < 0)
1793                         goto fail;
1794         }
1795
1796         r = journal_file_map_field_hash_table(f);
1797         if (r < 0)
1798                 goto fail;
1799
1800         r = journal_file_map_data_hash_table(f);
1801         if (r < 0)
1802                 goto fail;
1803
1804         if (ret)
1805                 *ret = f;
1806
1807         return 0;
1808
1809 fail:
1810         journal_file_close(f);
1811
1812         return r;
1813 }
1814
1815 int journal_file_rotate(JournalFile **f) {
1816         char *p;
1817         size_t l;
1818         JournalFile *old_file, *new_file = NULL;
1819         int r;
1820
1821         assert(f);
1822         assert(*f);
1823
1824         old_file = *f;
1825
1826         if (!old_file->writable)
1827                 return -EINVAL;
1828
1829         if (!endswith(old_file->path, ".journal"))
1830                 return -EINVAL;
1831
1832         l = strlen(old_file->path);
1833
1834         p = new(char, l + 1 + 16 + 1 + 32 + 1 + 16 + 1);
1835         if (!p)
1836                 return -ENOMEM;
1837
1838         memcpy(p, old_file->path, l - 8);
1839         p[l-8] = '@';
1840         sd_id128_to_string(old_file->header->seqnum_id, p + l - 8 + 1);
1841         snprintf(p + l - 8 + 1 + 32, 1 + 16 + 1 + 16 + 8 + 1,
1842                  "-%016llx-%016llx.journal",
1843                  (unsigned long long) le64toh((*f)->header->seqnum),
1844                  (unsigned long long) le64toh((*f)->header->tail_entry_realtime));
1845
1846         r = rename(old_file->path, p);
1847         free(p);
1848
1849         if (r < 0)
1850                 return -errno;
1851
1852         old_file->header->state = le32toh(STATE_ARCHIVED);
1853
1854         r = journal_file_open(old_file->path, old_file->flags, old_file->mode, old_file, &new_file);
1855         journal_file_close(old_file);
1856
1857         *f = new_file;
1858         return r;
1859 }
1860
1861 struct vacuum_info {
1862         off_t usage;
1863         char *filename;
1864
1865         uint64_t realtime;
1866         sd_id128_t seqnum_id;
1867         uint64_t seqnum;
1868 };
1869
1870 static int vacuum_compare(const void *_a, const void *_b) {
1871         const struct vacuum_info *a, *b;
1872
1873         a = _a;
1874         b = _b;
1875
1876         if (sd_id128_equal(a->seqnum_id, b->seqnum_id)) {
1877                 if (a->seqnum < b->seqnum)
1878                         return -1;
1879                 else if (a->seqnum > b->seqnum)
1880                         return 1;
1881                 else
1882                         return 0;
1883         }
1884
1885         if (a->realtime < b->realtime)
1886                 return -1;
1887         else if (a->realtime > b->realtime)
1888                 return 1;
1889         else
1890                 return memcmp(&a->seqnum_id, &b->seqnum_id, 16);
1891 }
1892
1893 int journal_directory_vacuum(const char *directory, uint64_t max_use, uint64_t min_free) {
1894         DIR *d;
1895         int r = 0;
1896         struct vacuum_info *list = NULL;
1897         unsigned n_list = 0, n_allocated = 0, i;
1898         uint64_t sum = 0;
1899
1900         assert(directory);
1901
1902         if (max_use <= 0)
1903                 return 0;
1904
1905         d = opendir(directory);
1906         if (!d)
1907                 return -errno;
1908
1909         for (;;) {
1910                 int k;
1911                 struct dirent buf, *de;
1912                 size_t q;
1913                 struct stat st;
1914                 char *p;
1915                 unsigned long long seqnum, realtime;
1916                 sd_id128_t seqnum_id;
1917
1918                 k = readdir_r(d, &buf, &de);
1919                 if (k != 0) {
1920                         r = -k;
1921                         goto finish;
1922                 }
1923
1924                 if (!de)
1925                         break;
1926
1927                 if (!dirent_is_file_with_suffix(de, ".journal"))
1928                         continue;
1929
1930                 q = strlen(de->d_name);
1931
1932                 if (q < 1 + 32 + 1 + 16 + 1 + 16 + 8)
1933                         continue;
1934
1935                 if (de->d_name[q-8-16-1] != '-' ||
1936                     de->d_name[q-8-16-1-16-1] != '-' ||
1937                     de->d_name[q-8-16-1-16-1-32-1] != '@')
1938                         continue;
1939
1940                 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
1941                         continue;
1942
1943                 if (!S_ISREG(st.st_mode))
1944                         continue;
1945
1946                 p = strdup(de->d_name);
1947                 if (!p) {
1948                         r = -ENOMEM;
1949                         goto finish;
1950                 }
1951
1952                 de->d_name[q-8-16-1-16-1] = 0;
1953                 if (sd_id128_from_string(de->d_name + q-8-16-1-16-1-32, &seqnum_id) < 0) {
1954                         free(p);
1955                         continue;
1956                 }
1957
1958                 if (sscanf(de->d_name + q-8-16-1-16, "%16llx-%16llx.journal", &seqnum, &realtime) != 2) {
1959                         free(p);
1960                         continue;
1961                 }
1962
1963                 if (n_list >= n_allocated) {
1964                         struct vacuum_info *j;
1965
1966                         n_allocated = MAX(n_allocated * 2U, 8U);
1967                         j = realloc(list, n_allocated * sizeof(struct vacuum_info));
1968                         if (!j) {
1969                                 free(p);
1970                                 r = -ENOMEM;
1971                                 goto finish;
1972                         }
1973
1974                         list = j;
1975                 }
1976
1977                 list[n_list].filename = p;
1978                 list[n_list].usage = (uint64_t) st.st_blksize * (uint64_t) st.st_blocks;
1979                 list[n_list].seqnum = seqnum;
1980                 list[n_list].realtime = realtime;
1981                 list[n_list].seqnum_id = seqnum_id;
1982
1983                 sum += list[n_list].usage;
1984
1985                 n_list ++;
1986         }
1987
1988         qsort(list, n_list, sizeof(struct vacuum_info), vacuum_compare);
1989
1990         for(i = 0; i < n_list; i++) {
1991                 struct statvfs ss;
1992
1993                 if (fstatvfs(dirfd(d), &ss) < 0) {
1994                         r = -errno;
1995                         goto finish;
1996                 }
1997
1998                 if (sum <= max_use &&
1999                     (uint64_t) ss.f_bavail * (uint64_t) ss.f_bsize >= min_free)
2000                         break;
2001
2002                 if (unlinkat(dirfd(d), list[i].filename, 0) >= 0) {
2003                         log_debug("Deleted archived journal %s/%s.", directory, list[i].filename);
2004                         sum -= list[i].usage;
2005                 } else if (errno != ENOENT)
2006                         log_warning("Failed to delete %s/%s: %m", directory, list[i].filename);
2007         }
2008
2009 finish:
2010         for (i = 0; i < n_list; i++)
2011                 free(list[i].filename);
2012
2013         free(list);
2014
2015         if (d)
2016                 closedir(d);
2017
2018         return r;
2019 }
2020
2021 int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset) {
2022         uint64_t i, n;
2023         uint64_t q, xor_hash = 0;
2024         int r;
2025         EntryItem *items;
2026         dual_timestamp ts;
2027
2028         assert(from);
2029         assert(to);
2030         assert(o);
2031         assert(p);
2032
2033         if (!to->writable)
2034                 return -EPERM;
2035
2036         ts.monotonic = le64toh(o->entry.monotonic);
2037         ts.realtime = le64toh(o->entry.realtime);
2038
2039         if (to->tail_entry_monotonic_valid &&
2040             ts.monotonic < le64toh(to->header->tail_entry_monotonic))
2041                 return -EINVAL;
2042
2043         if (ts.realtime < le64toh(to->header->tail_entry_realtime))
2044                 return -EINVAL;
2045
2046         n = journal_file_entry_n_items(o);
2047         items = alloca(sizeof(EntryItem) * n);
2048
2049         for (i = 0; i < n; i++) {
2050                 uint64_t le_hash, l, h;
2051                 size_t t;
2052                 void *data;
2053                 Object *u;
2054
2055                 q = le64toh(o->entry.items[i].object_offset);
2056                 le_hash = o->entry.items[i].hash;
2057
2058                 r = journal_file_move_to_object(from, OBJECT_DATA, q, &o);
2059                 if (r < 0)
2060                         return r;
2061
2062                 if (le_hash != o->data.hash)
2063                         return -EBADMSG;
2064
2065                 l = le64toh(o->object.size) - offsetof(Object, data.payload);
2066                 t = (size_t) l;
2067
2068                 /* We hit the limit on 32bit machines */
2069                 if ((uint64_t) t != l)
2070                         return -E2BIG;
2071
2072                 if (o->object.flags & OBJECT_COMPRESSED) {
2073 #ifdef HAVE_XZ
2074                         uint64_t rsize;
2075
2076                         if (!uncompress_blob(o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize))
2077                                 return -EBADMSG;
2078
2079                         data = from->compress_buffer;
2080                         l = rsize;
2081 #else
2082                         return -EPROTONOSUPPORT;
2083 #endif
2084                 } else
2085                         data = o->data.payload;
2086
2087                 r = journal_file_append_data(to, data, l, &u, &h);
2088                 if (r < 0)
2089                         return r;
2090
2091                 xor_hash ^= le64toh(u->data.hash);
2092                 items[i].object_offset = htole64(h);
2093                 items[i].hash = u->data.hash;
2094
2095                 r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
2096                 if (r < 0)
2097                         return r;
2098         }
2099
2100         return journal_file_append_entry_internal(to, &ts, xor_hash, items, n, seqnum, ret, offset);
2101 }
2102
2103 void journal_default_metrics(JournalMetrics *m, int fd) {
2104         uint64_t fs_size = 0;
2105         struct statvfs ss;
2106         char a[FORMAT_BYTES_MAX], b[FORMAT_BYTES_MAX], c[FORMAT_BYTES_MAX], d[FORMAT_BYTES_MAX];
2107
2108         assert(m);
2109         assert(fd >= 0);
2110
2111         if (fstatvfs(fd, &ss) >= 0)
2112                 fs_size = ss.f_frsize * ss.f_blocks;
2113
2114         if (m->max_use == (uint64_t) -1) {
2115
2116                 if (fs_size > 0) {
2117                         m->max_use = PAGE_ALIGN(fs_size / 10); /* 10% of file system size */
2118
2119                         if (m->max_use > DEFAULT_MAX_USE_UPPER)
2120                                 m->max_use = DEFAULT_MAX_USE_UPPER;
2121
2122                         if (m->max_use < DEFAULT_MAX_USE_LOWER)
2123                                 m->max_use = DEFAULT_MAX_USE_LOWER;
2124                 } else
2125                         m->max_use = DEFAULT_MAX_USE_LOWER;
2126         } else {
2127                 m->max_use = PAGE_ALIGN(m->max_use);
2128
2129                 if (m->max_use < JOURNAL_FILE_SIZE_MIN*2)
2130                         m->max_use = JOURNAL_FILE_SIZE_MIN*2;
2131         }
2132
2133         if (m->max_size == (uint64_t) -1) {
2134                 m->max_size = PAGE_ALIGN(m->max_use / 8); /* 8 chunks */
2135
2136                 if (m->max_size > DEFAULT_MAX_SIZE_UPPER)
2137                         m->max_size = DEFAULT_MAX_SIZE_UPPER;
2138         } else
2139                 m->max_size = PAGE_ALIGN(m->max_size);
2140
2141         if (m->max_size < JOURNAL_FILE_SIZE_MIN)
2142                 m->max_size = JOURNAL_FILE_SIZE_MIN;
2143
2144         if (m->max_size*2 > m->max_use)
2145                 m->max_use = m->max_size*2;
2146
2147         if (m->min_size == (uint64_t) -1)
2148                 m->min_size = JOURNAL_FILE_SIZE_MIN;
2149         else {
2150                 m->min_size = PAGE_ALIGN(m->min_size);
2151
2152                 if (m->min_size < JOURNAL_FILE_SIZE_MIN)
2153                         m->min_size = JOURNAL_FILE_SIZE_MIN;
2154
2155                 if (m->min_size > m->max_size)
2156                         m->max_size = m->min_size;
2157         }
2158
2159         if (m->keep_free == (uint64_t) -1) {
2160
2161                 if (fs_size > 0) {
2162                         m->keep_free = PAGE_ALIGN(fs_size / 20); /* 5% of file system size */
2163
2164                         if (m->keep_free > DEFAULT_KEEP_FREE_UPPER)
2165                                 m->keep_free = DEFAULT_KEEP_FREE_UPPER;
2166
2167                 } else
2168                         m->keep_free = DEFAULT_KEEP_FREE;
2169         }
2170
2171         log_debug("Fixed max_use=%s max_size=%s min_size=%s keep_free=%s",
2172                   format_bytes(a, sizeof(a), m->max_use),
2173                   format_bytes(b, sizeof(b), m->max_size),
2174                   format_bytes(c, sizeof(c), m->min_size),
2175                   format_bytes(d, sizeof(d), m->keep_free));
2176 }