]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/journal/journal-file.c
tree-wide: use IN_SET where possible
[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
feb12d3e 334#ifdef 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
d89c8fdf 381#if defined(HAVE_XZ) || defined(HAVE_LZ4)
807e17f0
LP
382 free(f->compress_buffer);
383#endif
384
7560fffc 385#ifdef 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) {
3b1a55e1 1404#if defined(HAVE_XZ) || defined(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
1516#ifdef HAVE_GCRYPT
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
d89c8fdf 1568#if defined(HAVE_XZ) || defined(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
33685a5a
FB
1593#ifdef HAVE_GCRYPT
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
LP
1652
1653 if (o->object.type != OBJECT_DATA_HASH_TABLE &&
1654 o->object.type != OBJECT_FIELD_HASH_TABLE)
1655 return 0;
fb9a24b6
LP
1656
1657 return (le64toh(o->object.size) - offsetof(Object, hash_table.items)) / sizeof(HashItem);
1658}
1659
de190aef 1660static int link_entry_into_array(JournalFile *f,
4fd052ae
FC
1661 le64_t *first,
1662 le64_t *idx,
de190aef 1663 uint64_t p) {
cec736d2 1664 int r;
de190aef
LP
1665 uint64_t n = 0, ap = 0, q, i, a, hidx;
1666 Object *o;
1667
cec736d2 1668 assert(f);
c88cc6af 1669 assert(f->header);
de190aef
LP
1670 assert(first);
1671 assert(idx);
1672 assert(p > 0);
cec736d2 1673
de190aef
LP
1674 a = le64toh(*first);
1675 i = hidx = le64toh(*idx);
1676 while (a > 0) {
1677
1678 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
1679 if (r < 0)
1680 return r;
cec736d2 1681
de190aef
LP
1682 n = journal_file_entry_array_n_items(o);
1683 if (i < n) {
1684 o->entry_array.items[i] = htole64(p);
1685 *idx = htole64(hidx + 1);
1686 return 0;
1687 }
cec736d2 1688
de190aef
LP
1689 i -= n;
1690 ap = a;
1691 a = le64toh(o->entry_array.next_entry_array_offset);
1692 }
1693
1694 if (hidx > n)
1695 n = (hidx+1) * 2;
1696 else
1697 n = n * 2;
1698
1699 if (n < 4)
1700 n = 4;
1701
1702 r = journal_file_append_object(f, OBJECT_ENTRY_ARRAY,
1703 offsetof(Object, entry_array.items) + n * sizeof(uint64_t),
1704 &o, &q);
cec736d2
LP
1705 if (r < 0)
1706 return r;
1707
feb12d3e 1708#ifdef HAVE_GCRYPT
5996c7c2 1709 r = journal_file_hmac_put_object(f, OBJECT_ENTRY_ARRAY, o, q);
b0af6f41
LP
1710 if (r < 0)
1711 return r;
feb12d3e 1712#endif
b0af6f41 1713
de190aef 1714 o->entry_array.items[i] = htole64(p);
cec736d2 1715
de190aef 1716 if (ap == 0)
7be3aa17 1717 *first = htole64(q);
cec736d2 1718 else {
de190aef 1719 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, ap, &o);
cec736d2
LP
1720 if (r < 0)
1721 return r;
1722
de190aef
LP
1723 o->entry_array.next_entry_array_offset = htole64(q);
1724 }
cec736d2 1725
2dee23eb
LP
1726 if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
1727 f->header->n_entry_arrays = htole64(le64toh(f->header->n_entry_arrays) + 1);
1728
de190aef
LP
1729 *idx = htole64(hidx + 1);
1730
1731 return 0;
1732}
cec736d2 1733
de190aef 1734static int link_entry_into_array_plus_one(JournalFile *f,
4fd052ae
FC
1735 le64_t *extra,
1736 le64_t *first,
1737 le64_t *idx,
de190aef
LP
1738 uint64_t p) {
1739
1740 int r;
1741
1742 assert(f);
1743 assert(extra);
1744 assert(first);
1745 assert(idx);
1746 assert(p > 0);
1747
1748 if (*idx == 0)
1749 *extra = htole64(p);
1750 else {
4fd052ae 1751 le64_t i;
de190aef 1752
7be3aa17 1753 i = htole64(le64toh(*idx) - 1);
de190aef
LP
1754 r = link_entry_into_array(f, first, &i, p);
1755 if (r < 0)
1756 return r;
cec736d2
LP
1757 }
1758
de190aef
LP
1759 *idx = htole64(le64toh(*idx) + 1);
1760 return 0;
1761}
1762
1763static int journal_file_link_entry_item(JournalFile *f, Object *o, uint64_t offset, uint64_t i) {
1764 uint64_t p;
1765 int r;
1766 assert(f);
1767 assert(o);
1768 assert(offset > 0);
1769
1770 p = le64toh(o->entry.items[i].object_offset);
1771 if (p == 0)
1772 return -EINVAL;
1773
1774 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
cec736d2
LP
1775 if (r < 0)
1776 return r;
1777
de190aef
LP
1778 return link_entry_into_array_plus_one(f,
1779 &o->data.entry_offset,
1780 &o->data.entry_array_offset,
1781 &o->data.n_entries,
1782 offset);
cec736d2
LP
1783}
1784
1785static int journal_file_link_entry(JournalFile *f, Object *o, uint64_t offset) {
de190aef 1786 uint64_t n, i;
cec736d2
LP
1787 int r;
1788
1789 assert(f);
c88cc6af 1790 assert(f->header);
cec736d2
LP
1791 assert(o);
1792 assert(offset > 0);
b588975f
LP
1793
1794 if (o->object.type != OBJECT_ENTRY)
1795 return -EINVAL;
cec736d2 1796
b788cc23
LP
1797 __sync_synchronize();
1798
cec736d2 1799 /* Link up the entry itself */
de190aef
LP
1800 r = link_entry_into_array(f,
1801 &f->header->entry_array_offset,
1802 &f->header->n_entries,
1803 offset);
1804 if (r < 0)
1805 return r;
cec736d2 1806
507f22bd 1807 /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
cec736d2 1808
de190aef 1809 if (f->header->head_entry_realtime == 0)
0ac38b70 1810 f->header->head_entry_realtime = o->entry.realtime;
cec736d2 1811
0ac38b70 1812 f->header->tail_entry_realtime = o->entry.realtime;
de190aef
LP
1813 f->header->tail_entry_monotonic = o->entry.monotonic;
1814
1815 f->tail_entry_monotonic_valid = true;
cec736d2
LP
1816
1817 /* Link up the items */
1818 n = journal_file_entry_n_items(o);
1819 for (i = 0; i < n; i++) {
1820 r = journal_file_link_entry_item(f, o, offset, i);
1821 if (r < 0)
1822 return r;
1823 }
1824
cec736d2
LP
1825 return 0;
1826}
1827
1828static int journal_file_append_entry_internal(
1829 JournalFile *f,
1830 const dual_timestamp *ts,
1831 uint64_t xor_hash,
1832 const EntryItem items[], unsigned n_items,
de190aef 1833 uint64_t *seqnum,
cec736d2
LP
1834 Object **ret, uint64_t *offset) {
1835 uint64_t np;
1836 uint64_t osize;
1837 Object *o;
1838 int r;
1839
1840 assert(f);
c88cc6af 1841 assert(f->header);
cec736d2 1842 assert(items || n_items == 0);
de190aef 1843 assert(ts);
cec736d2
LP
1844
1845 osize = offsetof(Object, entry.items) + (n_items * sizeof(EntryItem));
1846
de190aef 1847 r = journal_file_append_object(f, OBJECT_ENTRY, osize, &o, &np);
cec736d2
LP
1848 if (r < 0)
1849 return r;
1850
d98cc1f2 1851 o->entry.seqnum = htole64(journal_file_entry_seqnum(f, seqnum));
75f32f04 1852 memcpy_safe(o->entry.items, items, n_items * sizeof(EntryItem));
de190aef
LP
1853 o->entry.realtime = htole64(ts->realtime);
1854 o->entry.monotonic = htole64(ts->monotonic);
cec736d2
LP
1855 o->entry.xor_hash = htole64(xor_hash);
1856 o->entry.boot_id = f->header->boot_id;
1857
feb12d3e 1858#ifdef HAVE_GCRYPT
5996c7c2 1859 r = journal_file_hmac_put_object(f, OBJECT_ENTRY, o, np);
b0af6f41
LP
1860 if (r < 0)
1861 return r;
feb12d3e 1862#endif
b0af6f41 1863
cec736d2
LP
1864 r = journal_file_link_entry(f, o, np);
1865 if (r < 0)
1866 return r;
1867
1868 if (ret)
1869 *ret = o;
1870
1871 if (offset)
1872 *offset = np;
1873
1874 return 0;
1875}
1876
cf244689 1877void journal_file_post_change(JournalFile *f) {
50f20cfd
LP
1878 assert(f);
1879
1880 /* inotify() does not receive IN_MODIFY events from file
1881 * accesses done via mmap(). After each access we hence
1882 * trigger IN_MODIFY by truncating the journal file to its
1883 * current size which triggers IN_MODIFY. */
1884
bc85bfee
LP
1885 __sync_synchronize();
1886
50f20cfd 1887 if (ftruncate(f->fd, f->last_stat.st_size) < 0)
e167d7fd 1888 log_debug_errno(errno, "Failed to truncate file to its own size: %m");
50f20cfd
LP
1889}
1890
7a24f3bf
VC
1891static int post_change_thunk(sd_event_source *timer, uint64_t usec, void *userdata) {
1892 assert(userdata);
1893
1894 journal_file_post_change(userdata);
1895
1896 return 1;
1897}
1898
1899static void schedule_post_change(JournalFile *f) {
1900 sd_event_source *timer;
1901 int enabled, r;
1902 uint64_t now;
1903
1904 assert(f);
1905 assert(f->post_change_timer);
1906
1907 timer = f->post_change_timer;
1908
1909 r = sd_event_source_get_enabled(timer, &enabled);
1910 if (r < 0) {
e167d7fd
LP
1911 log_debug_errno(r, "Failed to get ftruncate timer state: %m");
1912 goto fail;
7a24f3bf
VC
1913 }
1914
1915 if (enabled == SD_EVENT_ONESHOT)
1916 return;
1917
1918 r = sd_event_now(sd_event_source_get_event(timer), CLOCK_MONOTONIC, &now);
1919 if (r < 0) {
e167d7fd
LP
1920 log_debug_errno(r, "Failed to get clock's now for scheduling ftruncate: %m");
1921 goto fail;
7a24f3bf
VC
1922 }
1923
1924 r = sd_event_source_set_time(timer, now+f->post_change_timer_period);
1925 if (r < 0) {
e167d7fd
LP
1926 log_debug_errno(r, "Failed to set time for scheduling ftruncate: %m");
1927 goto fail;
7a24f3bf
VC
1928 }
1929
1930 r = sd_event_source_set_enabled(timer, SD_EVENT_ONESHOT);
1931 if (r < 0) {
e167d7fd
LP
1932 log_debug_errno(r, "Failed to enable scheduled ftruncate: %m");
1933 goto fail;
7a24f3bf 1934 }
e167d7fd
LP
1935
1936 return;
1937
1938fail:
1939 /* On failure, let's simply post the change immediately. */
1940 journal_file_post_change(f);
7a24f3bf
VC
1941}
1942
1943/* Enable coalesced change posting in a timer on the provided sd_event instance */
1944int journal_file_enable_post_change_timer(JournalFile *f, sd_event *e, usec_t t) {
1945 _cleanup_(sd_event_source_unrefp) sd_event_source *timer = NULL;
1946 int r;
1947
1948 assert(f);
1949 assert_return(!f->post_change_timer, -EINVAL);
1950 assert(e);
1951 assert(t);
1952
1953 r = sd_event_add_time(e, &timer, CLOCK_MONOTONIC, 0, 0, post_change_thunk, f);
1954 if (r < 0)
1955 return r;
1956
1957 r = sd_event_source_set_enabled(timer, SD_EVENT_OFF);
1958 if (r < 0)
1959 return r;
1960
1961 f->post_change_timer = timer;
1962 timer = NULL;
1963 f->post_change_timer_period = t;
1964
1965 return r;
1966}
1967
1f2da9ec
LP
1968static int entry_item_cmp(const void *_a, const void *_b) {
1969 const EntryItem *a = _a, *b = _b;
1970
1971 if (le64toh(a->object_offset) < le64toh(b->object_offset))
1972 return -1;
1973 if (le64toh(a->object_offset) > le64toh(b->object_offset))
1974 return 1;
1975 return 0;
1976}
1977
de190aef 1978int 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
1979 unsigned i;
1980 EntryItem *items;
1981 int r;
1982 uint64_t xor_hash = 0;
de190aef 1983 struct dual_timestamp _ts;
cec736d2
LP
1984
1985 assert(f);
c88cc6af 1986 assert(f->header);
cec736d2
LP
1987 assert(iovec || n_iovec == 0);
1988
de190aef
LP
1989 if (!ts) {
1990 dual_timestamp_get(&_ts);
1991 ts = &_ts;
1992 }
1993
feb12d3e 1994#ifdef HAVE_GCRYPT
7560fffc
LP
1995 r = journal_file_maybe_append_tag(f, ts->realtime);
1996 if (r < 0)
1997 return r;
feb12d3e 1998#endif
7560fffc 1999
64825d3c 2000 /* alloca() can't take 0, hence let's allocate at least one */
9607d947 2001 items = alloca(sizeof(EntryItem) * MAX(1u, n_iovec));
cec736d2
LP
2002
2003 for (i = 0; i < n_iovec; i++) {
2004 uint64_t p;
2005 Object *o;
2006
2007 r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p);
2008 if (r < 0)
cf244689 2009 return r;
cec736d2
LP
2010
2011 xor_hash ^= le64toh(o->data.hash);
2012 items[i].object_offset = htole64(p);
de7b95cd 2013 items[i].hash = o->data.hash;
cec736d2
LP
2014 }
2015
1f2da9ec
LP
2016 /* Order by the position on disk, in order to improve seek
2017 * times for rotating media. */
7ff7394d 2018 qsort_safe(items, n_iovec, sizeof(EntryItem), entry_item_cmp);
1f2da9ec 2019
de190aef 2020 r = journal_file_append_entry_internal(f, ts, xor_hash, items, n_iovec, seqnum, ret, offset);
cec736d2 2021
fa6ac760
LP
2022 /* If the memory mapping triggered a SIGBUS then we return an
2023 * IO error and ignore the error code passed down to us, since
2024 * it is very likely just an effect of a nullified replacement
2025 * mapping page */
2026
be7cdd8e 2027 if (mmap_cache_got_sigbus(f->mmap, f->cache_fd))
fa6ac760
LP
2028 r = -EIO;
2029
7a24f3bf
VC
2030 if (f->post_change_timer)
2031 schedule_post_change(f);
2032 else
2033 journal_file_post_change(f);
50f20cfd 2034
cec736d2
LP
2035 return r;
2036}
2037
a4bcff5b 2038typedef struct ChainCacheItem {
fb099c8d 2039 uint64_t first; /* the array at the beginning of the chain */
a4bcff5b
LP
2040 uint64_t array; /* the cached array */
2041 uint64_t begin; /* the first item in the cached array */
2042 uint64_t total; /* the total number of items in all arrays before this one in the chain */
f268980d 2043 uint64_t last_index; /* the last index we looked at, to optimize locality when bisecting */
a4bcff5b
LP
2044} ChainCacheItem;
2045
2046static void chain_cache_put(
4743015d 2047 OrderedHashmap *h,
a4bcff5b
LP
2048 ChainCacheItem *ci,
2049 uint64_t first,
2050 uint64_t array,
2051 uint64_t begin,
f268980d
LP
2052 uint64_t total,
2053 uint64_t last_index) {
a4bcff5b
LP
2054
2055 if (!ci) {
34741aa3
LP
2056 /* If the chain item to cache for this chain is the
2057 * first one it's not worth caching anything */
2058 if (array == first)
2059 return;
2060
29433089 2061 if (ordered_hashmap_size(h) >= CHAIN_CACHE_MAX) {
4743015d 2062 ci = ordered_hashmap_steal_first(h);
29433089
LP
2063 assert(ci);
2064 } else {
a4bcff5b
LP
2065 ci = new(ChainCacheItem, 1);
2066 if (!ci)
2067 return;
2068 }
2069
2070 ci->first = first;
2071
4743015d 2072 if (ordered_hashmap_put(h, &ci->first, ci) < 0) {
a4bcff5b
LP
2073 free(ci);
2074 return;
2075 }
2076 } else
2077 assert(ci->first == first);
2078
2079 ci->array = array;
2080 ci->begin = begin;
2081 ci->total = total;
f268980d 2082 ci->last_index = last_index;
a4bcff5b
LP
2083}
2084
f268980d
LP
2085static int generic_array_get(
2086 JournalFile *f,
2087 uint64_t first,
2088 uint64_t i,
2089 Object **ret, uint64_t *offset) {
de190aef 2090
cec736d2 2091 Object *o;
a4bcff5b 2092 uint64_t p = 0, a, t = 0;
cec736d2 2093 int r;
a4bcff5b 2094 ChainCacheItem *ci;
cec736d2
LP
2095
2096 assert(f);
2097
de190aef 2098 a = first;
a4bcff5b
LP
2099
2100 /* Try the chain cache first */
4743015d 2101 ci = ordered_hashmap_get(f->chain_cache, &first);
a4bcff5b
LP
2102 if (ci && i > ci->total) {
2103 a = ci->array;
2104 i -= ci->total;
2105 t = ci->total;
2106 }
2107
de190aef 2108 while (a > 0) {
a4bcff5b 2109 uint64_t k;
cec736d2 2110
de190aef
LP
2111 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
2112 if (r < 0)
2113 return r;
cec736d2 2114
a4bcff5b
LP
2115 k = journal_file_entry_array_n_items(o);
2116 if (i < k) {
de190aef 2117 p = le64toh(o->entry_array.items[i]);
a4bcff5b 2118 goto found;
cec736d2
LP
2119 }
2120
a4bcff5b
LP
2121 i -= k;
2122 t += k;
de190aef
LP
2123 a = le64toh(o->entry_array.next_entry_array_offset);
2124 }
2125
a4bcff5b
LP
2126 return 0;
2127
2128found:
2129 /* Let's cache this item for the next invocation */
af13a6b0 2130 chain_cache_put(f->chain_cache, ci, first, a, le64toh(o->entry_array.items[0]), t, i);
de190aef
LP
2131
2132 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2133 if (r < 0)
2134 return r;
2135
2136 if (ret)
2137 *ret = o;
2138
2139 if (offset)
2140 *offset = p;
2141
2142 return 1;
2143}
2144
f268980d
LP
2145static int generic_array_get_plus_one(
2146 JournalFile *f,
2147 uint64_t extra,
2148 uint64_t first,
2149 uint64_t i,
2150 Object **ret, uint64_t *offset) {
de190aef
LP
2151
2152 Object *o;
2153
2154 assert(f);
2155
2156 if (i == 0) {
2157 int r;
2158
2159 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
cec736d2
LP
2160 if (r < 0)
2161 return r;
2162
de190aef
LP
2163 if (ret)
2164 *ret = o;
cec736d2 2165
de190aef
LP
2166 if (offset)
2167 *offset = extra;
cec736d2 2168
de190aef 2169 return 1;
cec736d2
LP
2170 }
2171
de190aef
LP
2172 return generic_array_get(f, first, i-1, ret, offset);
2173}
cec736d2 2174
de190aef
LP
2175enum {
2176 TEST_FOUND,
2177 TEST_LEFT,
2178 TEST_RIGHT
2179};
cec736d2 2180
f268980d
LP
2181static int generic_array_bisect(
2182 JournalFile *f,
2183 uint64_t first,
2184 uint64_t n,
2185 uint64_t needle,
2186 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
2187 direction_t direction,
2188 Object **ret,
2189 uint64_t *offset,
2190 uint64_t *idx) {
2191
2192 uint64_t a, p, t = 0, i = 0, last_p = 0, last_index = (uint64_t) -1;
de190aef
LP
2193 bool subtract_one = false;
2194 Object *o, *array = NULL;
2195 int r;
a4bcff5b 2196 ChainCacheItem *ci;
cec736d2 2197
de190aef
LP
2198 assert(f);
2199 assert(test_object);
cec736d2 2200
a4bcff5b 2201 /* Start with the first array in the chain */
de190aef 2202 a = first;
a4bcff5b 2203
4743015d 2204 ci = ordered_hashmap_get(f->chain_cache, &first);
a4bcff5b
LP
2205 if (ci && n > ci->total) {
2206 /* Ah, we have iterated this bisection array chain
2207 * previously! Let's see if we can skip ahead in the
2208 * chain, as far as the last time. But we can't jump
2209 * backwards in the chain, so let's check that
2210 * first. */
2211
2212 r = test_object(f, ci->begin, needle);
2213 if (r < 0)
2214 return r;
2215
2216 if (r == TEST_LEFT) {
f268980d 2217 /* OK, what we are looking for is right of the
a4bcff5b
LP
2218 * begin of this EntryArray, so let's jump
2219 * straight to previously cached array in the
2220 * chain */
2221
2222 a = ci->array;
2223 n -= ci->total;
2224 t = ci->total;
f268980d 2225 last_index = ci->last_index;
a4bcff5b
LP
2226 }
2227 }
2228
de190aef
LP
2229 while (a > 0) {
2230 uint64_t left, right, k, lp;
2231
2232 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
cec736d2
LP
2233 if (r < 0)
2234 return r;
2235
de190aef
LP
2236 k = journal_file_entry_array_n_items(array);
2237 right = MIN(k, n);
2238 if (right <= 0)
2239 return 0;
cec736d2 2240
de190aef
LP
2241 i = right - 1;
2242 lp = p = le64toh(array->entry_array.items[i]);
2243 if (p <= 0)
bee6a291
LP
2244 r = -EBADMSG;
2245 else
2246 r = test_object(f, p, needle);
2247 if (r == -EBADMSG) {
2248 log_debug_errno(r, "Encountered invalid entry while bisecting, cutting algorithm short. (1)");
2249 n = i;
2250 continue;
2251 }
de190aef
LP
2252 if (r < 0)
2253 return r;
cec736d2 2254
de190aef
LP
2255 if (r == TEST_FOUND)
2256 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2257
2258 if (r == TEST_RIGHT) {
2259 left = 0;
2260 right -= 1;
f268980d
LP
2261
2262 if (last_index != (uint64_t) -1) {
2263 assert(last_index <= right);
2264
2265 /* If we cached the last index we
2266 * looked at, let's try to not to jump
2267 * too wildly around and see if we can
2268 * limit the range to look at early to
2269 * the immediate neighbors of the last
2270 * index we looked at. */
2271
2272 if (last_index > 0) {
2273 uint64_t x = last_index - 1;
2274
2275 p = le64toh(array->entry_array.items[x]);
2276 if (p <= 0)
2277 return -EBADMSG;
2278
2279 r = test_object(f, p, needle);
2280 if (r < 0)
2281 return r;
2282
2283 if (r == TEST_FOUND)
2284 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2285
2286 if (r == TEST_RIGHT)
2287 right = x;
2288 else
2289 left = x + 1;
2290 }
2291
2292 if (last_index < right) {
2293 uint64_t y = last_index + 1;
2294
2295 p = le64toh(array->entry_array.items[y]);
2296 if (p <= 0)
2297 return -EBADMSG;
2298
2299 r = test_object(f, p, needle);
2300 if (r < 0)
2301 return r;
2302
2303 if (r == TEST_FOUND)
2304 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2305
2306 if (r == TEST_RIGHT)
2307 right = y;
2308 else
2309 left = y + 1;
2310 }
f268980d
LP
2311 }
2312
de190aef
LP
2313 for (;;) {
2314 if (left == right) {
2315 if (direction == DIRECTION_UP)
2316 subtract_one = true;
2317
2318 i = left;
2319 goto found;
2320 }
2321
2322 assert(left < right);
de190aef 2323 i = (left + right) / 2;
f268980d 2324
de190aef
LP
2325 p = le64toh(array->entry_array.items[i]);
2326 if (p <= 0)
bee6a291
LP
2327 r = -EBADMSG;
2328 else
2329 r = test_object(f, p, needle);
2330 if (r == -EBADMSG) {
2331 log_debug_errno(r, "Encountered invalid entry while bisecting, cutting algorithm short. (2)");
2332 right = n = i;
2333 continue;
2334 }
de190aef
LP
2335 if (r < 0)
2336 return r;
cec736d2 2337
de190aef
LP
2338 if (r == TEST_FOUND)
2339 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2340
2341 if (r == TEST_RIGHT)
2342 right = i;
2343 else
2344 left = i + 1;
2345 }
2346 }
2347
2173cbf8 2348 if (k >= n) {
cbdca852
LP
2349 if (direction == DIRECTION_UP) {
2350 i = n;
2351 subtract_one = true;
2352 goto found;
2353 }
2354
cec736d2 2355 return 0;
cbdca852 2356 }
cec736d2 2357
de190aef
LP
2358 last_p = lp;
2359
2360 n -= k;
2361 t += k;
f268980d 2362 last_index = (uint64_t) -1;
de190aef 2363 a = le64toh(array->entry_array.next_entry_array_offset);
cec736d2
LP
2364 }
2365
2366 return 0;
de190aef
LP
2367
2368found:
2369 if (subtract_one && t == 0 && i == 0)
2370 return 0;
2371
a4bcff5b 2372 /* Let's cache this item for the next invocation */
af13a6b0 2373 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 2374
de190aef
LP
2375 if (subtract_one && i == 0)
2376 p = last_p;
2377 else if (subtract_one)
2378 p = le64toh(array->entry_array.items[i-1]);
2379 else
2380 p = le64toh(array->entry_array.items[i]);
2381
2382 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2383 if (r < 0)
2384 return r;
2385
2386 if (ret)
2387 *ret = o;
2388
2389 if (offset)
2390 *offset = p;
2391
2392 if (idx)
cbdca852 2393 *idx = t + i + (subtract_one ? -1 : 0);
de190aef
LP
2394
2395 return 1;
cec736d2
LP
2396}
2397
f268980d
LP
2398static int generic_array_bisect_plus_one(
2399 JournalFile *f,
2400 uint64_t extra,
2401 uint64_t first,
2402 uint64_t n,
2403 uint64_t needle,
2404 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
2405 direction_t direction,
2406 Object **ret,
2407 uint64_t *offset,
2408 uint64_t *idx) {
de190aef 2409
cec736d2 2410 int r;
cbdca852
LP
2411 bool step_back = false;
2412 Object *o;
cec736d2
LP
2413
2414 assert(f);
de190aef 2415 assert(test_object);
cec736d2 2416
de190aef
LP
2417 if (n <= 0)
2418 return 0;
cec736d2 2419
de190aef
LP
2420 /* This bisects the array in object 'first', but first checks
2421 * an extra */
de190aef
LP
2422 r = test_object(f, extra, needle);
2423 if (r < 0)
2424 return r;
a536e261
LP
2425
2426 if (r == TEST_FOUND)
2427 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2428
cbdca852
LP
2429 /* if we are looking with DIRECTION_UP then we need to first
2430 see if in the actual array there is a matching entry, and
2431 return the last one of that. But if there isn't any we need
2432 to return this one. Hence remember this, and return it
2433 below. */
2434 if (r == TEST_LEFT)
2435 step_back = direction == DIRECTION_UP;
de190aef 2436
cbdca852
LP
2437 if (r == TEST_RIGHT) {
2438 if (direction == DIRECTION_DOWN)
2439 goto found;
2440 else
2441 return 0;
a536e261 2442 }
cec736d2 2443
de190aef
LP
2444 r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret, offset, idx);
2445
cbdca852
LP
2446 if (r == 0 && step_back)
2447 goto found;
2448
ecf68b1d 2449 if (r > 0 && idx)
313cefa1 2450 (*idx)++;
de190aef
LP
2451
2452 return r;
cbdca852
LP
2453
2454found:
2455 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
2456 if (r < 0)
2457 return r;
2458
2459 if (ret)
2460 *ret = o;
2461
2462 if (offset)
2463 *offset = extra;
2464
2465 if (idx)
2466 *idx = 0;
2467
2468 return 1;
2469}
2470
44a6b1b6 2471_pure_ static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) {
cbdca852
LP
2472 assert(f);
2473 assert(p > 0);
2474
2475 if (p == needle)
2476 return TEST_FOUND;
2477 else if (p < needle)
2478 return TEST_LEFT;
2479 else
2480 return TEST_RIGHT;
2481}
2482
de190aef
LP
2483static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) {
2484 Object *o;
2485 int r;
2486
2487 assert(f);
2488 assert(p > 0);
2489
2490 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
cec736d2
LP
2491 if (r < 0)
2492 return r;
2493
de190aef
LP
2494 if (le64toh(o->entry.seqnum) == needle)
2495 return TEST_FOUND;
2496 else if (le64toh(o->entry.seqnum) < needle)
2497 return TEST_LEFT;
2498 else
2499 return TEST_RIGHT;
2500}
cec736d2 2501
de190aef
LP
2502int journal_file_move_to_entry_by_seqnum(
2503 JournalFile *f,
2504 uint64_t seqnum,
2505 direction_t direction,
2506 Object **ret,
2507 uint64_t *offset) {
c88cc6af
VC
2508 assert(f);
2509 assert(f->header);
de190aef
LP
2510
2511 return generic_array_bisect(f,
2512 le64toh(f->header->entry_array_offset),
2513 le64toh(f->header->n_entries),
2514 seqnum,
2515 test_object_seqnum,
2516 direction,
2517 ret, offset, NULL);
2518}
cec736d2 2519
de190aef
LP
2520static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) {
2521 Object *o;
2522 int r;
2523
2524 assert(f);
2525 assert(p > 0);
2526
2527 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2528 if (r < 0)
2529 return r;
2530
2531 if (le64toh(o->entry.realtime) == needle)
2532 return TEST_FOUND;
2533 else if (le64toh(o->entry.realtime) < needle)
2534 return TEST_LEFT;
2535 else
2536 return TEST_RIGHT;
cec736d2
LP
2537}
2538
de190aef
LP
2539int journal_file_move_to_entry_by_realtime(
2540 JournalFile *f,
2541 uint64_t realtime,
2542 direction_t direction,
2543 Object **ret,
2544 uint64_t *offset) {
c88cc6af
VC
2545 assert(f);
2546 assert(f->header);
de190aef
LP
2547
2548 return generic_array_bisect(f,
2549 le64toh(f->header->entry_array_offset),
2550 le64toh(f->header->n_entries),
2551 realtime,
2552 test_object_realtime,
2553 direction,
2554 ret, offset, NULL);
2555}
2556
2557static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) {
2558 Object *o;
2559 int r;
2560
2561 assert(f);
2562 assert(p > 0);
2563
2564 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2565 if (r < 0)
2566 return r;
2567
2568 if (le64toh(o->entry.monotonic) == needle)
2569 return TEST_FOUND;
2570 else if (le64toh(o->entry.monotonic) < needle)
2571 return TEST_LEFT;
2572 else
2573 return TEST_RIGHT;
2574}
2575
2a560338 2576static int find_data_object_by_boot_id(
47838ab3
ZJS
2577 JournalFile *f,
2578 sd_id128_t boot_id,
2579 Object **o,
2580 uint64_t *b) {
2a560338 2581
47838ab3
ZJS
2582 char t[sizeof("_BOOT_ID=")-1 + 32 + 1] = "_BOOT_ID=";
2583
2584 sd_id128_to_string(boot_id, t + 9);
2585 return journal_file_find_data_object(f, t, sizeof(t) - 1, o, b);
2586}
2587
de190aef
LP
2588int journal_file_move_to_entry_by_monotonic(
2589 JournalFile *f,
2590 sd_id128_t boot_id,
2591 uint64_t monotonic,
2592 direction_t direction,
2593 Object **ret,
2594 uint64_t *offset) {
2595
de190aef
LP
2596 Object *o;
2597 int r;
2598
cbdca852 2599 assert(f);
de190aef 2600
47838ab3 2601 r = find_data_object_by_boot_id(f, boot_id, &o, NULL);
de190aef
LP
2602 if (r < 0)
2603 return r;
cbdca852 2604 if (r == 0)
de190aef
LP
2605 return -ENOENT;
2606
2607 return generic_array_bisect_plus_one(f,
2608 le64toh(o->data.entry_offset),
2609 le64toh(o->data.entry_array_offset),
2610 le64toh(o->data.n_entries),
2611 monotonic,
2612 test_object_monotonic,
2613 direction,
2614 ret, offset, NULL);
2615}
2616
1fc605b0 2617void journal_file_reset_location(JournalFile *f) {
6573ef05 2618 f->location_type = LOCATION_HEAD;
1fc605b0 2619 f->current_offset = 0;
6573ef05
MS
2620 f->current_seqnum = 0;
2621 f->current_realtime = 0;
2622 f->current_monotonic = 0;
2623 zero(f->current_boot_id);
2624 f->current_xor_hash = 0;
2625}
2626
950c07d4 2627void journal_file_save_location(JournalFile *f, Object *o, uint64_t offset) {
6573ef05
MS
2628 f->location_type = LOCATION_SEEK;
2629 f->current_offset = offset;
2630 f->current_seqnum = le64toh(o->entry.seqnum);
2631 f->current_realtime = le64toh(o->entry.realtime);
2632 f->current_monotonic = le64toh(o->entry.monotonic);
2633 f->current_boot_id = o->entry.boot_id;
2634 f->current_xor_hash = le64toh(o->entry.xor_hash);
1fc605b0
MS
2635}
2636
d8ae66d7
MS
2637int journal_file_compare_locations(JournalFile *af, JournalFile *bf) {
2638 assert(af);
c88cc6af 2639 assert(af->header);
d8ae66d7 2640 assert(bf);
c88cc6af 2641 assert(bf->header);
d8ae66d7
MS
2642 assert(af->location_type == LOCATION_SEEK);
2643 assert(bf->location_type == LOCATION_SEEK);
2644
2645 /* If contents and timestamps match, these entries are
2646 * identical, even if the seqnum does not match */
2647 if (sd_id128_equal(af->current_boot_id, bf->current_boot_id) &&
2648 af->current_monotonic == bf->current_monotonic &&
2649 af->current_realtime == bf->current_realtime &&
2650 af->current_xor_hash == bf->current_xor_hash)
2651 return 0;
2652
2653 if (sd_id128_equal(af->header->seqnum_id, bf->header->seqnum_id)) {
2654
2655 /* If this is from the same seqnum source, compare
2656 * seqnums */
2657 if (af->current_seqnum < bf->current_seqnum)
2658 return -1;
2659 if (af->current_seqnum > bf->current_seqnum)
2660 return 1;
2661
2662 /* Wow! This is weird, different data but the same
2663 * seqnums? Something is borked, but let's make the
2664 * best of it and compare by time. */
2665 }
2666
2667 if (sd_id128_equal(af->current_boot_id, bf->current_boot_id)) {
2668
2669 /* If the boot id matches, compare monotonic time */
2670 if (af->current_monotonic < bf->current_monotonic)
2671 return -1;
2672 if (af->current_monotonic > bf->current_monotonic)
2673 return 1;
2674 }
2675
2676 /* Otherwise, compare UTC time */
2677 if (af->current_realtime < bf->current_realtime)
2678 return -1;
2679 if (af->current_realtime > bf->current_realtime)
2680 return 1;
2681
2682 /* Finally, compare by contents */
2683 if (af->current_xor_hash < bf->current_xor_hash)
2684 return -1;
2685 if (af->current_xor_hash > bf->current_xor_hash)
2686 return 1;
2687
2688 return 0;
2689}
2690
aa598ba5
LP
2691static int bump_array_index(uint64_t *i, direction_t direction, uint64_t n) {
2692
2693 /* Increase or decrease the specified index, in the right direction. */
2694
2695 if (direction == DIRECTION_DOWN) {
2696 if (*i >= n - 1)
2697 return 0;
2698
2699 (*i) ++;
2700 } else {
2701 if (*i <= 0)
2702 return 0;
2703
2704 (*i) --;
2705 }
2706
2707 return 1;
2708}
2709
b6da4ed0
LP
2710static bool check_properly_ordered(uint64_t new_offset, uint64_t old_offset, direction_t direction) {
2711
2712 /* Consider it an error if any of the two offsets is uninitialized */
2713 if (old_offset == 0 || new_offset == 0)
2714 return false;
2715
2716 /* If we go down, the new offset must be larger than the old one. */
2717 return direction == DIRECTION_DOWN ?
2718 new_offset > old_offset :
2719 new_offset < old_offset;
2720}
2721
de190aef
LP
2722int journal_file_next_entry(
2723 JournalFile *f,
f534928a 2724 uint64_t p,
de190aef
LP
2725 direction_t direction,
2726 Object **ret, uint64_t *offset) {
2727
fb099c8d 2728 uint64_t i, n, ofs;
cec736d2
LP
2729 int r;
2730
2731 assert(f);
c88cc6af 2732 assert(f->header);
de190aef
LP
2733
2734 n = le64toh(f->header->n_entries);
2735 if (n <= 0)
2736 return 0;
cec736d2 2737
f534928a 2738 if (p == 0)
de190aef 2739 i = direction == DIRECTION_DOWN ? 0 : n - 1;
cec736d2 2740 else {
de190aef
LP
2741 r = generic_array_bisect(f,
2742 le64toh(f->header->entry_array_offset),
2743 le64toh(f->header->n_entries),
2744 p,
2745 test_object_offset,
2746 DIRECTION_DOWN,
2747 NULL, NULL,
2748 &i);
2749 if (r <= 0)
2750 return r;
2751
aa598ba5
LP
2752 r = bump_array_index(&i, direction, n);
2753 if (r <= 0)
2754 return r;
cec736d2
LP
2755 }
2756
de190aef 2757 /* And jump to it */
989793d3
LP
2758 for (;;) {
2759 r = generic_array_get(f,
2760 le64toh(f->header->entry_array_offset),
2761 i,
2762 ret, &ofs);
2763 if (r > 0)
2764 break;
2765 if (r != -EBADMSG)
2766 return r;
2767
2768 /* OK, so this entry is borked. Most likely some entry didn't get synced to disk properly, let's see if
2769 * the next one might work for us instead. */
2770 log_debug_errno(r, "Entry item %" PRIu64 " is bad, skipping over it.", i);
2771
2772 r = bump_array_index(&i, direction, n);
2773 if (r <= 0)
2774 return r;
caeab8f6 2775 }
fb099c8d 2776
b6da4ed0
LP
2777 /* Ensure our array is properly ordered. */
2778 if (p > 0 && !check_properly_ordered(ofs, p, direction)) {
2779 log_debug("%s: entry array not properly ordered at entry %" PRIu64, f->path, i);
fb099c8d
ZJS
2780 return -EBADMSG;
2781 }
2782
2783 if (offset)
2784 *offset = ofs;
2785
2786 return 1;
de190aef 2787}
cec736d2 2788
de190aef
LP
2789int journal_file_next_entry_for_data(
2790 JournalFile *f,
2791 Object *o, uint64_t p,
2792 uint64_t data_offset,
2793 direction_t direction,
2794 Object **ret, uint64_t *offset) {
2795
ded5034e 2796 uint64_t i, n, ofs;
de190aef 2797 Object *d;
989793d3 2798 int r;
cec736d2
LP
2799
2800 assert(f);
de190aef 2801 assert(p > 0 || !o);
cec736d2 2802
de190aef 2803 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
466ccd92 2804 if (r < 0)
de190aef 2805 return r;
cec736d2 2806
de190aef
LP
2807 n = le64toh(d->data.n_entries);
2808 if (n <= 0)
2809 return n;
cec736d2 2810
de190aef
LP
2811 if (!o)
2812 i = direction == DIRECTION_DOWN ? 0 : n - 1;
2813 else {
2814 if (o->object.type != OBJECT_ENTRY)
2815 return -EINVAL;
cec736d2 2816
de190aef
LP
2817 r = generic_array_bisect_plus_one(f,
2818 le64toh(d->data.entry_offset),
2819 le64toh(d->data.entry_array_offset),
2820 le64toh(d->data.n_entries),
2821 p,
2822 test_object_offset,
2823 DIRECTION_DOWN,
2824 NULL, NULL,
2825 &i);
2826
2827 if (r <= 0)
cec736d2
LP
2828 return r;
2829
aa598ba5
LP
2830 r = bump_array_index(&i, direction, n);
2831 if (r <= 0)
2832 return r;
de190aef 2833 }
cec736d2 2834
989793d3
LP
2835 for (;;) {
2836 r = generic_array_get_plus_one(f,
2837 le64toh(d->data.entry_offset),
2838 le64toh(d->data.entry_array_offset),
2839 i,
2840 ret, &ofs);
2841 if (r > 0)
2842 break;
2843 if (r != -EBADMSG)
2844 return r;
2845
2846 log_debug_errno(r, "Data entry item %" PRIu64 " is bad, skipping over it.", i);
2847
2848 r = bump_array_index(&i, direction, n);
2849 if (r <= 0)
2850 return r;
2851 }
ded5034e
LP
2852
2853 /* Ensure our array is properly ordered. */
2854 if (p > 0 && check_properly_ordered(ofs, p, direction)) {
2855 log_debug("%s data entry array not properly ordered at entry %" PRIu64, f->path, i);
2856 return -EBADMSG;
2857 }
2858
2859 if (offset)
2860 *offset = ofs;
2861
2862 return 1;
de190aef 2863}
cec736d2 2864
cbdca852
LP
2865int journal_file_move_to_entry_by_offset_for_data(
2866 JournalFile *f,
2867 uint64_t data_offset,
2868 uint64_t p,
2869 direction_t direction,
2870 Object **ret, uint64_t *offset) {
2871
2872 int r;
2873 Object *d;
2874
2875 assert(f);
2876
2877 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
2878 if (r < 0)
2879 return r;
2880
2881 return generic_array_bisect_plus_one(f,
2882 le64toh(d->data.entry_offset),
2883 le64toh(d->data.entry_array_offset),
2884 le64toh(d->data.n_entries),
2885 p,
2886 test_object_offset,
2887 direction,
2888 ret, offset, NULL);
2889}
2890
2891int journal_file_move_to_entry_by_monotonic_for_data(
2892 JournalFile *f,
2893 uint64_t data_offset,
2894 sd_id128_t boot_id,
2895 uint64_t monotonic,
2896 direction_t direction,
2897 Object **ret, uint64_t *offset) {
2898
cbdca852
LP
2899 Object *o, *d;
2900 int r;
2901 uint64_t b, z;
2902
2903 assert(f);
2904
2905 /* First, seek by time */
47838ab3 2906 r = find_data_object_by_boot_id(f, boot_id, &o, &b);
cbdca852
LP
2907 if (r < 0)
2908 return r;
2909 if (r == 0)
2910 return -ENOENT;
2911
2912 r = generic_array_bisect_plus_one(f,
2913 le64toh(o->data.entry_offset),
2914 le64toh(o->data.entry_array_offset),
2915 le64toh(o->data.n_entries),
2916 monotonic,
2917 test_object_monotonic,
2918 direction,
2919 NULL, &z, NULL);
2920 if (r <= 0)
2921 return r;
2922
2923 /* And now, continue seeking until we find an entry that
2924 * exists in both bisection arrays */
2925
2926 for (;;) {
2927 Object *qo;
2928 uint64_t p, q;
2929
2930 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
2931 if (r < 0)
2932 return r;
2933
2934 r = generic_array_bisect_plus_one(f,
2935 le64toh(d->data.entry_offset),
2936 le64toh(d->data.entry_array_offset),
2937 le64toh(d->data.n_entries),
2938 z,
2939 test_object_offset,
2940 direction,
2941 NULL, &p, NULL);
2942 if (r <= 0)
2943 return r;
2944
2945 r = journal_file_move_to_object(f, OBJECT_DATA, b, &o);
2946 if (r < 0)
2947 return r;
2948
2949 r = generic_array_bisect_plus_one(f,
2950 le64toh(o->data.entry_offset),
2951 le64toh(o->data.entry_array_offset),
2952 le64toh(o->data.n_entries),
2953 p,
2954 test_object_offset,
2955 direction,
2956 &qo, &q, NULL);
2957
2958 if (r <= 0)
2959 return r;
2960
2961 if (p == q) {
2962 if (ret)
2963 *ret = qo;
2964 if (offset)
2965 *offset = q;
2966
2967 return 1;
2968 }
2969
2970 z = q;
2971 }
cbdca852
LP
2972}
2973
de190aef
LP
2974int journal_file_move_to_entry_by_seqnum_for_data(
2975 JournalFile *f,
2976 uint64_t data_offset,
2977 uint64_t seqnum,
2978 direction_t direction,
2979 Object **ret, uint64_t *offset) {
cec736d2 2980
de190aef
LP
2981 Object *d;
2982 int r;
cec736d2 2983
91a31dde
LP
2984 assert(f);
2985
de190aef 2986 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
91a31dde 2987 if (r < 0)
de190aef 2988 return r;
cec736d2 2989
de190aef
LP
2990 return generic_array_bisect_plus_one(f,
2991 le64toh(d->data.entry_offset),
2992 le64toh(d->data.entry_array_offset),
2993 le64toh(d->data.n_entries),
2994 seqnum,
2995 test_object_seqnum,
2996 direction,
2997 ret, offset, NULL);
2998}
cec736d2 2999
de190aef
LP
3000int journal_file_move_to_entry_by_realtime_for_data(
3001 JournalFile *f,
3002 uint64_t data_offset,
3003 uint64_t realtime,
3004 direction_t direction,
3005 Object **ret, uint64_t *offset) {
3006
3007 Object *d;
3008 int r;
3009
91a31dde
LP
3010 assert(f);
3011
de190aef 3012 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
91a31dde 3013 if (r < 0)
de190aef
LP
3014 return r;
3015
3016 return generic_array_bisect_plus_one(f,
3017 le64toh(d->data.entry_offset),
3018 le64toh(d->data.entry_array_offset),
3019 le64toh(d->data.n_entries),
3020 realtime,
3021 test_object_realtime,
3022 direction,
3023 ret, offset, NULL);
cec736d2
LP
3024}
3025
0284adc6 3026void journal_file_dump(JournalFile *f) {
7560fffc 3027 Object *o;
7560fffc 3028 int r;
0284adc6 3029 uint64_t p;
7560fffc
LP
3030
3031 assert(f);
c88cc6af 3032 assert(f->header);
7560fffc 3033
0284adc6 3034 journal_file_print_header(f);
7560fffc 3035
0284adc6
LP
3036 p = le64toh(f->header->header_size);
3037 while (p != 0) {
d05089d8 3038 r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o);
0284adc6
LP
3039 if (r < 0)
3040 goto fail;
7560fffc 3041
0284adc6 3042 switch (o->object.type) {
d98cc1f2 3043
0284adc6
LP
3044 case OBJECT_UNUSED:
3045 printf("Type: OBJECT_UNUSED\n");
3046 break;
d98cc1f2 3047
0284adc6
LP
3048 case OBJECT_DATA:
3049 printf("Type: OBJECT_DATA\n");
3050 break;
7560fffc 3051
3c1668da
LP
3052 case OBJECT_FIELD:
3053 printf("Type: OBJECT_FIELD\n");
3054 break;
3055
0284adc6 3056 case OBJECT_ENTRY:
507f22bd
ZJS
3057 printf("Type: OBJECT_ENTRY seqnum=%"PRIu64" monotonic=%"PRIu64" realtime=%"PRIu64"\n",
3058 le64toh(o->entry.seqnum),
3059 le64toh(o->entry.monotonic),
3060 le64toh(o->entry.realtime));
0284adc6 3061 break;
7560fffc 3062
0284adc6
LP
3063 case OBJECT_FIELD_HASH_TABLE:
3064 printf("Type: OBJECT_FIELD_HASH_TABLE\n");
3065 break;
7560fffc 3066
0284adc6
LP
3067 case OBJECT_DATA_HASH_TABLE:
3068 printf("Type: OBJECT_DATA_HASH_TABLE\n");
3069 break;
7560fffc 3070
0284adc6
LP
3071 case OBJECT_ENTRY_ARRAY:
3072 printf("Type: OBJECT_ENTRY_ARRAY\n");
3073 break;
7560fffc 3074
0284adc6 3075 case OBJECT_TAG:
507f22bd
ZJS
3076 printf("Type: OBJECT_TAG seqnum=%"PRIu64" epoch=%"PRIu64"\n",
3077 le64toh(o->tag.seqnum),
3078 le64toh(o->tag.epoch));
0284adc6 3079 break;
3c1668da
LP
3080
3081 default:
8facc349 3082 printf("Type: unknown (%i)\n", o->object.type);
3c1668da 3083 break;
0284adc6 3084 }
7560fffc 3085
d89c8fdf
ZJS
3086 if (o->object.flags & OBJECT_COMPRESSION_MASK)
3087 printf("Flags: %s\n",
3088 object_compressed_to_string(o->object.flags & OBJECT_COMPRESSION_MASK));
7560fffc 3089
0284adc6
LP
3090 if (p == le64toh(f->header->tail_object_offset))
3091 p = 0;
3092 else
3093 p = p + ALIGN64(le64toh(o->object.size));
3094 }
7560fffc 3095
0284adc6
LP
3096 return;
3097fail:
3098 log_error("File corrupt");
7560fffc
LP
3099}
3100
718fe4b1
ZJS
3101static const char* format_timestamp_safe(char *buf, size_t l, usec_t t) {
3102 const char *x;
3103
3104 x = format_timestamp(buf, l, t);
3105 if (x)
3106 return x;
3107 return " --- ";
3108}
3109
0284adc6 3110void journal_file_print_header(JournalFile *f) {
2765b7bb 3111 char a[33], b[33], c[33], d[33];
ed375beb 3112 char x[FORMAT_TIMESTAMP_MAX], y[FORMAT_TIMESTAMP_MAX], z[FORMAT_TIMESTAMP_MAX];
a1a03e30
LP
3113 struct stat st;
3114 char bytes[FORMAT_BYTES_MAX];
7560fffc
LP
3115
3116 assert(f);
c88cc6af 3117 assert(f->header);
7560fffc 3118
0284adc6
LP
3119 printf("File Path: %s\n"
3120 "File ID: %s\n"
3121 "Machine ID: %s\n"
3122 "Boot ID: %s\n"
3123 "Sequential Number ID: %s\n"
3124 "State: %s\n"
3125 "Compatible Flags:%s%s\n"
d89c8fdf 3126 "Incompatible Flags:%s%s%s\n"
507f22bd
ZJS
3127 "Header size: %"PRIu64"\n"
3128 "Arena size: %"PRIu64"\n"
3129 "Data Hash Table Size: %"PRIu64"\n"
3130 "Field Hash Table Size: %"PRIu64"\n"
0284adc6 3131 "Rotate Suggested: %s\n"
0808b92f
LP
3132 "Head Sequential Number: %"PRIu64" (%"PRIx64")\n"
3133 "Tail Sequential Number: %"PRIu64" (%"PRIx64")\n"
3134 "Head Realtime Timestamp: %s (%"PRIx64")\n"
3135 "Tail Realtime Timestamp: %s (%"PRIx64")\n"
3136 "Tail Monotonic Timestamp: %s (%"PRIx64")\n"
507f22bd
ZJS
3137 "Objects: %"PRIu64"\n"
3138 "Entry Objects: %"PRIu64"\n",
0284adc6
LP
3139 f->path,
3140 sd_id128_to_string(f->header->file_id, a),
3141 sd_id128_to_string(f->header->machine_id, b),
3142 sd_id128_to_string(f->header->boot_id, c),
2765b7bb 3143 sd_id128_to_string(f->header->seqnum_id, d),
3223f44f
LP
3144 f->header->state == STATE_OFFLINE ? "OFFLINE" :
3145 f->header->state == STATE_ONLINE ? "ONLINE" :
3146 f->header->state == STATE_ARCHIVED ? "ARCHIVED" : "UNKNOWN",
8088cbd3 3147 JOURNAL_HEADER_SEALED(f->header) ? " SEALED" : "",
d89c8fdf
ZJS
3148 (le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_ANY) ? " ???" : "",
3149 JOURNAL_HEADER_COMPRESSED_XZ(f->header) ? " COMPRESSED-XZ" : "",
3150 JOURNAL_HEADER_COMPRESSED_LZ4(f->header) ? " COMPRESSED-LZ4" : "",
3151 (le32toh(f->header->incompatible_flags) & ~HEADER_INCOMPATIBLE_ANY) ? " ???" : "",
507f22bd
ZJS
3152 le64toh(f->header->header_size),
3153 le64toh(f->header->arena_size),
3154 le64toh(f->header->data_hash_table_size) / sizeof(HashItem),
3155 le64toh(f->header->field_hash_table_size) / sizeof(HashItem),
fb0951b0 3156 yes_no(journal_file_rotate_suggested(f, 0)),
0808b92f
LP
3157 le64toh(f->header->head_entry_seqnum), le64toh(f->header->head_entry_seqnum),
3158 le64toh(f->header->tail_entry_seqnum), le64toh(f->header->tail_entry_seqnum),
3159 format_timestamp_safe(x, sizeof(x), le64toh(f->header->head_entry_realtime)), le64toh(f->header->head_entry_realtime),
3160 format_timestamp_safe(y, sizeof(y), le64toh(f->header->tail_entry_realtime)), le64toh(f->header->tail_entry_realtime),
3161 format_timespan(z, sizeof(z), le64toh(f->header->tail_entry_monotonic), USEC_PER_MSEC), le64toh(f->header->tail_entry_monotonic),
507f22bd
ZJS
3162 le64toh(f->header->n_objects),
3163 le64toh(f->header->n_entries));
7560fffc 3164
0284adc6 3165 if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
507f22bd 3166 printf("Data Objects: %"PRIu64"\n"
0284adc6 3167 "Data Hash Table Fill: %.1f%%\n",
507f22bd 3168 le64toh(f->header->n_data),
0284adc6 3169 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))));
7560fffc 3170
0284adc6 3171 if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
507f22bd 3172 printf("Field Objects: %"PRIu64"\n"
0284adc6 3173 "Field Hash Table Fill: %.1f%%\n",
507f22bd 3174 le64toh(f->header->n_fields),
0284adc6 3175 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))));
3223f44f
LP
3176
3177 if (JOURNAL_HEADER_CONTAINS(f->header, n_tags))
507f22bd
ZJS
3178 printf("Tag Objects: %"PRIu64"\n",
3179 le64toh(f->header->n_tags));
3223f44f 3180 if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
507f22bd
ZJS
3181 printf("Entry Array Objects: %"PRIu64"\n",
3182 le64toh(f->header->n_entry_arrays));
a1a03e30
LP
3183
3184 if (fstat(f->fd, &st) >= 0)
59f448cf 3185 printf("Disk usage: %s\n", format_bytes(bytes, sizeof(bytes), (uint64_t) st.st_blocks * 512ULL));
7560fffc
LP
3186}
3187
fc68c929
LP
3188static int journal_file_warn_btrfs(JournalFile *f) {
3189 unsigned attrs;
3190 int r;
3191
3192 assert(f);
3193
3194 /* Before we write anything, check if the COW logic is turned
3195 * off on btrfs. Given our write pattern that is quite
3196 * unfriendly to COW file systems this should greatly improve
3197 * performance on COW file systems, such as btrfs, at the
3198 * expense of data integrity features (which shouldn't be too
3199 * bad, given that we do our own checksumming). */
3200
3201 r = btrfs_is_filesystem(f->fd);
3202 if (r < 0)
3203 return log_warning_errno(r, "Failed to determine if journal is on btrfs: %m");
3204 if (!r)
3205 return 0;
3206
3207 r = read_attr_fd(f->fd, &attrs);
3208 if (r < 0)
3209 return log_warning_errno(r, "Failed to read file attributes: %m");
3210
3211 if (attrs & FS_NOCOW_FL) {
3212 log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
3213 return 0;
3214 }
3215
3216 log_notice("Creating journal file %s on a btrfs file system, and copy-on-write is enabled. "
3217 "This is likely to slow down journal access substantially, please consider turning "
3218 "off the copy-on-write file attribute on the journal directory, using chattr +C.", f->path);
3219
3220 return 1;
3221}
3222
0284adc6 3223int journal_file_open(
5d1ce257 3224 int fd,
0284adc6
LP
3225 const char *fname,
3226 int flags,
3227 mode_t mode,
3228 bool compress,
baed47c3 3229 bool seal,
0284adc6
LP
3230 JournalMetrics *metrics,
3231 MMapCache *mmap_cache,
b58c888f 3232 Set *deferred_closes,
0284adc6
LP
3233 JournalFile *template,
3234 JournalFile **ret) {
7560fffc 3235
fa6ac760 3236 bool newly_created = false;
0284adc6 3237 JournalFile *f;
fa6ac760 3238 void *h;
0284adc6 3239 int r;
7560fffc 3240
0559d3a5 3241 assert(ret);
5d1ce257 3242 assert(fd >= 0 || fname);
7560fffc 3243
0284adc6
LP
3244 if ((flags & O_ACCMODE) != O_RDONLY &&
3245 (flags & O_ACCMODE) != O_RDWR)
3246 return -EINVAL;
7560fffc 3247
5d1ce257
LP
3248 if (fname) {
3249 if (!endswith(fname, ".journal") &&
3250 !endswith(fname, ".journal~"))
3251 return -EINVAL;
3252 }
7560fffc 3253
0284adc6
LP
3254 f = new0(JournalFile, 1);
3255 if (!f)
3256 return -ENOMEM;
7560fffc 3257
5d1ce257 3258 f->fd = fd;
0284adc6 3259 f->mode = mode;
7560fffc 3260
0284adc6
LP
3261 f->flags = flags;
3262 f->prot = prot_from_flags(flags);
3263 f->writable = (flags & O_ACCMODE) != O_RDONLY;
92261977 3264#if defined(HAVE_LZ4)
d89c8fdf
ZJS
3265 f->compress_lz4 = compress;
3266#elif defined(HAVE_XZ)
3267 f->compress_xz = compress;
48b61739 3268#endif
49a32d43 3269#ifdef HAVE_GCRYPT
baed47c3 3270 f->seal = seal;
49a32d43 3271#endif
7560fffc 3272
0284adc6
LP
3273 if (mmap_cache)
3274 f->mmap = mmap_cache_ref(mmap_cache);
3275 else {
84168d80 3276 f->mmap = mmap_cache_new();
0284adc6
LP
3277 if (!f->mmap) {
3278 r = -ENOMEM;
3279 goto fail;
3280 }
3281 }
7560fffc 3282
7645c77b 3283 if (fname) {
5d1ce257 3284 f->path = strdup(fname);
7645c77b
ZJS
3285 if (!f->path) {
3286 r = -ENOMEM;
3287 goto fail;
3288 }
3289 } else {
3290 /* If we don't know the path, fill in something explanatory and vaguely useful */
3291 if (asprintf(&f->path, "/proc/self/%i", fd) < 0) {
3292 r = -ENOMEM;
3293 goto fail;
3294 }
0284adc6 3295 }
7560fffc 3296
4743015d 3297 f->chain_cache = ordered_hashmap_new(&uint64_hash_ops);
a4bcff5b
LP
3298 if (!f->chain_cache) {
3299 r = -ENOMEM;
3300 goto fail;
3301 }
3302
0284adc6 3303 if (f->fd < 0) {
5d1ce257
LP
3304 f->fd = open(f->path, f->flags|O_CLOEXEC, f->mode);
3305 if (f->fd < 0) {
3306 r = -errno;
3307 goto fail;
3308 }
3309
3310 /* fds we opened here by us should also be closed by us. */
3311 f->close_fd = true;
7560fffc 3312 }
7560fffc 3313
be7cdd8e
VC
3314 f->cache_fd = mmap_cache_add_fd(f->mmap, f->fd);
3315 if (!f->cache_fd) {
3316 r = -ENOMEM;
3317 goto fail;
3318 }
3319
2678031a
LP
3320 r = journal_file_fstat(f);
3321 if (r < 0)
0284adc6 3322 goto fail;
7560fffc 3323
0284adc6 3324 if (f->last_stat.st_size == 0 && f->writable) {
11689d2a 3325
fc68c929 3326 (void) journal_file_warn_btrfs(f);
11689d2a 3327
fb0951b0
LP
3328 /* Let's attach the creation time to the journal file,
3329 * so that the vacuuming code knows the age of this
3330 * file even if the file might end up corrupted one
3331 * day... Ideally we'd just use the creation time many
3332 * file systems maintain for each file, but there is
3333 * currently no usable API to query this, hence let's
3334 * emulate this via extended attributes. If extended
3335 * attributes are not supported we'll just skip this,
7517e174 3336 * and rely solely on mtime/atime/ctime of the file. */
fb0951b0 3337
d61b600d 3338 fd_setcrtime(f->fd, 0);
7560fffc 3339
feb12d3e 3340#ifdef HAVE_GCRYPT
0284adc6 3341 /* Try to load the FSPRG state, and if we can't, then
baed47c3 3342 * just don't do sealing */
49a32d43
LP
3343 if (f->seal) {
3344 r = journal_file_fss_load(f);
3345 if (r < 0)
3346 f->seal = false;
3347 }
feb12d3e 3348#endif
7560fffc 3349
0284adc6
LP
3350 r = journal_file_init_header(f, template);
3351 if (r < 0)
3352 goto fail;
7560fffc 3353
2678031a
LP
3354 r = journal_file_fstat(f);
3355 if (r < 0)
0284adc6 3356 goto fail;
fb0951b0
LP
3357
3358 newly_created = true;
0284adc6 3359 }
7560fffc 3360
0284adc6 3361 if (f->last_stat.st_size < (off_t) HEADER_SIZE_MIN) {
cfb571f3 3362 r = -ENODATA;
0284adc6
LP
3363 goto fail;
3364 }
7560fffc 3365
b42549ad 3366 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 3367 if (r < 0)
0284adc6 3368 goto fail;
7560fffc 3369
fa6ac760
LP
3370 f->header = h;
3371
0284adc6 3372 if (!newly_created) {
b58c888f
VC
3373 if (deferred_closes)
3374 journal_file_close_set(deferred_closes);
3375
0284adc6
LP
3376 r = journal_file_verify_header(f);
3377 if (r < 0)
3378 goto fail;
3379 }
7560fffc 3380
feb12d3e 3381#ifdef HAVE_GCRYPT
0284adc6 3382 if (!newly_created && f->writable) {
baed47c3 3383 r = journal_file_fss_load(f);
0284adc6
LP
3384 if (r < 0)
3385 goto fail;
3386 }
feb12d3e 3387#endif
cec736d2
LP
3388
3389 if (f->writable) {
4a92baf3
LP
3390 if (metrics) {
3391 journal_default_metrics(metrics, f->fd);
3392 f->metrics = *metrics;
3393 } else if (template)
3394 f->metrics = template->metrics;
3395
cec736d2
LP
3396 r = journal_file_refresh_header(f);
3397 if (r < 0)
3398 goto fail;
3399 }
3400
feb12d3e 3401#ifdef HAVE_GCRYPT
baed47c3 3402 r = journal_file_hmac_setup(f);
14d10188
LP
3403 if (r < 0)
3404 goto fail;
feb12d3e 3405#endif
14d10188 3406
cec736d2 3407 if (newly_created) {
de190aef 3408 r = journal_file_setup_field_hash_table(f);
cec736d2
LP
3409 if (r < 0)
3410 goto fail;
3411
de190aef 3412 r = journal_file_setup_data_hash_table(f);
cec736d2
LP
3413 if (r < 0)
3414 goto fail;
7560fffc 3415
feb12d3e 3416#ifdef HAVE_GCRYPT
7560fffc
LP
3417 r = journal_file_append_first_tag(f);
3418 if (r < 0)
3419 goto fail;
feb12d3e 3420#endif
cec736d2
LP
3421 }
3422
be7cdd8e 3423 if (mmap_cache_got_sigbus(f->mmap, f->cache_fd)) {
fa6ac760
LP
3424 r = -EIO;
3425 goto fail;
3426 }
3427
7a24f3bf 3428 if (template && template->post_change_timer) {
e167d7fd
LP
3429 r = journal_file_enable_post_change_timer(
3430 f,
3431 sd_event_source_get_event(template->post_change_timer),
3432 template->post_change_timer_period);
7a24f3bf 3433
7a24f3bf
VC
3434 if (r < 0)
3435 goto fail;
3436 }
3437
f8e2f4d6 3438 /* The file is opened now successfully, thus we take possession of any passed in fd. */
5d1ce257
LP
3439 f->close_fd = true;
3440
0559d3a5 3441 *ret = f;
cec736d2
LP
3442 return 0;
3443
3444fail:
be7cdd8e 3445 if (f->cache_fd && mmap_cache_got_sigbus(f->mmap, f->cache_fd))
fa6ac760
LP
3446 r = -EIO;
3447
69a3a6fd 3448 (void) journal_file_close(f);
cec736d2
LP
3449
3450 return r;
3451}
0ac38b70 3452
b58c888f 3453int journal_file_rotate(JournalFile **f, bool compress, bool seal, Set *deferred_closes) {
57535f47 3454 _cleanup_free_ char *p = NULL;
0ac38b70
LP
3455 size_t l;
3456 JournalFile *old_file, *new_file = NULL;
3457 int r;
3458
3459 assert(f);
3460 assert(*f);
3461
3462 old_file = *f;
3463
3464 if (!old_file->writable)
3465 return -EINVAL;
3466
5d1ce257 3467 /* 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 3468 * rotation, since we don't know the actual path, and couldn't rename the file hence. */
5d1ce257
LP
3469 if (path_startswith(old_file->path, "/proc/self/fd"))
3470 return -EINVAL;
3471
0ac38b70
LP
3472 if (!endswith(old_file->path, ".journal"))
3473 return -EINVAL;
3474
3475 l = strlen(old_file->path);
57535f47
ZJS
3476 r = asprintf(&p, "%.*s@" SD_ID128_FORMAT_STR "-%016"PRIx64"-%016"PRIx64".journal",
3477 (int) l - 8, old_file->path,
3478 SD_ID128_FORMAT_VAL(old_file->header->seqnum_id),
3479 le64toh((*f)->header->head_entry_seqnum),
3480 le64toh((*f)->header->head_entry_realtime));
3481 if (r < 0)
0ac38b70
LP
3482 return -ENOMEM;
3483
2678031a
LP
3484 /* Try to rename the file to the archived version. If the file
3485 * already was deleted, we'll get ENOENT, let's ignore that
3486 * case. */
0ac38b70 3487 r = rename(old_file->path, p);
2678031a 3488 if (r < 0 && errno != ENOENT)
0ac38b70
LP
3489 return -errno;
3490
1fcefd88
LP
3491 /* Sync the rename to disk */
3492 (void) fsync_directory_of_file(old_file->fd);
3493
8eb85171
VC
3494 /* Set as archive so offlining commits w/state=STATE_ARCHIVED.
3495 * Previously we would set old_file->header->state to STATE_ARCHIVED directly here,
3496 * but journal_file_set_offline() short-circuits when state != STATE_ONLINE, which
3497 * would result in the rotated journal never getting fsync() called before closing.
3498 * Now we simply queue the archive state by setting an archive bit, leaving the state
3499 * as STATE_ONLINE so proper offlining occurs. */
3500 old_file->archive = true;
0ac38b70 3501
f27a3864
LP
3502 /* Currently, btrfs is not very good with out write patterns
3503 * and fragments heavily. Let's defrag our journal files when
3504 * we archive them */
3505 old_file->defrag_on_close = true;
3506
5d1ce257 3507 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
3508
3509 if (deferred_closes &&
3510 set_put(deferred_closes, old_file) >= 0)
3511 (void) journal_file_set_offline(old_file, false);
3512 else
3513 (void) journal_file_close(old_file);
0ac38b70
LP
3514
3515 *f = new_file;
3516 return r;
3517}
3518
9447a7f1
LP
3519int journal_file_open_reliably(
3520 const char *fname,
3521 int flags,
3522 mode_t mode,
7560fffc 3523 bool compress,
baed47c3 3524 bool seal,
4a92baf3 3525 JournalMetrics *metrics,
27370278 3526 MMapCache *mmap_cache,
b58c888f 3527 Set *deferred_closes,
9447a7f1
LP
3528 JournalFile *template,
3529 JournalFile **ret) {
3530
3531 int r;
3532 size_t l;
ed375beb 3533 _cleanup_free_ char *p = NULL;
9447a7f1 3534
5d1ce257 3535 r = journal_file_open(-1, fname, flags, mode, compress, seal, metrics, mmap_cache, deferred_closes, template, ret);
288359db 3536 if (!IN_SET(r,
b288cdeb
ZJS
3537 -EBADMSG, /* Corrupted */
3538 -ENODATA, /* Truncated */
3539 -EHOSTDOWN, /* Other machine */
3540 -EPROTONOSUPPORT, /* Incompatible feature */
3541 -EBUSY, /* Unclean shutdown */
3542 -ESHUTDOWN, /* Already archived */
288359db 3543 -EIO, /* IO error, including SIGBUS on mmap */
ae739cc1
LP
3544 -EIDRM, /* File has been deleted */
3545 -ETXTBSY)) /* File is from the future */
9447a7f1
LP
3546 return r;
3547
3548 if ((flags & O_ACCMODE) == O_RDONLY)
3549 return r;
3550
3551 if (!(flags & O_CREAT))
3552 return r;
3553
7560fffc
LP
3554 if (!endswith(fname, ".journal"))
3555 return r;
3556
5c70eab4
LP
3557 /* The file is corrupted. Rotate it away and try it again (but only once) */
3558
9447a7f1 3559 l = strlen(fname);
d587eca5 3560 if (asprintf(&p, "%.*s@%016"PRIx64 "-%016"PRIx64 ".journal~",
57535f47 3561 (int) l - 8, fname,
d587eca5 3562 now(CLOCK_REALTIME),
9bf3b535 3563 random_u64()) < 0)
9447a7f1
LP
3564 return -ENOMEM;
3565
65089b82 3566 if (rename(fname, p) < 0)
9447a7f1
LP
3567 return -errno;
3568
f27a3864
LP
3569 /* btrfs doesn't cope well with our write pattern and
3570 * fragments heavily. Let's defrag all files we rotate */
11689d2a 3571
a67d68b8 3572 (void) chattr_path(p, 0, FS_NOCOW_FL);
f27a3864
LP
3573 (void) btrfs_defrag(p);
3574
65089b82 3575 log_warning_errno(r, "File %s corrupted or uncleanly shut down, renaming and replacing.", fname);
9447a7f1 3576
5d1ce257 3577 return journal_file_open(-1, fname, flags, mode, compress, seal, metrics, mmap_cache, deferred_closes, template, ret);
9447a7f1
LP
3578}
3579
cf244689
LP
3580int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset) {
3581 uint64_t i, n;
3582 uint64_t q, xor_hash = 0;
3583 int r;
3584 EntryItem *items;
3585 dual_timestamp ts;
3586
3587 assert(from);
3588 assert(to);
3589 assert(o);
3590 assert(p);
3591
3592 if (!to->writable)
3593 return -EPERM;
3594
3595 ts.monotonic = le64toh(o->entry.monotonic);
3596 ts.realtime = le64toh(o->entry.realtime);
3597
cf244689 3598 n = journal_file_entry_n_items(o);
4faa7004
TA
3599 /* alloca() can't take 0, hence let's allocate at least one */
3600 items = alloca(sizeof(EntryItem) * MAX(1u, n));
cf244689
LP
3601
3602 for (i = 0; i < n; i++) {
4fd052ae
FC
3603 uint64_t l, h;
3604 le64_t le_hash;
cf244689
LP
3605 size_t t;
3606 void *data;
3607 Object *u;
3608
3609 q = le64toh(o->entry.items[i].object_offset);
3610 le_hash = o->entry.items[i].hash;
3611
3612 r = journal_file_move_to_object(from, OBJECT_DATA, q, &o);
3613 if (r < 0)
3614 return r;
3615
3616 if (le_hash != o->data.hash)
3617 return -EBADMSG;
3618
3619 l = le64toh(o->object.size) - offsetof(Object, data.payload);
3620 t = (size_t) l;
3621
3622 /* We hit the limit on 32bit machines */
3623 if ((uint64_t) t != l)
3624 return -E2BIG;
3625
d89c8fdf 3626 if (o->object.flags & OBJECT_COMPRESSION_MASK) {
3b1a55e1 3627#if defined(HAVE_XZ) || defined(HAVE_LZ4)
a7f7d1bd 3628 size_t rsize = 0;
cf244689 3629
d89c8fdf
ZJS
3630 r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK,
3631 o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize, 0);
3632 if (r < 0)
3633 return r;
cf244689
LP
3634
3635 data = from->compress_buffer;
3636 l = rsize;
3b1a55e1
ZJS
3637#else
3638 return -EPROTONOSUPPORT;
3639#endif
cf244689
LP
3640 } else
3641 data = o->data.payload;
3642
3643 r = journal_file_append_data(to, data, l, &u, &h);
3644 if (r < 0)
3645 return r;
3646
3647 xor_hash ^= le64toh(u->data.hash);
3648 items[i].object_offset = htole64(h);
3649 items[i].hash = u->data.hash;
3650
3651 r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
3652 if (r < 0)
3653 return r;
3654 }
3655
fa6ac760
LP
3656 r = journal_file_append_entry_internal(to, &ts, xor_hash, items, n, seqnum, ret, offset);
3657
be7cdd8e 3658 if (mmap_cache_got_sigbus(to->mmap, to->cache_fd))
fa6ac760
LP
3659 return -EIO;
3660
3661 return r;
cf244689 3662}
babfc091 3663
8580d1f7
LP
3664void journal_reset_metrics(JournalMetrics *m) {
3665 assert(m);
3666
3667 /* Set everything to "pick automatic values". */
3668
3669 *m = (JournalMetrics) {
3670 .min_use = (uint64_t) -1,
3671 .max_use = (uint64_t) -1,
3672 .min_size = (uint64_t) -1,
3673 .max_size = (uint64_t) -1,
3674 .keep_free = (uint64_t) -1,
3675 .n_max_files = (uint64_t) -1,
3676 };
3677}
3678
babfc091 3679void journal_default_metrics(JournalMetrics *m, int fd) {
8580d1f7 3680 char a[FORMAT_BYTES_MAX], b[FORMAT_BYTES_MAX], c[FORMAT_BYTES_MAX], d[FORMAT_BYTES_MAX], e[FORMAT_BYTES_MAX];
babfc091 3681 struct statvfs ss;
8580d1f7 3682 uint64_t fs_size;
babfc091
LP
3683
3684 assert(m);
3685 assert(fd >= 0);
3686
3687 if (fstatvfs(fd, &ss) >= 0)
3688 fs_size = ss.f_frsize * ss.f_blocks;
8580d1f7
LP
3689 else {
3690 log_debug_errno(errno, "Failed to detremine disk size: %m");
3691 fs_size = 0;
3692 }
babfc091
LP
3693
3694 if (m->max_use == (uint64_t) -1) {
3695
3696 if (fs_size > 0) {
3697 m->max_use = PAGE_ALIGN(fs_size / 10); /* 10% of file system size */
3698
3699 if (m->max_use > DEFAULT_MAX_USE_UPPER)
3700 m->max_use = DEFAULT_MAX_USE_UPPER;
3701
3702 if (m->max_use < DEFAULT_MAX_USE_LOWER)
3703 m->max_use = DEFAULT_MAX_USE_LOWER;
3704 } else
3705 m->max_use = DEFAULT_MAX_USE_LOWER;
3706 } else {
3707 m->max_use = PAGE_ALIGN(m->max_use);
3708
8580d1f7 3709 if (m->max_use != 0 && m->max_use < JOURNAL_FILE_SIZE_MIN*2)
babfc091
LP
3710 m->max_use = JOURNAL_FILE_SIZE_MIN*2;
3711 }
3712
8580d1f7
LP
3713 if (m->min_use == (uint64_t) -1)
3714 m->min_use = DEFAULT_MIN_USE;
3715
3716 if (m->min_use > m->max_use)
3717 m->min_use = m->max_use;
3718
babfc091
LP
3719 if (m->max_size == (uint64_t) -1) {
3720 m->max_size = PAGE_ALIGN(m->max_use / 8); /* 8 chunks */
3721
3722 if (m->max_size > DEFAULT_MAX_SIZE_UPPER)
3723 m->max_size = DEFAULT_MAX_SIZE_UPPER;
3724 } else
3725 m->max_size = PAGE_ALIGN(m->max_size);
3726
8580d1f7
LP
3727 if (m->max_size != 0) {
3728 if (m->max_size < JOURNAL_FILE_SIZE_MIN)
3729 m->max_size = JOURNAL_FILE_SIZE_MIN;
babfc091 3730
8580d1f7
LP
3731 if (m->max_use != 0 && m->max_size*2 > m->max_use)
3732 m->max_use = m->max_size*2;
3733 }
babfc091
LP
3734
3735 if (m->min_size == (uint64_t) -1)
3736 m->min_size = JOURNAL_FILE_SIZE_MIN;
3737 else {
3738 m->min_size = PAGE_ALIGN(m->min_size);
3739
3740 if (m->min_size < JOURNAL_FILE_SIZE_MIN)
3741 m->min_size = JOURNAL_FILE_SIZE_MIN;
3742
8580d1f7 3743 if (m->max_size != 0 && m->min_size > m->max_size)
babfc091
LP
3744 m->max_size = m->min_size;
3745 }
3746
3747 if (m->keep_free == (uint64_t) -1) {
3748
3749 if (fs_size > 0) {
8621b110 3750 m->keep_free = PAGE_ALIGN(fs_size * 3 / 20); /* 15% of file system size */
babfc091
LP
3751
3752 if (m->keep_free > DEFAULT_KEEP_FREE_UPPER)
3753 m->keep_free = DEFAULT_KEEP_FREE_UPPER;
3754
3755 } else
3756 m->keep_free = DEFAULT_KEEP_FREE;
3757 }
3758
8580d1f7
LP
3759 if (m->n_max_files == (uint64_t) -1)
3760 m->n_max_files = DEFAULT_N_MAX_FILES;
3761
3762 log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64,
3763 format_bytes(a, sizeof(a), m->min_use),
3764 format_bytes(b, sizeof(b), m->max_use),
3765 format_bytes(c, sizeof(c), m->max_size),
3766 format_bytes(d, sizeof(d), m->min_size),
3767 format_bytes(e, sizeof(e), m->keep_free),
3768 m->n_max_files);
babfc091 3769}
08984293
LP
3770
3771int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *from, usec_t *to) {
08984293 3772 assert(f);
c88cc6af 3773 assert(f->header);
08984293
LP
3774 assert(from || to);
3775
3776 if (from) {
162566a4
LP
3777 if (f->header->head_entry_realtime == 0)
3778 return -ENOENT;
08984293 3779
162566a4 3780 *from = le64toh(f->header->head_entry_realtime);
08984293
LP
3781 }
3782
3783 if (to) {
162566a4
LP
3784 if (f->header->tail_entry_realtime == 0)
3785 return -ENOENT;
08984293 3786
162566a4 3787 *to = le64toh(f->header->tail_entry_realtime);
08984293
LP
3788 }
3789
3790 return 1;
3791}
3792
3793int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot_id, usec_t *from, usec_t *to) {
08984293
LP
3794 Object *o;
3795 uint64_t p;
3796 int r;
3797
3798 assert(f);
3799 assert(from || to);
3800
47838ab3 3801 r = find_data_object_by_boot_id(f, boot_id, &o, &p);
08984293
LP
3802 if (r <= 0)
3803 return r;
3804
3805 if (le64toh(o->data.n_entries) <= 0)
3806 return 0;
3807
3808 if (from) {
3809 r = journal_file_move_to_object(f, OBJECT_ENTRY, le64toh(o->data.entry_offset), &o);
3810 if (r < 0)
3811 return r;
3812
3813 *from = le64toh(o->entry.monotonic);
3814 }
3815
3816 if (to) {
3817 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
3818 if (r < 0)
3819 return r;
3820
3821 r = generic_array_get_plus_one(f,
3822 le64toh(o->data.entry_offset),
3823 le64toh(o->data.entry_array_offset),
3824 le64toh(o->data.n_entries)-1,
3825 &o, NULL);
3826 if (r <= 0)
3827 return r;
3828
3829 *to = le64toh(o->entry.monotonic);
3830 }
3831
3832 return 1;
3833}
dca6219e 3834
fb0951b0 3835bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec) {
dca6219e 3836 assert(f);
c88cc6af 3837 assert(f->header);
dca6219e
LP
3838
3839 /* If we gained new header fields we gained new features,
3840 * hence suggest a rotation */
361f9cbc
LP
3841 if (le64toh(f->header->header_size) < sizeof(Header)) {
3842 log_debug("%s uses an outdated header, suggesting rotation.", f->path);
dca6219e 3843 return true;
361f9cbc 3844 }
dca6219e
LP
3845
3846 /* Let's check if the hash tables grew over a certain fill
3847 * level (75%, borrowing this value from Java's hash table
3848 * implementation), and if so suggest a rotation. To calculate
3849 * the fill level we need the n_data field, which only exists
3850 * in newer versions. */
3851
3852 if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
361f9cbc 3853 if (le64toh(f->header->n_data) * 4ULL > (le64toh(f->header->data_hash_table_size) / sizeof(HashItem)) * 3ULL) {
507f22bd 3854 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
3855 f->path,
3856 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))),
507f22bd
ZJS
3857 le64toh(f->header->n_data),
3858 le64toh(f->header->data_hash_table_size) / sizeof(HashItem),
3859 (unsigned long long) f->last_stat.st_size,
3860 f->last_stat.st_size / le64toh(f->header->n_data));
dca6219e 3861 return true;
361f9cbc 3862 }
dca6219e
LP
3863
3864 if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
361f9cbc 3865 if (le64toh(f->header->n_fields) * 4ULL > (le64toh(f->header->field_hash_table_size) / sizeof(HashItem)) * 3ULL) {
507f22bd 3866 log_debug("Field hash table of %s has a fill level at %.1f (%"PRIu64" of %"PRIu64" items), suggesting rotation.",
361f9cbc
LP
3867 f->path,
3868 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))),
507f22bd
ZJS
3869 le64toh(f->header->n_fields),
3870 le64toh(f->header->field_hash_table_size) / sizeof(HashItem));
dca6219e 3871 return true;
361f9cbc 3872 }
dca6219e 3873
0598fd4a
LP
3874 /* Are the data objects properly indexed by field objects? */
3875 if (JOURNAL_HEADER_CONTAINS(f->header, n_data) &&
3876 JOURNAL_HEADER_CONTAINS(f->header, n_fields) &&
3877 le64toh(f->header->n_data) > 0 &&
3878 le64toh(f->header->n_fields) == 0)
3879 return true;
3880
fb0951b0
LP
3881 if (max_file_usec > 0) {
3882 usec_t t, h;
3883
3884 h = le64toh(f->header->head_entry_realtime);
3885 t = now(CLOCK_REALTIME);
3886
3887 if (h > 0 && t > h + max_file_usec)
3888 return true;
3889 }
3890
dca6219e
LP
3891 return false;
3892}