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