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