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