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