]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/journal/journal-file.c
Merge pull request #7388 from keszybz/doc-tweak
[thirdparty/systemd.git] / src / journal / journal-file.c
CommitLineData
cec736d2
LP
1/***
2 This file is part of systemd.
3
4 Copyright 2011 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
cec736d2
LP
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 14 Lesser General Public License for more details.
cec736d2 15
5430f7f2 16 You should have received a copy of the GNU Lesser General Public License
cec736d2
LP
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
cec736d2 20#include <errno.h>
cec736d2 21#include <fcntl.h>
11689d2a 22#include <linux/fs.h>
ac2e41f5 23#include <pthread.h>
07630cea
LP
24#include <stddef.h>
25#include <sys/mman.h>
26#include <sys/statvfs.h>
27#include <sys/uio.h>
28#include <unistd.h>
fb0951b0 29
b5efdb8a 30#include "alloc-util.h"
f27a3864 31#include "btrfs-util.h"
c8b3094d 32#include "chattr-util.h"
07630cea 33#include "compress.h"
3ffd4af2 34#include "fd-util.h"
0284adc6 35#include "journal-authenticate.h"
cec736d2
LP
36#include "journal-def.h"
37#include "journal-file.h"
38#include "lookup3.h"
6bedfcbb 39#include "parse-util.h"
5d1ce257 40#include "path-util.h"
3df3e884 41#include "random-util.h"
7a24f3bf 42#include "sd-event.h"
b58c888f 43#include "set.h"
07630cea 44#include "string-util.h"
4761fd0f 45#include "strv.h"
89a5a90c 46#include "xattr-util.h"
cec736d2 47
4a92baf3
LP
48#define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem))
49#define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem))
cec736d2 50
be19b7df 51#define COMPRESSION_SIZE_THRESHOLD (512ULL)
807e17f0 52
babfc091 53/* This is the minimum journal file size */
16098e93 54#define JOURNAL_FILE_SIZE_MIN (512ULL*1024ULL) /* 512 KiB */
babfc091
LP
55
56/* These are the lower and upper bounds if we deduce the max_use value
57 * from the file system size */
58#define DEFAULT_MAX_USE_LOWER (1ULL*1024ULL*1024ULL) /* 1 MiB */
59#define DEFAULT_MAX_USE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
60
8580d1f7
LP
61/* This is the default minimal use limit, how much we'll use even if keep_free suggests otherwise. */
62#define DEFAULT_MIN_USE (1ULL*1024ULL*1024ULL) /* 1 MiB */
63
babfc091 64/* This is the upper bound if we deduce max_size from max_use */
71100051 65#define DEFAULT_MAX_SIZE_UPPER (128ULL*1024ULL*1024ULL) /* 128 MiB */
babfc091
LP
66
67/* This is the upper bound if we deduce the keep_free value from the
68 * file system size */
69#define DEFAULT_KEEP_FREE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
70
71/* This is the keep_free value when we can't determine the system
72 * size */
73#define DEFAULT_KEEP_FREE (1024ULL*1024ULL) /* 1 MB */
74
8580d1f7
LP
75/* This is the default maximum number of journal files to keep around. */
76#define DEFAULT_N_MAX_FILES (100)
77
dca6219e
LP
78/* n_data was the first entry we added after the initial file format design */
79#define HEADER_SIZE_MIN ALIGN64(offsetof(Header, n_data))
cec736d2 80
a4bcff5b
LP
81/* How many entries to keep in the entry array chain cache at max */
82#define CHAIN_CACHE_MAX 20
83
a676e665
LP
84/* How much to increase the journal file size at once each time we allocate something new. */
85#define FILE_SIZE_INCREASE (8ULL*1024ULL*1024ULL) /* 8MB */
86
2678031a
LP
87/* Reread fstat() of the file for detecting deletions at least this often */
88#define LAST_STAT_REFRESH_USEC (5*USEC_PER_SEC)
89
fa6ac760
LP
90/* The mmap context to use for the header we pick as one above the last defined typed */
91#define CONTEXT_HEADER _OBJECT_TYPE_MAX
92
51804460
ZJS
93#ifdef __clang__
94# pragma GCC diagnostic ignored "-Waddress-of-packed-member"
95#endif
96
ac2e41f5
VC
97/* This may be called from a separate thread to prevent blocking the caller for the duration of fsync().
98 * As a result we use atomic operations on f->offline_state for inter-thread communications with
99 * journal_file_set_offline() and journal_file_set_online(). */
100static void journal_file_set_offline_internal(JournalFile *f) {
26687bf8 101 assert(f);
ac2e41f5
VC
102 assert(f->fd >= 0);
103 assert(f->header);
104
105 for (;;) {
106 switch (f->offline_state) {
107 case OFFLINE_CANCEL:
108 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_CANCEL, OFFLINE_DONE))
109 continue;
110 return;
111
112 case OFFLINE_AGAIN_FROM_SYNCING:
113 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_SYNCING, OFFLINE_SYNCING))
114 continue;
115 break;
116
117 case OFFLINE_AGAIN_FROM_OFFLINING:
118 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_OFFLINING, OFFLINE_SYNCING))
119 continue;
120 break;
121
122 case OFFLINE_SYNCING:
123 (void) fsync(f->fd);
26687bf8 124
ac2e41f5
VC
125 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_SYNCING, OFFLINE_OFFLINING))
126 continue;
26687bf8 127
8eb85171 128 f->header->state = f->archive ? STATE_ARCHIVED : STATE_OFFLINE;
ac2e41f5
VC
129 (void) fsync(f->fd);
130 break;
131
132 case OFFLINE_OFFLINING:
133 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_OFFLINING, OFFLINE_DONE))
134 continue;
135 /* fall through */
136
137 case OFFLINE_DONE:
138 return;
139
140 case OFFLINE_JOINED:
141 log_debug("OFFLINE_JOINED unexpected offline state for journal_file_set_offline_internal()");
142 return;
143 }
144 }
145}
146
147static void * journal_file_set_offline_thread(void *arg) {
148 JournalFile *f = arg;
149
150 journal_file_set_offline_internal(f);
151
152 return NULL;
153}
154
155static int journal_file_set_offline_thread_join(JournalFile *f) {
156 int r;
157
158 assert(f);
159
160 if (f->offline_state == OFFLINE_JOINED)
161 return 0;
162
163 r = pthread_join(f->offline_thread, NULL);
164 if (r)
165 return -r;
166
167 f->offline_state = OFFLINE_JOINED;
26687bf8 168
be7cdd8e 169 if (mmap_cache_got_sigbus(f->mmap, f->cache_fd))
fa6ac760
LP
170 return -EIO;
171
ac2e41f5
VC
172 return 0;
173}
26687bf8 174
ac2e41f5
VC
175/* Trigger a restart if the offline thread is mid-flight in a restartable state. */
176static bool journal_file_set_offline_try_restart(JournalFile *f) {
177 for (;;) {
178 switch (f->offline_state) {
179 case OFFLINE_AGAIN_FROM_SYNCING:
180 case OFFLINE_AGAIN_FROM_OFFLINING:
181 return true;
182
183 case OFFLINE_CANCEL:
184 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_CANCEL, OFFLINE_AGAIN_FROM_SYNCING))
185 continue;
186 return true;
187
188 case OFFLINE_SYNCING:
189 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_SYNCING, OFFLINE_AGAIN_FROM_SYNCING))
190 continue;
191 return true;
192
193 case OFFLINE_OFFLINING:
194 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_OFFLINING, OFFLINE_AGAIN_FROM_OFFLINING))
195 continue;
196 return true;
26687bf8
OS
197
198 default:
ac2e41f5
VC
199 return false;
200 }
26687bf8
OS
201 }
202}
203
ac2e41f5
VC
204/* Sets a journal offline.
205 *
206 * If wait is false then an offline is dispatched in a separate thread for a
207 * subsequent journal_file_set_offline() or journal_file_set_online() of the
208 * same journal to synchronize with.
209 *
210 * If wait is true, then either an existing offline thread will be restarted
211 * and joined, or if none exists the offline is simply performed in this
212 * context without involving another thread.
213 */
214int journal_file_set_offline(JournalFile *f, bool wait) {
215 bool restarted;
216 int r;
217
26687bf8
OS
218 assert(f);
219
220 if (!f->writable)
221 return -EPERM;
222
223 if (!(f->fd >= 0 && f->header))
224 return -EINVAL;
225
b8f99e27
VC
226 /* An offlining journal is implicitly online and may modify f->header->state,
227 * we must also join any potentially lingering offline thread when not online. */
228 if (!journal_file_is_offlining(f) && f->header->state != STATE_ONLINE)
229 return journal_file_set_offline_thread_join(f);
26687bf8 230
ac2e41f5
VC
231 /* Restart an in-flight offline thread and wait if needed, or join a lingering done one. */
232 restarted = journal_file_set_offline_try_restart(f);
233 if ((restarted && wait) || !restarted) {
234 r = journal_file_set_offline_thread_join(f);
235 if (r < 0)
236 return r;
237 }
26687bf8 238
ac2e41f5
VC
239 if (restarted)
240 return 0;
241
242 /* Initiate a new offline. */
243 f->offline_state = OFFLINE_SYNCING;
fa6ac760 244
ac2e41f5
VC
245 if (wait) /* Without using a thread if waiting. */
246 journal_file_set_offline_internal(f);
247 else {
248 r = pthread_create(&f->offline_thread, NULL, journal_file_set_offline_thread, f);
ec9ffa2c
VC
249 if (r > 0) {
250 f->offline_state = OFFLINE_JOINED;
ac2e41f5 251 return -r;
ec9ffa2c 252 }
ac2e41f5
VC
253 }
254
255 return 0;
256}
257
258static int journal_file_set_online(JournalFile *f) {
259 bool joined = false;
260
261 assert(f);
262
263 if (!f->writable)
264 return -EPERM;
265
266 if (!(f->fd >= 0 && f->header))
267 return -EINVAL;
268
269 while (!joined) {
270 switch (f->offline_state) {
271 case OFFLINE_JOINED:
272 /* No offline thread, no need to wait. */
273 joined = true;
274 break;
275
276 case OFFLINE_SYNCING:
277 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_SYNCING, OFFLINE_CANCEL))
278 continue;
279 /* Canceled syncing prior to offlining, no need to wait. */
280 break;
281
282 case OFFLINE_AGAIN_FROM_SYNCING:
283 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_SYNCING, OFFLINE_CANCEL))
284 continue;
285 /* Canceled restart from syncing, no need to wait. */
286 break;
287
288 case OFFLINE_AGAIN_FROM_OFFLINING:
289 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_OFFLINING, OFFLINE_CANCEL))
290 continue;
291 /* Canceled restart from offlining, must wait for offlining to complete however. */
292
ec251fe7 293 /* fall through */
ac2e41f5
VC
294 default: {
295 int r;
296
297 r = journal_file_set_offline_thread_join(f);
298 if (r < 0)
299 return r;
300
301 joined = true;
302 break;
303 }
304 }
305 }
26687bf8 306
be7cdd8e 307 if (mmap_cache_got_sigbus(f->mmap, f->cache_fd))
fa6ac760
LP
308 return -EIO;
309
ac2e41f5
VC
310 switch (f->header->state) {
311 case STATE_ONLINE:
312 return 0;
26687bf8 313
ac2e41f5
VC
314 case STATE_OFFLINE:
315 f->header->state = STATE_ONLINE;
316 (void) fsync(f->fd);
317 return 0;
318
319 default:
320 return -EINVAL;
321 }
26687bf8
OS
322}
323
b58c888f
VC
324bool journal_file_is_offlining(JournalFile *f) {
325 assert(f);
326
327 __sync_synchronize();
328
3742095b 329 if (IN_SET(f->offline_state, OFFLINE_DONE, OFFLINE_JOINED))
b58c888f
VC
330 return false;
331
332 return true;
333}
334
804ae586 335JournalFile* journal_file_close(JournalFile *f) {
de190aef 336 assert(f);
cec736d2 337
349cc4a5 338#if HAVE_GCRYPT
b0af6f41 339 /* Write the final tag */
43cd8794
FB
340 if (f->seal && f->writable) {
341 int r;
342
343 r = journal_file_append_tag(f);
344 if (r < 0)
345 log_error_errno(r, "Failed to append tag when closing journal: %m");
346 }
feb12d3e 347#endif
b0af6f41 348
7a24f3bf
VC
349 if (f->post_change_timer) {
350 int enabled;
351
352 if (sd_event_source_get_enabled(f->post_change_timer, &enabled) >= 0)
353 if (enabled == SD_EVENT_ONESHOT)
354 journal_file_post_change(f);
355
e167d7fd 356 (void) sd_event_source_set_enabled(f->post_change_timer, SD_EVENT_OFF);
7a24f3bf
VC
357 sd_event_source_unref(f->post_change_timer);
358 }
359
ac2e41f5 360 journal_file_set_offline(f, true);
cec736d2 361
be7cdd8e
VC
362 if (f->mmap && f->cache_fd)
363 mmap_cache_free_fd(f->mmap, f->cache_fd);
cec736d2 364
11689d2a
LP
365 if (f->fd >= 0 && f->defrag_on_close) {
366
367 /* Be friendly to btrfs: turn COW back on again now,
368 * and defragment the file. We won't write to the file
369 * ever again, hence remove all fragmentation, and
370 * reenable all the good bits COW usually provides
371 * (such as data checksumming). */
372
1ed8f8c1 373 (void) chattr_fd(f->fd, 0, FS_NOCOW_FL);
11689d2a
LP
374 (void) btrfs_defrag_fd(f->fd);
375 }
f27a3864 376
5d1ce257
LP
377 if (f->close_fd)
378 safe_close(f->fd);
cec736d2 379 free(f->path);
807e17f0 380
f649045c 381 mmap_cache_unref(f->mmap);
16e9f408 382
4743015d 383 ordered_hashmap_free_free(f->chain_cache);
a4bcff5b 384
349cc4a5 385#if HAVE_XZ || HAVE_LZ4
807e17f0
LP
386 free(f->compress_buffer);
387#endif
388
349cc4a5 389#if HAVE_GCRYPT
baed47c3
LP
390 if (f->fss_file)
391 munmap(f->fss_file, PAGE_ALIGN(f->fss_file_size));
dc4ebc07 392 else
b7c9ae91
LP
393 free(f->fsprg_state);
394
395 free(f->fsprg_seed);
7560fffc
LP
396
397 if (f->hmac)
398 gcry_md_close(f->hmac);
399#endif
400
6b430fdb 401 return mfree(f);
cec736d2
LP
402}
403
b58c888f
VC
404void journal_file_close_set(Set *s) {
405 JournalFile *f;
406
407 assert(s);
408
409 while ((f = set_steal_first(s)))
410 (void) journal_file_close(f);
411}
412
0ac38b70 413static int journal_file_init_header(JournalFile *f, JournalFile *template) {
d89c8fdf 414 Header h = {};
cec736d2
LP
415 ssize_t k;
416 int r;
417
418 assert(f);
419
7560fffc 420 memcpy(h.signature, HEADER_SIGNATURE, 8);
23b0b2b2 421 h.header_size = htole64(ALIGN64(sizeof(h)));
cec736d2 422
d89c8fdf
ZJS
423 h.incompatible_flags |= htole32(
424 f->compress_xz * HEADER_INCOMPATIBLE_COMPRESSED_XZ |
425 f->compress_lz4 * HEADER_INCOMPATIBLE_COMPRESSED_LZ4);
7560fffc 426
d89c8fdf
ZJS
427 h.compatible_flags = htole32(
428 f->seal * HEADER_COMPATIBLE_SEALED);
7560fffc 429
cec736d2
LP
430 r = sd_id128_randomize(&h.file_id);
431 if (r < 0)
432 return r;
433
0ac38b70
LP
434 if (template) {
435 h.seqnum_id = template->header->seqnum_id;
beec0085 436 h.tail_entry_seqnum = template->header->tail_entry_seqnum;
0ac38b70
LP
437 } else
438 h.seqnum_id = h.file_id;
cec736d2
LP
439
440 k = pwrite(f->fd, &h, sizeof(h), 0);
441 if (k < 0)
442 return -errno;
443
444 if (k != sizeof(h))
445 return -EIO;
446
447 return 0;
448}
449
a0fe2a2d
LP
450static int fsync_directory_of_file(int fd) {
451 _cleanup_free_ char *path = NULL, *dn = NULL;
452 _cleanup_close_ int dfd = -1;
453 struct stat st;
454 int r;
455
456 if (fstat(fd, &st) < 0)
457 return -errno;
458
459 if (!S_ISREG(st.st_mode))
460 return -EBADFD;
461
462 r = fd_get_path(fd, &path);
463 if (r < 0)
464 return r;
465
466 if (!path_is_absolute(path))
467 return -EINVAL;
468
469 dn = dirname_malloc(path);
470 if (!dn)
471 return -ENOMEM;
472
473 dfd = open(dn, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
474 if (dfd < 0)
475 return -errno;
476
477 if (fsync(dfd) < 0)
478 return -errno;
479
480 return 0;
481}
482
cec736d2 483static int journal_file_refresh_header(JournalFile *f) {
de190aef 484 sd_id128_t boot_id;
fa6ac760 485 int r;
cec736d2
LP
486
487 assert(f);
c88cc6af 488 assert(f->header);
cec736d2
LP
489
490 r = sd_id128_get_machine(&f->header->machine_id);
491 if (r < 0)
492 return r;
493
de190aef 494 r = sd_id128_get_boot(&boot_id);
cec736d2
LP
495 if (r < 0)
496 return r;
497
de190aef
LP
498 if (sd_id128_equal(boot_id, f->header->boot_id))
499 f->tail_entry_monotonic_valid = true;
500
501 f->header->boot_id = boot_id;
502
fa6ac760 503 r = journal_file_set_online(f);
b788cc23 504
7560fffc 505 /* Sync the online state to disk */
fb426037 506 (void) fsync(f->fd);
b788cc23 507
a0fe2a2d
LP
508 /* We likely just created a new file, also sync the directory this file is located in. */
509 (void) fsync_directory_of_file(f->fd);
510
fa6ac760 511 return r;
cec736d2
LP
512}
513
4214009f
ZJS
514static bool warn_wrong_flags(const JournalFile *f, bool compatible) {
515 const uint32_t any = compatible ? HEADER_COMPATIBLE_ANY : HEADER_INCOMPATIBLE_ANY,
516 supported = compatible ? HEADER_COMPATIBLE_SUPPORTED : HEADER_INCOMPATIBLE_SUPPORTED;
517 const char *type = compatible ? "compatible" : "incompatible";
d89c8fdf
ZJS
518 uint32_t flags;
519
4214009f
ZJS
520 flags = le32toh(compatible ? f->header->compatible_flags : f->header->incompatible_flags);
521
522 if (flags & ~supported) {
523 if (flags & ~any)
4761fd0f 524 log_debug("Journal file %s has unknown %s flags 0x%"PRIx32,
4214009f
ZJS
525 f->path, type, flags & ~any);
526 flags = (flags & any) & ~supported;
4761fd0f
ZJS
527 if (flags) {
528 const char* strv[3];
529 unsigned n = 0;
530 _cleanup_free_ char *t = NULL;
531
532 if (compatible && (flags & HEADER_COMPATIBLE_SEALED))
533 strv[n++] = "sealed";
534 if (!compatible && (flags & HEADER_INCOMPATIBLE_COMPRESSED_XZ))
535 strv[n++] = "xz-compressed";
536 if (!compatible && (flags & HEADER_INCOMPATIBLE_COMPRESSED_LZ4))
537 strv[n++] = "lz4-compressed";
538 strv[n] = NULL;
539 assert(n < ELEMENTSOF(strv));
540
541 t = strv_join((char**) strv, ", ");
542 log_debug("Journal file %s uses %s %s %s disabled at compilation time.",
543 f->path, type, n > 1 ? "flags" : "flag", strnull(t));
544 }
4214009f
ZJS
545 return true;
546 }
547
548 return false;
549}
550
551static int journal_file_verify_header(JournalFile *f) {
6f94e420
TS
552 uint64_t arena_size, header_size;
553
cec736d2 554 assert(f);
c88cc6af 555 assert(f->header);
cec736d2 556
7560fffc 557 if (memcmp(f->header->signature, HEADER_SIGNATURE, 8))
cec736d2
LP
558 return -EBADMSG;
559
4214009f
ZJS
560 /* In both read and write mode we refuse to open files with incompatible
561 * flags we don't know. */
562 if (warn_wrong_flags(f, false))
cec736d2
LP
563 return -EPROTONOSUPPORT;
564
4214009f
ZJS
565 /* When open for writing we refuse to open files with compatible flags, too. */
566 if (f->writable && warn_wrong_flags(f, true))
d89c8fdf 567 return -EPROTONOSUPPORT;
7560fffc 568
db11ac1a
LP
569 if (f->header->state >= _STATE_MAX)
570 return -EBADMSG;
571
6f94e420
TS
572 header_size = le64toh(f->header->header_size);
573
dca6219e 574 /* The first addition was n_data, so check that we are at least this large */
6f94e420 575 if (header_size < HEADER_SIZE_MIN)
23b0b2b2
LP
576 return -EBADMSG;
577
8088cbd3 578 if (JOURNAL_HEADER_SEALED(f->header) && !JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
beec0085
LP
579 return -EBADMSG;
580
6f94e420
TS
581 arena_size = le64toh(f->header->arena_size);
582
583 if (UINT64_MAX - header_size < arena_size || header_size + arena_size > (uint64_t) f->last_stat.st_size)
db11ac1a
LP
584 return -ENODATA;
585
6f94e420 586 if (le64toh(f->header->tail_object_offset) > header_size + arena_size)
db11ac1a
LP
587 return -ENODATA;
588
7762e02b
LP
589 if (!VALID64(le64toh(f->header->data_hash_table_offset)) ||
590 !VALID64(le64toh(f->header->field_hash_table_offset)) ||
591 !VALID64(le64toh(f->header->tail_object_offset)) ||
592 !VALID64(le64toh(f->header->entry_array_offset)))
593 return -ENODATA;
594
cec736d2 595 if (f->writable) {
cec736d2 596 sd_id128_t machine_id;
ae739cc1 597 uint8_t state;
cec736d2
LP
598 int r;
599
600 r = sd_id128_get_machine(&machine_id);
601 if (r < 0)
602 return r;
603
604 if (!sd_id128_equal(machine_id, f->header->machine_id))
605 return -EHOSTDOWN;
606
de190aef 607 state = f->header->state;
cec736d2 608
b288cdeb
ZJS
609 if (state == STATE_ARCHIVED)
610 return -ESHUTDOWN; /* Already archived */
611 else if (state == STATE_ONLINE) {
71fa6f00
LP
612 log_debug("Journal file %s is already online. Assuming unclean closing.", f->path);
613 return -EBUSY;
b288cdeb 614 } else if (state != STATE_OFFLINE) {
8facc349 615 log_debug("Journal file %s has unknown state %i.", f->path, state);
71fa6f00
LP
616 return -EBUSY;
617 }
ae739cc1 618
5b3cc0c8
YN
619 if (f->header->field_hash_table_size == 0 || f->header->data_hash_table_size == 0)
620 return -EBADMSG;
621
ae739cc1
LP
622 /* Don't permit appending to files from the future. Because otherwise the realtime timestamps wouldn't
623 * be strictly ordered in the entries in the file anymore, and we can't have that since it breaks
624 * bisection. */
625 if (le64toh(f->header->tail_entry_realtime) > now(CLOCK_REALTIME)) {
626 log_debug("Journal file %s is from the future, refusing to append new data to it that'd be older.", f->path);
627 return -ETXTBSY;
628 }
cec736d2
LP
629 }
630
d89c8fdf
ZJS
631 f->compress_xz = JOURNAL_HEADER_COMPRESSED_XZ(f->header);
632 f->compress_lz4 = JOURNAL_HEADER_COMPRESSED_LZ4(f->header);
c586dbf1 633
f1889c91 634 f->seal = JOURNAL_HEADER_SEALED(f->header);
7560fffc 635
cec736d2
LP
636 return 0;
637}
638
2678031a
LP
639static int journal_file_fstat(JournalFile *f) {
640 assert(f);
641 assert(f->fd >= 0);
642
643 if (fstat(f->fd, &f->last_stat) < 0)
644 return -errno;
645
646 f->last_stat_usec = now(CLOCK_MONOTONIC);
647
648 /* Refuse appending to files that are already deleted */
649 if (f->last_stat.st_nlink <= 0)
650 return -EIDRM;
651
652 return 0;
653}
654
cec736d2 655static int journal_file_allocate(JournalFile *f, uint64_t offset, uint64_t size) {
eda4b58b 656 uint64_t old_size, new_size;
fec2aa2f 657 int r;
cec736d2
LP
658
659 assert(f);
c88cc6af 660 assert(f->header);
cec736d2 661
cec736d2 662 /* We assume that this file is not sparse, and we know that
38ac38b2 663 * for sure, since we always call posix_fallocate()
cec736d2
LP
664 * ourselves */
665
be7cdd8e 666 if (mmap_cache_got_sigbus(f->mmap, f->cache_fd))
fa6ac760
LP
667 return -EIO;
668
cec736d2 669 old_size =
23b0b2b2 670 le64toh(f->header->header_size) +
cec736d2
LP
671 le64toh(f->header->arena_size);
672
bc85bfee 673 new_size = PAGE_ALIGN(offset + size);
23b0b2b2
LP
674 if (new_size < le64toh(f->header->header_size))
675 new_size = le64toh(f->header->header_size);
bc85bfee 676
2678031a
LP
677 if (new_size <= old_size) {
678
679 /* We already pre-allocated enough space, but before
680 * we write to it, let's check with fstat() if the
681 * file got deleted, in order make sure we don't throw
682 * away the data immediately. Don't check fstat() for
683 * all writes though, but only once ever 10s. */
684
685 if (f->last_stat_usec + LAST_STAT_REFRESH_USEC > now(CLOCK_MONOTONIC))
686 return 0;
687
688 return journal_file_fstat(f);
689 }
690
691 /* Allocate more space. */
cec736d2 692
a676e665 693 if (f->metrics.max_size > 0 && new_size > f->metrics.max_size)
bc85bfee 694 return -E2BIG;
cec736d2 695
a676e665 696 if (new_size > f->metrics.min_size && f->metrics.keep_free > 0) {
cec736d2
LP
697 struct statvfs svfs;
698
699 if (fstatvfs(f->fd, &svfs) >= 0) {
700 uint64_t available;
701
070052ab 702 available = LESS_BY((uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize, f->metrics.keep_free);
cec736d2
LP
703
704 if (new_size - old_size > available)
705 return -E2BIG;
706 }
707 }
708
eda4b58b
LP
709 /* Increase by larger blocks at once */
710 new_size = ((new_size+FILE_SIZE_INCREASE-1) / FILE_SIZE_INCREASE) * FILE_SIZE_INCREASE;
711 if (f->metrics.max_size > 0 && new_size > f->metrics.max_size)
712 new_size = f->metrics.max_size;
713
bc85bfee
LP
714 /* Note that the glibc fallocate() fallback is very
715 inefficient, hence we try to minimize the allocation area
716 as we can. */
fec2aa2f
GV
717 r = posix_fallocate(f->fd, old_size, new_size - old_size);
718 if (r != 0)
719 return -r;
cec736d2 720
23b0b2b2 721 f->header->arena_size = htole64(new_size - le64toh(f->header->header_size));
cec736d2 722
2678031a 723 return journal_file_fstat(f);
cec736d2
LP
724}
725
78519831 726static unsigned type_to_context(ObjectType type) {
d3d3208f 727 /* One context for each type, plus one catch-all for the rest */
69adae51 728 assert_cc(_OBJECT_TYPE_MAX <= MMAP_CACHE_MAX_CONTEXTS);
fa6ac760 729 assert_cc(CONTEXT_HEADER < MMAP_CACHE_MAX_CONTEXTS);
d05089d8 730 return type > OBJECT_UNUSED && type < _OBJECT_TYPE_MAX ? type : 0;
d3d3208f
MS
731}
732
b439282e 733static int journal_file_move_to(JournalFile *f, ObjectType type, bool keep_always, uint64_t offset, uint64_t size, void **ret, size_t *ret_size) {
2678031a
LP
734 int r;
735
cec736d2 736 assert(f);
cec736d2
LP
737 assert(ret);
738
7762e02b
LP
739 if (size <= 0)
740 return -EINVAL;
741
2a59ea54 742 /* Avoid SIGBUS on invalid accesses */
4bbdcdb3
LP
743 if (offset + size > (uint64_t) f->last_stat.st_size) {
744 /* Hmm, out of range? Let's refresh the fstat() data
745 * first, before we trust that check. */
746
2678031a
LP
747 r = journal_file_fstat(f);
748 if (r < 0)
749 return r;
750
751 if (offset + size > (uint64_t) f->last_stat.st_size)
4bbdcdb3
LP
752 return -EADDRNOTAVAIL;
753 }
754
b439282e 755 return mmap_cache_get(f->mmap, f->cache_fd, f->prot, type_to_context(type), keep_always, offset, size, &f->last_stat, ret, ret_size);
cec736d2
LP
756}
757
16e9f408
LP
758static uint64_t minimum_header_size(Object *o) {
759
b8e891e6 760 static const uint64_t table[] = {
16e9f408
LP
761 [OBJECT_DATA] = sizeof(DataObject),
762 [OBJECT_FIELD] = sizeof(FieldObject),
763 [OBJECT_ENTRY] = sizeof(EntryObject),
764 [OBJECT_DATA_HASH_TABLE] = sizeof(HashTableObject),
765 [OBJECT_FIELD_HASH_TABLE] = sizeof(HashTableObject),
766 [OBJECT_ENTRY_ARRAY] = sizeof(EntryArrayObject),
767 [OBJECT_TAG] = sizeof(TagObject),
768 };
769
770 if (o->object.type >= ELEMENTSOF(table) || table[o->object.type] <= 0)
771 return sizeof(ObjectHeader);
772
773 return table[o->object.type];
774}
775
24754f36
TR
776/* Lightweight object checks. We want this to be fast, so that we won't
777 * slowdown every journal_file_move_to_object() call too much. */
778static int journal_file_check_object(JournalFile *f, uint64_t offset, Object *o) {
779 assert(f);
780 assert(o);
781
782 switch (o->object.type) {
783
784 case OBJECT_DATA: {
785 if ((le64toh(o->data.entry_offset) == 0) ^ (le64toh(o->data.n_entries) == 0)) {
786 log_debug("Bad n_entries: %"PRIu64": %"PRIu64,
10e8445b 787 le64toh(o->data.n_entries), offset);
24754f36
TR
788 return -EBADMSG;
789 }
790
791 if (le64toh(o->object.size) - offsetof(DataObject, payload) <= 0) {
792 log_debug("Bad object size (<= %zu): %"PRIu64": %"PRIu64,
793 offsetof(DataObject, payload),
794 le64toh(o->object.size),
795 offset);
796 return -EBADMSG;
797 }
798
10e8445b
TR
799 if (!VALID64(le64toh(o->data.next_hash_offset)) ||
800 !VALID64(le64toh(o->data.next_field_offset)) ||
801 !VALID64(le64toh(o->data.entry_offset)) ||
802 !VALID64(le64toh(o->data.entry_array_offset))) {
24754f36
TR
803 log_debug("Invalid offset, next_hash_offset="OFSfmt", next_field_offset="OFSfmt
804 ", entry_offset="OFSfmt", entry_array_offset="OFSfmt": %"PRIu64,
10e8445b
TR
805 le64toh(o->data.next_hash_offset),
806 le64toh(o->data.next_field_offset),
807 le64toh(o->data.entry_offset),
808 le64toh(o->data.entry_array_offset),
24754f36
TR
809 offset);
810 return -EBADMSG;
811 }
812
813 break;
814 }
815
816 case OBJECT_FIELD:
817 if (le64toh(o->object.size) - offsetof(FieldObject, payload) <= 0) {
818 log_debug(
819 "Bad field size (<= %zu): %"PRIu64": %"PRIu64,
820 offsetof(FieldObject, payload),
821 le64toh(o->object.size),
822 offset);
823 return -EBADMSG;
824 }
825
10e8445b
TR
826 if (!VALID64(le64toh(o->field.next_hash_offset)) ||
827 !VALID64(le64toh(o->field.head_data_offset))) {
24754f36
TR
828 log_debug(
829 "Invalid offset, next_hash_offset="OFSfmt
830 ", head_data_offset="OFSfmt": %"PRIu64,
10e8445b
TR
831 le64toh(o->field.next_hash_offset),
832 le64toh(o->field.head_data_offset),
24754f36
TR
833 offset);
834 return -EBADMSG;
835 }
836 break;
837
838 case OBJECT_ENTRY:
839 if ((le64toh(o->object.size) - offsetof(EntryObject, items)) % sizeof(EntryItem) != 0) {
840 log_debug(
841 "Bad entry size (<= %zu): %"PRIu64": %"PRIu64,
842 offsetof(EntryObject, items),
843 le64toh(o->object.size),
844 offset);
845 return -EBADMSG;
846 }
847
848 if ((le64toh(o->object.size) - offsetof(EntryObject, items)) / sizeof(EntryItem) <= 0) {
849 log_debug(
850 "Invalid number items in entry: %"PRIu64": %"PRIu64,
851 (le64toh(o->object.size) - offsetof(EntryObject, items)) / sizeof(EntryItem),
852 offset);
853 return -EBADMSG;
854 }
855
856 if (le64toh(o->entry.seqnum) <= 0) {
857 log_debug(
858 "Invalid entry seqnum: %"PRIx64": %"PRIu64,
859 le64toh(o->entry.seqnum),
860 offset);
861 return -EBADMSG;
862 }
863
864 if (!VALID_REALTIME(le64toh(o->entry.realtime))) {
865 log_debug(
866 "Invalid entry realtime timestamp: %"PRIu64": %"PRIu64,
867 le64toh(o->entry.realtime),
868 offset);
869 return -EBADMSG;
870 }
871
872 if (!VALID_MONOTONIC(le64toh(o->entry.monotonic))) {
873 log_debug(
874 "Invalid entry monotonic timestamp: %"PRIu64": %"PRIu64,
875 le64toh(o->entry.monotonic),
876 offset);
877 return -EBADMSG;
878 }
879
880 break;
881
882 case OBJECT_DATA_HASH_TABLE:
883 case OBJECT_FIELD_HASH_TABLE:
884 if ((le64toh(o->object.size) - offsetof(HashTableObject, items)) % sizeof(HashItem) != 0 ||
885 (le64toh(o->object.size) - offsetof(HashTableObject, items)) / sizeof(HashItem) <= 0) {
886 log_debug(
887 "Invalid %s hash table size: %"PRIu64": %"PRIu64,
888 o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field",
889 le64toh(o->object.size),
890 offset);
891 return -EBADMSG;
892 }
893
894 break;
895
896 case OBJECT_ENTRY_ARRAY:
897 if ((le64toh(o->object.size) - offsetof(EntryArrayObject, items)) % sizeof(le64_t) != 0 ||
898 (le64toh(o->object.size) - offsetof(EntryArrayObject, items)) / sizeof(le64_t) <= 0) {
899 log_debug(
900 "Invalid object entry array size: %"PRIu64": %"PRIu64,
901 le64toh(o->object.size),
902 offset);
903 return -EBADMSG;
904 }
905
10e8445b 906 if (!VALID64(le64toh(o->entry_array.next_entry_array_offset))) {
24754f36
TR
907 log_debug(
908 "Invalid object entry array next_entry_array_offset: "OFSfmt": %"PRIu64,
10e8445b 909 le64toh(o->entry_array.next_entry_array_offset),
24754f36
TR
910 offset);
911 return -EBADMSG;
912 }
913
914 break;
915
916 case OBJECT_TAG:
917 if (le64toh(o->object.size) != sizeof(TagObject)) {
918 log_debug(
919 "Invalid object tag size: %"PRIu64": %"PRIu64,
920 le64toh(o->object.size),
921 offset);
922 return -EBADMSG;
923 }
924
10e8445b 925 if (!VALID_EPOCH(le64toh(o->tag.epoch))) {
24754f36
TR
926 log_debug(
927 "Invalid object tag epoch: %"PRIu64": %"PRIu64,
10e8445b 928 le64toh(o->tag.epoch),
24754f36
TR
929 offset);
930 return -EBADMSG;
931 }
932
933 break;
934 }
935
936 return 0;
937}
938
78519831 939int journal_file_move_to_object(JournalFile *f, ObjectType type, uint64_t offset, Object **ret) {
cec736d2
LP
940 int r;
941 void *t;
b439282e 942 size_t tsize;
cec736d2
LP
943 Object *o;
944 uint64_t s;
945
946 assert(f);
947 assert(ret);
948
db11ac1a 949 /* Objects may only be located at multiple of 64 bit */
202fd896
LP
950 if (!VALID64(offset)) {
951 log_debug("Attempt to move to object at non-64bit boundary: %" PRIu64, offset);
bd30fdf2 952 return -EBADMSG;
202fd896 953 }
db11ac1a 954
50809d7a 955 /* Object may not be located in the file header */
202fd896
LP
956 if (offset < le64toh(f->header->header_size)) {
957 log_debug("Attempt to move to object located in file header: %" PRIu64, offset);
50809d7a 958 return -EBADMSG;
202fd896 959 }
50809d7a 960
b439282e 961 r = journal_file_move_to(f, type, false, offset, sizeof(ObjectHeader), &t, &tsize);
cec736d2
LP
962 if (r < 0)
963 return r;
964
965 o = (Object*) t;
966 s = le64toh(o->object.size);
967
1c69f096
LP
968 if (s == 0) {
969 log_debug("Attempt to move to uninitialized object: %" PRIu64, offset);
970 return -EBADMSG;
971 }
202fd896
LP
972 if (s < sizeof(ObjectHeader)) {
973 log_debug("Attempt to move to overly short object: %" PRIu64, offset);
cec736d2 974 return -EBADMSG;
202fd896 975 }
cec736d2 976
202fd896
LP
977 if (o->object.type <= OBJECT_UNUSED) {
978 log_debug("Attempt to move to object with invalid type: %" PRIu64, offset);
16e9f408 979 return -EBADMSG;
202fd896 980 }
16e9f408 981
202fd896
LP
982 if (s < minimum_header_size(o)) {
983 log_debug("Attempt to move to truncated object: %" PRIu64, offset);
16e9f408 984 return -EBADMSG;
202fd896 985 }
16e9f408 986
202fd896
LP
987 if (type > OBJECT_UNUSED && o->object.type != type) {
988 log_debug("Attempt to move to object of unexpected type: %" PRIu64, offset);
cec736d2 989 return -EBADMSG;
202fd896 990 }
cec736d2 991
b439282e
VC
992 if (s > tsize) {
993 r = journal_file_move_to(f, type, false, offset, s, &t, NULL);
cec736d2
LP
994 if (r < 0)
995 return r;
996
997 o = (Object*) t;
998 }
999
24754f36
TR
1000 r = journal_file_check_object(f, offset, o);
1001 if (r < 0)
1002 return r;
1003
cec736d2
LP
1004 *ret = o;
1005 return 0;
1006}
1007
d98cc1f2 1008static uint64_t journal_file_entry_seqnum(JournalFile *f, uint64_t *seqnum) {
cec736d2
LP
1009 uint64_t r;
1010
1011 assert(f);
c88cc6af 1012 assert(f->header);
cec736d2 1013
beec0085 1014 r = le64toh(f->header->tail_entry_seqnum) + 1;
c2373f84
LP
1015
1016 if (seqnum) {
de190aef 1017 /* If an external seqnum counter was passed, we update
c2373f84
LP
1018 * both the local and the external one, and set it to
1019 * the maximum of both */
1020
1021 if (*seqnum + 1 > r)
1022 r = *seqnum + 1;
1023
1024 *seqnum = r;
1025 }
1026
beec0085 1027 f->header->tail_entry_seqnum = htole64(r);
cec736d2 1028
beec0085
LP
1029 if (f->header->head_entry_seqnum == 0)
1030 f->header->head_entry_seqnum = htole64(r);
de190aef 1031
cec736d2
LP
1032 return r;
1033}
1034
78519831 1035int journal_file_append_object(JournalFile *f, ObjectType type, uint64_t size, Object **ret, uint64_t *offset) {
cec736d2
LP
1036 int r;
1037 uint64_t p;
1038 Object *tail, *o;
1039 void *t;
1040
1041 assert(f);
c88cc6af 1042 assert(f->header);
d05089d8 1043 assert(type > OBJECT_UNUSED && type < _OBJECT_TYPE_MAX);
cec736d2
LP
1044 assert(size >= sizeof(ObjectHeader));
1045 assert(offset);
1046 assert(ret);
1047
26687bf8
OS
1048 r = journal_file_set_online(f);
1049 if (r < 0)
1050 return r;
1051
cec736d2 1052 p = le64toh(f->header->tail_object_offset);
cec736d2 1053 if (p == 0)
23b0b2b2 1054 p = le64toh(f->header->header_size);
cec736d2 1055 else {
d05089d8 1056 r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &tail);
cec736d2
LP
1057 if (r < 0)
1058 return r;
1059
1060 p += ALIGN64(le64toh(tail->object.size));
1061 }
1062
1063 r = journal_file_allocate(f, p, size);
1064 if (r < 0)
1065 return r;
1066
b439282e 1067 r = journal_file_move_to(f, type, false, p, size, &t, NULL);
cec736d2
LP
1068 if (r < 0)
1069 return r;
1070
1071 o = (Object*) t;
1072
1073 zero(o->object);
de190aef 1074 o->object.type = type;
cec736d2
LP
1075 o->object.size = htole64(size);
1076
1077 f->header->tail_object_offset = htole64(p);
cec736d2
LP
1078 f->header->n_objects = htole64(le64toh(f->header->n_objects) + 1);
1079
1080 *ret = o;
1081 *offset = p;
1082
1083 return 0;
1084}
1085
de190aef 1086static int journal_file_setup_data_hash_table(JournalFile *f) {
cec736d2
LP
1087 uint64_t s, p;
1088 Object *o;
1089 int r;
1090
1091 assert(f);
c88cc6af 1092 assert(f->header);
cec736d2 1093
070052ab
LP
1094 /* We estimate that we need 1 hash table entry per 768 bytes
1095 of journal file and we want to make sure we never get
1096 beyond 75% fill level. Calculate the hash table size for
1097 the maximum file size based on these metrics. */
4a92baf3 1098
dfabe643 1099 s = (f->metrics.max_size * 4 / 768 / 3) * sizeof(HashItem);
4a92baf3
LP
1100 if (s < DEFAULT_DATA_HASH_TABLE_SIZE)
1101 s = DEFAULT_DATA_HASH_TABLE_SIZE;
1102
507f22bd 1103 log_debug("Reserving %"PRIu64" entries in hash table.", s / sizeof(HashItem));
4a92baf3 1104
de190aef
LP
1105 r = journal_file_append_object(f,
1106 OBJECT_DATA_HASH_TABLE,
1107 offsetof(Object, hash_table.items) + s,
1108 &o, &p);
cec736d2
LP
1109 if (r < 0)
1110 return r;
1111
29804cc1 1112 memzero(o->hash_table.items, s);
cec736d2 1113
de190aef
LP
1114 f->header->data_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
1115 f->header->data_hash_table_size = htole64(s);
cec736d2
LP
1116
1117 return 0;
1118}
1119
de190aef 1120static int journal_file_setup_field_hash_table(JournalFile *f) {
cec736d2
LP
1121 uint64_t s, p;
1122 Object *o;
1123 int r;
1124
1125 assert(f);
c88cc6af 1126 assert(f->header);
cec736d2 1127
3c1668da
LP
1128 /* We use a fixed size hash table for the fields as this
1129 * number should grow very slowly only */
1130
de190aef
LP
1131 s = DEFAULT_FIELD_HASH_TABLE_SIZE;
1132 r = journal_file_append_object(f,
1133 OBJECT_FIELD_HASH_TABLE,
1134 offsetof(Object, hash_table.items) + s,
1135 &o, &p);
cec736d2
LP
1136 if (r < 0)
1137 return r;
1138
29804cc1 1139 memzero(o->hash_table.items, s);
cec736d2 1140
de190aef
LP
1141 f->header->field_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
1142 f->header->field_hash_table_size = htole64(s);
cec736d2
LP
1143
1144 return 0;
1145}
1146
dade37d4 1147int journal_file_map_data_hash_table(JournalFile *f) {
cec736d2
LP
1148 uint64_t s, p;
1149 void *t;
1150 int r;
1151
1152 assert(f);
c88cc6af 1153 assert(f->header);
cec736d2 1154
dade37d4
LP
1155 if (f->data_hash_table)
1156 return 0;
1157
de190aef
LP
1158 p = le64toh(f->header->data_hash_table_offset);
1159 s = le64toh(f->header->data_hash_table_size);
cec736d2 1160
de190aef 1161 r = journal_file_move_to(f,
16e9f408 1162 OBJECT_DATA_HASH_TABLE,
fcde2389 1163 true,
de190aef 1164 p, s,
b42549ad 1165 &t, NULL);
cec736d2
LP
1166 if (r < 0)
1167 return r;
1168
de190aef 1169 f->data_hash_table = t;
cec736d2
LP
1170 return 0;
1171}
1172
dade37d4 1173int journal_file_map_field_hash_table(JournalFile *f) {
cec736d2
LP
1174 uint64_t s, p;
1175 void *t;
1176 int r;
1177
1178 assert(f);
c88cc6af 1179 assert(f->header);
cec736d2 1180
dade37d4
LP
1181 if (f->field_hash_table)
1182 return 0;
1183
de190aef
LP
1184 p = le64toh(f->header->field_hash_table_offset);
1185 s = le64toh(f->header->field_hash_table_size);
cec736d2 1186
de190aef 1187 r = journal_file_move_to(f,
16e9f408 1188 OBJECT_FIELD_HASH_TABLE,
fcde2389 1189 true,
de190aef 1190 p, s,
b42549ad 1191 &t, NULL);
cec736d2
LP
1192 if (r < 0)
1193 return r;
1194
de190aef 1195 f->field_hash_table = t;
cec736d2
LP
1196 return 0;
1197}
1198
3c1668da
LP
1199static int journal_file_link_field(
1200 JournalFile *f,
1201 Object *o,
1202 uint64_t offset,
1203 uint64_t hash) {
1204
805d1486 1205 uint64_t p, h, m;
3c1668da
LP
1206 int r;
1207
1208 assert(f);
c88cc6af 1209 assert(f->header);
90d222c1 1210 assert(f->field_hash_table);
3c1668da
LP
1211 assert(o);
1212 assert(offset > 0);
1213
1214 if (o->object.type != OBJECT_FIELD)
1215 return -EINVAL;
1216
805d1486
LP
1217 m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem);
1218 if (m <= 0)
1219 return -EBADMSG;
3c1668da 1220
805d1486 1221 /* This might alter the window we are looking at */
3c1668da
LP
1222 o->field.next_hash_offset = o->field.head_data_offset = 0;
1223
805d1486 1224 h = hash % m;
3c1668da
LP
1225 p = le64toh(f->field_hash_table[h].tail_hash_offset);
1226 if (p == 0)
1227 f->field_hash_table[h].head_hash_offset = htole64(offset);
1228 else {
1229 r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
1230 if (r < 0)
1231 return r;
1232
1233 o->field.next_hash_offset = htole64(offset);
1234 }
1235
1236 f->field_hash_table[h].tail_hash_offset = htole64(offset);
1237
1238 if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
1239 f->header->n_fields = htole64(le64toh(f->header->n_fields) + 1);
1240
1241 return 0;
1242}
1243
1244static int journal_file_link_data(
1245 JournalFile *f,
1246 Object *o,
1247 uint64_t offset,
1248 uint64_t hash) {
1249
805d1486 1250 uint64_t p, h, m;
cec736d2
LP
1251 int r;
1252
1253 assert(f);
c88cc6af 1254 assert(f->header);
90d222c1 1255 assert(f->data_hash_table);
cec736d2
LP
1256 assert(o);
1257 assert(offset > 0);
b588975f
LP
1258
1259 if (o->object.type != OBJECT_DATA)
1260 return -EINVAL;
cec736d2 1261
805d1486
LP
1262 m = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
1263 if (m <= 0)
1264 return -EBADMSG;
48496df6 1265
805d1486 1266 /* This might alter the window we are looking at */
de190aef
LP
1267 o->data.next_hash_offset = o->data.next_field_offset = 0;
1268 o->data.entry_offset = o->data.entry_array_offset = 0;
1269 o->data.n_entries = 0;
cec736d2 1270
805d1486 1271 h = hash % m;
8db4213e 1272 p = le64toh(f->data_hash_table[h].tail_hash_offset);
3c1668da 1273 if (p == 0)
cec736d2 1274 /* Only entry in the hash table is easy */
de190aef 1275 f->data_hash_table[h].head_hash_offset = htole64(offset);
3c1668da 1276 else {
48496df6
LP
1277 /* Move back to the previous data object, to patch in
1278 * pointer */
cec736d2 1279
de190aef 1280 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
cec736d2
LP
1281 if (r < 0)
1282 return r;
1283
de190aef 1284 o->data.next_hash_offset = htole64(offset);
cec736d2
LP
1285 }
1286
de190aef 1287 f->data_hash_table[h].tail_hash_offset = htole64(offset);
cec736d2 1288
dca6219e
LP
1289 if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
1290 f->header->n_data = htole64(le64toh(f->header->n_data) + 1);
1291
cec736d2
LP
1292 return 0;
1293}
1294
3c1668da
LP
1295int journal_file_find_field_object_with_hash(
1296 JournalFile *f,
1297 const void *field, uint64_t size, uint64_t hash,
1298 Object **ret, uint64_t *offset) {
1299
805d1486 1300 uint64_t p, osize, h, m;
3c1668da
LP
1301 int r;
1302
1303 assert(f);
c88cc6af 1304 assert(f->header);
3c1668da
LP
1305 assert(field && size > 0);
1306
dade37d4
LP
1307 /* If the field hash table is empty, we can't find anything */
1308 if (le64toh(f->header->field_hash_table_size) <= 0)
1309 return 0;
1310
1311 /* Map the field hash table, if it isn't mapped yet. */
1312 r = journal_file_map_field_hash_table(f);
1313 if (r < 0)
1314 return r;
1315
3c1668da
LP
1316 osize = offsetof(Object, field.payload) + size;
1317
805d1486 1318 m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem);
805d1486 1319 if (m <= 0)
3c1668da
LP
1320 return -EBADMSG;
1321
805d1486 1322 h = hash % m;
3c1668da
LP
1323 p = le64toh(f->field_hash_table[h].head_hash_offset);
1324
1325 while (p > 0) {
1326 Object *o;
1327
1328 r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
1329 if (r < 0)
1330 return r;
1331
1332 if (le64toh(o->field.hash) == hash &&
1333 le64toh(o->object.size) == osize &&
1334 memcmp(o->field.payload, field, size) == 0) {
1335
1336 if (ret)
1337 *ret = o;
1338 if (offset)
1339 *offset = p;
1340
1341 return 1;
1342 }
1343
1344 p = le64toh(o->field.next_hash_offset);
1345 }
1346
1347 return 0;
1348}
1349
1350int journal_file_find_field_object(
1351 JournalFile *f,
1352 const void *field, uint64_t size,
1353 Object **ret, uint64_t *offset) {
1354
1355 uint64_t hash;
1356
1357 assert(f);
1358 assert(field && size > 0);
1359
1360 hash = hash64(field, size);
1361
1362 return journal_file_find_field_object_with_hash(f,
1363 field, size, hash,
1364 ret, offset);
1365}
1366
de190aef
LP
1367int journal_file_find_data_object_with_hash(
1368 JournalFile *f,
1369 const void *data, uint64_t size, uint64_t hash,
1370 Object **ret, uint64_t *offset) {
48496df6 1371
805d1486 1372 uint64_t p, osize, h, m;
cec736d2
LP
1373 int r;
1374
1375 assert(f);
c88cc6af 1376 assert(f->header);
cec736d2
LP
1377 assert(data || size == 0);
1378
dade37d4
LP
1379 /* If there's no data hash table, then there's no entry. */
1380 if (le64toh(f->header->data_hash_table_size) <= 0)
1381 return 0;
1382
1383 /* Map the data hash table, if it isn't mapped yet. */
1384 r = journal_file_map_data_hash_table(f);
1385 if (r < 0)
1386 return r;
1387
cec736d2
LP
1388 osize = offsetof(Object, data.payload) + size;
1389
805d1486
LP
1390 m = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
1391 if (m <= 0)
bc85bfee
LP
1392 return -EBADMSG;
1393
805d1486 1394 h = hash % m;
de190aef 1395 p = le64toh(f->data_hash_table[h].head_hash_offset);
cec736d2 1396
de190aef
LP
1397 while (p > 0) {
1398 Object *o;
cec736d2 1399
de190aef 1400 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
cec736d2
LP
1401 if (r < 0)
1402 return r;
1403
807e17f0 1404 if (le64toh(o->data.hash) != hash)
85a131e8 1405 goto next;
807e17f0 1406
d89c8fdf 1407 if (o->object.flags & OBJECT_COMPRESSION_MASK) {
349cc4a5 1408#if HAVE_XZ || HAVE_LZ4
fa1c4b51 1409 uint64_t l;
a7f7d1bd 1410 size_t rsize = 0;
cec736d2 1411
807e17f0
LP
1412 l = le64toh(o->object.size);
1413 if (l <= offsetof(Object, data.payload))
cec736d2
LP
1414 return -EBADMSG;
1415
807e17f0
LP
1416 l -= offsetof(Object, data.payload);
1417
d89c8fdf
ZJS
1418 r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK,
1419 o->data.payload, l, &f->compress_buffer, &f->compress_buffer_size, &rsize, 0);
1420 if (r < 0)
1421 return r;
807e17f0 1422
b785c858 1423 if (rsize == size &&
807e17f0
LP
1424 memcmp(f->compress_buffer, data, size) == 0) {
1425
1426 if (ret)
1427 *ret = o;
1428
1429 if (offset)
1430 *offset = p;
1431
1432 return 1;
1433 }
3b1a55e1
ZJS
1434#else
1435 return -EPROTONOSUPPORT;
1436#endif
807e17f0
LP
1437 } else if (le64toh(o->object.size) == osize &&
1438 memcmp(o->data.payload, data, size) == 0) {
1439
cec736d2
LP
1440 if (ret)
1441 *ret = o;
1442
1443 if (offset)
1444 *offset = p;
1445
de190aef 1446 return 1;
cec736d2
LP
1447 }
1448
85a131e8 1449 next:
cec736d2
LP
1450 p = le64toh(o->data.next_hash_offset);
1451 }
1452
de190aef
LP
1453 return 0;
1454}
1455
1456int journal_file_find_data_object(
1457 JournalFile *f,
1458 const void *data, uint64_t size,
1459 Object **ret, uint64_t *offset) {
1460
1461 uint64_t hash;
1462
1463 assert(f);
1464 assert(data || size == 0);
1465
1466 hash = hash64(data, size);
1467
1468 return journal_file_find_data_object_with_hash(f,
1469 data, size, hash,
1470 ret, offset);
1471}
1472
3c1668da
LP
1473static int journal_file_append_field(
1474 JournalFile *f,
1475 const void *field, uint64_t size,
1476 Object **ret, uint64_t *offset) {
1477
1478 uint64_t hash, p;
1479 uint64_t osize;
1480 Object *o;
1481 int r;
1482
1483 assert(f);
1484 assert(field && size > 0);
1485
1486 hash = hash64(field, size);
1487
1488 r = journal_file_find_field_object_with_hash(f, field, size, hash, &o, &p);
1489 if (r < 0)
1490 return r;
1491 else if (r > 0) {
1492
1493 if (ret)
1494 *ret = o;
1495
1496 if (offset)
1497 *offset = p;
1498
1499 return 0;
1500 }
1501
1502 osize = offsetof(Object, field.payload) + size;
1503 r = journal_file_append_object(f, OBJECT_FIELD, osize, &o, &p);
8c92d4bb
LP
1504 if (r < 0)
1505 return r;
3c1668da
LP
1506
1507 o->field.hash = htole64(hash);
1508 memcpy(o->field.payload, field, size);
1509
1510 r = journal_file_link_field(f, o, p, hash);
1511 if (r < 0)
1512 return r;
1513
1514 /* The linking might have altered the window, so let's
1515 * refresh our pointer */
1516 r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
1517 if (r < 0)
1518 return r;
1519
349cc4a5 1520#if HAVE_GCRYPT
3c1668da
LP
1521 r = journal_file_hmac_put_object(f, OBJECT_FIELD, o, p);
1522 if (r < 0)
1523 return r;
1524#endif
1525
1526 if (ret)
1527 *ret = o;
1528
1529 if (offset)
1530 *offset = p;
1531
1532 return 0;
1533}
1534
48496df6
LP
1535static int journal_file_append_data(
1536 JournalFile *f,
1537 const void *data, uint64_t size,
1538 Object **ret, uint64_t *offset) {
1539
de190aef
LP
1540 uint64_t hash, p;
1541 uint64_t osize;
1542 Object *o;
d89c8fdf 1543 int r, compression = 0;
3c1668da 1544 const void *eq;
de190aef
LP
1545
1546 assert(f);
1547 assert(data || size == 0);
1548
1549 hash = hash64(data, size);
1550
1551 r = journal_file_find_data_object_with_hash(f, data, size, hash, &o, &p);
1552 if (r < 0)
1553 return r;
0240c603 1554 if (r > 0) {
de190aef
LP
1555
1556 if (ret)
1557 *ret = o;
1558
1559 if (offset)
1560 *offset = p;
1561
1562 return 0;
1563 }
1564
1565 osize = offsetof(Object, data.payload) + size;
1566 r = journal_file_append_object(f, OBJECT_DATA, osize, &o, &p);
cec736d2
LP
1567 if (r < 0)
1568 return r;
1569
cec736d2 1570 o->data.hash = htole64(hash);
807e17f0 1571
349cc4a5 1572#if HAVE_XZ || HAVE_LZ4
d1afbcd2 1573 if (JOURNAL_FILE_COMPRESS(f) && size >= COMPRESSION_SIZE_THRESHOLD) {
a7f7d1bd 1574 size_t rsize = 0;
807e17f0 1575
5d6f46b6 1576 compression = compress_blob(data, size, o->data.payload, size - 1, &rsize);
807e17f0 1577
d1afbcd2 1578 if (compression >= 0) {
807e17f0 1579 o->object.size = htole64(offsetof(Object, data.payload) + rsize);
d89c8fdf 1580 o->object.flags |= compression;
807e17f0 1581
fa1c4b51 1582 log_debug("Compressed data object %"PRIu64" -> %zu using %s",
d89c8fdf 1583 size, rsize, object_compressed_to_string(compression));
d1afbcd2
LP
1584 } else
1585 /* Compression didn't work, we don't really care why, let's continue without compression */
1586 compression = 0;
807e17f0
LP
1587 }
1588#endif
1589
75f32f04
ZJS
1590 if (compression == 0)
1591 memcpy_safe(o->data.payload, data, size);
cec736d2 1592
de190aef 1593 r = journal_file_link_data(f, o, p, hash);
cec736d2
LP
1594 if (r < 0)
1595 return r;
1596
349cc4a5 1597#if HAVE_GCRYPT
33685a5a
FB
1598 r = journal_file_hmac_put_object(f, OBJECT_DATA, o, p);
1599 if (r < 0)
1600 return r;
1601#endif
1602
48496df6
LP
1603 /* The linking might have altered the window, so let's
1604 * refresh our pointer */
1605 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
1606 if (r < 0)
1607 return r;
1608
08c6f819
SL
1609 if (!data)
1610 eq = NULL;
1611 else
1612 eq = memchr(data, '=', size);
3c1668da 1613 if (eq && eq > data) {
748db592 1614 Object *fo = NULL;
3c1668da 1615 uint64_t fp;
3c1668da
LP
1616
1617 /* Create field object ... */
1618 r = journal_file_append_field(f, data, (uint8_t*) eq - (uint8_t*) data, &fo, &fp);
1619 if (r < 0)
1620 return r;
1621
1622 /* ... and link it in. */
1623 o->data.next_field_offset = fo->field.head_data_offset;
1624 fo->field.head_data_offset = le64toh(p);
1625 }
1626
cec736d2
LP
1627 if (ret)
1628 *ret = o;
1629
1630 if (offset)
de190aef 1631 *offset = p;
cec736d2
LP
1632
1633 return 0;
1634}
1635
1636uint64_t journal_file_entry_n_items(Object *o) {
1637 assert(o);
b588975f
LP
1638
1639 if (o->object.type != OBJECT_ENTRY)
1640 return 0;
cec736d2
LP
1641
1642 return (le64toh(o->object.size) - offsetof(Object, entry.items)) / sizeof(EntryItem);
1643}
1644
0284adc6 1645uint64_t journal_file_entry_array_n_items(Object *o) {
de190aef 1646 assert(o);
b588975f
LP
1647
1648 if (o->object.type != OBJECT_ENTRY_ARRAY)
1649 return 0;
de190aef
LP
1650
1651 return (le64toh(o->object.size) - offsetof(Object, entry_array.items)) / sizeof(uint64_t);
1652}
1653
fb9a24b6
LP
1654uint64_t journal_file_hash_table_n_items(Object *o) {
1655 assert(o);
b588975f 1656
ec2ce0c5 1657 if (!IN_SET(o->object.type, OBJECT_DATA_HASH_TABLE, OBJECT_FIELD_HASH_TABLE))
b588975f 1658 return 0;
fb9a24b6
LP
1659
1660 return (le64toh(o->object.size) - offsetof(Object, hash_table.items)) / sizeof(HashItem);
1661}
1662
de190aef 1663static int link_entry_into_array(JournalFile *f,
4fd052ae
FC
1664 le64_t *first,
1665 le64_t *idx,
de190aef 1666 uint64_t p) {
cec736d2 1667 int r;
de190aef
LP
1668 uint64_t n = 0, ap = 0, q, i, a, hidx;
1669 Object *o;
1670
cec736d2 1671 assert(f);
c88cc6af 1672 assert(f->header);
de190aef
LP
1673 assert(first);
1674 assert(idx);
1675 assert(p > 0);
cec736d2 1676
de190aef
LP
1677 a = le64toh(*first);
1678 i = hidx = le64toh(*idx);
1679 while (a > 0) {
1680
1681 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
1682 if (r < 0)
1683 return r;
cec736d2 1684
de190aef
LP
1685 n = journal_file_entry_array_n_items(o);
1686 if (i < n) {
1687 o->entry_array.items[i] = htole64(p);
1688 *idx = htole64(hidx + 1);
1689 return 0;
1690 }
cec736d2 1691
de190aef
LP
1692 i -= n;
1693 ap = a;
1694 a = le64toh(o->entry_array.next_entry_array_offset);
1695 }
1696
1697 if (hidx > n)
1698 n = (hidx+1) * 2;
1699 else
1700 n = n * 2;
1701
1702 if (n < 4)
1703 n = 4;
1704
1705 r = journal_file_append_object(f, OBJECT_ENTRY_ARRAY,
1706 offsetof(Object, entry_array.items) + n * sizeof(uint64_t),
1707 &o, &q);
cec736d2
LP
1708 if (r < 0)
1709 return r;
1710
349cc4a5 1711#if HAVE_GCRYPT
5996c7c2 1712 r = journal_file_hmac_put_object(f, OBJECT_ENTRY_ARRAY, o, q);
b0af6f41
LP
1713 if (r < 0)
1714 return r;
feb12d3e 1715#endif
b0af6f41 1716
de190aef 1717 o->entry_array.items[i] = htole64(p);
cec736d2 1718
de190aef 1719 if (ap == 0)
7be3aa17 1720 *first = htole64(q);
cec736d2 1721 else {
de190aef 1722 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, ap, &o);
cec736d2
LP
1723 if (r < 0)
1724 return r;
1725
de190aef
LP
1726 o->entry_array.next_entry_array_offset = htole64(q);
1727 }
cec736d2 1728
2dee23eb
LP
1729 if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
1730 f->header->n_entry_arrays = htole64(le64toh(f->header->n_entry_arrays) + 1);
1731
de190aef
LP
1732 *idx = htole64(hidx + 1);
1733
1734 return 0;
1735}
cec736d2 1736
de190aef 1737static int link_entry_into_array_plus_one(JournalFile *f,
4fd052ae
FC
1738 le64_t *extra,
1739 le64_t *first,
1740 le64_t *idx,
de190aef
LP
1741 uint64_t p) {
1742
1743 int r;
1744
1745 assert(f);
1746 assert(extra);
1747 assert(first);
1748 assert(idx);
1749 assert(p > 0);
1750
1751 if (*idx == 0)
1752 *extra = htole64(p);
1753 else {
4fd052ae 1754 le64_t i;
de190aef 1755
7be3aa17 1756 i = htole64(le64toh(*idx) - 1);
de190aef
LP
1757 r = link_entry_into_array(f, first, &i, p);
1758 if (r < 0)
1759 return r;
cec736d2
LP
1760 }
1761
de190aef
LP
1762 *idx = htole64(le64toh(*idx) + 1);
1763 return 0;
1764}
1765
1766static int journal_file_link_entry_item(JournalFile *f, Object *o, uint64_t offset, uint64_t i) {
1767 uint64_t p;
1768 int r;
1769 assert(f);
1770 assert(o);
1771 assert(offset > 0);
1772
1773 p = le64toh(o->entry.items[i].object_offset);
1774 if (p == 0)
1775 return -EINVAL;
1776
1777 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
cec736d2
LP
1778 if (r < 0)
1779 return r;
1780
de190aef
LP
1781 return link_entry_into_array_plus_one(f,
1782 &o->data.entry_offset,
1783 &o->data.entry_array_offset,
1784 &o->data.n_entries,
1785 offset);
cec736d2
LP
1786}
1787
1788static int journal_file_link_entry(JournalFile *f, Object *o, uint64_t offset) {
de190aef 1789 uint64_t n, i;
cec736d2
LP
1790 int r;
1791
1792 assert(f);
c88cc6af 1793 assert(f->header);
cec736d2
LP
1794 assert(o);
1795 assert(offset > 0);
b588975f
LP
1796
1797 if (o->object.type != OBJECT_ENTRY)
1798 return -EINVAL;
cec736d2 1799
b788cc23
LP
1800 __sync_synchronize();
1801
cec736d2 1802 /* Link up the entry itself */
de190aef
LP
1803 r = link_entry_into_array(f,
1804 &f->header->entry_array_offset,
1805 &f->header->n_entries,
1806 offset);
1807 if (r < 0)
1808 return r;
cec736d2 1809
507f22bd 1810 /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
cec736d2 1811
de190aef 1812 if (f->header->head_entry_realtime == 0)
0ac38b70 1813 f->header->head_entry_realtime = o->entry.realtime;
cec736d2 1814
0ac38b70 1815 f->header->tail_entry_realtime = o->entry.realtime;
de190aef
LP
1816 f->header->tail_entry_monotonic = o->entry.monotonic;
1817
1818 f->tail_entry_monotonic_valid = true;
cec736d2
LP
1819
1820 /* Link up the items */
1821 n = journal_file_entry_n_items(o);
1822 for (i = 0; i < n; i++) {
1823 r = journal_file_link_entry_item(f, o, offset, i);
1824 if (r < 0)
1825 return r;
1826 }
1827
cec736d2
LP
1828 return 0;
1829}
1830
1831static int journal_file_append_entry_internal(
1832 JournalFile *f,
1833 const dual_timestamp *ts,
1834 uint64_t xor_hash,
1835 const EntryItem items[], unsigned n_items,
de190aef 1836 uint64_t *seqnum,
cec736d2
LP
1837 Object **ret, uint64_t *offset) {
1838 uint64_t np;
1839 uint64_t osize;
1840 Object *o;
1841 int r;
1842
1843 assert(f);
c88cc6af 1844 assert(f->header);
cec736d2 1845 assert(items || n_items == 0);
de190aef 1846 assert(ts);
cec736d2
LP
1847
1848 osize = offsetof(Object, entry.items) + (n_items * sizeof(EntryItem));
1849
de190aef 1850 r = journal_file_append_object(f, OBJECT_ENTRY, osize, &o, &np);
cec736d2
LP
1851 if (r < 0)
1852 return r;
1853
d98cc1f2 1854 o->entry.seqnum = htole64(journal_file_entry_seqnum(f, seqnum));
75f32f04 1855 memcpy_safe(o->entry.items, items, n_items * sizeof(EntryItem));
de190aef
LP
1856 o->entry.realtime = htole64(ts->realtime);
1857 o->entry.monotonic = htole64(ts->monotonic);
cec736d2
LP
1858 o->entry.xor_hash = htole64(xor_hash);
1859 o->entry.boot_id = f->header->boot_id;
1860
349cc4a5 1861#if HAVE_GCRYPT
5996c7c2 1862 r = journal_file_hmac_put_object(f, OBJECT_ENTRY, o, np);
b0af6f41
LP
1863 if (r < 0)
1864 return r;
feb12d3e 1865#endif
b0af6f41 1866
cec736d2
LP
1867 r = journal_file_link_entry(f, o, np);
1868 if (r < 0)
1869 return r;
1870
1871 if (ret)
1872 *ret = o;
1873
1874 if (offset)
1875 *offset = np;
1876
1877 return 0;
1878}
1879
cf244689 1880void journal_file_post_change(JournalFile *f) {
50f20cfd
LP
1881 assert(f);
1882
1883 /* inotify() does not receive IN_MODIFY events from file
1884 * accesses done via mmap(). After each access we hence
1885 * trigger IN_MODIFY by truncating the journal file to its
1886 * current size which triggers IN_MODIFY. */
1887
bc85bfee
LP
1888 __sync_synchronize();
1889
50f20cfd 1890 if (ftruncate(f->fd, f->last_stat.st_size) < 0)
e167d7fd 1891 log_debug_errno(errno, "Failed to truncate file to its own size: %m");
50f20cfd
LP
1892}
1893
7a24f3bf
VC
1894static int post_change_thunk(sd_event_source *timer, uint64_t usec, void *userdata) {
1895 assert(userdata);
1896
1897 journal_file_post_change(userdata);
1898
1899 return 1;
1900}
1901
1902static void schedule_post_change(JournalFile *f) {
1903 sd_event_source *timer;
1904 int enabled, r;
1905 uint64_t now;
1906
1907 assert(f);
1908 assert(f->post_change_timer);
1909
1910 timer = f->post_change_timer;
1911
1912 r = sd_event_source_get_enabled(timer, &enabled);
1913 if (r < 0) {
e167d7fd
LP
1914 log_debug_errno(r, "Failed to get ftruncate timer state: %m");
1915 goto fail;
7a24f3bf
VC
1916 }
1917
1918 if (enabled == SD_EVENT_ONESHOT)
1919 return;
1920
1921 r = sd_event_now(sd_event_source_get_event(timer), CLOCK_MONOTONIC, &now);
1922 if (r < 0) {
e167d7fd
LP
1923 log_debug_errno(r, "Failed to get clock's now for scheduling ftruncate: %m");
1924 goto fail;
7a24f3bf
VC
1925 }
1926
1927 r = sd_event_source_set_time(timer, now+f->post_change_timer_period);
1928 if (r < 0) {
e167d7fd
LP
1929 log_debug_errno(r, "Failed to set time for scheduling ftruncate: %m");
1930 goto fail;
7a24f3bf
VC
1931 }
1932
1933 r = sd_event_source_set_enabled(timer, SD_EVENT_ONESHOT);
1934 if (r < 0) {
e167d7fd
LP
1935 log_debug_errno(r, "Failed to enable scheduled ftruncate: %m");
1936 goto fail;
7a24f3bf 1937 }
e167d7fd
LP
1938
1939 return;
1940
1941fail:
1942 /* On failure, let's simply post the change immediately. */
1943 journal_file_post_change(f);
7a24f3bf
VC
1944}
1945
1946/* Enable coalesced change posting in a timer on the provided sd_event instance */
1947int journal_file_enable_post_change_timer(JournalFile *f, sd_event *e, usec_t t) {
1948 _cleanup_(sd_event_source_unrefp) sd_event_source *timer = NULL;
1949 int r;
1950
1951 assert(f);
1952 assert_return(!f->post_change_timer, -EINVAL);
1953 assert(e);
1954 assert(t);
1955
1956 r = sd_event_add_time(e, &timer, CLOCK_MONOTONIC, 0, 0, post_change_thunk, f);
1957 if (r < 0)
1958 return r;
1959
1960 r = sd_event_source_set_enabled(timer, SD_EVENT_OFF);
1961 if (r < 0)
1962 return r;
1963
1964 f->post_change_timer = timer;
1965 timer = NULL;
1966 f->post_change_timer_period = t;
1967
1968 return r;
1969}
1970
1f2da9ec
LP
1971static int entry_item_cmp(const void *_a, const void *_b) {
1972 const EntryItem *a = _a, *b = _b;
1973
1974 if (le64toh(a->object_offset) < le64toh(b->object_offset))
1975 return -1;
1976 if (le64toh(a->object_offset) > le64toh(b->object_offset))
1977 return 1;
1978 return 0;
1979}
1980
de190aef 1981int 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) {
cec736d2
LP
1982 unsigned i;
1983 EntryItem *items;
1984 int r;
1985 uint64_t xor_hash = 0;
de190aef 1986 struct dual_timestamp _ts;
cec736d2
LP
1987
1988 assert(f);
c88cc6af 1989 assert(f->header);
cec736d2
LP
1990 assert(iovec || n_iovec == 0);
1991
de190aef
LP
1992 if (!ts) {
1993 dual_timestamp_get(&_ts);
1994 ts = &_ts;
1995 }
1996
349cc4a5 1997#if HAVE_GCRYPT
7560fffc
LP
1998 r = journal_file_maybe_append_tag(f, ts->realtime);
1999 if (r < 0)
2000 return r;
feb12d3e 2001#endif
7560fffc 2002
64825d3c 2003 /* alloca() can't take 0, hence let's allocate at least one */
9607d947 2004 items = alloca(sizeof(EntryItem) * MAX(1u, n_iovec));
cec736d2
LP
2005
2006 for (i = 0; i < n_iovec; i++) {
2007 uint64_t p;
2008 Object *o;
2009
2010 r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p);
2011 if (r < 0)
cf244689 2012 return r;
cec736d2
LP
2013
2014 xor_hash ^= le64toh(o->data.hash);
2015 items[i].object_offset = htole64(p);
de7b95cd 2016 items[i].hash = o->data.hash;
cec736d2
LP
2017 }
2018
1f2da9ec
LP
2019 /* Order by the position on disk, in order to improve seek
2020 * times for rotating media. */
7ff7394d 2021 qsort_safe(items, n_iovec, sizeof(EntryItem), entry_item_cmp);
1f2da9ec 2022
de190aef 2023 r = journal_file_append_entry_internal(f, ts, xor_hash, items, n_iovec, seqnum, ret, offset);
cec736d2 2024
fa6ac760
LP
2025 /* If the memory mapping triggered a SIGBUS then we return an
2026 * IO error and ignore the error code passed down to us, since
2027 * it is very likely just an effect of a nullified replacement
2028 * mapping page */
2029
be7cdd8e 2030 if (mmap_cache_got_sigbus(f->mmap, f->cache_fd))
fa6ac760
LP
2031 r = -EIO;
2032
7a24f3bf
VC
2033 if (f->post_change_timer)
2034 schedule_post_change(f);
2035 else
2036 journal_file_post_change(f);
50f20cfd 2037
cec736d2
LP
2038 return r;
2039}
2040
a4bcff5b 2041typedef struct ChainCacheItem {
fb099c8d 2042 uint64_t first; /* the array at the beginning of the chain */
a4bcff5b
LP
2043 uint64_t array; /* the cached array */
2044 uint64_t begin; /* the first item in the cached array */
2045 uint64_t total; /* the total number of items in all arrays before this one in the chain */
f268980d 2046 uint64_t last_index; /* the last index we looked at, to optimize locality when bisecting */
a4bcff5b
LP
2047} ChainCacheItem;
2048
2049static void chain_cache_put(
4743015d 2050 OrderedHashmap *h,
a4bcff5b
LP
2051 ChainCacheItem *ci,
2052 uint64_t first,
2053 uint64_t array,
2054 uint64_t begin,
f268980d
LP
2055 uint64_t total,
2056 uint64_t last_index) {
a4bcff5b
LP
2057
2058 if (!ci) {
34741aa3
LP
2059 /* If the chain item to cache for this chain is the
2060 * first one it's not worth caching anything */
2061 if (array == first)
2062 return;
2063
29433089 2064 if (ordered_hashmap_size(h) >= CHAIN_CACHE_MAX) {
4743015d 2065 ci = ordered_hashmap_steal_first(h);
29433089
LP
2066 assert(ci);
2067 } else {
a4bcff5b
LP
2068 ci = new(ChainCacheItem, 1);
2069 if (!ci)
2070 return;
2071 }
2072
2073 ci->first = first;
2074
4743015d 2075 if (ordered_hashmap_put(h, &ci->first, ci) < 0) {
a4bcff5b
LP
2076 free(ci);
2077 return;
2078 }
2079 } else
2080 assert(ci->first == first);
2081
2082 ci->array = array;
2083 ci->begin = begin;
2084 ci->total = total;
f268980d 2085 ci->last_index = last_index;
a4bcff5b
LP
2086}
2087
f268980d
LP
2088static int generic_array_get(
2089 JournalFile *f,
2090 uint64_t first,
2091 uint64_t i,
2092 Object **ret, uint64_t *offset) {
de190aef 2093
cec736d2 2094 Object *o;
a4bcff5b 2095 uint64_t p = 0, a, t = 0;
cec736d2 2096 int r;
a4bcff5b 2097 ChainCacheItem *ci;
cec736d2
LP
2098
2099 assert(f);
2100
de190aef 2101 a = first;
a4bcff5b
LP
2102
2103 /* Try the chain cache first */
4743015d 2104 ci = ordered_hashmap_get(f->chain_cache, &first);
a4bcff5b
LP
2105 if (ci && i > ci->total) {
2106 a = ci->array;
2107 i -= ci->total;
2108 t = ci->total;
2109 }
2110
de190aef 2111 while (a > 0) {
a4bcff5b 2112 uint64_t k;
cec736d2 2113
de190aef
LP
2114 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
2115 if (r < 0)
2116 return r;
cec736d2 2117
a4bcff5b
LP
2118 k = journal_file_entry_array_n_items(o);
2119 if (i < k) {
de190aef 2120 p = le64toh(o->entry_array.items[i]);
a4bcff5b 2121 goto found;
cec736d2
LP
2122 }
2123
a4bcff5b
LP
2124 i -= k;
2125 t += k;
de190aef
LP
2126 a = le64toh(o->entry_array.next_entry_array_offset);
2127 }
2128
a4bcff5b
LP
2129 return 0;
2130
2131found:
2132 /* Let's cache this item for the next invocation */
af13a6b0 2133 chain_cache_put(f->chain_cache, ci, first, a, le64toh(o->entry_array.items[0]), t, i);
de190aef
LP
2134
2135 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2136 if (r < 0)
2137 return r;
2138
2139 if (ret)
2140 *ret = o;
2141
2142 if (offset)
2143 *offset = p;
2144
2145 return 1;
2146}
2147
f268980d
LP
2148static int generic_array_get_plus_one(
2149 JournalFile *f,
2150 uint64_t extra,
2151 uint64_t first,
2152 uint64_t i,
2153 Object **ret, uint64_t *offset) {
de190aef
LP
2154
2155 Object *o;
2156
2157 assert(f);
2158
2159 if (i == 0) {
2160 int r;
2161
2162 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
cec736d2
LP
2163 if (r < 0)
2164 return r;
2165
de190aef
LP
2166 if (ret)
2167 *ret = o;
cec736d2 2168
de190aef
LP
2169 if (offset)
2170 *offset = extra;
cec736d2 2171
de190aef 2172 return 1;
cec736d2
LP
2173 }
2174
de190aef
LP
2175 return generic_array_get(f, first, i-1, ret, offset);
2176}
cec736d2 2177
de190aef
LP
2178enum {
2179 TEST_FOUND,
2180 TEST_LEFT,
2181 TEST_RIGHT
2182};
cec736d2 2183
f268980d
LP
2184static int generic_array_bisect(
2185 JournalFile *f,
2186 uint64_t first,
2187 uint64_t n,
2188 uint64_t needle,
2189 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
2190 direction_t direction,
2191 Object **ret,
2192 uint64_t *offset,
2193 uint64_t *idx) {
2194
2195 uint64_t a, p, t = 0, i = 0, last_p = 0, last_index = (uint64_t) -1;
de190aef
LP
2196 bool subtract_one = false;
2197 Object *o, *array = NULL;
2198 int r;
a4bcff5b 2199 ChainCacheItem *ci;
cec736d2 2200
de190aef
LP
2201 assert(f);
2202 assert(test_object);
cec736d2 2203
a4bcff5b 2204 /* Start with the first array in the chain */
de190aef 2205 a = first;
a4bcff5b 2206
4743015d 2207 ci = ordered_hashmap_get(f->chain_cache, &first);
a4bcff5b
LP
2208 if (ci && n > ci->total) {
2209 /* Ah, we have iterated this bisection array chain
2210 * previously! Let's see if we can skip ahead in the
2211 * chain, as far as the last time. But we can't jump
2212 * backwards in the chain, so let's check that
2213 * first. */
2214
2215 r = test_object(f, ci->begin, needle);
2216 if (r < 0)
2217 return r;
2218
2219 if (r == TEST_LEFT) {
f268980d 2220 /* OK, what we are looking for is right of the
a4bcff5b
LP
2221 * begin of this EntryArray, so let's jump
2222 * straight to previously cached array in the
2223 * chain */
2224
2225 a = ci->array;
2226 n -= ci->total;
2227 t = ci->total;
f268980d 2228 last_index = ci->last_index;
a4bcff5b
LP
2229 }
2230 }
2231
de190aef
LP
2232 while (a > 0) {
2233 uint64_t left, right, k, lp;
2234
2235 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
cec736d2
LP
2236 if (r < 0)
2237 return r;
2238
de190aef
LP
2239 k = journal_file_entry_array_n_items(array);
2240 right = MIN(k, n);
2241 if (right <= 0)
2242 return 0;
cec736d2 2243
de190aef
LP
2244 i = right - 1;
2245 lp = p = le64toh(array->entry_array.items[i]);
2246 if (p <= 0)
bee6a291
LP
2247 r = -EBADMSG;
2248 else
2249 r = test_object(f, p, needle);
2250 if (r == -EBADMSG) {
2251 log_debug_errno(r, "Encountered invalid entry while bisecting, cutting algorithm short. (1)");
2252 n = i;
2253 continue;
2254 }
de190aef
LP
2255 if (r < 0)
2256 return r;
cec736d2 2257
de190aef
LP
2258 if (r == TEST_FOUND)
2259 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2260
2261 if (r == TEST_RIGHT) {
2262 left = 0;
2263 right -= 1;
f268980d
LP
2264
2265 if (last_index != (uint64_t) -1) {
2266 assert(last_index <= right);
2267
2268 /* If we cached the last index we
2269 * looked at, let's try to not to jump
2270 * too wildly around and see if we can
2271 * limit the range to look at early to
2272 * the immediate neighbors of the last
2273 * index we looked at. */
2274
2275 if (last_index > 0) {
2276 uint64_t x = last_index - 1;
2277
2278 p = le64toh(array->entry_array.items[x]);
2279 if (p <= 0)
2280 return -EBADMSG;
2281
2282 r = test_object(f, p, needle);
2283 if (r < 0)
2284 return r;
2285
2286 if (r == TEST_FOUND)
2287 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2288
2289 if (r == TEST_RIGHT)
2290 right = x;
2291 else
2292 left = x + 1;
2293 }
2294
2295 if (last_index < right) {
2296 uint64_t y = last_index + 1;
2297
2298 p = le64toh(array->entry_array.items[y]);
2299 if (p <= 0)
2300 return -EBADMSG;
2301
2302 r = test_object(f, p, needle);
2303 if (r < 0)
2304 return r;
2305
2306 if (r == TEST_FOUND)
2307 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2308
2309 if (r == TEST_RIGHT)
2310 right = y;
2311 else
2312 left = y + 1;
2313 }
f268980d
LP
2314 }
2315
de190aef
LP
2316 for (;;) {
2317 if (left == right) {
2318 if (direction == DIRECTION_UP)
2319 subtract_one = true;
2320
2321 i = left;
2322 goto found;
2323 }
2324
2325 assert(left < right);
de190aef 2326 i = (left + right) / 2;
f268980d 2327
de190aef
LP
2328 p = le64toh(array->entry_array.items[i]);
2329 if (p <= 0)
bee6a291
LP
2330 r = -EBADMSG;
2331 else
2332 r = test_object(f, p, needle);
2333 if (r == -EBADMSG) {
2334 log_debug_errno(r, "Encountered invalid entry while bisecting, cutting algorithm short. (2)");
2335 right = n = i;
2336 continue;
2337 }
de190aef
LP
2338 if (r < 0)
2339 return r;
cec736d2 2340
de190aef
LP
2341 if (r == TEST_FOUND)
2342 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2343
2344 if (r == TEST_RIGHT)
2345 right = i;
2346 else
2347 left = i + 1;
2348 }
2349 }
2350
2173cbf8 2351 if (k >= n) {
cbdca852
LP
2352 if (direction == DIRECTION_UP) {
2353 i = n;
2354 subtract_one = true;
2355 goto found;
2356 }
2357
cec736d2 2358 return 0;
cbdca852 2359 }
cec736d2 2360
de190aef
LP
2361 last_p = lp;
2362
2363 n -= k;
2364 t += k;
f268980d 2365 last_index = (uint64_t) -1;
de190aef 2366 a = le64toh(array->entry_array.next_entry_array_offset);
cec736d2
LP
2367 }
2368
2369 return 0;
de190aef
LP
2370
2371found:
2372 if (subtract_one && t == 0 && i == 0)
2373 return 0;
2374
a4bcff5b 2375 /* Let's cache this item for the next invocation */
af13a6b0 2376 chain_cache_put(f->chain_cache, ci, first, a, le64toh(array->entry_array.items[0]), t, subtract_one ? (i > 0 ? i-1 : (uint64_t) -1) : i);
a4bcff5b 2377
de190aef
LP
2378 if (subtract_one && i == 0)
2379 p = last_p;
2380 else if (subtract_one)
2381 p = le64toh(array->entry_array.items[i-1]);
2382 else
2383 p = le64toh(array->entry_array.items[i]);
2384
2385 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2386 if (r < 0)
2387 return r;
2388
2389 if (ret)
2390 *ret = o;
2391
2392 if (offset)
2393 *offset = p;
2394
2395 if (idx)
cbdca852 2396 *idx = t + i + (subtract_one ? -1 : 0);
de190aef
LP
2397
2398 return 1;
cec736d2
LP
2399}
2400
f268980d
LP
2401static int generic_array_bisect_plus_one(
2402 JournalFile *f,
2403 uint64_t extra,
2404 uint64_t first,
2405 uint64_t n,
2406 uint64_t needle,
2407 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
2408 direction_t direction,
2409 Object **ret,
2410 uint64_t *offset,
2411 uint64_t *idx) {
de190aef 2412
cec736d2 2413 int r;
cbdca852
LP
2414 bool step_back = false;
2415 Object *o;
cec736d2
LP
2416
2417 assert(f);
de190aef 2418 assert(test_object);
cec736d2 2419
de190aef
LP
2420 if (n <= 0)
2421 return 0;
cec736d2 2422
de190aef
LP
2423 /* This bisects the array in object 'first', but first checks
2424 * an extra */
de190aef
LP
2425 r = test_object(f, extra, needle);
2426 if (r < 0)
2427 return r;
a536e261
LP
2428
2429 if (r == TEST_FOUND)
2430 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2431
cbdca852
LP
2432 /* if we are looking with DIRECTION_UP then we need to first
2433 see if in the actual array there is a matching entry, and
2434 return the last one of that. But if there isn't any we need
2435 to return this one. Hence remember this, and return it
2436 below. */
2437 if (r == TEST_LEFT)
2438 step_back = direction == DIRECTION_UP;
de190aef 2439
cbdca852
LP
2440 if (r == TEST_RIGHT) {
2441 if (direction == DIRECTION_DOWN)
2442 goto found;
2443 else
2444 return 0;
a536e261 2445 }
cec736d2 2446
de190aef
LP
2447 r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret, offset, idx);
2448
cbdca852
LP
2449 if (r == 0 && step_back)
2450 goto found;
2451
ecf68b1d 2452 if (r > 0 && idx)
313cefa1 2453 (*idx)++;
de190aef
LP
2454
2455 return r;
cbdca852
LP
2456
2457found:
2458 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
2459 if (r < 0)
2460 return r;
2461
2462 if (ret)
2463 *ret = o;
2464
2465 if (offset)
2466 *offset = extra;
2467
2468 if (idx)
2469 *idx = 0;
2470
2471 return 1;
2472}
2473
44a6b1b6 2474_pure_ static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) {
cbdca852
LP
2475 assert(f);
2476 assert(p > 0);
2477
2478 if (p == needle)
2479 return TEST_FOUND;
2480 else if (p < needle)
2481 return TEST_LEFT;
2482 else
2483 return TEST_RIGHT;
2484}
2485
de190aef
LP
2486static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) {
2487 Object *o;
2488 int r;
2489
2490 assert(f);
2491 assert(p > 0);
2492
2493 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
cec736d2
LP
2494 if (r < 0)
2495 return r;
2496
de190aef
LP
2497 if (le64toh(o->entry.seqnum) == needle)
2498 return TEST_FOUND;
2499 else if (le64toh(o->entry.seqnum) < needle)
2500 return TEST_LEFT;
2501 else
2502 return TEST_RIGHT;
2503}
cec736d2 2504
de190aef
LP
2505int journal_file_move_to_entry_by_seqnum(
2506 JournalFile *f,
2507 uint64_t seqnum,
2508 direction_t direction,
2509 Object **ret,
2510 uint64_t *offset) {
c88cc6af
VC
2511 assert(f);
2512 assert(f->header);
de190aef
LP
2513
2514 return generic_array_bisect(f,
2515 le64toh(f->header->entry_array_offset),
2516 le64toh(f->header->n_entries),
2517 seqnum,
2518 test_object_seqnum,
2519 direction,
2520 ret, offset, NULL);
2521}
cec736d2 2522
de190aef
LP
2523static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) {
2524 Object *o;
2525 int r;
2526
2527 assert(f);
2528 assert(p > 0);
2529
2530 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2531 if (r < 0)
2532 return r;
2533
2534 if (le64toh(o->entry.realtime) == needle)
2535 return TEST_FOUND;
2536 else if (le64toh(o->entry.realtime) < needle)
2537 return TEST_LEFT;
2538 else
2539 return TEST_RIGHT;
cec736d2
LP
2540}
2541
de190aef
LP
2542int journal_file_move_to_entry_by_realtime(
2543 JournalFile *f,
2544 uint64_t realtime,
2545 direction_t direction,
2546 Object **ret,
2547 uint64_t *offset) {
c88cc6af
VC
2548 assert(f);
2549 assert(f->header);
de190aef
LP
2550
2551 return generic_array_bisect(f,
2552 le64toh(f->header->entry_array_offset),
2553 le64toh(f->header->n_entries),
2554 realtime,
2555 test_object_realtime,
2556 direction,
2557 ret, offset, NULL);
2558}
2559
2560static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) {
2561 Object *o;
2562 int r;
2563
2564 assert(f);
2565 assert(p > 0);
2566
2567 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2568 if (r < 0)
2569 return r;
2570
2571 if (le64toh(o->entry.monotonic) == needle)
2572 return TEST_FOUND;
2573 else if (le64toh(o->entry.monotonic) < needle)
2574 return TEST_LEFT;
2575 else
2576 return TEST_RIGHT;
2577}
2578
2a560338 2579static int find_data_object_by_boot_id(
47838ab3
ZJS
2580 JournalFile *f,
2581 sd_id128_t boot_id,
2582 Object **o,
2583 uint64_t *b) {
2a560338 2584
47838ab3
ZJS
2585 char t[sizeof("_BOOT_ID=")-1 + 32 + 1] = "_BOOT_ID=";
2586
2587 sd_id128_to_string(boot_id, t + 9);
2588 return journal_file_find_data_object(f, t, sizeof(t) - 1, o, b);
2589}
2590
de190aef
LP
2591int journal_file_move_to_entry_by_monotonic(
2592 JournalFile *f,
2593 sd_id128_t boot_id,
2594 uint64_t monotonic,
2595 direction_t direction,
2596 Object **ret,
2597 uint64_t *offset) {
2598
de190aef
LP
2599 Object *o;
2600 int r;
2601
cbdca852 2602 assert(f);
de190aef 2603
47838ab3 2604 r = find_data_object_by_boot_id(f, boot_id, &o, NULL);
de190aef
LP
2605 if (r < 0)
2606 return r;
cbdca852 2607 if (r == 0)
de190aef
LP
2608 return -ENOENT;
2609
2610 return generic_array_bisect_plus_one(f,
2611 le64toh(o->data.entry_offset),
2612 le64toh(o->data.entry_array_offset),
2613 le64toh(o->data.n_entries),
2614 monotonic,
2615 test_object_monotonic,
2616 direction,
2617 ret, offset, NULL);
2618}
2619
1fc605b0 2620void journal_file_reset_location(JournalFile *f) {
6573ef05 2621 f->location_type = LOCATION_HEAD;
1fc605b0 2622 f->current_offset = 0;
6573ef05
MS
2623 f->current_seqnum = 0;
2624 f->current_realtime = 0;
2625 f->current_monotonic = 0;
2626 zero(f->current_boot_id);
2627 f->current_xor_hash = 0;
2628}
2629
950c07d4 2630void journal_file_save_location(JournalFile *f, Object *o, uint64_t offset) {
6573ef05
MS
2631 f->location_type = LOCATION_SEEK;
2632 f->current_offset = offset;
2633 f->current_seqnum = le64toh(o->entry.seqnum);
2634 f->current_realtime = le64toh(o->entry.realtime);
2635 f->current_monotonic = le64toh(o->entry.monotonic);
2636 f->current_boot_id = o->entry.boot_id;
2637 f->current_xor_hash = le64toh(o->entry.xor_hash);
1fc605b0
MS
2638}
2639
d8ae66d7
MS
2640int journal_file_compare_locations(JournalFile *af, JournalFile *bf) {
2641 assert(af);
c88cc6af 2642 assert(af->header);
d8ae66d7 2643 assert(bf);
c88cc6af 2644 assert(bf->header);
d8ae66d7
MS
2645 assert(af->location_type == LOCATION_SEEK);
2646 assert(bf->location_type == LOCATION_SEEK);
2647
2648 /* If contents and timestamps match, these entries are
2649 * identical, even if the seqnum does not match */
2650 if (sd_id128_equal(af->current_boot_id, bf->current_boot_id) &&
2651 af->current_monotonic == bf->current_monotonic &&
2652 af->current_realtime == bf->current_realtime &&
2653 af->current_xor_hash == bf->current_xor_hash)
2654 return 0;
2655
2656 if (sd_id128_equal(af->header->seqnum_id, bf->header->seqnum_id)) {
2657
2658 /* If this is from the same seqnum source, compare
2659 * seqnums */
2660 if (af->current_seqnum < bf->current_seqnum)
2661 return -1;
2662 if (af->current_seqnum > bf->current_seqnum)
2663 return 1;
2664
2665 /* Wow! This is weird, different data but the same
2666 * seqnums? Something is borked, but let's make the
2667 * best of it and compare by time. */
2668 }
2669
2670 if (sd_id128_equal(af->current_boot_id, bf->current_boot_id)) {
2671
2672 /* If the boot id matches, compare monotonic time */
2673 if (af->current_monotonic < bf->current_monotonic)
2674 return -1;
2675 if (af->current_monotonic > bf->current_monotonic)
2676 return 1;
2677 }
2678
2679 /* Otherwise, compare UTC time */
2680 if (af->current_realtime < bf->current_realtime)
2681 return -1;
2682 if (af->current_realtime > bf->current_realtime)
2683 return 1;
2684
2685 /* Finally, compare by contents */
2686 if (af->current_xor_hash < bf->current_xor_hash)
2687 return -1;
2688 if (af->current_xor_hash > bf->current_xor_hash)
2689 return 1;
2690
2691 return 0;
2692}
2693
aa598ba5
LP
2694static int bump_array_index(uint64_t *i, direction_t direction, uint64_t n) {
2695
2696 /* Increase or decrease the specified index, in the right direction. */
2697
2698 if (direction == DIRECTION_DOWN) {
2699 if (*i >= n - 1)
2700 return 0;
2701
2702 (*i) ++;
2703 } else {
2704 if (*i <= 0)
2705 return 0;
2706
2707 (*i) --;
2708 }
2709
2710 return 1;
2711}
2712
b6da4ed0
LP
2713static bool check_properly_ordered(uint64_t new_offset, uint64_t old_offset, direction_t direction) {
2714
2715 /* Consider it an error if any of the two offsets is uninitialized */
2716 if (old_offset == 0 || new_offset == 0)
2717 return false;
2718
2719 /* If we go down, the new offset must be larger than the old one. */
2720 return direction == DIRECTION_DOWN ?
2721 new_offset > old_offset :
2722 new_offset < old_offset;
2723}
2724
de190aef
LP
2725int journal_file_next_entry(
2726 JournalFile *f,
f534928a 2727 uint64_t p,
de190aef
LP
2728 direction_t direction,
2729 Object **ret, uint64_t *offset) {
2730
fb099c8d 2731 uint64_t i, n, ofs;
cec736d2
LP
2732 int r;
2733
2734 assert(f);
c88cc6af 2735 assert(f->header);
de190aef
LP
2736
2737 n = le64toh(f->header->n_entries);
2738 if (n <= 0)
2739 return 0;
cec736d2 2740
f534928a 2741 if (p == 0)
de190aef 2742 i = direction == DIRECTION_DOWN ? 0 : n - 1;
cec736d2 2743 else {
de190aef
LP
2744 r = generic_array_bisect(f,
2745 le64toh(f->header->entry_array_offset),
2746 le64toh(f->header->n_entries),
2747 p,
2748 test_object_offset,
2749 DIRECTION_DOWN,
2750 NULL, NULL,
2751 &i);
2752 if (r <= 0)
2753 return r;
2754
aa598ba5
LP
2755 r = bump_array_index(&i, direction, n);
2756 if (r <= 0)
2757 return r;
cec736d2
LP
2758 }
2759
de190aef 2760 /* And jump to it */
989793d3
LP
2761 for (;;) {
2762 r = generic_array_get(f,
2763 le64toh(f->header->entry_array_offset),
2764 i,
2765 ret, &ofs);
2766 if (r > 0)
2767 break;
2768 if (r != -EBADMSG)
2769 return r;
2770
2771 /* OK, so this entry is borked. Most likely some entry didn't get synced to disk properly, let's see if
2772 * the next one might work for us instead. */
2773 log_debug_errno(r, "Entry item %" PRIu64 " is bad, skipping over it.", i);
2774
2775 r = bump_array_index(&i, direction, n);
2776 if (r <= 0)
2777 return r;
caeab8f6 2778 }
fb099c8d 2779
b6da4ed0
LP
2780 /* Ensure our array is properly ordered. */
2781 if (p > 0 && !check_properly_ordered(ofs, p, direction)) {
2782 log_debug("%s: entry array not properly ordered at entry %" PRIu64, f->path, i);
fb099c8d
ZJS
2783 return -EBADMSG;
2784 }
2785
2786 if (offset)
2787 *offset = ofs;
2788
2789 return 1;
de190aef 2790}
cec736d2 2791
de190aef
LP
2792int journal_file_next_entry_for_data(
2793 JournalFile *f,
2794 Object *o, uint64_t p,
2795 uint64_t data_offset,
2796 direction_t direction,
2797 Object **ret, uint64_t *offset) {
2798
ded5034e 2799 uint64_t i, n, ofs;
de190aef 2800 Object *d;
989793d3 2801 int r;
cec736d2
LP
2802
2803 assert(f);
de190aef 2804 assert(p > 0 || !o);
cec736d2 2805
de190aef 2806 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
466ccd92 2807 if (r < 0)
de190aef 2808 return r;
cec736d2 2809
de190aef
LP
2810 n = le64toh(d->data.n_entries);
2811 if (n <= 0)
2812 return n;
cec736d2 2813
de190aef
LP
2814 if (!o)
2815 i = direction == DIRECTION_DOWN ? 0 : n - 1;
2816 else {
2817 if (o->object.type != OBJECT_ENTRY)
2818 return -EINVAL;
cec736d2 2819
de190aef
LP
2820 r = generic_array_bisect_plus_one(f,
2821 le64toh(d->data.entry_offset),
2822 le64toh(d->data.entry_array_offset),
2823 le64toh(d->data.n_entries),
2824 p,
2825 test_object_offset,
2826 DIRECTION_DOWN,
2827 NULL, NULL,
2828 &i);
2829
2830 if (r <= 0)
cec736d2
LP
2831 return r;
2832
aa598ba5
LP
2833 r = bump_array_index(&i, direction, n);
2834 if (r <= 0)
2835 return r;
de190aef 2836 }
cec736d2 2837
989793d3
LP
2838 for (;;) {
2839 r = generic_array_get_plus_one(f,
2840 le64toh(d->data.entry_offset),
2841 le64toh(d->data.entry_array_offset),
2842 i,
2843 ret, &ofs);
2844 if (r > 0)
2845 break;
2846 if (r != -EBADMSG)
2847 return r;
2848
2849 log_debug_errno(r, "Data entry item %" PRIu64 " is bad, skipping over it.", i);
2850
2851 r = bump_array_index(&i, direction, n);
2852 if (r <= 0)
2853 return r;
2854 }
ded5034e
LP
2855
2856 /* Ensure our array is properly ordered. */
2857 if (p > 0 && check_properly_ordered(ofs, p, direction)) {
2858 log_debug("%s data entry array not properly ordered at entry %" PRIu64, f->path, i);
2859 return -EBADMSG;
2860 }
2861
2862 if (offset)
2863 *offset = ofs;
2864
2865 return 1;
de190aef 2866}
cec736d2 2867
cbdca852
LP
2868int journal_file_move_to_entry_by_offset_for_data(
2869 JournalFile *f,
2870 uint64_t data_offset,
2871 uint64_t p,
2872 direction_t direction,
2873 Object **ret, uint64_t *offset) {
2874
2875 int r;
2876 Object *d;
2877
2878 assert(f);
2879
2880 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
2881 if (r < 0)
2882 return r;
2883
2884 return generic_array_bisect_plus_one(f,
2885 le64toh(d->data.entry_offset),
2886 le64toh(d->data.entry_array_offset),
2887 le64toh(d->data.n_entries),
2888 p,
2889 test_object_offset,
2890 direction,
2891 ret, offset, NULL);
2892}
2893
2894int journal_file_move_to_entry_by_monotonic_for_data(
2895 JournalFile *f,
2896 uint64_t data_offset,
2897 sd_id128_t boot_id,
2898 uint64_t monotonic,
2899 direction_t direction,
2900 Object **ret, uint64_t *offset) {
2901
cbdca852
LP
2902 Object *o, *d;
2903 int r;
2904 uint64_t b, z;
2905
2906 assert(f);
2907
2908 /* First, seek by time */
47838ab3 2909 r = find_data_object_by_boot_id(f, boot_id, &o, &b);
cbdca852
LP
2910 if (r < 0)
2911 return r;
2912 if (r == 0)
2913 return -ENOENT;
2914
2915 r = generic_array_bisect_plus_one(f,
2916 le64toh(o->data.entry_offset),
2917 le64toh(o->data.entry_array_offset),
2918 le64toh(o->data.n_entries),
2919 monotonic,
2920 test_object_monotonic,
2921 direction,
2922 NULL, &z, NULL);
2923 if (r <= 0)
2924 return r;
2925
2926 /* And now, continue seeking until we find an entry that
2927 * exists in both bisection arrays */
2928
2929 for (;;) {
2930 Object *qo;
2931 uint64_t p, q;
2932
2933 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
2934 if (r < 0)
2935 return r;
2936
2937 r = generic_array_bisect_plus_one(f,
2938 le64toh(d->data.entry_offset),
2939 le64toh(d->data.entry_array_offset),
2940 le64toh(d->data.n_entries),
2941 z,
2942 test_object_offset,
2943 direction,
2944 NULL, &p, NULL);
2945 if (r <= 0)
2946 return r;
2947
2948 r = journal_file_move_to_object(f, OBJECT_DATA, b, &o);
2949 if (r < 0)
2950 return r;
2951
2952 r = generic_array_bisect_plus_one(f,
2953 le64toh(o->data.entry_offset),
2954 le64toh(o->data.entry_array_offset),
2955 le64toh(o->data.n_entries),
2956 p,
2957 test_object_offset,
2958 direction,
2959 &qo, &q, NULL);
2960
2961 if (r <= 0)
2962 return r;
2963
2964 if (p == q) {
2965 if (ret)
2966 *ret = qo;
2967 if (offset)
2968 *offset = q;
2969
2970 return 1;
2971 }
2972
2973 z = q;
2974 }
cbdca852
LP
2975}
2976
de190aef
LP
2977int journal_file_move_to_entry_by_seqnum_for_data(
2978 JournalFile *f,
2979 uint64_t data_offset,
2980 uint64_t seqnum,
2981 direction_t direction,
2982 Object **ret, uint64_t *offset) {
cec736d2 2983
de190aef
LP
2984 Object *d;
2985 int r;
cec736d2 2986
91a31dde
LP
2987 assert(f);
2988
de190aef 2989 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
91a31dde 2990 if (r < 0)
de190aef 2991 return r;
cec736d2 2992
de190aef
LP
2993 return generic_array_bisect_plus_one(f,
2994 le64toh(d->data.entry_offset),
2995 le64toh(d->data.entry_array_offset),
2996 le64toh(d->data.n_entries),
2997 seqnum,
2998 test_object_seqnum,
2999 direction,
3000 ret, offset, NULL);
3001}
cec736d2 3002
de190aef
LP
3003int journal_file_move_to_entry_by_realtime_for_data(
3004 JournalFile *f,
3005 uint64_t data_offset,
3006 uint64_t realtime,
3007 direction_t direction,
3008 Object **ret, uint64_t *offset) {
3009
3010 Object *d;
3011 int r;
3012
91a31dde
LP
3013 assert(f);
3014
de190aef 3015 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
91a31dde 3016 if (r < 0)
de190aef
LP
3017 return r;
3018
3019 return generic_array_bisect_plus_one(f,
3020 le64toh(d->data.entry_offset),
3021 le64toh(d->data.entry_array_offset),
3022 le64toh(d->data.n_entries),
3023 realtime,
3024 test_object_realtime,
3025 direction,
3026 ret, offset, NULL);
cec736d2
LP
3027}
3028
0284adc6 3029void journal_file_dump(JournalFile *f) {
7560fffc 3030 Object *o;
7560fffc 3031 int r;
0284adc6 3032 uint64_t p;
7560fffc
LP
3033
3034 assert(f);
c88cc6af 3035 assert(f->header);
7560fffc 3036
0284adc6 3037 journal_file_print_header(f);
7560fffc 3038
0284adc6
LP
3039 p = le64toh(f->header->header_size);
3040 while (p != 0) {
d05089d8 3041 r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o);
0284adc6
LP
3042 if (r < 0)
3043 goto fail;
7560fffc 3044
0284adc6 3045 switch (o->object.type) {
d98cc1f2 3046
0284adc6
LP
3047 case OBJECT_UNUSED:
3048 printf("Type: OBJECT_UNUSED\n");
3049 break;
d98cc1f2 3050
0284adc6
LP
3051 case OBJECT_DATA:
3052 printf("Type: OBJECT_DATA\n");
3053 break;
7560fffc 3054
3c1668da
LP
3055 case OBJECT_FIELD:
3056 printf("Type: OBJECT_FIELD\n");
3057 break;
3058
0284adc6 3059 case OBJECT_ENTRY:
507f22bd
ZJS
3060 printf("Type: OBJECT_ENTRY seqnum=%"PRIu64" monotonic=%"PRIu64" realtime=%"PRIu64"\n",
3061 le64toh(o->entry.seqnum),
3062 le64toh(o->entry.monotonic),
3063 le64toh(o->entry.realtime));
0284adc6 3064 break;
7560fffc 3065
0284adc6
LP
3066 case OBJECT_FIELD_HASH_TABLE:
3067 printf("Type: OBJECT_FIELD_HASH_TABLE\n");
3068 break;
7560fffc 3069
0284adc6
LP
3070 case OBJECT_DATA_HASH_TABLE:
3071 printf("Type: OBJECT_DATA_HASH_TABLE\n");
3072 break;
7560fffc 3073
0284adc6
LP
3074 case OBJECT_ENTRY_ARRAY:
3075 printf("Type: OBJECT_ENTRY_ARRAY\n");
3076 break;
7560fffc 3077
0284adc6 3078 case OBJECT_TAG:
507f22bd
ZJS
3079 printf("Type: OBJECT_TAG seqnum=%"PRIu64" epoch=%"PRIu64"\n",
3080 le64toh(o->tag.seqnum),
3081 le64toh(o->tag.epoch));
0284adc6 3082 break;
3c1668da
LP
3083
3084 default:
8facc349 3085 printf("Type: unknown (%i)\n", o->object.type);
3c1668da 3086 break;
0284adc6 3087 }
7560fffc 3088
d89c8fdf
ZJS
3089 if (o->object.flags & OBJECT_COMPRESSION_MASK)
3090 printf("Flags: %s\n",
3091 object_compressed_to_string(o->object.flags & OBJECT_COMPRESSION_MASK));
7560fffc 3092
0284adc6
LP
3093 if (p == le64toh(f->header->tail_object_offset))
3094 p = 0;
3095 else
3096 p = p + ALIGN64(le64toh(o->object.size));
3097 }
7560fffc 3098
0284adc6
LP
3099 return;
3100fail:
3101 log_error("File corrupt");
7560fffc
LP
3102}
3103
718fe4b1
ZJS
3104static const char* format_timestamp_safe(char *buf, size_t l, usec_t t) {
3105 const char *x;
3106
3107 x = format_timestamp(buf, l, t);
3108 if (x)
3109 return x;
3110 return " --- ";
3111}
3112
0284adc6 3113void journal_file_print_header(JournalFile *f) {
2765b7bb 3114 char a[33], b[33], c[33], d[33];
ed375beb 3115 char x[FORMAT_TIMESTAMP_MAX], y[FORMAT_TIMESTAMP_MAX], z[FORMAT_TIMESTAMP_MAX];
a1a03e30
LP
3116 struct stat st;
3117 char bytes[FORMAT_BYTES_MAX];
7560fffc
LP
3118
3119 assert(f);
c88cc6af 3120 assert(f->header);
7560fffc 3121
0284adc6
LP
3122 printf("File Path: %s\n"
3123 "File ID: %s\n"
3124 "Machine ID: %s\n"
3125 "Boot ID: %s\n"
3126 "Sequential Number ID: %s\n"
3127 "State: %s\n"
3128 "Compatible Flags:%s%s\n"
d89c8fdf 3129 "Incompatible Flags:%s%s%s\n"
507f22bd
ZJS
3130 "Header size: %"PRIu64"\n"
3131 "Arena size: %"PRIu64"\n"
3132 "Data Hash Table Size: %"PRIu64"\n"
3133 "Field Hash Table Size: %"PRIu64"\n"
0284adc6 3134 "Rotate Suggested: %s\n"
0808b92f
LP
3135 "Head Sequential Number: %"PRIu64" (%"PRIx64")\n"
3136 "Tail Sequential Number: %"PRIu64" (%"PRIx64")\n"
3137 "Head Realtime Timestamp: %s (%"PRIx64")\n"
3138 "Tail Realtime Timestamp: %s (%"PRIx64")\n"
3139 "Tail Monotonic Timestamp: %s (%"PRIx64")\n"
507f22bd
ZJS
3140 "Objects: %"PRIu64"\n"
3141 "Entry Objects: %"PRIu64"\n",
0284adc6
LP
3142 f->path,
3143 sd_id128_to_string(f->header->file_id, a),
3144 sd_id128_to_string(f->header->machine_id, b),
3145 sd_id128_to_string(f->header->boot_id, c),
2765b7bb 3146 sd_id128_to_string(f->header->seqnum_id, d),
3223f44f
LP
3147 f->header->state == STATE_OFFLINE ? "OFFLINE" :
3148 f->header->state == STATE_ONLINE ? "ONLINE" :
3149 f->header->state == STATE_ARCHIVED ? "ARCHIVED" : "UNKNOWN",
8088cbd3 3150 JOURNAL_HEADER_SEALED(f->header) ? " SEALED" : "",
d89c8fdf
ZJS
3151 (le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_ANY) ? " ???" : "",
3152 JOURNAL_HEADER_COMPRESSED_XZ(f->header) ? " COMPRESSED-XZ" : "",
3153 JOURNAL_HEADER_COMPRESSED_LZ4(f->header) ? " COMPRESSED-LZ4" : "",
3154 (le32toh(f->header->incompatible_flags) & ~HEADER_INCOMPATIBLE_ANY) ? " ???" : "",
507f22bd
ZJS
3155 le64toh(f->header->header_size),
3156 le64toh(f->header->arena_size),
3157 le64toh(f->header->data_hash_table_size) / sizeof(HashItem),
3158 le64toh(f->header->field_hash_table_size) / sizeof(HashItem),
fb0951b0 3159 yes_no(journal_file_rotate_suggested(f, 0)),
0808b92f
LP
3160 le64toh(f->header->head_entry_seqnum), le64toh(f->header->head_entry_seqnum),
3161 le64toh(f->header->tail_entry_seqnum), le64toh(f->header->tail_entry_seqnum),
3162 format_timestamp_safe(x, sizeof(x), le64toh(f->header->head_entry_realtime)), le64toh(f->header->head_entry_realtime),
3163 format_timestamp_safe(y, sizeof(y), le64toh(f->header->tail_entry_realtime)), le64toh(f->header->tail_entry_realtime),
3164 format_timespan(z, sizeof(z), le64toh(f->header->tail_entry_monotonic), USEC_PER_MSEC), le64toh(f->header->tail_entry_monotonic),
507f22bd
ZJS
3165 le64toh(f->header->n_objects),
3166 le64toh(f->header->n_entries));
7560fffc 3167
0284adc6 3168 if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
507f22bd 3169 printf("Data Objects: %"PRIu64"\n"
0284adc6 3170 "Data Hash Table Fill: %.1f%%\n",
507f22bd 3171 le64toh(f->header->n_data),
0284adc6 3172 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))));
7560fffc 3173
0284adc6 3174 if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
507f22bd 3175 printf("Field Objects: %"PRIu64"\n"
0284adc6 3176 "Field Hash Table Fill: %.1f%%\n",
507f22bd 3177 le64toh(f->header->n_fields),
0284adc6 3178 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))));
3223f44f
LP
3179
3180 if (JOURNAL_HEADER_CONTAINS(f->header, n_tags))
507f22bd
ZJS
3181 printf("Tag Objects: %"PRIu64"\n",
3182 le64toh(f->header->n_tags));
3223f44f 3183 if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
507f22bd
ZJS
3184 printf("Entry Array Objects: %"PRIu64"\n",
3185 le64toh(f->header->n_entry_arrays));
a1a03e30
LP
3186
3187 if (fstat(f->fd, &st) >= 0)
59f448cf 3188 printf("Disk usage: %s\n", format_bytes(bytes, sizeof(bytes), (uint64_t) st.st_blocks * 512ULL));
7560fffc
LP
3189}
3190
fc68c929
LP
3191static int journal_file_warn_btrfs(JournalFile *f) {
3192 unsigned attrs;
3193 int r;
3194
3195 assert(f);
3196
3197 /* Before we write anything, check if the COW logic is turned
3198 * off on btrfs. Given our write pattern that is quite
3199 * unfriendly to COW file systems this should greatly improve
3200 * performance on COW file systems, such as btrfs, at the
3201 * expense of data integrity features (which shouldn't be too
3202 * bad, given that we do our own checksumming). */
3203
3204 r = btrfs_is_filesystem(f->fd);
3205 if (r < 0)
3206 return log_warning_errno(r, "Failed to determine if journal is on btrfs: %m");
3207 if (!r)
3208 return 0;
3209
3210 r = read_attr_fd(f->fd, &attrs);
3211 if (r < 0)
3212 return log_warning_errno(r, "Failed to read file attributes: %m");
3213
3214 if (attrs & FS_NOCOW_FL) {
3215 log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
3216 return 0;
3217 }
3218
3219 log_notice("Creating journal file %s on a btrfs file system, and copy-on-write is enabled. "
3220 "This is likely to slow down journal access substantially, please consider turning "
3221 "off the copy-on-write file attribute on the journal directory, using chattr +C.", f->path);
3222
3223 return 1;
3224}
3225
0284adc6 3226int journal_file_open(
5d1ce257 3227 int fd,
0284adc6
LP
3228 const char *fname,
3229 int flags,
3230 mode_t mode,
3231 bool compress,
baed47c3 3232 bool seal,
0284adc6
LP
3233 JournalMetrics *metrics,
3234 MMapCache *mmap_cache,
b58c888f 3235 Set *deferred_closes,
0284adc6
LP
3236 JournalFile *template,
3237 JournalFile **ret) {
7560fffc 3238
fa6ac760 3239 bool newly_created = false;
0284adc6 3240 JournalFile *f;
fa6ac760 3241 void *h;
0284adc6 3242 int r;
7560fffc 3243
0559d3a5 3244 assert(ret);
5d1ce257 3245 assert(fd >= 0 || fname);
7560fffc 3246
ec2ce0c5 3247 if (!IN_SET((flags & O_ACCMODE), O_RDONLY, O_RDWR))
0284adc6 3248 return -EINVAL;
7560fffc 3249
5d1ce257
LP
3250 if (fname) {
3251 if (!endswith(fname, ".journal") &&
3252 !endswith(fname, ".journal~"))
3253 return -EINVAL;
3254 }
7560fffc 3255
0284adc6
LP
3256 f = new0(JournalFile, 1);
3257 if (!f)
3258 return -ENOMEM;
7560fffc 3259
5d1ce257 3260 f->fd = fd;
0284adc6 3261 f->mode = mode;
7560fffc 3262
0284adc6
LP
3263 f->flags = flags;
3264 f->prot = prot_from_flags(flags);
3265 f->writable = (flags & O_ACCMODE) != O_RDONLY;
349cc4a5 3266#if HAVE_LZ4
d89c8fdf 3267 f->compress_lz4 = compress;
349cc4a5 3268#elif HAVE_XZ
d89c8fdf 3269 f->compress_xz = compress;
48b61739 3270#endif
349cc4a5 3271#if HAVE_GCRYPT
baed47c3 3272 f->seal = seal;
49a32d43 3273#endif
7560fffc 3274
0284adc6
LP
3275 if (mmap_cache)
3276 f->mmap = mmap_cache_ref(mmap_cache);
3277 else {
84168d80 3278 f->mmap = mmap_cache_new();
0284adc6
LP
3279 if (!f->mmap) {
3280 r = -ENOMEM;
3281 goto fail;
3282 }
3283 }
7560fffc 3284
7645c77b 3285 if (fname) {
5d1ce257 3286 f->path = strdup(fname);
7645c77b
ZJS
3287 if (!f->path) {
3288 r = -ENOMEM;
3289 goto fail;
3290 }
3291 } else {
3292 /* If we don't know the path, fill in something explanatory and vaguely useful */
3293 if (asprintf(&f->path, "/proc/self/%i", fd) < 0) {
3294 r = -ENOMEM;
3295 goto fail;
3296 }
0284adc6 3297 }
7560fffc 3298
4743015d 3299 f->chain_cache = ordered_hashmap_new(&uint64_hash_ops);
a4bcff5b
LP
3300 if (!f->chain_cache) {
3301 r = -ENOMEM;
3302 goto fail;
3303 }
3304
0284adc6 3305 if (f->fd < 0) {
5d1ce257
LP
3306 f->fd = open(f->path, f->flags|O_CLOEXEC, f->mode);
3307 if (f->fd < 0) {
3308 r = -errno;
3309 goto fail;
3310 }
3311
3312 /* fds we opened here by us should also be closed by us. */
3313 f->close_fd = true;
7560fffc 3314 }
7560fffc 3315
be7cdd8e
VC
3316 f->cache_fd = mmap_cache_add_fd(f->mmap, f->fd);
3317 if (!f->cache_fd) {
3318 r = -ENOMEM;
3319 goto fail;
3320 }
3321
2678031a
LP
3322 r = journal_file_fstat(f);
3323 if (r < 0)
0284adc6 3324 goto fail;
7560fffc 3325
0284adc6 3326 if (f->last_stat.st_size == 0 && f->writable) {
11689d2a 3327
fc68c929 3328 (void) journal_file_warn_btrfs(f);
11689d2a 3329
fb0951b0
LP
3330 /* Let's attach the creation time to the journal file,
3331 * so that the vacuuming code knows the age of this
3332 * file even if the file might end up corrupted one
3333 * day... Ideally we'd just use the creation time many
3334 * file systems maintain for each file, but there is
3335 * currently no usable API to query this, hence let's
3336 * emulate this via extended attributes. If extended
3337 * attributes are not supported we'll just skip this,
7517e174 3338 * and rely solely on mtime/atime/ctime of the file. */
fb0951b0 3339
d61b600d 3340 fd_setcrtime(f->fd, 0);
7560fffc 3341
349cc4a5 3342#if HAVE_GCRYPT
0284adc6 3343 /* Try to load the FSPRG state, and if we can't, then
baed47c3 3344 * just don't do sealing */
49a32d43
LP
3345 if (f->seal) {
3346 r = journal_file_fss_load(f);
3347 if (r < 0)
3348 f->seal = false;
3349 }
feb12d3e 3350#endif
7560fffc 3351
0284adc6
LP
3352 r = journal_file_init_header(f, template);
3353 if (r < 0)
3354 goto fail;
7560fffc 3355
2678031a
LP
3356 r = journal_file_fstat(f);
3357 if (r < 0)
0284adc6 3358 goto fail;
fb0951b0
LP
3359
3360 newly_created = true;
0284adc6 3361 }
7560fffc 3362
0284adc6 3363 if (f->last_stat.st_size < (off_t) HEADER_SIZE_MIN) {
cfb571f3 3364 r = -ENODATA;
0284adc6
LP
3365 goto fail;
3366 }
7560fffc 3367
b42549ad 3368 r = mmap_cache_get(f->mmap, f->cache_fd, f->prot, CONTEXT_HEADER, true, 0, PAGE_ALIGN(sizeof(Header)), &f->last_stat, &h, NULL);
977eaa1e 3369 if (r < 0)
0284adc6 3370 goto fail;
7560fffc 3371
fa6ac760
LP
3372 f->header = h;
3373
0284adc6 3374 if (!newly_created) {
b58c888f
VC
3375 if (deferred_closes)
3376 journal_file_close_set(deferred_closes);
3377
0284adc6
LP
3378 r = journal_file_verify_header(f);
3379 if (r < 0)
3380 goto fail;
3381 }
7560fffc 3382
349cc4a5 3383#if HAVE_GCRYPT
0284adc6 3384 if (!newly_created && f->writable) {
baed47c3 3385 r = journal_file_fss_load(f);
0284adc6
LP
3386 if (r < 0)
3387 goto fail;
3388 }
feb12d3e 3389#endif
cec736d2
LP
3390
3391 if (f->writable) {
4a92baf3
LP
3392 if (metrics) {
3393 journal_default_metrics(metrics, f->fd);
3394 f->metrics = *metrics;
3395 } else if (template)
3396 f->metrics = template->metrics;
3397
cec736d2
LP
3398 r = journal_file_refresh_header(f);
3399 if (r < 0)
3400 goto fail;
3401 }
3402
349cc4a5 3403#if HAVE_GCRYPT
baed47c3 3404 r = journal_file_hmac_setup(f);
14d10188
LP
3405 if (r < 0)
3406 goto fail;
feb12d3e 3407#endif
14d10188 3408
cec736d2 3409 if (newly_created) {
de190aef 3410 r = journal_file_setup_field_hash_table(f);
cec736d2
LP
3411 if (r < 0)
3412 goto fail;
3413
de190aef 3414 r = journal_file_setup_data_hash_table(f);
cec736d2
LP
3415 if (r < 0)
3416 goto fail;
7560fffc 3417
349cc4a5 3418#if HAVE_GCRYPT
7560fffc
LP
3419 r = journal_file_append_first_tag(f);
3420 if (r < 0)
3421 goto fail;
feb12d3e 3422#endif
cec736d2
LP
3423 }
3424
be7cdd8e 3425 if (mmap_cache_got_sigbus(f->mmap, f->cache_fd)) {
fa6ac760
LP
3426 r = -EIO;
3427 goto fail;
3428 }
3429
7a24f3bf 3430 if (template && template->post_change_timer) {
e167d7fd
LP
3431 r = journal_file_enable_post_change_timer(
3432 f,
3433 sd_event_source_get_event(template->post_change_timer),
3434 template->post_change_timer_period);
7a24f3bf 3435
7a24f3bf
VC
3436 if (r < 0)
3437 goto fail;
3438 }
3439
f8e2f4d6 3440 /* The file is opened now successfully, thus we take possession of any passed in fd. */
5d1ce257
LP
3441 f->close_fd = true;
3442
0559d3a5 3443 *ret = f;
cec736d2
LP
3444 return 0;
3445
3446fail:
be7cdd8e 3447 if (f->cache_fd && mmap_cache_got_sigbus(f->mmap, f->cache_fd))
fa6ac760
LP
3448 r = -EIO;
3449
69a3a6fd 3450 (void) journal_file_close(f);
cec736d2
LP
3451
3452 return r;
3453}
0ac38b70 3454
b58c888f 3455int journal_file_rotate(JournalFile **f, bool compress, bool seal, Set *deferred_closes) {
57535f47 3456 _cleanup_free_ char *p = NULL;
0ac38b70
LP
3457 size_t l;
3458 JournalFile *old_file, *new_file = NULL;
3459 int r;
3460
3461 assert(f);
3462 assert(*f);
3463
3464 old_file = *f;
3465
3466 if (!old_file->writable)
3467 return -EINVAL;
3468
5d1ce257 3469 /* Is this a journal file that was passed to us as fd? If so, we synthesized a path name for it, and we refuse
13e785f7 3470 * rotation, since we don't know the actual path, and couldn't rename the file hence. */
5d1ce257
LP
3471 if (path_startswith(old_file->path, "/proc/self/fd"))
3472 return -EINVAL;
3473
0ac38b70
LP
3474 if (!endswith(old_file->path, ".journal"))
3475 return -EINVAL;
3476
3477 l = strlen(old_file->path);
57535f47
ZJS
3478 r = asprintf(&p, "%.*s@" SD_ID128_FORMAT_STR "-%016"PRIx64"-%016"PRIx64".journal",
3479 (int) l - 8, old_file->path,
3480 SD_ID128_FORMAT_VAL(old_file->header->seqnum_id),
3481 le64toh((*f)->header->head_entry_seqnum),
3482 le64toh((*f)->header->head_entry_realtime));
3483 if (r < 0)
0ac38b70
LP
3484 return -ENOMEM;
3485
2678031a
LP
3486 /* Try to rename the file to the archived version. If the file
3487 * already was deleted, we'll get ENOENT, let's ignore that
3488 * case. */
0ac38b70 3489 r = rename(old_file->path, p);
2678031a 3490 if (r < 0 && errno != ENOENT)
0ac38b70
LP
3491 return -errno;
3492
1fcefd88
LP
3493 /* Sync the rename to disk */
3494 (void) fsync_directory_of_file(old_file->fd);
3495
8eb85171
VC
3496 /* Set as archive so offlining commits w/state=STATE_ARCHIVED.
3497 * Previously we would set old_file->header->state to STATE_ARCHIVED directly here,
3498 * but journal_file_set_offline() short-circuits when state != STATE_ONLINE, which
3499 * would result in the rotated journal never getting fsync() called before closing.
3500 * Now we simply queue the archive state by setting an archive bit, leaving the state
3501 * as STATE_ONLINE so proper offlining occurs. */
3502 old_file->archive = true;
0ac38b70 3503
f27a3864
LP
3504 /* Currently, btrfs is not very good with out write patterns
3505 * and fragments heavily. Let's defrag our journal files when
3506 * we archive them */
3507 old_file->defrag_on_close = true;
3508
5d1ce257 3509 r = journal_file_open(-1, old_file->path, old_file->flags, old_file->mode, compress, seal, NULL, old_file->mmap, deferred_closes, old_file, &new_file);
b58c888f
VC
3510
3511 if (deferred_closes &&
3512 set_put(deferred_closes, old_file) >= 0)
3513 (void) journal_file_set_offline(old_file, false);
3514 else
3515 (void) journal_file_close(old_file);
0ac38b70
LP
3516
3517 *f = new_file;
3518 return r;
3519}
3520
9447a7f1
LP
3521int journal_file_open_reliably(
3522 const char *fname,
3523 int flags,
3524 mode_t mode,
7560fffc 3525 bool compress,
baed47c3 3526 bool seal,
4a92baf3 3527 JournalMetrics *metrics,
27370278 3528 MMapCache *mmap_cache,
b58c888f 3529 Set *deferred_closes,
9447a7f1
LP
3530 JournalFile *template,
3531 JournalFile **ret) {
3532
3533 int r;
3534 size_t l;
ed375beb 3535 _cleanup_free_ char *p = NULL;
9447a7f1 3536
5d1ce257 3537 r = journal_file_open(-1, fname, flags, mode, compress, seal, metrics, mmap_cache, deferred_closes, template, ret);
288359db 3538 if (!IN_SET(r,
b288cdeb
ZJS
3539 -EBADMSG, /* Corrupted */
3540 -ENODATA, /* Truncated */
3541 -EHOSTDOWN, /* Other machine */
3542 -EPROTONOSUPPORT, /* Incompatible feature */
3543 -EBUSY, /* Unclean shutdown */
3544 -ESHUTDOWN, /* Already archived */
288359db 3545 -EIO, /* IO error, including SIGBUS on mmap */
ae739cc1
LP
3546 -EIDRM, /* File has been deleted */
3547 -ETXTBSY)) /* File is from the future */
9447a7f1
LP
3548 return r;
3549
3550 if ((flags & O_ACCMODE) == O_RDONLY)
3551 return r;
3552
3553 if (!(flags & O_CREAT))
3554 return r;
3555
7560fffc
LP
3556 if (!endswith(fname, ".journal"))
3557 return r;
3558
5c70eab4
LP
3559 /* The file is corrupted. Rotate it away and try it again (but only once) */
3560
9447a7f1 3561 l = strlen(fname);
d587eca5 3562 if (asprintf(&p, "%.*s@%016"PRIx64 "-%016"PRIx64 ".journal~",
57535f47 3563 (int) l - 8, fname,
d587eca5 3564 now(CLOCK_REALTIME),
9bf3b535 3565 random_u64()) < 0)
9447a7f1
LP
3566 return -ENOMEM;
3567
65089b82 3568 if (rename(fname, p) < 0)
9447a7f1
LP
3569 return -errno;
3570
f27a3864
LP
3571 /* btrfs doesn't cope well with our write pattern and
3572 * fragments heavily. Let's defrag all files we rotate */
11689d2a 3573
a67d68b8 3574 (void) chattr_path(p, 0, FS_NOCOW_FL);
f27a3864
LP
3575 (void) btrfs_defrag(p);
3576
65089b82 3577 log_warning_errno(r, "File %s corrupted or uncleanly shut down, renaming and replacing.", fname);
9447a7f1 3578
5d1ce257 3579 return journal_file_open(-1, fname, flags, mode, compress, seal, metrics, mmap_cache, deferred_closes, template, ret);
9447a7f1
LP
3580}
3581
cf244689
LP
3582int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset) {
3583 uint64_t i, n;
3584 uint64_t q, xor_hash = 0;
3585 int r;
3586 EntryItem *items;
3587 dual_timestamp ts;
3588
3589 assert(from);
3590 assert(to);
3591 assert(o);
3592 assert(p);
3593
3594 if (!to->writable)
3595 return -EPERM;
3596
3597 ts.monotonic = le64toh(o->entry.monotonic);
3598 ts.realtime = le64toh(o->entry.realtime);
3599
cf244689 3600 n = journal_file_entry_n_items(o);
4faa7004
TA
3601 /* alloca() can't take 0, hence let's allocate at least one */
3602 items = alloca(sizeof(EntryItem) * MAX(1u, n));
cf244689
LP
3603
3604 for (i = 0; i < n; i++) {
4fd052ae
FC
3605 uint64_t l, h;
3606 le64_t le_hash;
cf244689
LP
3607 size_t t;
3608 void *data;
3609 Object *u;
3610
3611 q = le64toh(o->entry.items[i].object_offset);
3612 le_hash = o->entry.items[i].hash;
3613
3614 r = journal_file_move_to_object(from, OBJECT_DATA, q, &o);
3615 if (r < 0)
3616 return r;
3617
3618 if (le_hash != o->data.hash)
3619 return -EBADMSG;
3620
3621 l = le64toh(o->object.size) - offsetof(Object, data.payload);
3622 t = (size_t) l;
3623
3624 /* We hit the limit on 32bit machines */
3625 if ((uint64_t) t != l)
3626 return -E2BIG;
3627
d89c8fdf 3628 if (o->object.flags & OBJECT_COMPRESSION_MASK) {
349cc4a5 3629#if HAVE_XZ || HAVE_LZ4
a7f7d1bd 3630 size_t rsize = 0;
cf244689 3631
d89c8fdf
ZJS
3632 r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK,
3633 o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize, 0);
3634 if (r < 0)
3635 return r;
cf244689
LP
3636
3637 data = from->compress_buffer;
3638 l = rsize;
3b1a55e1
ZJS
3639#else
3640 return -EPROTONOSUPPORT;
3641#endif
cf244689
LP
3642 } else
3643 data = o->data.payload;
3644
3645 r = journal_file_append_data(to, data, l, &u, &h);
3646 if (r < 0)
3647 return r;
3648
3649 xor_hash ^= le64toh(u->data.hash);
3650 items[i].object_offset = htole64(h);
3651 items[i].hash = u->data.hash;
3652
3653 r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
3654 if (r < 0)
3655 return r;
3656 }
3657
fa6ac760
LP
3658 r = journal_file_append_entry_internal(to, &ts, xor_hash, items, n, seqnum, ret, offset);
3659
be7cdd8e 3660 if (mmap_cache_got_sigbus(to->mmap, to->cache_fd))
fa6ac760
LP
3661 return -EIO;
3662
3663 return r;
cf244689 3664}
babfc091 3665
8580d1f7
LP
3666void journal_reset_metrics(JournalMetrics *m) {
3667 assert(m);
3668
3669 /* Set everything to "pick automatic values". */
3670
3671 *m = (JournalMetrics) {
3672 .min_use = (uint64_t) -1,
3673 .max_use = (uint64_t) -1,
3674 .min_size = (uint64_t) -1,
3675 .max_size = (uint64_t) -1,
3676 .keep_free = (uint64_t) -1,
3677 .n_max_files = (uint64_t) -1,
3678 };
3679}
3680
babfc091 3681void journal_default_metrics(JournalMetrics *m, int fd) {
8580d1f7 3682 char a[FORMAT_BYTES_MAX], b[FORMAT_BYTES_MAX], c[FORMAT_BYTES_MAX], d[FORMAT_BYTES_MAX], e[FORMAT_BYTES_MAX];
babfc091 3683 struct statvfs ss;
8580d1f7 3684 uint64_t fs_size;
babfc091
LP
3685
3686 assert(m);
3687 assert(fd >= 0);
3688
3689 if (fstatvfs(fd, &ss) >= 0)
3690 fs_size = ss.f_frsize * ss.f_blocks;
8580d1f7
LP
3691 else {
3692 log_debug_errno(errno, "Failed to detremine disk size: %m");
3693 fs_size = 0;
3694 }
babfc091
LP
3695
3696 if (m->max_use == (uint64_t) -1) {
3697
3698 if (fs_size > 0) {
3699 m->max_use = PAGE_ALIGN(fs_size / 10); /* 10% of file system size */
3700
3701 if (m->max_use > DEFAULT_MAX_USE_UPPER)
3702 m->max_use = DEFAULT_MAX_USE_UPPER;
3703
3704 if (m->max_use < DEFAULT_MAX_USE_LOWER)
3705 m->max_use = DEFAULT_MAX_USE_LOWER;
3706 } else
3707 m->max_use = DEFAULT_MAX_USE_LOWER;
3708 } else {
3709 m->max_use = PAGE_ALIGN(m->max_use);
3710
8580d1f7 3711 if (m->max_use != 0 && m->max_use < JOURNAL_FILE_SIZE_MIN*2)
babfc091
LP
3712 m->max_use = JOURNAL_FILE_SIZE_MIN*2;
3713 }
3714
8580d1f7
LP
3715 if (m->min_use == (uint64_t) -1)
3716 m->min_use = DEFAULT_MIN_USE;
3717
3718 if (m->min_use > m->max_use)
3719 m->min_use = m->max_use;
3720
babfc091
LP
3721 if (m->max_size == (uint64_t) -1) {
3722 m->max_size = PAGE_ALIGN(m->max_use / 8); /* 8 chunks */
3723
3724 if (m->max_size > DEFAULT_MAX_SIZE_UPPER)
3725 m->max_size = DEFAULT_MAX_SIZE_UPPER;
3726 } else
3727 m->max_size = PAGE_ALIGN(m->max_size);
3728
8580d1f7
LP
3729 if (m->max_size != 0) {
3730 if (m->max_size < JOURNAL_FILE_SIZE_MIN)
3731 m->max_size = JOURNAL_FILE_SIZE_MIN;
babfc091 3732
8580d1f7
LP
3733 if (m->max_use != 0 && m->max_size*2 > m->max_use)
3734 m->max_use = m->max_size*2;
3735 }
babfc091
LP
3736
3737 if (m->min_size == (uint64_t) -1)
3738 m->min_size = JOURNAL_FILE_SIZE_MIN;
3739 else {
3740 m->min_size = PAGE_ALIGN(m->min_size);
3741
3742 if (m->min_size < JOURNAL_FILE_SIZE_MIN)
3743 m->min_size = JOURNAL_FILE_SIZE_MIN;
3744
8580d1f7 3745 if (m->max_size != 0 && m->min_size > m->max_size)
babfc091
LP
3746 m->max_size = m->min_size;
3747 }
3748
3749 if (m->keep_free == (uint64_t) -1) {
3750
3751 if (fs_size > 0) {
8621b110 3752 m->keep_free = PAGE_ALIGN(fs_size * 3 / 20); /* 15% of file system size */
babfc091
LP
3753
3754 if (m->keep_free > DEFAULT_KEEP_FREE_UPPER)
3755 m->keep_free = DEFAULT_KEEP_FREE_UPPER;
3756
3757 } else
3758 m->keep_free = DEFAULT_KEEP_FREE;
3759 }
3760
8580d1f7
LP
3761 if (m->n_max_files == (uint64_t) -1)
3762 m->n_max_files = DEFAULT_N_MAX_FILES;
3763
3764 log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64,
3765 format_bytes(a, sizeof(a), m->min_use),
3766 format_bytes(b, sizeof(b), m->max_use),
3767 format_bytes(c, sizeof(c), m->max_size),
3768 format_bytes(d, sizeof(d), m->min_size),
3769 format_bytes(e, sizeof(e), m->keep_free),
3770 m->n_max_files);
babfc091 3771}
08984293
LP
3772
3773int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *from, usec_t *to) {
08984293 3774 assert(f);
c88cc6af 3775 assert(f->header);
08984293
LP
3776 assert(from || to);
3777
3778 if (from) {
162566a4
LP
3779 if (f->header->head_entry_realtime == 0)
3780 return -ENOENT;
08984293 3781
162566a4 3782 *from = le64toh(f->header->head_entry_realtime);
08984293
LP
3783 }
3784
3785 if (to) {
162566a4
LP
3786 if (f->header->tail_entry_realtime == 0)
3787 return -ENOENT;
08984293 3788
162566a4 3789 *to = le64toh(f->header->tail_entry_realtime);
08984293
LP
3790 }
3791
3792 return 1;
3793}
3794
3795int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot_id, usec_t *from, usec_t *to) {
08984293
LP
3796 Object *o;
3797 uint64_t p;
3798 int r;
3799
3800 assert(f);
3801 assert(from || to);
3802
47838ab3 3803 r = find_data_object_by_boot_id(f, boot_id, &o, &p);
08984293
LP
3804 if (r <= 0)
3805 return r;
3806
3807 if (le64toh(o->data.n_entries) <= 0)
3808 return 0;
3809
3810 if (from) {
3811 r = journal_file_move_to_object(f, OBJECT_ENTRY, le64toh(o->data.entry_offset), &o);
3812 if (r < 0)
3813 return r;
3814
3815 *from = le64toh(o->entry.monotonic);
3816 }
3817
3818 if (to) {
3819 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
3820 if (r < 0)
3821 return r;
3822
3823 r = generic_array_get_plus_one(f,
3824 le64toh(o->data.entry_offset),
3825 le64toh(o->data.entry_array_offset),
3826 le64toh(o->data.n_entries)-1,
3827 &o, NULL);
3828 if (r <= 0)
3829 return r;
3830
3831 *to = le64toh(o->entry.monotonic);
3832 }
3833
3834 return 1;
3835}
dca6219e 3836
fb0951b0 3837bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec) {
dca6219e 3838 assert(f);
c88cc6af 3839 assert(f->header);
dca6219e
LP
3840
3841 /* If we gained new header fields we gained new features,
3842 * hence suggest a rotation */
361f9cbc
LP
3843 if (le64toh(f->header->header_size) < sizeof(Header)) {
3844 log_debug("%s uses an outdated header, suggesting rotation.", f->path);
dca6219e 3845 return true;
361f9cbc 3846 }
dca6219e
LP
3847
3848 /* Let's check if the hash tables grew over a certain fill
3849 * level (75%, borrowing this value from Java's hash table
3850 * implementation), and if so suggest a rotation. To calculate
3851 * the fill level we need the n_data field, which only exists
3852 * in newer versions. */
3853
3854 if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
361f9cbc 3855 if (le64toh(f->header->n_data) * 4ULL > (le64toh(f->header->data_hash_table_size) / sizeof(HashItem)) * 3ULL) {
507f22bd 3856 log_debug("Data hash table of %s has a fill level at %.1f (%"PRIu64" of %"PRIu64" items, %llu file size, %"PRIu64" bytes per hash table item), suggesting rotation.",
361f9cbc
LP
3857 f->path,
3858 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))),
507f22bd
ZJS
3859 le64toh(f->header->n_data),
3860 le64toh(f->header->data_hash_table_size) / sizeof(HashItem),
3861 (unsigned long long) f->last_stat.st_size,
3862 f->last_stat.st_size / le64toh(f->header->n_data));
dca6219e 3863 return true;
361f9cbc 3864 }
dca6219e
LP
3865
3866 if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
361f9cbc 3867 if (le64toh(f->header->n_fields) * 4ULL > (le64toh(f->header->field_hash_table_size) / sizeof(HashItem)) * 3ULL) {
507f22bd 3868 log_debug("Field hash table of %s has a fill level at %.1f (%"PRIu64" of %"PRIu64" items), suggesting rotation.",
361f9cbc
LP
3869 f->path,
3870 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))),
507f22bd
ZJS
3871 le64toh(f->header->n_fields),
3872 le64toh(f->header->field_hash_table_size) / sizeof(HashItem));
dca6219e 3873 return true;
361f9cbc 3874 }
dca6219e 3875
0598fd4a
LP
3876 /* Are the data objects properly indexed by field objects? */
3877 if (JOURNAL_HEADER_CONTAINS(f->header, n_data) &&
3878 JOURNAL_HEADER_CONTAINS(f->header, n_fields) &&
3879 le64toh(f->header->n_data) > 0 &&
3880 le64toh(f->header->n_fields) == 0)
3881 return true;
3882
fb0951b0
LP
3883 if (max_file_usec > 0) {
3884 usec_t t, h;
3885
3886 h = le64toh(f->header->head_entry_realtime);
3887 t = now(CLOCK_REALTIME);
3888
3889 if (h > 0 && t > h + max_file_usec)
3890 return true;
3891 }
3892
dca6219e
LP
3893 return false;
3894}