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