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