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