chiark / gitweb /
journald: don't assume size_t and uint64_t are the same
[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 = (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;
644                         size_t rsize;
645
646                         l = le64toh(o->object.size);
647                         if (l <= offsetof(Object, data.payload))
648                                 return -EBADMSG;
649
650                         l -= offsetof(Object, data.payload);
651
652                         if (!uncompress_blob(o->data.payload, l, &f->compress_buffer, &f->compress_buffer_size, &rsize))
653                                 return -EBADMSG;
654
655                         if ((uint64_t) rsize == size &&
656                             memcmp(f->compress_buffer, data, size) == 0) {
657
658                                 if (ret)
659                                         *ret = o;
660
661                                 if (offset)
662                                         *offset = p;
663
664                                 return 1;
665                         }
666 #else
667                         return -EPROTONOSUPPORT;
668 #endif
669
670                 } else if (le64toh(o->object.size) == osize &&
671                            memcmp(o->data.payload, data, size) == 0) {
672
673                         if (ret)
674                                 *ret = o;
675
676                         if (offset)
677                                 *offset = p;
678
679                         return 1;
680                 }
681
682         next:
683                 p = le64toh(o->data.next_hash_offset);
684         }
685
686         return 0;
687 }
688
689 int journal_file_find_data_object(
690                 JournalFile *f,
691                 const void *data, uint64_t size,
692                 Object **ret, uint64_t *offset) {
693
694         uint64_t hash;
695
696         assert(f);
697         assert(data || size == 0);
698
699         hash = hash64(data, size);
700
701         return journal_file_find_data_object_with_hash(f,
702                                                        data, size, hash,
703                                                        ret, offset);
704 }
705
706 static int journal_file_append_data(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset) {
707         uint64_t hash, p;
708         uint64_t osize;
709         Object *o;
710         int r;
711         bool compressed = false;
712
713         assert(f);
714         assert(data || size == 0);
715
716         hash = hash64(data, size);
717
718         r = journal_file_find_data_object_with_hash(f, data, size, hash, &o, &p);
719         if (r < 0)
720                 return r;
721         else if (r > 0) {
722
723                 if (ret)
724                         *ret = o;
725
726                 if (offset)
727                         *offset = p;
728
729                 return 0;
730         }
731
732         osize = offsetof(Object, data.payload) + size;
733         r = journal_file_append_object(f, OBJECT_DATA, osize, &o, &p);
734         if (r < 0)
735                 return r;
736
737         o->data.hash = htole64(hash);
738
739 #ifdef HAVE_XZ
740         if (f->compress &&
741             size >= COMPRESSION_SIZE_THRESHOLD) {
742                 uint64_t rsize;
743
744                 compressed = compress_blob(data, size, o->data.payload, &rsize);
745
746                 if (compressed) {
747                         o->object.size = htole64(offsetof(Object, data.payload) + rsize);
748                         o->object.flags |= OBJECT_COMPRESSED;
749
750                         f->header->incompatible_flags = htole32(le32toh(f->header->incompatible_flags) | HEADER_INCOMPATIBLE_COMPRESSED);
751
752                         log_debug("Compressed data object %lu -> %lu", (unsigned long) size, (unsigned long) rsize);
753                 }
754         }
755 #endif
756
757         if (!compressed)
758                 memcpy(o->data.payload, data, size);
759
760         r = journal_file_link_data(f, o, p, hash);
761         if (r < 0)
762                 return r;
763
764         if (ret)
765                 *ret = o;
766
767         if (offset)
768                 *offset = p;
769
770         return 0;
771 }
772
773 uint64_t journal_file_entry_n_items(Object *o) {
774         assert(o);
775         assert(o->object.type == htole64(OBJECT_ENTRY));
776
777         return (le64toh(o->object.size) - offsetof(Object, entry.items)) / sizeof(EntryItem);
778 }
779
780 static uint64_t journal_file_entry_array_n_items(Object *o) {
781         assert(o);
782         assert(o->object.type == htole64(OBJECT_ENTRY_ARRAY));
783
784         return (le64toh(o->object.size) - offsetof(Object, entry_array.items)) / sizeof(uint64_t);
785 }
786
787 static int link_entry_into_array(JournalFile *f,
788                                  uint64_t *first,
789                                  uint64_t *idx,
790                                  uint64_t p) {
791         int r;
792         uint64_t n = 0, ap = 0, q, i, a, hidx;
793         Object *o;
794
795         assert(f);
796         assert(first);
797         assert(idx);
798         assert(p > 0);
799
800         a = le64toh(*first);
801         i = hidx = le64toh(*idx);
802         while (a > 0) {
803
804                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
805                 if (r < 0)
806                         return r;
807
808                 n = journal_file_entry_array_n_items(o);
809                 if (i < n) {
810                         o->entry_array.items[i] = htole64(p);
811                         *idx = htole64(hidx + 1);
812                         return 0;
813                 }
814
815                 i -= n;
816                 ap = a;
817                 a = le64toh(o->entry_array.next_entry_array_offset);
818         }
819
820         if (hidx > n)
821                 n = (hidx+1) * 2;
822         else
823                 n = n * 2;
824
825         if (n < 4)
826                 n = 4;
827
828         r = journal_file_append_object(f, OBJECT_ENTRY_ARRAY,
829                                        offsetof(Object, entry_array.items) + n * sizeof(uint64_t),
830                                        &o, &q);
831         if (r < 0)
832                 return r;
833
834         o->entry_array.items[i] = htole64(p);
835
836         if (ap == 0)
837                 *first = q;
838         else {
839                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, ap, &o);
840                 if (r < 0)
841                         return r;
842
843                 o->entry_array.next_entry_array_offset = htole64(q);
844         }
845
846         *idx = htole64(hidx + 1);
847
848         return 0;
849 }
850
851 static int link_entry_into_array_plus_one(JournalFile *f,
852                                           uint64_t *extra,
853                                           uint64_t *first,
854                                           uint64_t *idx,
855                                           uint64_t p) {
856
857         int r;
858
859         assert(f);
860         assert(extra);
861         assert(first);
862         assert(idx);
863         assert(p > 0);
864
865         if (*idx == 0)
866                 *extra = htole64(p);
867         else {
868                 uint64_t i;
869
870                 i = le64toh(*idx) - 1;
871                 r = link_entry_into_array(f, first, &i, p);
872                 if (r < 0)
873                         return r;
874         }
875
876         *idx = htole64(le64toh(*idx) + 1);
877         return 0;
878 }
879
880 static int journal_file_link_entry_item(JournalFile *f, Object *o, uint64_t offset, uint64_t i) {
881         uint64_t p;
882         int r;
883         assert(f);
884         assert(o);
885         assert(offset > 0);
886
887         p = le64toh(o->entry.items[i].object_offset);
888         if (p == 0)
889                 return -EINVAL;
890
891         r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
892         if (r < 0)
893                 return r;
894
895         return link_entry_into_array_plus_one(f,
896                                               &o->data.entry_offset,
897                                               &o->data.entry_array_offset,
898                                               &o->data.n_entries,
899                                               offset);
900 }
901
902 static int journal_file_link_entry(JournalFile *f, Object *o, uint64_t offset) {
903         uint64_t n, i;
904         int r;
905
906         assert(f);
907         assert(o);
908         assert(offset > 0);
909         assert(o->object.type == OBJECT_ENTRY);
910
911         __sync_synchronize();
912
913         /* Link up the entry itself */
914         r = link_entry_into_array(f,
915                                   &f->header->entry_array_offset,
916                                   &f->header->n_entries,
917                                   offset);
918         if (r < 0)
919                 return r;
920
921         /* log_debug("=> %s seqnr=%lu n_entries=%lu", f->path, (unsigned long) o->entry.seqnum, (unsigned long) f->header->n_entries); */
922
923         if (f->header->head_entry_realtime == 0)
924                 f->header->head_entry_realtime = o->entry.realtime;
925
926         f->header->tail_entry_realtime = o->entry.realtime;
927         f->header->tail_entry_monotonic = o->entry.monotonic;
928
929         f->tail_entry_monotonic_valid = true;
930
931         /* Link up the items */
932         n = journal_file_entry_n_items(o);
933         for (i = 0; i < n; i++) {
934                 r = journal_file_link_entry_item(f, o, offset, i);
935                 if (r < 0)
936                         return r;
937         }
938
939         return 0;
940 }
941
942 static int journal_file_append_entry_internal(
943                 JournalFile *f,
944                 const dual_timestamp *ts,
945                 uint64_t xor_hash,
946                 const EntryItem items[], unsigned n_items,
947                 uint64_t *seqnum,
948                 Object **ret, uint64_t *offset) {
949         uint64_t np;
950         uint64_t osize;
951         Object *o;
952         int r;
953
954         assert(f);
955         assert(items || n_items == 0);
956         assert(ts);
957
958         osize = offsetof(Object, entry.items) + (n_items * sizeof(EntryItem));
959
960         r = journal_file_append_object(f, OBJECT_ENTRY, osize, &o, &np);
961         if (r < 0)
962                 return r;
963
964         o->entry.seqnum = htole64(journal_file_seqnum(f, seqnum));
965         memcpy(o->entry.items, items, n_items * sizeof(EntryItem));
966         o->entry.realtime = htole64(ts->realtime);
967         o->entry.monotonic = htole64(ts->monotonic);
968         o->entry.xor_hash = htole64(xor_hash);
969         o->entry.boot_id = f->header->boot_id;
970
971         r = journal_file_link_entry(f, o, np);
972         if (r < 0)
973                 return r;
974
975         if (ret)
976                 *ret = o;
977
978         if (offset)
979                 *offset = np;
980
981         return 0;
982 }
983
984 void journal_file_post_change(JournalFile *f) {
985         assert(f);
986
987         /* inotify() does not receive IN_MODIFY events from file
988          * accesses done via mmap(). After each access we hence
989          * trigger IN_MODIFY by truncating the journal file to its
990          * current size which triggers IN_MODIFY. */
991
992         __sync_synchronize();
993
994         if (ftruncate(f->fd, f->last_stat.st_size) < 0)
995                 log_error("Failed to to truncate file to its own size: %m");
996 }
997
998 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) {
999         unsigned i;
1000         EntryItem *items;
1001         int r;
1002         uint64_t xor_hash = 0;
1003         struct dual_timestamp _ts;
1004
1005         assert(f);
1006         assert(iovec || n_iovec == 0);
1007
1008         if (!f->writable)
1009                 return -EPERM;
1010
1011         if (!ts) {
1012                 dual_timestamp_get(&_ts);
1013                 ts = &_ts;
1014         }
1015
1016         if (f->tail_entry_monotonic_valid &&
1017             ts->monotonic < le64toh(f->header->tail_entry_monotonic))
1018                 return -EINVAL;
1019
1020         items = alloca(sizeof(EntryItem) * n_iovec);
1021
1022         for (i = 0; i < n_iovec; i++) {
1023                 uint64_t p;
1024                 Object *o;
1025
1026                 r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p);
1027                 if (r < 0)
1028                         return r;
1029
1030                 xor_hash ^= le64toh(o->data.hash);
1031                 items[i].object_offset = htole64(p);
1032                 items[i].hash = o->data.hash;
1033         }
1034
1035         r = journal_file_append_entry_internal(f, ts, xor_hash, items, n_iovec, seqnum, ret, offset);
1036
1037         journal_file_post_change(f);
1038
1039         return r;
1040 }
1041
1042 static int generic_array_get(JournalFile *f,
1043                              uint64_t first,
1044                              uint64_t i,
1045                              Object **ret, uint64_t *offset) {
1046
1047         Object *o;
1048         uint64_t p = 0, a;
1049         int r;
1050
1051         assert(f);
1052
1053         a = first;
1054         while (a > 0) {
1055                 uint64_t n;
1056
1057                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
1058                 if (r < 0)
1059                         return r;
1060
1061                 n = journal_file_entry_array_n_items(o);
1062                 if (i < n) {
1063                         p = le64toh(o->entry_array.items[i]);
1064                         break;
1065                 }
1066
1067                 i -= n;
1068                 a = le64toh(o->entry_array.next_entry_array_offset);
1069         }
1070
1071         if (a <= 0 || p <= 0)
1072                 return 0;
1073
1074         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1075         if (r < 0)
1076                 return r;
1077
1078         if (ret)
1079                 *ret = o;
1080
1081         if (offset)
1082                 *offset = p;
1083
1084         return 1;
1085 }
1086
1087 static int generic_array_get_plus_one(JournalFile *f,
1088                                       uint64_t extra,
1089                                       uint64_t first,
1090                                       uint64_t i,
1091                                       Object **ret, uint64_t *offset) {
1092
1093         Object *o;
1094
1095         assert(f);
1096
1097         if (i == 0) {
1098                 int r;
1099
1100                 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
1101                 if (r < 0)
1102                         return r;
1103
1104                 if (ret)
1105                         *ret = o;
1106
1107                 if (offset)
1108                         *offset = extra;
1109
1110                 return 1;
1111         }
1112
1113         return generic_array_get(f, first, i-1, ret, offset);
1114 }
1115
1116 enum {
1117         TEST_FOUND,
1118         TEST_LEFT,
1119         TEST_RIGHT
1120 };
1121
1122 static int generic_array_bisect(JournalFile *f,
1123                                 uint64_t first,
1124                                 uint64_t n,
1125                                 uint64_t needle,
1126                                 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
1127                                 direction_t direction,
1128                                 Object **ret,
1129                                 uint64_t *offset,
1130                                 uint64_t *idx) {
1131
1132         uint64_t a, p, t = 0, i = 0, last_p = 0;
1133         bool subtract_one = false;
1134         Object *o, *array = NULL;
1135         int r;
1136
1137         assert(f);
1138         assert(test_object);
1139
1140         a = first;
1141         while (a > 0) {
1142                 uint64_t left, right, k, lp;
1143
1144                 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
1145                 if (r < 0)
1146                         return r;
1147
1148                 k = journal_file_entry_array_n_items(array);
1149                 right = MIN(k, n);
1150                 if (right <= 0)
1151                         return 0;
1152
1153                 i = right - 1;
1154                 lp = p = le64toh(array->entry_array.items[i]);
1155                 if (p <= 0)
1156                         return -EBADMSG;
1157
1158                 r = test_object(f, p, needle);
1159                 if (r < 0)
1160                         return r;
1161
1162                 if (r == TEST_FOUND)
1163                         r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
1164
1165                 if (r == TEST_RIGHT) {
1166                         left = 0;
1167                         right -= 1;
1168                         for (;;) {
1169                                 if (left == right) {
1170                                         if (direction == DIRECTION_UP)
1171                                                 subtract_one = true;
1172
1173                                         i = left;
1174                                         goto found;
1175                                 }
1176
1177                                 assert(left < right);
1178
1179                                 i = (left + right) / 2;
1180                                 p = le64toh(array->entry_array.items[i]);
1181                                 if (p <= 0)
1182                                         return -EBADMSG;
1183
1184                                 r = test_object(f, p, needle);
1185                                 if (r < 0)
1186                                         return r;
1187
1188                                 if (r == TEST_FOUND)
1189                                         r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
1190
1191                                 if (r == TEST_RIGHT)
1192                                         right = i;
1193                                 else
1194                                         left = i + 1;
1195                         }
1196                 }
1197
1198                 if (k > n)
1199                         return 0;
1200
1201                 last_p = lp;
1202
1203                 n -= k;
1204                 t += k;
1205                 a = le64toh(array->entry_array.next_entry_array_offset);
1206         }
1207
1208         return 0;
1209
1210 found:
1211         if (subtract_one && t == 0 && i == 0)
1212                 return 0;
1213
1214         if (subtract_one && i == 0)
1215                 p = last_p;
1216         else if (subtract_one)
1217                 p = le64toh(array->entry_array.items[i-1]);
1218         else
1219                 p = le64toh(array->entry_array.items[i]);
1220
1221         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1222         if (r < 0)
1223                 return r;
1224
1225         if (ret)
1226                 *ret = o;
1227
1228         if (offset)
1229                 *offset = p;
1230
1231         if (idx)
1232                 *idx = t + i - (subtract_one ? 1 : 0);
1233
1234         return 1;
1235 }
1236
1237 static int generic_array_bisect_plus_one(JournalFile *f,
1238                                          uint64_t extra,
1239                                          uint64_t first,
1240                                          uint64_t n,
1241                                          uint64_t needle,
1242                                          int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
1243                                          direction_t direction,
1244                                          Object **ret,
1245                                          uint64_t *offset,
1246                                          uint64_t *idx) {
1247
1248         int r;
1249
1250         assert(f);
1251         assert(test_object);
1252
1253         if (n <= 0)
1254                 return 0;
1255
1256         /* This bisects the array in object 'first', but first checks
1257          * an extra  */
1258         r = test_object(f, extra, needle);
1259         if (r < 0)
1260                 return r;
1261         else if (r == TEST_FOUND) {
1262                 Object *o;
1263
1264                 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
1265                 if (r < 0)
1266                         return r;
1267
1268                 if (ret)
1269                         *ret = o;
1270
1271                 if (offset)
1272                         *offset = extra;
1273
1274                 if (idx)
1275                         *idx = 0;
1276
1277                 return 1;
1278         } else if (r == TEST_RIGHT)
1279                 return 0;
1280
1281         r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret, offset, idx);
1282
1283         if (r > 0)
1284                 (*idx) ++;
1285
1286         return r;
1287 }
1288
1289 static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) {
1290         Object *o;
1291         int r;
1292
1293         assert(f);
1294         assert(p > 0);
1295
1296         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1297         if (r < 0)
1298                 return r;
1299
1300         if (le64toh(o->entry.seqnum) == needle)
1301                 return TEST_FOUND;
1302         else if (le64toh(o->entry.seqnum) < needle)
1303                 return TEST_LEFT;
1304         else
1305                 return TEST_RIGHT;
1306 }
1307
1308 int journal_file_move_to_entry_by_seqnum(
1309                 JournalFile *f,
1310                 uint64_t seqnum,
1311                 direction_t direction,
1312                 Object **ret,
1313                 uint64_t *offset) {
1314
1315         return generic_array_bisect(f,
1316                                     le64toh(f->header->entry_array_offset),
1317                                     le64toh(f->header->n_entries),
1318                                     seqnum,
1319                                     test_object_seqnum,
1320                                     direction,
1321                                     ret, offset, NULL);
1322 }
1323
1324 static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) {
1325         Object *o;
1326         int r;
1327
1328         assert(f);
1329         assert(p > 0);
1330
1331         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1332         if (r < 0)
1333                 return r;
1334
1335         if (le64toh(o->entry.realtime) == needle)
1336                 return TEST_FOUND;
1337         else if (le64toh(o->entry.realtime) < needle)
1338                 return TEST_LEFT;
1339         else
1340                 return TEST_RIGHT;
1341 }
1342
1343 int journal_file_move_to_entry_by_realtime(
1344                 JournalFile *f,
1345                 uint64_t realtime,
1346                 direction_t direction,
1347                 Object **ret,
1348                 uint64_t *offset) {
1349
1350         return generic_array_bisect(f,
1351                                     le64toh(f->header->entry_array_offset),
1352                                     le64toh(f->header->n_entries),
1353                                     realtime,
1354                                     test_object_realtime,
1355                                     direction,
1356                                     ret, offset, NULL);
1357 }
1358
1359 static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) {
1360         Object *o;
1361         int r;
1362
1363         assert(f);
1364         assert(p > 0);
1365
1366         r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1367         if (r < 0)
1368                 return r;
1369
1370         if (le64toh(o->entry.monotonic) == needle)
1371                 return TEST_FOUND;
1372         else if (le64toh(o->entry.monotonic) < needle)
1373                 return TEST_LEFT;
1374         else
1375                 return TEST_RIGHT;
1376 }
1377
1378 int journal_file_move_to_entry_by_monotonic(
1379                 JournalFile *f,
1380                 sd_id128_t boot_id,
1381                 uint64_t monotonic,
1382                 direction_t direction,
1383                 Object **ret,
1384                 uint64_t *offset) {
1385
1386         char t[8+32+1] = "_BOOT_ID=";
1387         Object *o;
1388         int r;
1389
1390         sd_id128_to_string(boot_id, t + 8);
1391
1392         r = journal_file_find_data_object(f, t, strlen(t), &o, NULL);
1393         if (r < 0)
1394                 return r;
1395         else if (r == 0)
1396                 return -ENOENT;
1397
1398         return generic_array_bisect_plus_one(f,
1399                                              le64toh(o->data.entry_offset),
1400                                              le64toh(o->data.entry_array_offset),
1401                                              le64toh(o->data.n_entries),
1402                                              monotonic,
1403                                              test_object_monotonic,
1404                                              direction,
1405                                              ret, offset, NULL);
1406 }
1407
1408 static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) {
1409         assert(f);
1410         assert(p > 0);
1411
1412         if (p == needle)
1413                 return TEST_FOUND;
1414         else if (p < needle)
1415                 return TEST_LEFT;
1416         else
1417                 return TEST_RIGHT;
1418 }
1419
1420 int journal_file_next_entry(
1421                 JournalFile *f,
1422                 Object *o, uint64_t p,
1423                 direction_t direction,
1424                 Object **ret, uint64_t *offset) {
1425
1426         uint64_t i, n;
1427         int r;
1428
1429         assert(f);
1430         assert(p > 0 || !o);
1431
1432         n = le64toh(f->header->n_entries);
1433         if (n <= 0)
1434                 return 0;
1435
1436         if (!o)
1437                 i = direction == DIRECTION_DOWN ? 0 : n - 1;
1438         else {
1439                 if (o->object.type != OBJECT_ENTRY)
1440                         return -EINVAL;
1441
1442                 r = generic_array_bisect(f,
1443                                          le64toh(f->header->entry_array_offset),
1444                                          le64toh(f->header->n_entries),
1445                                          p,
1446                                          test_object_offset,
1447                                          DIRECTION_DOWN,
1448                                          NULL, NULL,
1449                                          &i);
1450                 if (r <= 0)
1451                         return r;
1452
1453                 if (direction == DIRECTION_DOWN) {
1454                         if (i >= n - 1)
1455                                 return 0;
1456
1457                         i++;
1458                 } else {
1459                         if (i <= 0)
1460                                 return 0;
1461
1462                         i--;
1463                 }
1464         }
1465
1466         /* And jump to it */
1467         return generic_array_get(f,
1468                                  le64toh(f->header->entry_array_offset),
1469                                  i,
1470                                  ret, offset);
1471 }
1472
1473 int journal_file_skip_entry(
1474                 JournalFile *f,
1475                 Object *o, uint64_t p,
1476                 int64_t skip,
1477                 Object **ret, uint64_t *offset) {
1478
1479         uint64_t i, n;
1480         int r;
1481
1482         assert(f);
1483         assert(o);
1484         assert(p > 0);
1485
1486         if (o->object.type != OBJECT_ENTRY)
1487                 return -EINVAL;
1488
1489         r = generic_array_bisect(f,
1490                                  le64toh(f->header->entry_array_offset),
1491                                  le64toh(f->header->n_entries),
1492                                  p,
1493                                  test_object_offset,
1494                                  DIRECTION_DOWN,
1495                                  NULL, NULL,
1496                                  &i);
1497         if (r <= 0)
1498                 return r;
1499
1500         /* Calculate new index */
1501         if (skip < 0) {
1502                 if ((uint64_t) -skip >= i)
1503                         i = 0;
1504                 else
1505                         i = i - (uint64_t) -skip;
1506         } else
1507                 i  += (uint64_t) skip;
1508
1509         n = le64toh(f->header->n_entries);
1510         if (n <= 0)
1511                 return -EBADMSG;
1512
1513         if (i >= n)
1514                 i = n-1;
1515
1516         return generic_array_get(f,
1517                                  le64toh(f->header->entry_array_offset),
1518                                  i,
1519                                  ret, offset);
1520 }
1521
1522 int journal_file_next_entry_for_data(
1523                 JournalFile *f,
1524                 Object *o, uint64_t p,
1525                 uint64_t data_offset,
1526                 direction_t direction,
1527                 Object **ret, uint64_t *offset) {
1528
1529         uint64_t n, i;
1530         int r;
1531         Object *d;
1532
1533         assert(f);
1534         assert(p > 0 || !o);
1535
1536         r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
1537         if (r < 0)
1538                 return r;
1539
1540         n = le64toh(d->data.n_entries);
1541         if (n <= 0)
1542                 return n;
1543
1544         if (!o)
1545                 i = direction == DIRECTION_DOWN ? 0 : n - 1;
1546         else {
1547                 if (o->object.type != OBJECT_ENTRY)
1548                         return -EINVAL;
1549
1550                 r = generic_array_bisect_plus_one(f,
1551                                                   le64toh(d->data.entry_offset),
1552                                                   le64toh(d->data.entry_array_offset),
1553                                                   le64toh(d->data.n_entries),
1554                                                   p,
1555                                                   test_object_offset,
1556                                                   DIRECTION_DOWN,
1557                                                   NULL, NULL,
1558                                                   &i);
1559
1560                 if (r <= 0)
1561                         return r;
1562
1563                 if (direction == DIRECTION_DOWN) {
1564                         if (i >= n - 1)
1565                                 return 0;
1566
1567                         i++;
1568                 } else {
1569                         if (i <= 0)
1570                                 return 0;
1571
1572                         i--;
1573                 }
1574
1575         }
1576
1577         return generic_array_get_plus_one(f,
1578                                           le64toh(d->data.entry_offset),
1579                                           le64toh(d->data.entry_array_offset),
1580                                           i,
1581                                           ret, offset);
1582 }
1583
1584 int journal_file_move_to_entry_by_seqnum_for_data(
1585                 JournalFile *f,
1586                 uint64_t data_offset,
1587                 uint64_t seqnum,
1588                 direction_t direction,
1589                 Object **ret, uint64_t *offset) {
1590
1591         Object *d;
1592         int r;
1593
1594         r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
1595         if (r <= 0)
1596                 return r;
1597
1598         return generic_array_bisect_plus_one(f,
1599                                              le64toh(d->data.entry_offset),
1600                                              le64toh(d->data.entry_array_offset),
1601                                              le64toh(d->data.n_entries),
1602                                              seqnum,
1603                                              test_object_seqnum,
1604                                              direction,
1605                                              ret, offset, NULL);
1606 }
1607
1608 int journal_file_move_to_entry_by_realtime_for_data(
1609                 JournalFile *f,
1610                 uint64_t data_offset,
1611                 uint64_t realtime,
1612                 direction_t direction,
1613                 Object **ret, uint64_t *offset) {
1614
1615         Object *d;
1616         int r;
1617
1618         r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
1619         if (r <= 0)
1620                 return r;
1621
1622         return generic_array_bisect_plus_one(f,
1623                                              le64toh(d->data.entry_offset),
1624                                              le64toh(d->data.entry_array_offset),
1625                                              le64toh(d->data.n_entries),
1626                                              realtime,
1627                                              test_object_realtime,
1628                                              direction,
1629                                              ret, offset, NULL);
1630 }
1631
1632 void journal_file_dump(JournalFile *f) {
1633         char a[33], b[33], c[33];
1634         Object *o;
1635         int r;
1636         uint64_t p;
1637
1638         assert(f);
1639
1640         printf("File Path: %s\n"
1641                "File ID: %s\n"
1642                "Machine ID: %s\n"
1643                "Boot ID: %s\n"
1644                "Arena size: %llu\n"
1645                "Objects: %lu\n"
1646                "Entries: %lu\n",
1647                f->path,
1648                sd_id128_to_string(f->header->file_id, a),
1649                sd_id128_to_string(f->header->machine_id, b),
1650                sd_id128_to_string(f->header->boot_id, c),
1651                (unsigned long long) le64toh(f->header->arena_size),
1652                (unsigned long) le64toh(f->header->n_objects),
1653                (unsigned long) le64toh(f->header->n_entries));
1654
1655         p = le64toh(f->header->arena_offset);
1656         while (p != 0) {
1657                 r = journal_file_move_to_object(f, -1, p, &o);
1658                 if (r < 0)
1659                         goto fail;
1660
1661                 switch (o->object.type) {
1662
1663                 case OBJECT_UNUSED:
1664                         printf("Type: OBJECT_UNUSED\n");
1665                         break;
1666
1667                 case OBJECT_DATA:
1668                         printf("Type: OBJECT_DATA\n");
1669                         break;
1670
1671                 case OBJECT_ENTRY:
1672                         printf("Type: OBJECT_ENTRY %llu %llu %llu\n",
1673                                (unsigned long long) le64toh(o->entry.seqnum),
1674                                (unsigned long long) le64toh(o->entry.monotonic),
1675                                (unsigned long long) le64toh(o->entry.realtime));
1676                         break;
1677
1678                 case OBJECT_FIELD_HASH_TABLE:
1679                         printf("Type: OBJECT_FIELD_HASH_TABLE\n");
1680                         break;
1681
1682                 case OBJECT_DATA_HASH_TABLE:
1683                         printf("Type: OBJECT_DATA_HASH_TABLE\n");
1684                         break;
1685
1686                 case OBJECT_ENTRY_ARRAY:
1687                         printf("Type: OBJECT_ENTRY_ARRAY\n");
1688                         break;
1689                 }
1690
1691                 if (o->object.flags & OBJECT_COMPRESSED)
1692                         printf("Flags: COMPRESSED\n");
1693
1694                 if (p == le64toh(f->header->tail_object_offset))
1695                         p = 0;
1696                 else
1697                         p = p + ALIGN64(le64toh(o->object.size));
1698         }
1699
1700         return;
1701 fail:
1702         log_error("File corrupt");
1703 }
1704
1705 int journal_file_open(
1706                 const char *fname,
1707                 int flags,
1708                 mode_t mode,
1709                 JournalFile *template,
1710                 JournalFile **ret) {
1711
1712         JournalFile *f;
1713         int r;
1714         bool newly_created = false;
1715
1716         assert(fname);
1717
1718         if ((flags & O_ACCMODE) != O_RDONLY &&
1719             (flags & O_ACCMODE) != O_RDWR)
1720                 return -EINVAL;
1721
1722         f = new0(JournalFile, 1);
1723         if (!f)
1724                 return -ENOMEM;
1725
1726         f->fd = -1;
1727         f->flags = flags;
1728         f->mode = mode;
1729         f->writable = (flags & O_ACCMODE) != O_RDONLY;
1730         f->prot = prot_from_flags(flags);
1731
1732         f->path = strdup(fname);
1733         if (!f->path) {
1734                 r = -ENOMEM;
1735                 goto fail;
1736         }
1737
1738         f->fd = open(f->path, f->flags|O_CLOEXEC, f->mode);
1739         if (f->fd < 0) {
1740                 r = -errno;
1741                 goto fail;
1742         }
1743
1744         if (fstat(f->fd, &f->last_stat) < 0) {
1745                 r = -errno;
1746                 goto fail;
1747         }
1748
1749         if (f->last_stat.st_size == 0 && f->writable) {
1750                 newly_created = true;
1751
1752                 r = journal_file_init_header(f, template);
1753                 if (r < 0)
1754                         goto fail;
1755
1756                 if (fstat(f->fd, &f->last_stat) < 0) {
1757                         r = -errno;
1758                         goto fail;
1759                 }
1760         }
1761
1762         if (f->last_stat.st_size < (off_t) sizeof(Header)) {
1763                 r = -EIO;
1764                 goto fail;
1765         }
1766
1767         f->header = mmap(NULL, PAGE_ALIGN(sizeof(Header)), prot_from_flags(flags), MAP_SHARED, f->fd, 0);
1768         if (f->header == MAP_FAILED) {
1769                 f->header = NULL;
1770                 r = -errno;
1771                 goto fail;
1772         }
1773
1774         if (!newly_created) {
1775                 r = journal_file_verify_header(f);
1776                 if (r < 0)
1777                         goto fail;
1778         }
1779
1780         if (f->writable) {
1781                 r = journal_file_refresh_header(f);
1782                 if (r < 0)
1783                         goto fail;
1784         }
1785
1786         if (newly_created) {
1787
1788                 r = journal_file_setup_field_hash_table(f);
1789                 if (r < 0)
1790                         goto fail;
1791
1792                 r = journal_file_setup_data_hash_table(f);
1793                 if (r < 0)
1794                         goto fail;
1795         }
1796
1797         r = journal_file_map_field_hash_table(f);
1798         if (r < 0)
1799                 goto fail;
1800
1801         r = journal_file_map_data_hash_table(f);
1802         if (r < 0)
1803                 goto fail;
1804
1805         if (ret)
1806                 *ret = f;
1807
1808         return 0;
1809
1810 fail:
1811         journal_file_close(f);
1812
1813         return r;
1814 }
1815
1816 int journal_file_rotate(JournalFile **f) {
1817         char *p;
1818         size_t l;
1819         JournalFile *old_file, *new_file = NULL;
1820         int r;
1821
1822         assert(f);
1823         assert(*f);
1824
1825         old_file = *f;
1826
1827         if (!old_file->writable)
1828                 return -EINVAL;
1829
1830         if (!endswith(old_file->path, ".journal"))
1831                 return -EINVAL;
1832
1833         l = strlen(old_file->path);
1834
1835         p = new(char, l + 1 + 16 + 1 + 32 + 1 + 16 + 1);
1836         if (!p)
1837                 return -ENOMEM;
1838
1839         memcpy(p, old_file->path, l - 8);
1840         p[l-8] = '@';
1841         sd_id128_to_string(old_file->header->seqnum_id, p + l - 8 + 1);
1842         snprintf(p + l - 8 + 1 + 32, 1 + 16 + 1 + 16 + 8 + 1,
1843                  "-%016llx-%016llx.journal",
1844                  (unsigned long long) le64toh((*f)->header->seqnum),
1845                  (unsigned long long) le64toh((*f)->header->tail_entry_realtime));
1846
1847         r = rename(old_file->path, p);
1848         free(p);
1849
1850         if (r < 0)
1851                 return -errno;
1852
1853         old_file->header->state = le32toh(STATE_ARCHIVED);
1854
1855         r = journal_file_open(old_file->path, old_file->flags, old_file->mode, old_file, &new_file);
1856         journal_file_close(old_file);
1857
1858         *f = new_file;
1859         return r;
1860 }
1861
1862 struct vacuum_info {
1863         off_t usage;
1864         char *filename;
1865
1866         uint64_t realtime;
1867         sd_id128_t seqnum_id;
1868         uint64_t seqnum;
1869 };
1870
1871 static int vacuum_compare(const void *_a, const void *_b) {
1872         const struct vacuum_info *a, *b;
1873
1874         a = _a;
1875         b = _b;
1876
1877         if (sd_id128_equal(a->seqnum_id, b->seqnum_id)) {
1878                 if (a->seqnum < b->seqnum)
1879                         return -1;
1880                 else if (a->seqnum > b->seqnum)
1881                         return 1;
1882                 else
1883                         return 0;
1884         }
1885
1886         if (a->realtime < b->realtime)
1887                 return -1;
1888         else if (a->realtime > b->realtime)
1889                 return 1;
1890         else
1891                 return memcmp(&a->seqnum_id, &b->seqnum_id, 16);
1892 }
1893
1894 int journal_directory_vacuum(const char *directory, uint64_t max_use, uint64_t min_free) {
1895         DIR *d;
1896         int r = 0;
1897         struct vacuum_info *list = NULL;
1898         unsigned n_list = 0, n_allocated = 0, i;
1899         uint64_t sum = 0;
1900
1901         assert(directory);
1902
1903         if (max_use <= 0)
1904                 return 0;
1905
1906         d = opendir(directory);
1907         if (!d)
1908                 return -errno;
1909
1910         for (;;) {
1911                 int k;
1912                 struct dirent buf, *de;
1913                 size_t q;
1914                 struct stat st;
1915                 char *p;
1916                 unsigned long long seqnum, realtime;
1917                 sd_id128_t seqnum_id;
1918
1919                 k = readdir_r(d, &buf, &de);
1920                 if (k != 0) {
1921                         r = -k;
1922                         goto finish;
1923                 }
1924
1925                 if (!de)
1926                         break;
1927
1928                 if (!dirent_is_file_with_suffix(de, ".journal"))
1929                         continue;
1930
1931                 q = strlen(de->d_name);
1932
1933                 if (q < 1 + 32 + 1 + 16 + 1 + 16 + 8)
1934                         continue;
1935
1936                 if (de->d_name[q-8-16-1] != '-' ||
1937                     de->d_name[q-8-16-1-16-1] != '-' ||
1938                     de->d_name[q-8-16-1-16-1-32-1] != '@')
1939                         continue;
1940
1941                 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
1942                         continue;
1943
1944                 if (!S_ISREG(st.st_mode))
1945                         continue;
1946
1947                 p = strdup(de->d_name);
1948                 if (!p) {
1949                         r = -ENOMEM;
1950                         goto finish;
1951                 }
1952
1953                 de->d_name[q-8-16-1-16-1] = 0;
1954                 if (sd_id128_from_string(de->d_name + q-8-16-1-16-1-32, &seqnum_id) < 0) {
1955                         free(p);
1956                         continue;
1957                 }
1958
1959                 if (sscanf(de->d_name + q-8-16-1-16, "%16llx-%16llx.journal", &seqnum, &realtime) != 2) {
1960                         free(p);
1961                         continue;
1962                 }
1963
1964                 if (n_list >= n_allocated) {
1965                         struct vacuum_info *j;
1966
1967                         n_allocated = MAX(n_allocated * 2U, 8U);
1968                         j = realloc(list, n_allocated * sizeof(struct vacuum_info));
1969                         if (!j) {
1970                                 free(p);
1971                                 r = -ENOMEM;
1972                                 goto finish;
1973                         }
1974
1975                         list = j;
1976                 }
1977
1978                 list[n_list].filename = p;
1979                 list[n_list].usage = (uint64_t) st.st_blksize * (uint64_t) st.st_blocks;
1980                 list[n_list].seqnum = seqnum;
1981                 list[n_list].realtime = realtime;
1982                 list[n_list].seqnum_id = seqnum_id;
1983
1984                 sum += list[n_list].usage;
1985
1986                 n_list ++;
1987         }
1988
1989         qsort(list, n_list, sizeof(struct vacuum_info), vacuum_compare);
1990
1991         for(i = 0; i < n_list; i++) {
1992                 struct statvfs ss;
1993
1994                 if (fstatvfs(dirfd(d), &ss) < 0) {
1995                         r = -errno;
1996                         goto finish;
1997                 }
1998
1999                 if (sum <= max_use &&
2000                     (uint64_t) ss.f_bavail * (uint64_t) ss.f_bsize >= min_free)
2001                         break;
2002
2003                 if (unlinkat(dirfd(d), list[i].filename, 0) >= 0) {
2004                         log_debug("Deleted archived journal %s/%s.", directory, list[i].filename);
2005                         sum -= list[i].usage;
2006                 } else if (errno != ENOENT)
2007                         log_warning("Failed to delete %s/%s: %m", directory, list[i].filename);
2008         }
2009
2010 finish:
2011         for (i = 0; i < n_list; i++)
2012                 free(list[i].filename);
2013
2014         free(list);
2015
2016         if (d)
2017                 closedir(d);
2018
2019         return r;
2020 }
2021
2022 int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset) {
2023         uint64_t i, n;
2024         uint64_t q, xor_hash = 0;
2025         int r;
2026         EntryItem *items;
2027         dual_timestamp ts;
2028
2029         assert(from);
2030         assert(to);
2031         assert(o);
2032         assert(p);
2033
2034         if (!to->writable)
2035                 return -EPERM;
2036
2037         ts.monotonic = le64toh(o->entry.monotonic);
2038         ts.realtime = le64toh(o->entry.realtime);
2039
2040         if (to->tail_entry_monotonic_valid &&
2041             ts.monotonic < le64toh(to->header->tail_entry_monotonic))
2042                 return -EINVAL;
2043
2044         if (ts.realtime < le64toh(to->header->tail_entry_realtime))
2045                 return -EINVAL;
2046
2047         n = journal_file_entry_n_items(o);
2048         items = alloca(sizeof(EntryItem) * n);
2049
2050         for (i = 0; i < n; i++) {
2051                 uint64_t le_hash, l, h;
2052                 size_t t;
2053                 void *data;
2054                 Object *u;
2055
2056                 q = le64toh(o->entry.items[i].object_offset);
2057                 le_hash = o->entry.items[i].hash;
2058
2059                 r = journal_file_move_to_object(from, OBJECT_DATA, q, &o);
2060                 if (r < 0)
2061                         return r;
2062
2063                 if (le_hash != o->data.hash)
2064                         return -EBADMSG;
2065
2066                 l = le64toh(o->object.size) - offsetof(Object, data.payload);
2067                 t = (size_t) l;
2068
2069                 /* We hit the limit on 32bit machines */
2070                 if ((uint64_t) t != l)
2071                         return -E2BIG;
2072
2073                 if (o->object.flags & OBJECT_COMPRESSED) {
2074 #ifdef HAVE_XZ
2075                         uint64_t rsize;
2076
2077                         if (!uncompress_blob(o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize))
2078                                 return -EBADMSG;
2079
2080                         data = from->compress_buffer;
2081                         l = rsize;
2082 #else
2083                         return -EPROTONOSUPPORT;
2084 #endif
2085                 } else
2086                         data = o->data.payload;
2087
2088                 r = journal_file_append_data(to, data, l, &u, &h);
2089                 if (r < 0)
2090                         return r;
2091
2092                 xor_hash ^= le64toh(u->data.hash);
2093                 items[i].object_offset = htole64(h);
2094                 items[i].hash = u->data.hash;
2095
2096                 r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
2097                 if (r < 0)
2098                         return r;
2099         }
2100
2101         return journal_file_append_entry_internal(to, &ts, xor_hash, items, n, seqnum, ret, offset);
2102 }
2103
2104 void journal_default_metrics(JournalMetrics *m, int fd) {
2105         uint64_t fs_size = 0;
2106         struct statvfs ss;
2107         char a[64], b[64], c[64], d[64];
2108
2109         assert(m);
2110         assert(fd >= 0);
2111
2112         if (fstatvfs(fd, &ss) >= 0)
2113                 fs_size = ss.f_frsize * ss.f_blocks;
2114
2115         if (m->max_use == (uint64_t) -1) {
2116
2117                 if (fs_size > 0) {
2118                         m->max_use = PAGE_ALIGN(fs_size / 10); /* 10% of file system size */
2119
2120                         if (m->max_use > DEFAULT_MAX_USE_UPPER)
2121                                 m->max_use = DEFAULT_MAX_USE_UPPER;
2122
2123                         if (m->max_use < DEFAULT_MAX_USE_LOWER)
2124                                 m->max_use = DEFAULT_MAX_USE_LOWER;
2125                 } else
2126                         m->max_use = DEFAULT_MAX_USE_LOWER;
2127         } else {
2128                 m->max_use = PAGE_ALIGN(m->max_use);
2129
2130                 if (m->max_use < JOURNAL_FILE_SIZE_MIN*2)
2131                         m->max_use = JOURNAL_FILE_SIZE_MIN*2;
2132         }
2133
2134         if (m->max_size == (uint64_t) -1) {
2135                 m->max_size = PAGE_ALIGN(m->max_use / 8); /* 8 chunks */
2136
2137                 if (m->max_size > DEFAULT_MAX_SIZE_UPPER)
2138                         m->max_size = DEFAULT_MAX_SIZE_UPPER;
2139         } else
2140                 m->max_size = PAGE_ALIGN(m->max_size);
2141
2142         if (m->max_size < JOURNAL_FILE_SIZE_MIN)
2143                 m->max_size = JOURNAL_FILE_SIZE_MIN;
2144
2145         if (m->max_size*2 > m->max_use)
2146                 m->max_use = m->max_size*2;
2147
2148         if (m->min_size == (uint64_t) -1)
2149                 m->min_size = JOURNAL_FILE_SIZE_MIN;
2150         else {
2151                 m->min_size = PAGE_ALIGN(m->min_size);
2152
2153                 if (m->min_size < JOURNAL_FILE_SIZE_MIN)
2154                         m->min_size = JOURNAL_FILE_SIZE_MIN;
2155
2156                 if (m->min_size > m->max_size)
2157                         m->max_size = m->min_size;
2158         }
2159
2160         if (m->keep_free == (uint64_t) -1) {
2161
2162                 if (fs_size > 0) {
2163                         m->keep_free = PAGE_ALIGN(fs_size / 20); /* 5% of file system size */
2164
2165                         if (m->keep_free > DEFAULT_KEEP_FREE_UPPER)
2166                                 m->keep_free = DEFAULT_KEEP_FREE_UPPER;
2167
2168                 } else
2169                         m->keep_free = DEFAULT_KEEP_FREE;
2170         }
2171
2172         log_debug("Fixed max_use=%s max_size=%s min_size=%s keep_free=%s",
2173                   format_bytes(a, sizeof(a), m->max_use),
2174                   format_bytes(b, sizeof(b), m->max_size),
2175                   format_bytes(c, sizeof(c), m->min_size),
2176                   format_bytes(d, sizeof(d), m->keep_free));
2177 }