1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include <linux/magic.h>
10 #include <sys/statvfs.h>
16 #include "alloc-util.h"
17 #include "chattr-util.h"
21 #include "format-util.h"
23 #include "journal-authenticate.h"
24 #include "journal-def.h"
25 #include "journal-file.h"
26 #include "journal-internal.h"
28 #include "memory-util.h"
29 #include "path-util.h"
30 #include "random-util.h"
32 #include "sort-util.h"
33 #include "stat-util.h"
34 #include "string-table.h"
35 #include "string-util.h"
37 #include "sync-util.h"
38 #include "user-util.h"
39 #include "xattr-util.h"
41 #define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem))
42 #define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem))
44 #define DEFAULT_COMPRESS_THRESHOLD (512ULL)
45 #define MIN_COMPRESS_THRESHOLD (8ULL)
47 /* This is the minimum journal file size */
48 #define JOURNAL_FILE_SIZE_MIN (512 * 1024ULL) /* 512 KiB */
49 #define JOURNAL_COMPACT_SIZE_MAX UINT32_MAX /* 4 GiB */
51 /* These are the lower and upper bounds if we deduce the max_use value
52 * from the file system size */
53 #define MAX_USE_LOWER (1 * 1024 * 1024ULL) /* 1 MiB */
54 #define MAX_USE_UPPER (4 * 1024 * 1024 * 1024ULL) /* 4 GiB */
56 /* Those are the lower and upper bounds for the minimal use limit,
57 * i.e. how much we'll use even if keep_free suggests otherwise. */
58 #define MIN_USE_LOW (1 * 1024 * 1024ULL) /* 1 MiB */
59 #define MIN_USE_HIGH (16 * 1024 * 1024ULL) /* 16 MiB */
61 /* This is the upper bound if we deduce max_size from max_use */
62 #define MAX_SIZE_UPPER (128 * 1024 * 1024ULL) /* 128 MiB */
64 /* This is the upper bound if we deduce the keep_free value from the
66 #define KEEP_FREE_UPPER (4 * 1024 * 1024 * 1024ULL) /* 4 GiB */
68 /* This is the keep_free value when we can't determine the system
70 #define DEFAULT_KEEP_FREE (1024 * 1024ULL) /* 1 MB */
72 /* This is the default maximum number of journal files to keep around. */
73 #define DEFAULT_N_MAX_FILES 100
75 /* n_data was the first entry we added after the initial file format design */
76 #define HEADER_SIZE_MIN ALIGN64(offsetof(Header, n_data))
78 /* How many entries to keep in the entry array chain cache at max */
79 #define CHAIN_CACHE_MAX 20
81 /* How much to increase the journal file size at once each time we allocate something new. */
82 #define FILE_SIZE_INCREASE (8 * 1024 * 1024ULL) /* 8MB */
84 /* Reread fstat() of the file for detecting deletions at least this often */
85 #define LAST_STAT_REFRESH_USEC (5*USEC_PER_SEC)
87 /* The mmap context to use for the header we pick as one above the last defined typed */
88 #define CONTEXT_HEADER _OBJECT_TYPE_MAX
90 /* Longest hash chain to rotate after */
91 #define HASH_CHAIN_DEPTH_MAX 100
94 # pragma GCC diagnostic ignored "-Waddress-of-packed-member"
97 static int mmap_prot_from_open_flags(int flags
) {
98 switch (flags
& O_ACCMODE
) {
104 return PROT_READ
|PROT_WRITE
;
106 assert_not_reached();
110 int journal_file_tail_end_by_pread(JournalFile
*f
, uint64_t *ret_offset
) {
118 /* Same as journal_file_tail_end_by_mmap() below, but operates with pread() to avoid the mmap cache
119 * (and thus is thread safe) */
121 p
= le64toh(f
->header
->tail_object_offset
);
123 p
= le64toh(f
->header
->header_size
);
128 r
= journal_file_read_object_header(f
, OBJECT_UNUSED
, p
, &tail
);
132 sz
= le64toh(tail
.object
.size
);
133 if (sz
> UINT64_MAX
- sizeof(uint64_t) + 1)
137 if (p
> UINT64_MAX
- sz
)
148 int journal_file_tail_end_by_mmap(JournalFile
*f
, uint64_t *ret_offset
) {
156 /* Same as journal_file_tail_end_by_pread() above, but operates with the usual mmap logic */
158 p
= le64toh(f
->header
->tail_object_offset
);
160 p
= le64toh(f
->header
->header_size
);
165 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &tail
);
169 sz
= le64toh(READ_NOW(tail
->object
.size
));
170 if (sz
> UINT64_MAX
- sizeof(uint64_t) + 1)
174 if (p
> UINT64_MAX
- sz
)
185 int journal_file_set_offline_thread_join(JournalFile
*f
) {
190 if (f
->offline_state
== OFFLINE_JOINED
)
193 r
= pthread_join(f
->offline_thread
, NULL
);
197 f
->offline_state
= OFFLINE_JOINED
;
199 if (mmap_cache_fd_got_sigbus(f
->cache_fd
))
205 static int journal_file_set_online(JournalFile
*f
) {
210 if (!journal_file_writable(f
))
213 if (f
->fd
< 0 || !f
->header
)
217 switch (f
->offline_state
) {
219 /* No offline thread, no need to wait. */
223 case OFFLINE_SYNCING
: {
224 OfflineState tmp_state
= OFFLINE_SYNCING
;
225 if (!__atomic_compare_exchange_n(&f
->offline_state
, &tmp_state
, OFFLINE_CANCEL
,
226 false, __ATOMIC_SEQ_CST
, __ATOMIC_SEQ_CST
))
229 /* Canceled syncing prior to offlining, no need to wait. */
233 case OFFLINE_AGAIN_FROM_SYNCING
: {
234 OfflineState tmp_state
= OFFLINE_AGAIN_FROM_SYNCING
;
235 if (!__atomic_compare_exchange_n(&f
->offline_state
, &tmp_state
, OFFLINE_CANCEL
,
236 false, __ATOMIC_SEQ_CST
, __ATOMIC_SEQ_CST
))
239 /* Canceled restart from syncing, no need to wait. */
243 case OFFLINE_AGAIN_FROM_OFFLINING
: {
244 OfflineState tmp_state
= OFFLINE_AGAIN_FROM_OFFLINING
;
245 if (!__atomic_compare_exchange_n(&f
->offline_state
, &tmp_state
, OFFLINE_CANCEL
,
246 false, __ATOMIC_SEQ_CST
, __ATOMIC_SEQ_CST
))
249 /* Canceled restart from offlining, must wait for offlining to complete however. */
254 r
= journal_file_set_offline_thread_join(f
);
264 if (mmap_cache_fd_got_sigbus(f
->cache_fd
))
267 switch (f
->header
->state
) {
272 f
->header
->state
= STATE_ONLINE
;
281 JournalFile
* journal_file_close(JournalFile
*f
) {
286 mmap_cache_fd_free(f
->cache_fd
);
292 ordered_hashmap_free_free(f
->chain_cache
);
295 free(f
->compress_buffer
);
300 munmap(f
->fss_file
, PAGE_ALIGN(f
->fss_file_size
));
302 free(f
->fsprg_state
);
307 gcry_md_close(f
->hmac
);
313 static bool keyed_hash_requested(void) {
316 r
= getenv_bool("SYSTEMD_JOURNAL_KEYED_HASH");
320 log_debug_errno(r
, "Failed to parse $SYSTEMD_JOURNAL_KEYED_HASH environment variable, ignoring: %m");
325 static bool compact_mode_requested(void) {
328 r
= getenv_bool("SYSTEMD_JOURNAL_COMPACT");
332 log_debug_errno(r
, "Failed to parse $SYSTEMD_JOURNAL_COMPACT environment variable, ignoring: %m");
337 static int journal_file_init_header(JournalFile
*f
, JournalFileFlags file_flags
, JournalFile
*template) {
346 /* Try to load the FSPRG state, and if we can't, then just don't do sealing */
347 seal
= FLAGS_SET(file_flags
, JOURNAL_SEAL
) && journal_file_fss_load(f
) >= 0;
350 memcpy(h
.signature
, HEADER_SIGNATURE
, 8);
351 h
.header_size
= htole64(ALIGN64(sizeof(h
)));
353 h
.incompatible_flags
|= htole32(
354 FLAGS_SET(file_flags
, JOURNAL_COMPRESS
) *
355 COMPRESSION_TO_HEADER_INCOMPATIBLE_FLAG(DEFAULT_COMPRESSION
) |
356 keyed_hash_requested() * HEADER_INCOMPATIBLE_KEYED_HASH
|
357 compact_mode_requested() * HEADER_INCOMPATIBLE_COMPACT
);
359 h
.compatible_flags
= htole32(seal
* HEADER_COMPATIBLE_SEALED
);
361 r
= sd_id128_randomize(&h
.file_id
);
366 h
.seqnum_id
= template->header
->seqnum_id
;
367 h
.tail_entry_seqnum
= template->header
->tail_entry_seqnum
;
369 h
.seqnum_id
= h
.file_id
;
371 k
= pwrite(f
->fd
, &h
, sizeof(h
), 0);
381 static int journal_file_refresh_header(JournalFile
*f
) {
387 r
= sd_id128_get_machine(&f
->header
->machine_id
);
388 if (IN_SET(r
, -ENOENT
, -ENOMEDIUM
, -ENOPKG
))
389 /* We don't have a machine-id, let's continue without */
390 zero(f
->header
->machine_id
);
394 r
= sd_id128_get_boot(&f
->header
->boot_id
);
398 r
= journal_file_set_online(f
);
400 /* Sync the online state to disk; likely just created a new file, also sync the directory this file
402 (void) fsync_full(f
->fd
);
407 static bool warn_wrong_flags(const JournalFile
*f
, bool compatible
) {
408 const uint32_t any
= compatible
? HEADER_COMPATIBLE_ANY
: HEADER_INCOMPATIBLE_ANY
,
409 supported
= compatible
? HEADER_COMPATIBLE_SUPPORTED
: HEADER_INCOMPATIBLE_SUPPORTED
;
410 const char *type
= compatible
? "compatible" : "incompatible";
416 flags
= le32toh(compatible
? f
->header
->compatible_flags
: f
->header
->incompatible_flags
);
418 if (flags
& ~supported
) {
420 log_debug("Journal file %s has unknown %s flags 0x%"PRIx32
,
421 f
->path
, type
, flags
& ~any
);
422 flags
= (flags
& any
) & ~supported
;
426 _cleanup_free_
char *t
= NULL
;
429 if (flags
& HEADER_COMPATIBLE_SEALED
)
430 strv
[n
++] = "sealed";
432 if (flags
& HEADER_INCOMPATIBLE_COMPRESSED_XZ
)
433 strv
[n
++] = "xz-compressed";
434 if (flags
& HEADER_INCOMPATIBLE_COMPRESSED_LZ4
)
435 strv
[n
++] = "lz4-compressed";
436 if (flags
& HEADER_INCOMPATIBLE_COMPRESSED_ZSTD
)
437 strv
[n
++] = "zstd-compressed";
438 if (flags
& HEADER_INCOMPATIBLE_KEYED_HASH
)
439 strv
[n
++] = "keyed-hash";
440 if (flags
& HEADER_INCOMPATIBLE_COMPACT
)
441 strv
[n
++] = "compact";
444 assert(n
< ELEMENTSOF(strv
));
446 t
= strv_join((char**) strv
, ", ");
447 log_debug("Journal file %s uses %s %s %s disabled at compilation time.",
448 f
->path
, type
, n
> 1 ? "flags" : "flag", strnull(t
));
456 static int journal_file_verify_header(JournalFile
*f
) {
457 uint64_t arena_size
, header_size
;
462 if (memcmp(f
->header
->signature
, HEADER_SIGNATURE
, 8))
465 /* In both read and write mode we refuse to open files with incompatible
466 * flags we don't know. */
467 if (warn_wrong_flags(f
, false))
468 return -EPROTONOSUPPORT
;
470 /* When open for writing we refuse to open files with compatible flags, too. */
471 if (journal_file_writable(f
) && warn_wrong_flags(f
, true))
472 return -EPROTONOSUPPORT
;
474 if (f
->header
->state
>= _STATE_MAX
)
477 header_size
= le64toh(READ_NOW(f
->header
->header_size
));
479 /* The first addition was n_data, so check that we are at least this large */
480 if (header_size
< HEADER_SIZE_MIN
)
483 if (JOURNAL_HEADER_SEALED(f
->header
) && !JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
486 arena_size
= le64toh(READ_NOW(f
->header
->arena_size
));
488 if (UINT64_MAX
- header_size
< arena_size
|| header_size
+ arena_size
> (uint64_t) f
->last_stat
.st_size
)
491 if (le64toh(f
->header
->tail_object_offset
) > header_size
+ arena_size
)
494 if (!VALID64(le64toh(f
->header
->data_hash_table_offset
)) ||
495 !VALID64(le64toh(f
->header
->field_hash_table_offset
)) ||
496 !VALID64(le64toh(f
->header
->tail_object_offset
)) ||
497 !VALID64(le64toh(f
->header
->entry_array_offset
)))
500 if (journal_file_writable(f
)) {
501 sd_id128_t machine_id
;
505 r
= sd_id128_get_machine(&machine_id
);
509 if (!sd_id128_equal(machine_id
, f
->header
->machine_id
))
512 state
= f
->header
->state
;
514 if (state
== STATE_ARCHIVED
)
515 return -ESHUTDOWN
; /* Already archived */
516 else if (state
== STATE_ONLINE
)
517 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
),
518 "Journal file %s is already online. Assuming unclean closing.",
520 else if (state
!= STATE_OFFLINE
)
521 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
),
522 "Journal file %s has unknown state %i.",
525 if (f
->header
->field_hash_table_size
== 0 || f
->header
->data_hash_table_size
== 0)
528 /* Don't permit appending to files from the future. Because otherwise the realtime timestamps wouldn't
529 * be strictly ordered in the entries in the file anymore, and we can't have that since it breaks
531 if (le64toh(f
->header
->tail_entry_realtime
) > now(CLOCK_REALTIME
))
532 return log_debug_errno(SYNTHETIC_ERRNO(ETXTBSY
),
533 "Journal file %s is from the future, refusing to append new data to it that'd be older.",
540 int journal_file_fstat(JournalFile
*f
) {
546 if (fstat(f
->fd
, &f
->last_stat
) < 0)
549 f
->last_stat_usec
= now(CLOCK_MONOTONIC
);
551 /* Refuse dealing with files that aren't regular */
552 r
= stat_verify_regular(&f
->last_stat
);
556 /* Refuse appending to files that are already deleted */
557 if (f
->last_stat
.st_nlink
<= 0)
563 static int journal_file_allocate(JournalFile
*f
, uint64_t offset
, uint64_t size
) {
564 uint64_t old_size
, new_size
, old_header_size
, old_arena_size
;
570 /* We assume that this file is not sparse, and we know that for sure, since we always call
571 * posix_fallocate() ourselves */
573 if (size
> PAGE_ALIGN_DOWN(UINT64_MAX
) - offset
)
576 if (mmap_cache_fd_got_sigbus(f
->cache_fd
))
579 old_header_size
= le64toh(READ_NOW(f
->header
->header_size
));
580 old_arena_size
= le64toh(READ_NOW(f
->header
->arena_size
));
581 if (old_arena_size
> PAGE_ALIGN_DOWN(UINT64_MAX
) - old_header_size
)
584 old_size
= old_header_size
+ old_arena_size
;
586 new_size
= MAX(PAGE_ALIGN(offset
+ size
), old_header_size
);
588 if (new_size
<= old_size
) {
590 /* We already pre-allocated enough space, but before
591 * we write to it, let's check with fstat() if the
592 * file got deleted, in order make sure we don't throw
593 * away the data immediately. Don't check fstat() for
594 * all writes though, but only once ever 10s. */
596 if (f
->last_stat_usec
+ LAST_STAT_REFRESH_USEC
> now(CLOCK_MONOTONIC
))
599 return journal_file_fstat(f
);
602 /* Allocate more space. */
604 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
607 /* Refuse to go over 4G in compact mode so offsets can be stored in 32-bit. */
608 if (JOURNAL_HEADER_COMPACT(f
->header
) && new_size
> UINT32_MAX
)
611 if (new_size
> f
->metrics
.min_size
&& f
->metrics
.keep_free
> 0) {
614 if (fstatvfs(f
->fd
, &svfs
) >= 0) {
617 available
= LESS_BY((uint64_t) svfs
.f_bfree
* (uint64_t) svfs
.f_bsize
, f
->metrics
.keep_free
);
619 if (new_size
- old_size
> available
)
624 /* Increase by larger blocks at once */
625 new_size
= DIV_ROUND_UP(new_size
, FILE_SIZE_INCREASE
) * FILE_SIZE_INCREASE
;
626 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
627 new_size
= f
->metrics
.max_size
;
629 /* Note that the glibc fallocate() fallback is very
630 inefficient, hence we try to minimize the allocation area
632 r
= posix_fallocate_loop(f
->fd
, old_size
, new_size
- old_size
);
636 f
->header
->arena_size
= htole64(new_size
- old_header_size
);
638 return journal_file_fstat(f
);
641 static unsigned type_to_context(ObjectType type
) {
642 /* One context for each type, plus one catch-all for the rest */
643 assert_cc(_OBJECT_TYPE_MAX
<= MMAP_CACHE_MAX_CONTEXTS
);
644 assert_cc(CONTEXT_HEADER
< MMAP_CACHE_MAX_CONTEXTS
);
645 return type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
? type
: 0;
648 static int journal_file_move_to(
661 /* This function may clear, overwrite, or alter previously cached entries. After this function has
662 * been called, all objects except for one obtained by this function are invalidated and must be
663 * re-read before use. */
668 if (size
> UINT64_MAX
- offset
)
671 /* Avoid SIGBUS on invalid accesses */
672 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
) {
673 /* Hmm, out of range? Let's refresh the fstat() data
674 * first, before we trust that check. */
676 r
= journal_file_fstat(f
);
680 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
)
681 return -EADDRNOTAVAIL
;
684 return mmap_cache_fd_get(f
->cache_fd
, type_to_context(type
), keep_always
, offset
, size
, &f
->last_stat
, ret
);
687 static uint64_t minimum_header_size(JournalFile
*f
, Object
*o
) {
689 static const uint64_t table
[] = {
690 [OBJECT_DATA
] = sizeof(DataObject
),
691 [OBJECT_FIELD
] = sizeof(FieldObject
),
692 [OBJECT_ENTRY
] = sizeof(EntryObject
),
693 [OBJECT_DATA_HASH_TABLE
] = sizeof(HashTableObject
),
694 [OBJECT_FIELD_HASH_TABLE
] = sizeof(HashTableObject
),
695 [OBJECT_ENTRY_ARRAY
] = sizeof(EntryArrayObject
),
696 [OBJECT_TAG
] = sizeof(TagObject
),
702 if (o
->object
.type
== OBJECT_DATA
)
703 return journal_file_data_payload_offset(f
);
705 if (o
->object
.type
>= ELEMENTSOF(table
) || table
[o
->object
.type
] <= 0)
706 return sizeof(ObjectHeader
);
708 return table
[o
->object
.type
];
711 static int check_object_header(JournalFile
*f
, Object
*o
, ObjectType type
, uint64_t offset
) {
717 s
= le64toh(READ_NOW(o
->object
.size
));
719 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
720 "Attempt to move to uninitialized object: %" PRIu64
,
723 if (s
< sizeof(ObjectHeader
))
724 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
725 "Attempt to move to overly short object: %" PRIu64
,
728 if (o
->object
.type
<= OBJECT_UNUSED
)
729 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
730 "Attempt to move to object with invalid type: %" PRIu64
,
733 if (type
> OBJECT_UNUSED
&& o
->object
.type
!= type
)
734 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
735 "Attempt to move to object of unexpected type: %" PRIu64
,
738 if (s
< minimum_header_size(f
, o
))
739 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
740 "Attempt to move to truncated object: %" PRIu64
,
746 /* Lightweight object checks. We want this to be fast, so that we won't
747 * slowdown every journal_file_move_to_object() call too much. */
748 static int check_object(JournalFile
*f
, Object
*o
, uint64_t offset
) {
752 switch (o
->object
.type
) {
755 if ((le64toh(o
->data
.entry_offset
) == 0) ^ (le64toh(o
->data
.n_entries
) == 0))
756 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
757 "Bad n_entries: %" PRIu64
": %" PRIu64
,
758 le64toh(o
->data
.n_entries
),
761 if (le64toh(o
->object
.size
) <= journal_file_data_payload_offset(f
))
762 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
763 "Bad object size (<= %zu): %" PRIu64
": %" PRIu64
,
764 journal_file_data_payload_offset(f
),
765 le64toh(o
->object
.size
),
768 if (!VALID64(le64toh(o
->data
.next_hash_offset
)) ||
769 !VALID64(le64toh(o
->data
.next_field_offset
)) ||
770 !VALID64(le64toh(o
->data
.entry_offset
)) ||
771 !VALID64(le64toh(o
->data
.entry_array_offset
)))
772 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
773 "Invalid offset, next_hash_offset=" OFSfmt
", next_field_offset=" OFSfmt
", entry_offset=" OFSfmt
", entry_array_offset=" OFSfmt
": %" PRIu64
,
774 le64toh(o
->data
.next_hash_offset
),
775 le64toh(o
->data
.next_field_offset
),
776 le64toh(o
->data
.entry_offset
),
777 le64toh(o
->data
.entry_array_offset
),
783 if (le64toh(o
->object
.size
) <= offsetof(Object
, field
.payload
))
784 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
785 "Bad field size (<= %zu): %" PRIu64
": %" PRIu64
,
786 offsetof(Object
, field
.payload
),
787 le64toh(o
->object
.size
),
790 if (!VALID64(le64toh(o
->field
.next_hash_offset
)) ||
791 !VALID64(le64toh(o
->field
.head_data_offset
)))
792 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
793 "Invalid offset, next_hash_offset=" OFSfmt
", head_data_offset=" OFSfmt
": %" PRIu64
,
794 le64toh(o
->field
.next_hash_offset
),
795 le64toh(o
->field
.head_data_offset
),
802 sz
= le64toh(READ_NOW(o
->object
.size
));
803 if (sz
< offsetof(Object
, entry
.items
) ||
804 (sz
- offsetof(Object
, entry
.items
)) % journal_file_entry_item_size(f
) != 0)
805 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
806 "Bad entry size (<= %zu): %" PRIu64
": %" PRIu64
,
807 offsetof(Object
, entry
.items
),
811 if ((sz
- offsetof(Object
, entry
.items
)) / journal_file_entry_item_size(f
) <= 0)
812 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
813 "Invalid number items in entry: %" PRIu64
": %" PRIu64
,
814 (sz
- offsetof(Object
, entry
.items
)) / journal_file_entry_item_size(f
),
817 if (le64toh(o
->entry
.seqnum
) <= 0)
818 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
819 "Invalid entry seqnum: %" PRIx64
": %" PRIu64
,
820 le64toh(o
->entry
.seqnum
),
823 if (!VALID_REALTIME(le64toh(o
->entry
.realtime
)))
824 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
825 "Invalid entry realtime timestamp: %" PRIu64
": %" PRIu64
,
826 le64toh(o
->entry
.realtime
),
829 if (!VALID_MONOTONIC(le64toh(o
->entry
.monotonic
)))
830 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
831 "Invalid entry monotonic timestamp: %" PRIu64
": %" PRIu64
,
832 le64toh(o
->entry
.monotonic
),
838 case OBJECT_DATA_HASH_TABLE
:
839 case OBJECT_FIELD_HASH_TABLE
: {
842 sz
= le64toh(READ_NOW(o
->object
.size
));
843 if (sz
< offsetof(Object
, hash_table
.items
) ||
844 (sz
- offsetof(Object
, hash_table
.items
)) % sizeof(HashItem
) != 0 ||
845 (sz
- offsetof(Object
, hash_table
.items
)) / sizeof(HashItem
) <= 0)
846 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
847 "Invalid %s hash table size: %" PRIu64
": %" PRIu64
,
848 o
->object
.type
== OBJECT_DATA_HASH_TABLE
? "data" : "field",
855 case OBJECT_ENTRY_ARRAY
: {
858 sz
= le64toh(READ_NOW(o
->object
.size
));
859 if (sz
< offsetof(Object
, entry_array
.items
) ||
860 (sz
- offsetof(Object
, entry_array
.items
)) % journal_file_entry_array_item_size(f
) != 0 ||
861 (sz
- offsetof(Object
, entry_array
.items
)) / journal_file_entry_array_item_size(f
) <= 0)
862 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
863 "Invalid object entry array size: %" PRIu64
": %" PRIu64
,
867 if (!VALID64(le64toh(o
->entry_array
.next_entry_array_offset
)))
868 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
869 "Invalid object entry array next_entry_array_offset: " OFSfmt
": %" PRIu64
,
870 le64toh(o
->entry_array
.next_entry_array_offset
),
877 if (le64toh(o
->object
.size
) != sizeof(TagObject
))
878 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
879 "Invalid object tag size: %" PRIu64
": %" PRIu64
,
880 le64toh(o
->object
.size
),
883 if (!VALID_EPOCH(le64toh(o
->tag
.epoch
)))
884 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
885 "Invalid object tag epoch: %" PRIu64
": %" PRIu64
,
886 le64toh(o
->tag
.epoch
), offset
);
894 int journal_file_move_to_object(JournalFile
*f
, ObjectType type
, uint64_t offset
, Object
**ret
) {
900 /* Even if this function fails, it may clear, overwrite, or alter previously cached entries. After
901 * this function has been called, all objects except for one obtained by this function are
902 * invalidated and must be re-read before use.. */
904 /* Objects may only be located at multiple of 64 bit */
905 if (!VALID64(offset
))
906 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
907 "Attempt to move to object at non-64bit boundary: %" PRIu64
,
910 /* Object may not be located in the file header */
911 if (offset
< le64toh(f
->header
->header_size
))
912 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
913 "Attempt to move to object located in file header: %" PRIu64
,
916 r
= journal_file_move_to(f
, type
, false, offset
, sizeof(ObjectHeader
), (void**) &o
);
920 r
= check_object_header(f
, o
, type
, offset
);
924 r
= journal_file_move_to(f
, type
, false, offset
, le64toh(READ_NOW(o
->object
.size
)), (void**) &o
);
928 r
= check_object_header(f
, o
, type
, offset
);
932 r
= check_object(f
, o
, offset
);
942 int journal_file_read_object_header(JournalFile
*f
, ObjectType type
, uint64_t offset
, Object
*ret
) {
949 /* Objects may only be located at multiple of 64 bit */
950 if (!VALID64(offset
))
951 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
952 "Attempt to read object at non-64bit boundary: %" PRIu64
,
955 /* Object may not be located in the file header */
956 if (offset
< le64toh(f
->header
->header_size
))
957 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
958 "Attempt to read object located in file header: %" PRIu64
,
961 /* This will likely read too much data but it avoids having to call pread() twice. */
962 n
= pread(f
->fd
, &o
, sizeof(o
), offset
);
964 return log_debug_errno(errno
, "Failed to read journal file at offset: %" PRIu64
,
967 if ((size_t) n
< sizeof(o
.object
))
968 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
969 "Failed to read short object at offset: %" PRIu64
,
972 r
= check_object_header(f
, &o
, type
, offset
);
976 if ((size_t) n
< minimum_header_size(f
, &o
))
977 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
978 "Short read while reading object: %" PRIu64
,
981 r
= check_object(f
, &o
, offset
);
991 static uint64_t journal_file_entry_seqnum(
1000 /* Picks a new sequence number for the entry we are about to add and returns it. */
1002 ret
= le64toh(f
->header
->tail_entry_seqnum
) + 1;
1005 /* If an external seqnum counter was passed, we update both the local and the external one,
1006 * and set it to the maximum of both */
1008 if (*seqnum
+ 1 > ret
)
1014 f
->header
->tail_entry_seqnum
= htole64(ret
);
1016 if (f
->header
->head_entry_seqnum
== 0)
1017 f
->header
->head_entry_seqnum
= htole64(ret
);
1022 int journal_file_append_object(
1026 Object
**ret_object
,
1027 uint64_t *ret_offset
) {
1035 assert(type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
);
1036 assert(size
>= sizeof(ObjectHeader
));
1038 r
= journal_file_set_online(f
);
1042 r
= journal_file_tail_end_by_mmap(f
, &p
);
1046 r
= journal_file_allocate(f
, p
, size
);
1050 r
= journal_file_move_to(f
, type
, false, p
, size
, (void**) &o
);
1054 o
->object
= (ObjectHeader
) {
1056 .size
= htole64(size
),
1059 f
->header
->tail_object_offset
= htole64(p
);
1060 f
->header
->n_objects
= htole64(le64toh(f
->header
->n_objects
) + 1);
1071 static int journal_file_setup_data_hash_table(JournalFile
*f
) {
1079 /* We estimate that we need 1 hash table entry per 768 bytes
1080 of journal file and we want to make sure we never get
1081 beyond 75% fill level. Calculate the hash table size for
1082 the maximum file size based on these metrics. */
1084 s
= (f
->metrics
.max_size
* 4 / 768 / 3) * sizeof(HashItem
);
1085 if (s
< DEFAULT_DATA_HASH_TABLE_SIZE
)
1086 s
= DEFAULT_DATA_HASH_TABLE_SIZE
;
1088 log_debug("Reserving %"PRIu64
" entries in data hash table.", s
/ sizeof(HashItem
));
1090 r
= journal_file_append_object(f
,
1091 OBJECT_DATA_HASH_TABLE
,
1092 offsetof(Object
, hash_table
.items
) + s
,
1097 memzero(o
->hash_table
.items
, s
);
1099 f
->header
->data_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
1100 f
->header
->data_hash_table_size
= htole64(s
);
1105 static int journal_file_setup_field_hash_table(JournalFile
*f
) {
1113 /* We use a fixed size hash table for the fields as this
1114 * number should grow very slowly only */
1116 s
= DEFAULT_FIELD_HASH_TABLE_SIZE
;
1117 log_debug("Reserving %"PRIu64
" entries in field hash table.", s
/ sizeof(HashItem
));
1119 r
= journal_file_append_object(f
,
1120 OBJECT_FIELD_HASH_TABLE
,
1121 offsetof(Object
, hash_table
.items
) + s
,
1126 memzero(o
->hash_table
.items
, s
);
1128 f
->header
->field_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
1129 f
->header
->field_hash_table_size
= htole64(s
);
1134 int journal_file_map_data_hash_table(JournalFile
*f
) {
1142 if (f
->data_hash_table
)
1145 p
= le64toh(f
->header
->data_hash_table_offset
);
1146 s
= le64toh(f
->header
->data_hash_table_size
);
1148 r
= journal_file_move_to(f
,
1149 OBJECT_DATA_HASH_TABLE
,
1156 f
->data_hash_table
= t
;
1160 int journal_file_map_field_hash_table(JournalFile
*f
) {
1168 if (f
->field_hash_table
)
1171 p
= le64toh(f
->header
->field_hash_table_offset
);
1172 s
= le64toh(f
->header
->field_hash_table_size
);
1174 r
= journal_file_move_to(f
,
1175 OBJECT_FIELD_HASH_TABLE
,
1182 f
->field_hash_table
= t
;
1186 static int journal_file_link_field(
1197 assert(f
->field_hash_table
);
1201 if (o
->object
.type
!= OBJECT_FIELD
)
1204 m
= le64toh(READ_NOW(f
->header
->field_hash_table_size
)) / sizeof(HashItem
);
1208 /* This might alter the window we are looking at */
1209 o
->field
.next_hash_offset
= o
->field
.head_data_offset
= 0;
1212 p
= le64toh(f
->field_hash_table
[h
].tail_hash_offset
);
1214 f
->field_hash_table
[h
].head_hash_offset
= htole64(offset
);
1216 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1220 o
->field
.next_hash_offset
= htole64(offset
);
1223 f
->field_hash_table
[h
].tail_hash_offset
= htole64(offset
);
1225 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
1226 f
->header
->n_fields
= htole64(le64toh(f
->header
->n_fields
) + 1);
1231 static int journal_file_link_data(
1242 assert(f
->data_hash_table
);
1246 if (o
->object
.type
!= OBJECT_DATA
)
1249 m
= le64toh(READ_NOW(f
->header
->data_hash_table_size
)) / sizeof(HashItem
);
1253 /* This might alter the window we are looking at */
1254 o
->data
.next_hash_offset
= o
->data
.next_field_offset
= 0;
1255 o
->data
.entry_offset
= o
->data
.entry_array_offset
= 0;
1256 o
->data
.n_entries
= 0;
1259 p
= le64toh(f
->data_hash_table
[h
].tail_hash_offset
);
1261 /* Only entry in the hash table is easy */
1262 f
->data_hash_table
[h
].head_hash_offset
= htole64(offset
);
1264 /* Move back to the previous data object, to patch in
1267 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1271 o
->data
.next_hash_offset
= htole64(offset
);
1274 f
->data_hash_table
[h
].tail_hash_offset
= htole64(offset
);
1276 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
1277 f
->header
->n_data
= htole64(le64toh(f
->header
->n_data
) + 1);
1282 static int get_next_hash_offset(
1285 le64_t
*next_hash_offset
,
1287 le64_t
*header_max_depth
) {
1293 assert(next_hash_offset
);
1296 nextp
= le64toh(READ_NOW(*next_hash_offset
));
1298 if (nextp
<= *p
) /* Refuse going in loops */
1299 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
1300 "Detected hash item loop in %s, refusing.", f
->path
);
1304 /* If the depth of this hash chain is larger than all others we have seen so far, record it */
1305 if (header_max_depth
&& journal_file_writable(f
))
1306 *header_max_depth
= htole64(MAX(*depth
, le64toh(*header_max_depth
)));
1313 int journal_file_find_field_object_with_hash(
1318 Object
**ret_object
,
1319 uint64_t *ret_offset
) {
1321 uint64_t p
, osize
, h
, m
, depth
= 0;
1329 /* If the field hash table is empty, we can't find anything */
1330 if (le64toh(f
->header
->field_hash_table_size
) <= 0)
1333 /* Map the field hash table, if it isn't mapped yet. */
1334 r
= journal_file_map_field_hash_table(f
);
1338 osize
= offsetof(Object
, field
.payload
) + size
;
1340 m
= le64toh(READ_NOW(f
->header
->field_hash_table_size
)) / sizeof(HashItem
);
1345 p
= le64toh(f
->field_hash_table
[h
].head_hash_offset
);
1349 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1353 if (le64toh(o
->field
.hash
) == hash
&&
1354 le64toh(o
->object
.size
) == osize
&&
1355 memcmp(o
->field
.payload
, field
, size
) == 0) {
1365 r
= get_next_hash_offset(
1368 &o
->field
.next_hash_offset
,
1370 JOURNAL_HEADER_CONTAINS(f
->header
, field_hash_chain_depth
) ? &f
->header
->field_hash_chain_depth
: NULL
);
1378 uint64_t journal_file_hash_data(
1385 assert(data
|| sz
== 0);
1387 /* We try to unify our codebase on siphash, hence new-styled journal files utilizing the keyed hash
1388 * function use siphash. Old journal files use the Jenkins hash. */
1390 if (JOURNAL_HEADER_KEYED_HASH(f
->header
))
1391 return siphash24(data
, sz
, f
->header
->file_id
.bytes
);
1393 return jenkins_hash64(data
, sz
);
1396 int journal_file_find_field_object(
1400 Object
**ret_object
,
1401 uint64_t *ret_offset
) {
1407 return journal_file_find_field_object_with_hash(
1410 journal_file_hash_data(f
, field
, size
),
1411 ret_object
, ret_offset
);
1414 int journal_file_find_data_object_with_hash(
1419 Object
**ret_object
,
1420 uint64_t *ret_offset
) {
1422 uint64_t p
, h
, m
, depth
= 0;
1427 assert(data
|| size
== 0);
1429 /* If there's no data hash table, then there's no entry. */
1430 if (le64toh(f
->header
->data_hash_table_size
) <= 0)
1433 /* Map the data hash table, if it isn't mapped yet. */
1434 r
= journal_file_map_data_hash_table(f
);
1438 m
= le64toh(READ_NOW(f
->header
->data_hash_table_size
)) / sizeof(HashItem
);
1443 p
= le64toh(f
->data_hash_table
[h
].head_hash_offset
);
1450 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1454 if (le64toh(o
->data
.hash
) != hash
)
1457 r
= journal_file_data_payload(f
, o
, p
, NULL
, 0, 0, &d
, &rsize
);
1460 assert(r
> 0); /* journal_file_data_payload() always returns > 0 if no field is provided. */
1462 if (memcmp_nn(data
, size
, d
, rsize
) == 0) {
1473 r
= get_next_hash_offset(
1476 &o
->data
.next_hash_offset
,
1478 JOURNAL_HEADER_CONTAINS(f
->header
, data_hash_chain_depth
) ? &f
->header
->data_hash_chain_depth
: NULL
);
1486 int journal_file_find_data_object(
1490 Object
**ret_object
,
1491 uint64_t *ret_offset
) {
1494 assert(data
|| size
== 0);
1496 return journal_file_find_data_object_with_hash(
1499 journal_file_hash_data(f
, data
, size
),
1500 ret_object
, ret_offset
);
1503 bool journal_field_valid(const char *p
, size_t l
, bool allow_protected
) {
1504 /* We kinda enforce POSIX syntax recommendations for
1505 environment variables here, but make a couple of additional
1508 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1515 /* No empty field names */
1519 /* Don't allow names longer than 64 chars */
1523 /* Variables starting with an underscore are protected */
1524 if (!allow_protected
&& p
[0] == '_')
1527 /* Don't allow digits as first character */
1528 if (ascii_isdigit(p
[0]))
1531 /* Only allow A-Z0-9 and '_' */
1532 for (const char *a
= p
; a
< p
+ l
; a
++)
1533 if ((*a
< 'A' || *a
> 'Z') &&
1534 !ascii_isdigit(*a
) &&
1541 static int journal_file_append_field(
1545 Object
**ret_object
,
1546 uint64_t *ret_offset
) {
1557 if (!journal_field_valid(field
, size
, true))
1560 hash
= journal_file_hash_data(f
, field
, size
);
1562 r
= journal_file_find_field_object_with_hash(f
, field
, size
, hash
, ret_object
, ret_offset
);
1568 osize
= offsetof(Object
, field
.payload
) + size
;
1569 r
= journal_file_append_object(f
, OBJECT_FIELD
, osize
, &o
, &p
);
1573 o
->field
.hash
= htole64(hash
);
1574 memcpy(o
->field
.payload
, field
, size
);
1576 r
= journal_file_link_field(f
, o
, p
, hash
);
1580 /* The linking might have altered the window, so let's only pass the offset to hmac which will
1581 * move to the object again if needed. */
1584 r
= journal_file_hmac_put_object(f
, OBJECT_FIELD
, NULL
, p
);
1590 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, ret_object
);
1601 static Compression
maybe_compress_payload(JournalFile
*f
, uint8_t *dst
, const uint8_t *src
, uint64_t size
, size_t *rsize
) {
1602 Compression compression
= COMPRESSION_NONE
;
1607 #if HAVE_COMPRESSION
1608 if (JOURNAL_FILE_COMPRESS(f
) && size
>= f
->compress_threshold_bytes
) {
1609 compression
= compress_blob(src
, size
, dst
, size
- 1, rsize
);
1610 if (compression
> 0)
1611 log_debug("Compressed data object %"PRIu64
" -> %zu using %s",
1612 size
, *rsize
, compression_to_string(compression
));
1614 /* Compression didn't work, we don't really care why, let's continue without compression */
1615 compression
= COMPRESSION_NONE
;
1622 static int journal_file_append_data(
1626 Object
**ret_object
,
1627 uint64_t *ret_offset
) {
1629 uint64_t hash
, p
, osize
;
1638 if (!data
|| size
== 0)
1641 hash
= journal_file_hash_data(f
, data
, size
);
1643 r
= journal_file_find_data_object_with_hash(f
, data
, size
, hash
, ret_object
, ret_offset
);
1649 eq
= memchr(data
, '=', size
);
1653 osize
= journal_file_data_payload_offset(f
) + size
;
1654 r
= journal_file_append_object(f
, OBJECT_DATA
, osize
, &o
, &p
);
1658 o
->data
.hash
= htole64(hash
);
1660 c
= maybe_compress_payload(f
, journal_file_data_payload_field(f
, o
), data
, size
, &rsize
);
1662 if (c
!= COMPRESSION_NONE
) {
1663 o
->object
.size
= htole64(journal_file_data_payload_offset(f
) + rsize
);
1664 o
->object
.flags
|= COMPRESSION_TO_OBJECT_FLAG(c
);
1666 memcpy_safe(journal_file_data_payload_field(f
, o
), data
, size
);
1668 r
= journal_file_link_data(f
, o
, p
, hash
);
1672 /* The linking might have altered the window, so let's refresh our pointer. */
1673 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1678 r
= journal_file_hmac_put_object(f
, OBJECT_DATA
, o
, p
);
1683 /* Create field object ... */
1684 r
= journal_file_append_field(f
, data
, (uint8_t*) eq
- (uint8_t*) data
, &fo
, NULL
);
1688 /* ... and link it in. */
1689 o
->data
.next_field_offset
= fo
->field
.head_data_offset
;
1690 fo
->field
.head_data_offset
= le64toh(p
);
1701 static int maybe_decompress_payload(
1705 Compression compression
,
1707 size_t field_length
,
1708 size_t data_threshold
,
1714 /* We can't read objects larger than 4G on a 32bit machine */
1715 if ((uint64_t) (size_t) size
!= size
)
1718 if (compression
!= COMPRESSION_NONE
) {
1719 #if HAVE_COMPRESSION
1724 r
= decompress_startswith(compression
, payload
, size
, &f
->compress_buffer
, field
,
1727 return log_debug_errno(r
,
1728 "Cannot decompress %s object of length %" PRIu64
": %m",
1729 compression_to_string(compression
),
1740 r
= decompress_blob(compression
, payload
, size
, &f
->compress_buffer
, &rsize
, 0);
1745 *ret_data
= f
->compress_buffer
;
1749 return -EPROTONOSUPPORT
;
1752 if (field
&& (size
< field_length
+ 1 || memcmp(payload
, field
, field_length
) != 0 || payload
[field_length
] != '=')) {
1761 *ret_data
= payload
;
1763 *ret_size
= (size_t) size
;
1769 int journal_file_data_payload(
1774 size_t field_length
,
1775 size_t data_threshold
,
1784 assert(!field
== (field_length
== 0)); /* These must be specified together. */
1787 r
= journal_file_move_to_object(f
, OBJECT_DATA
, offset
, &o
);
1792 size
= le64toh(READ_NOW(o
->object
.size
));
1793 if (size
< journal_file_data_payload_offset(f
))
1796 size
-= journal_file_data_payload_offset(f
);
1798 c
= COMPRESSION_FROM_OBJECT(o
);
1800 return -EPROTONOSUPPORT
;
1802 return maybe_decompress_payload(f
, journal_file_data_payload_field(f
, o
), size
, c
, field
,
1803 field_length
, data_threshold
, ret_data
, ret_size
);
1806 uint64_t journal_file_entry_n_items(JournalFile
*f
, Object
*o
) {
1812 if (o
->object
.type
!= OBJECT_ENTRY
)
1815 sz
= le64toh(READ_NOW(o
->object
.size
));
1816 if (sz
< offsetof(Object
, entry
.items
))
1819 return (sz
- offsetof(Object
, entry
.items
)) / journal_file_entry_item_size(f
);
1822 uint64_t journal_file_entry_array_n_items(JournalFile
*f
, Object
*o
) {
1828 if (o
->object
.type
!= OBJECT_ENTRY_ARRAY
)
1831 sz
= le64toh(READ_NOW(o
->object
.size
));
1832 if (sz
< offsetof(Object
, entry_array
.items
))
1835 return (sz
- offsetof(Object
, entry_array
.items
)) / journal_file_entry_array_item_size(f
);
1838 uint64_t journal_file_hash_table_n_items(Object
*o
) {
1843 if (!IN_SET(o
->object
.type
, OBJECT_DATA_HASH_TABLE
, OBJECT_FIELD_HASH_TABLE
))
1846 sz
= le64toh(READ_NOW(o
->object
.size
));
1847 if (sz
< offsetof(Object
, hash_table
.items
))
1850 return (sz
- offsetof(Object
, hash_table
.items
)) / sizeof(HashItem
);
1853 static void write_entry_array_item(JournalFile
*f
, Object
*o
, uint64_t i
, uint64_t p
) {
1857 if (JOURNAL_HEADER_COMPACT(f
->header
)) {
1858 assert(p
<= UINT32_MAX
);
1859 o
->entry_array
.items
.compact
[i
] = htole32(p
);
1861 o
->entry_array
.items
.regular
[i
] = htole64(p
);
1864 static int link_entry_into_array(
1872 uint64_t n
= 0, ap
= 0, q
, i
, a
, hidx
;
1882 a
= tail
? le32toh(*tail
) : le64toh(*first
);
1883 hidx
= le64toh(READ_NOW(*idx
));
1884 i
= tidx
? le32toh(READ_NOW(*tidx
)) : hidx
;
1887 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
1891 n
= journal_file_entry_array_n_items(f
, o
);
1893 write_entry_array_item(f
, o
, i
, p
);
1894 *idx
= htole64(hidx
+ 1);
1896 *tidx
= htole32(le32toh(*tidx
) + 1);
1902 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
1913 r
= journal_file_append_object(f
, OBJECT_ENTRY_ARRAY
,
1914 offsetof(Object
, entry_array
.items
) + n
* journal_file_entry_array_item_size(f
),
1920 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY_ARRAY
, o
, q
);
1925 write_entry_array_item(f
, o
, i
, p
);
1928 *first
= htole64(q
);
1930 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, ap
, &o
);
1934 o
->entry_array
.next_entry_array_offset
= htole64(q
);
1940 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
1941 f
->header
->n_entry_arrays
= htole64(le64toh(f
->header
->n_entry_arrays
) + 1);
1943 *idx
= htole64(hidx
+ 1);
1950 static int link_entry_into_array_plus_one(
1968 hidx
= le64toh(READ_NOW(*idx
));
1969 if (hidx
== UINT64_MAX
)
1972 *extra
= htole64(p
);
1976 i
= htole64(hidx
- 1);
1977 r
= link_entry_into_array(f
, first
, &i
, tail
, tidx
, p
);
1982 *idx
= htole64(hidx
+ 1);
1986 static int journal_file_link_entry_item(JournalFile
*f
, uint64_t offset
, uint64_t p
) {
1993 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1997 return link_entry_into_array_plus_one(f
,
1998 &o
->data
.entry_offset
,
1999 &o
->data
.entry_array_offset
,
2001 JOURNAL_HEADER_COMPACT(f
->header
) ? &o
->data
.compact
.tail_entry_array_offset
: NULL
,
2002 JOURNAL_HEADER_COMPACT(f
->header
) ? &o
->data
.compact
.tail_entry_array_n_entries
: NULL
,
2006 static int journal_file_link_entry(
2010 const EntryItem items
[],
2020 if (o
->object
.type
!= OBJECT_ENTRY
)
2023 __atomic_thread_fence(__ATOMIC_SEQ_CST
);
2025 /* Link up the entry itself */
2026 r
= link_entry_into_array(f
,
2027 &f
->header
->entry_array_offset
,
2028 &f
->header
->n_entries
,
2029 JOURNAL_HEADER_CONTAINS(f
->header
, tail_entry_array_offset
) ? &f
->header
->tail_entry_array_offset
: NULL
,
2030 JOURNAL_HEADER_CONTAINS(f
->header
, tail_entry_array_n_entries
) ? &f
->header
->tail_entry_array_n_entries
: NULL
,
2035 /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
2037 if (f
->header
->head_entry_realtime
== 0)
2038 f
->header
->head_entry_realtime
= o
->entry
.realtime
;
2040 f
->header
->tail_entry_realtime
= o
->entry
.realtime
;
2041 f
->header
->tail_entry_monotonic
= o
->entry
.monotonic
;
2043 /* Link up the items */
2044 for (uint64_t i
= 0; i
< n_items
; i
++) {
2047 /* If we fail to link an entry item because we can't allocate a new entry array, don't fail
2048 * immediately but try to link the other entry items since it might still be possible to link
2049 * those if they don't require a new entry array to be allocated. */
2051 k
= journal_file_link_entry_item(f
, offset
, items
[i
].object_offset
);
2061 static void write_entry_item(JournalFile
*f
, Object
*o
, uint64_t i
, const EntryItem
*item
) {
2066 if (JOURNAL_HEADER_COMPACT(f
->header
)) {
2067 assert(item
->object_offset
<= UINT32_MAX
);
2068 o
->entry
.items
.compact
[i
].object_offset
= htole32(item
->object_offset
);
2070 o
->entry
.items
.regular
[i
].object_offset
= htole64(item
->object_offset
);
2071 o
->entry
.items
.regular
[i
].hash
= htole64(item
->hash
);
2075 static int journal_file_append_entry_internal(
2077 const dual_timestamp
*ts
,
2078 const sd_id128_t
*boot_id
,
2080 const EntryItem items
[],
2083 Object
**ret_object
,
2084 uint64_t *ret_offset
) {
2094 assert(items
|| n_items
== 0);
2096 if (ts
->realtime
< le64toh(f
->header
->tail_entry_realtime
))
2097 return log_debug_errno(SYNTHETIC_ERRNO(EREMCHG
),
2098 "Realtime timestamp %" PRIu64
" smaller than previous realtime "
2099 "timestamp %" PRIu64
", refusing entry.",
2100 ts
->realtime
, le64toh(f
->header
->tail_entry_realtime
));
2102 osize
= offsetof(Object
, entry
.items
) + (n_items
* journal_file_entry_item_size(f
));
2104 r
= journal_file_append_object(f
, OBJECT_ENTRY
, osize
, &o
, &np
);
2108 o
->entry
.seqnum
= htole64(journal_file_entry_seqnum(f
, seqnum
));
2109 o
->entry
.realtime
= htole64(ts
->realtime
);
2110 o
->entry
.monotonic
= htole64(ts
->monotonic
);
2111 o
->entry
.xor_hash
= htole64(xor_hash
);
2113 f
->header
->boot_id
= *boot_id
;
2114 o
->entry
.boot_id
= f
->header
->boot_id
;
2116 for (size_t i
= 0; i
< n_items
; i
++)
2117 write_entry_item(f
, o
, i
, &items
[i
]);
2120 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY
, o
, np
);
2125 r
= journal_file_link_entry(f
, o
, np
, items
, n_items
);
2138 void journal_file_post_change(JournalFile
*f
) {
2144 /* inotify() does not receive IN_MODIFY events from file
2145 * accesses done via mmap(). After each access we hence
2146 * trigger IN_MODIFY by truncating the journal file to its
2147 * current size which triggers IN_MODIFY. */
2149 __atomic_thread_fence(__ATOMIC_SEQ_CST
);
2151 if (ftruncate(f
->fd
, f
->last_stat
.st_size
) < 0)
2152 log_debug_errno(errno
, "Failed to truncate file to its own size: %m");
2155 static int post_change_thunk(sd_event_source
*timer
, uint64_t usec
, void *userdata
) {
2158 journal_file_post_change(userdata
);
2163 static void schedule_post_change(JournalFile
*f
) {
2168 assert(f
->post_change_timer
);
2170 assert_se(e
= sd_event_source_get_event(f
->post_change_timer
));
2172 /* If we are already going down, post the change immediately. */
2173 if (IN_SET(sd_event_get_state(e
), SD_EVENT_EXITING
, SD_EVENT_FINISHED
))
2176 r
= sd_event_source_get_enabled(f
->post_change_timer
, NULL
);
2178 log_debug_errno(r
, "Failed to get ftruncate timer state: %m");
2184 r
= sd_event_source_set_time_relative(f
->post_change_timer
, f
->post_change_timer_period
);
2186 log_debug_errno(r
, "Failed to set time for scheduling ftruncate: %m");
2190 r
= sd_event_source_set_enabled(f
->post_change_timer
, SD_EVENT_ONESHOT
);
2192 log_debug_errno(r
, "Failed to enable scheduled ftruncate: %m");
2199 /* On failure, let's simply post the change immediately. */
2200 journal_file_post_change(f
);
2203 /* Enable coalesced change posting in a timer on the provided sd_event instance */
2204 int journal_file_enable_post_change_timer(JournalFile
*f
, sd_event
*e
, usec_t t
) {
2205 _cleanup_(sd_event_source_unrefp
) sd_event_source
*timer
= NULL
;
2209 assert_return(!f
->post_change_timer
, -EINVAL
);
2213 r
= sd_event_add_time(e
, &timer
, CLOCK_MONOTONIC
, 0, 0, post_change_thunk
, f
);
2217 r
= sd_event_source_set_enabled(timer
, SD_EVENT_OFF
);
2221 f
->post_change_timer
= TAKE_PTR(timer
);
2222 f
->post_change_timer_period
= t
;
2227 static int entry_item_cmp(const EntryItem
*a
, const EntryItem
*b
) {
2228 return CMP(ASSERT_PTR(a
)->object_offset
, ASSERT_PTR(b
)->object_offset
);
2231 static size_t remove_duplicate_entry_items(EntryItem items
[], size_t n
) {
2234 assert(items
|| n
== 0);
2239 for (size_t i
= 1; i
< n
; i
++)
2240 if (items
[i
].object_offset
!= items
[j
- 1].object_offset
)
2241 items
[j
++] = items
[i
];
2246 int journal_file_append_entry(
2248 const dual_timestamp
*ts
,
2249 const sd_id128_t
*boot_id
,
2250 const struct iovec iovec
[],
2253 Object
**ret_object
,
2254 uint64_t *ret_offset
) {
2256 _cleanup_free_ EntryItem
*items_alloc
= NULL
;
2258 uint64_t xor_hash
= 0;
2259 struct dual_timestamp _ts
;
2265 assert(n_iovec
> 0);
2268 if (!VALID_REALTIME(ts
->realtime
))
2269 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
2270 "Invalid realtime timestamp %" PRIu64
", refusing entry.",
2272 if (!VALID_MONOTONIC(ts
->monotonic
))
2273 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
2274 "Invalid monotomic timestamp %" PRIu64
", refusing entry.",
2277 dual_timestamp_get(&_ts
);
2282 r
= journal_file_maybe_append_tag(f
, ts
->realtime
);
2287 if (n_iovec
< ALLOCA_MAX
/ sizeof(EntryItem
) / 2)
2288 items
= newa(EntryItem
, n_iovec
);
2290 items_alloc
= new(EntryItem
, n_iovec
);
2294 items
= items_alloc
;
2297 for (size_t i
= 0; i
< n_iovec
; i
++) {
2301 r
= journal_file_append_data(f
, iovec
[i
].iov_base
, iovec
[i
].iov_len
, &o
, &p
);
2305 /* When calculating the XOR hash field, we need to take special care if the "keyed-hash"
2306 * journal file flag is on. We use the XOR hash field to quickly determine the identity of a
2307 * specific record, and give records with otherwise identical position (i.e. match in seqno,
2308 * timestamp, …) a stable ordering. But for that we can't have it that the hash of the
2309 * objects in each file is different since they are keyed. Hence let's calculate the Jenkins
2310 * hash here for that. This also has the benefit that cursors for old and new journal files
2311 * are completely identical (they include the XOR hash after all). For classic Jenkins-hash
2312 * files things are easier, we can just take the value from the stored record directly. */
2314 if (JOURNAL_HEADER_KEYED_HASH(f
->header
))
2315 xor_hash
^= jenkins_hash64(iovec
[i
].iov_base
, iovec
[i
].iov_len
);
2317 xor_hash
^= le64toh(o
->data
.hash
);
2319 items
[i
] = (EntryItem
) {
2321 .hash
= le64toh(o
->data
.hash
),
2325 /* Order by the position on disk, in order to improve seek
2326 * times for rotating media. */
2327 typesafe_qsort(items
, n_iovec
, entry_item_cmp
);
2328 n_iovec
= remove_duplicate_entry_items(items
, n_iovec
);
2330 r
= journal_file_append_entry_internal(f
, ts
, boot_id
, xor_hash
, items
, n_iovec
, seqnum
, ret_object
, ret_offset
);
2332 /* If the memory mapping triggered a SIGBUS then we return an
2333 * IO error and ignore the error code passed down to us, since
2334 * it is very likely just an effect of a nullified replacement
2337 if (mmap_cache_fd_got_sigbus(f
->cache_fd
))
2340 if (f
->post_change_timer
)
2341 schedule_post_change(f
);
2343 journal_file_post_change(f
);
2348 typedef struct ChainCacheItem
{
2349 uint64_t first
; /* the array at the beginning of the chain */
2350 uint64_t array
; /* the cached array */
2351 uint64_t begin
; /* the first item in the cached array */
2352 uint64_t total
; /* the total number of items in all arrays before this one in the chain */
2353 uint64_t last_index
; /* the last index we looked at, to optimize locality when bisecting */
2356 static void chain_cache_put(
2363 uint64_t last_index
) {
2368 /* If the chain item to cache for this chain is the
2369 * first one it's not worth caching anything */
2373 if (ordered_hashmap_size(h
) >= CHAIN_CACHE_MAX
) {
2374 ci
= ordered_hashmap_steal_first(h
);
2377 ci
= new(ChainCacheItem
, 1);
2384 if (ordered_hashmap_put(h
, &ci
->first
, ci
) < 0) {
2389 assert(ci
->first
== first
);
2394 ci
->last_index
= last_index
;
2397 static int bump_array_index(uint64_t *i
, direction_t direction
, uint64_t n
) {
2400 /* Increase or decrease the specified index, in the right direction. */
2402 if (direction
== DIRECTION_DOWN
) {
2417 static int bump_entry_array(
2422 direction_t direction
,
2432 if (direction
== DIRECTION_DOWN
) {
2434 return le64toh(o
->entry_array
.next_entry_array_offset
);
2437 /* Entry array chains are a singly linked list, so to find the previous array in the chain, we have
2438 * to start iterating from the top. */
2442 while (p
> 0 && p
!= offset
) {
2443 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, p
, &o
);
2448 p
= le64toh(o
->entry_array
.next_entry_array_offset
);
2451 /* If we can't find the previous entry array in the entry array chain, we're likely dealing with a
2452 * corrupted journal file. */
2461 static int generic_array_get(
2465 direction_t direction
,
2466 Object
**ret_object
,
2467 uint64_t *ret_offset
) {
2469 uint64_t p
= 0, a
, t
= 0, k
;
2476 /* FIXME: fix return value assignment on success. */
2480 /* Try the chain cache first */
2481 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
2482 if (ci
&& i
> ci
->total
) {
2489 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
2490 if (IN_SET(r
, -EBADMSG
, -EADDRNOTAVAIL
)) {
2491 /* If there's corruption and we're going downwards, let's pretend we reached the
2492 * final entry in the entry array chain. */
2494 if (direction
== DIRECTION_DOWN
)
2497 /* If there's corruption and we're going upwards, move back to the previous entry
2498 * array and start iterating entries from there. */
2500 r
= bump_entry_array(f
, NULL
, a
, first
, DIRECTION_UP
, &a
);
2511 k
= journal_file_entry_array_n_items(f
, o
);
2517 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
2520 /* If we've found the right location, now look for the first non-corrupt entry object (in the right
2524 /* In the first iteration of the while loop, we reuse i, k and o from the previous while
2526 if (i
== UINT64_MAX
) {
2527 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
2531 k
= journal_file_entry_array_n_items(f
, o
);
2535 i
= direction
== DIRECTION_DOWN
? 0 : k
- 1;
2539 p
= journal_file_entry_array_item(f
, o
, i
);
2541 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, ret_object
);
2543 /* Let's cache this item for the next invocation */
2544 chain_cache_put(f
->chain_cache
, ci
, first
, a
, journal_file_entry_array_item(f
, o
, 0), t
, i
);
2551 if (!IN_SET(r
, -EADDRNOTAVAIL
, -EBADMSG
))
2554 /* OK, so this entry is borked. Most likely some entry didn't get synced to
2555 * disk properly, let's see if the next one might work for us instead. */
2556 log_debug_errno(r
, "Entry item %" PRIu64
" is bad, skipping over it.", i
);
2557 } while (bump_array_index(&i
, direction
, k
) > 0);
2559 r
= bump_entry_array(f
, o
, a
, first
, direction
, &a
);
2570 static int generic_array_get_plus_one(
2575 direction_t direction
,
2576 Object
**ret_object
,
2577 uint64_t *ret_offset
) {
2583 /* FIXME: fix return value assignment on success. */
2586 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, ret_object
);
2587 if (IN_SET(r
, -EADDRNOTAVAIL
, -EBADMSG
))
2588 return generic_array_get(f
, first
, 0, direction
, ret_object
, ret_offset
);
2593 *ret_offset
= extra
;
2598 return generic_array_get(f
, first
, i
- 1, direction
, ret_object
, ret_offset
);
2607 static int generic_array_bisect(
2612 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
2613 direction_t direction
,
2614 Object
**ret_object
,
2615 uint64_t *ret_offset
,
2616 uint64_t *ret_idx
) {
2618 /* Given an entry array chain, this function finds the object "closest" to the given needle in the
2619 * chain, taking into account the provided direction. A function can be provided to determine how
2620 * an object is matched against the given needle.
2622 * Given a journal file, the offset of an object and the needle, the test_object() function should
2623 * return TEST_LEFT if the needle is located earlier in the entry array chain, TEST_RIGHT if the
2624 * needle is located later in the entry array chain and TEST_FOUND if the object matches the needle.
2625 * If test_object() returns TEST_FOUND for a specific object, that object's information will be used
2626 * to populate the return values of this function. If test_object() never returns TEST_FOUND, the
2627 * return values are populated with the details of one of the objects closest to the needle. If the
2628 * direction is DIRECTION_UP, the earlier object is used. Otherwise, the later object is used.
2631 uint64_t a
, p
, t
= 0, i
= 0, last_p
= 0, last_index
= UINT64_MAX
;
2632 bool subtract_one
= false;
2633 Object
*array
= NULL
;
2638 assert(test_object
);
2640 /* Start with the first array in the chain */
2643 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
2644 if (ci
&& n
> ci
->total
&& ci
->begin
!= 0) {
2645 /* Ah, we have iterated this bisection array chain
2646 * previously! Let's see if we can skip ahead in the
2647 * chain, as far as the last time. But we can't jump
2648 * backwards in the chain, so let's check that
2651 r
= test_object(f
, ci
->begin
, needle
);
2655 if (r
== TEST_LEFT
) {
2656 /* OK, what we are looking for is right of the
2657 * begin of this EntryArray, so let's jump
2658 * straight to previously cached array in the
2664 last_index
= ci
->last_index
;
2669 uint64_t left
, right
, k
, lp
;
2671 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &array
);
2675 k
= journal_file_entry_array_n_items(f
, array
);
2681 lp
= p
= journal_file_entry_array_item(f
, array
, i
);
2685 r
= test_object(f
, p
, needle
);
2686 if (r
== -EBADMSG
) {
2687 log_debug_errno(r
, "Encountered invalid entry while bisecting, cutting algorithm short. (1)");
2694 if (r
== TEST_FOUND
)
2695 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2697 if (r
== TEST_RIGHT
) {
2701 if (last_index
!= UINT64_MAX
) {
2702 assert(last_index
<= right
);
2704 /* If we cached the last index we
2705 * looked at, let's try to not to jump
2706 * too wildly around and see if we can
2707 * limit the range to look at early to
2708 * the immediate neighbors of the last
2709 * index we looked at. */
2711 if (last_index
> 0) {
2712 uint64_t x
= last_index
- 1;
2714 p
= journal_file_entry_array_item(f
, array
, x
);
2718 r
= test_object(f
, p
, needle
);
2722 if (r
== TEST_FOUND
)
2723 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2725 if (r
== TEST_RIGHT
)
2731 if (last_index
< right
) {
2732 uint64_t y
= last_index
+ 1;
2734 p
= journal_file_entry_array_item(f
, array
, y
);
2738 r
= test_object(f
, p
, needle
);
2742 if (r
== TEST_FOUND
)
2743 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2745 if (r
== TEST_RIGHT
)
2753 if (left
== right
) {
2754 if (direction
== DIRECTION_UP
)
2755 subtract_one
= true;
2761 assert(left
< right
);
2762 i
= (left
+ right
) / 2;
2764 p
= journal_file_entry_array_item(f
, array
, i
);
2768 r
= test_object(f
, p
, needle
);
2769 if (r
== -EBADMSG
) {
2770 log_debug_errno(r
, "Encountered invalid entry while bisecting, cutting algorithm short. (2)");
2777 if (r
== TEST_FOUND
)
2778 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2780 if (r
== TEST_RIGHT
)
2788 if (direction
== DIRECTION_UP
) {
2790 subtract_one
= true;
2801 last_index
= UINT64_MAX
;
2802 a
= le64toh(array
->entry_array
.next_entry_array_offset
);
2808 if (subtract_one
&& t
== 0 && i
== 0)
2811 /* Let's cache this item for the next invocation */
2812 chain_cache_put(f
->chain_cache
, ci
, first
, a
, journal_file_entry_array_item(f
, array
, 0), t
, subtract_one
? (i
> 0 ? i
-1 : UINT64_MAX
) : i
);
2814 if (subtract_one
&& i
== 0)
2816 else if (subtract_one
)
2817 p
= journal_file_entry_array_item(f
, array
, i
- 1);
2819 p
= journal_file_entry_array_item(f
, array
, i
);
2822 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, ret_object
);
2831 *ret_idx
= t
+ i
+ (subtract_one
? -1 : 0);
2836 static int generic_array_bisect_plus_one(
2842 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
2843 direction_t direction
,
2844 Object
**ret_object
,
2845 uint64_t *ret_offset
,
2846 uint64_t *ret_idx
) {
2849 bool step_back
= false;
2852 assert(test_object
);
2857 /* This bisects the array in object 'first', but first checks
2859 r
= test_object(f
, extra
, needle
);
2863 if (r
== TEST_FOUND
)
2864 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2866 /* if we are looking with DIRECTION_UP then we need to first
2867 see if in the actual array there is a matching entry, and
2868 return the last one of that. But if there isn't any we need
2869 to return this one. Hence remember this, and return it
2872 step_back
= direction
== DIRECTION_UP
;
2874 if (r
== TEST_RIGHT
) {
2875 if (direction
== DIRECTION_DOWN
)
2881 r
= generic_array_bisect(f
, first
, n
-1, needle
, test_object
, direction
, ret_object
, ret_offset
, ret_idx
);
2883 if (r
== 0 && step_back
)
2886 if (r
> 0 && ret_idx
)
2893 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, ret_object
);
2899 *ret_offset
= extra
;
2907 _pure_
static int test_object_offset(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2913 else if (p
< needle
)
2919 int journal_file_move_to_entry_by_offset(
2922 direction_t direction
,
2923 Object
**ret_object
,
2924 uint64_t *ret_offset
) {
2929 return generic_array_bisect(
2931 le64toh(f
->header
->entry_array_offset
),
2932 le64toh(f
->header
->n_entries
),
2936 ret_object
, ret_offset
, NULL
);
2939 static int test_object_seqnum(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2947 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2951 sq
= le64toh(READ_NOW(o
->entry
.seqnum
));
2954 else if (sq
< needle
)
2960 int journal_file_move_to_entry_by_seqnum(
2963 direction_t direction
,
2964 Object
**ret_object
,
2965 uint64_t *ret_offset
) {
2970 return generic_array_bisect(
2972 le64toh(f
->header
->entry_array_offset
),
2973 le64toh(f
->header
->n_entries
),
2977 ret_object
, ret_offset
, NULL
);
2980 static int test_object_realtime(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2988 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2992 rt
= le64toh(READ_NOW(o
->entry
.realtime
));
2995 else if (rt
< needle
)
3001 int journal_file_move_to_entry_by_realtime(
3004 direction_t direction
,
3005 Object
**ret_object
,
3006 uint64_t *ret_offset
) {
3011 return generic_array_bisect(
3013 le64toh(f
->header
->entry_array_offset
),
3014 le64toh(f
->header
->n_entries
),
3016 test_object_realtime
,
3018 ret_object
, ret_offset
, NULL
);
3021 static int test_object_monotonic(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
3029 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
3033 m
= le64toh(READ_NOW(o
->entry
.monotonic
));
3036 else if (m
< needle
)
3042 static int find_data_object_by_boot_id(
3045 Object
**ret_object
,
3046 uint64_t *ret_offset
) {
3048 char t
[STRLEN("_BOOT_ID=") + 32 + 1] = "_BOOT_ID=";
3052 sd_id128_to_string(boot_id
, t
+ 9);
3053 return journal_file_find_data_object(f
, t
, sizeof(t
) - 1, ret_object
, ret_offset
);
3056 int journal_file_move_to_entry_by_monotonic(
3060 direction_t direction
,
3061 Object
**ret_object
,
3062 uint64_t *ret_offset
) {
3069 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, NULL
);
3075 return generic_array_bisect_plus_one(
3077 le64toh(o
->data
.entry_offset
),
3078 le64toh(o
->data
.entry_array_offset
),
3079 le64toh(o
->data
.n_entries
),
3081 test_object_monotonic
,
3083 ret_object
, ret_offset
, NULL
);
3086 void journal_file_reset_location(JournalFile
*f
) {
3089 f
->location_type
= LOCATION_HEAD
;
3090 f
->current_offset
= 0;
3091 f
->current_seqnum
= 0;
3092 f
->current_realtime
= 0;
3093 f
->current_monotonic
= 0;
3094 zero(f
->current_boot_id
);
3095 f
->current_xor_hash
= 0;
3098 void journal_file_save_location(JournalFile
*f
, Object
*o
, uint64_t offset
) {
3102 f
->location_type
= LOCATION_SEEK
;
3103 f
->current_offset
= offset
;
3104 f
->current_seqnum
= le64toh(o
->entry
.seqnum
);
3105 f
->current_realtime
= le64toh(o
->entry
.realtime
);
3106 f
->current_monotonic
= le64toh(o
->entry
.monotonic
);
3107 f
->current_boot_id
= o
->entry
.boot_id
;
3108 f
->current_xor_hash
= le64toh(o
->entry
.xor_hash
);
3111 int journal_file_compare_locations(JournalFile
*af
, JournalFile
*bf
) {
3118 assert(af
->location_type
== LOCATION_SEEK
);
3119 assert(bf
->location_type
== LOCATION_SEEK
);
3121 /* If contents, timestamps and seqnum match, these entries are
3123 if (sd_id128_equal(af
->current_boot_id
, bf
->current_boot_id
) &&
3124 af
->current_monotonic
== bf
->current_monotonic
&&
3125 af
->current_realtime
== bf
->current_realtime
&&
3126 af
->current_xor_hash
== bf
->current_xor_hash
&&
3127 sd_id128_equal(af
->header
->seqnum_id
, bf
->header
->seqnum_id
) &&
3128 af
->current_seqnum
== bf
->current_seqnum
)
3131 if (sd_id128_equal(af
->header
->seqnum_id
, bf
->header
->seqnum_id
)) {
3133 /* If this is from the same seqnum source, compare
3135 r
= CMP(af
->current_seqnum
, bf
->current_seqnum
);
3139 /* Wow! This is weird, different data but the same
3140 * seqnums? Something is borked, but let's make the
3141 * best of it and compare by time. */
3144 if (sd_id128_equal(af
->current_boot_id
, bf
->current_boot_id
)) {
3146 /* If the boot id matches, compare monotonic time */
3147 r
= CMP(af
->current_monotonic
, bf
->current_monotonic
);
3152 /* Otherwise, compare UTC time */
3153 r
= CMP(af
->current_realtime
, bf
->current_realtime
);
3157 /* Finally, compare by contents */
3158 return CMP(af
->current_xor_hash
, bf
->current_xor_hash
);
3161 static bool check_properly_ordered(uint64_t new_offset
, uint64_t old_offset
, direction_t direction
) {
3163 /* Consider it an error if any of the two offsets is uninitialized */
3164 if (old_offset
== 0 || new_offset
== 0)
3167 /* If we go down, the new offset must be larger than the old one. */
3168 return direction
== DIRECTION_DOWN
?
3169 new_offset
> old_offset
:
3170 new_offset
< old_offset
;
3173 int journal_file_next_entry(
3176 direction_t direction
,
3177 Object
**ret_object
,
3178 uint64_t *ret_offset
) {
3186 /* FIXME: fix return value assignment. */
3188 n
= le64toh(READ_NOW(f
->header
->n_entries
));
3193 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
3195 r
= generic_array_bisect(f
,
3196 le64toh(f
->header
->entry_array_offset
),
3197 le64toh(f
->header
->n_entries
),
3206 r
= bump_array_index(&i
, direction
, n
);
3211 /* And jump to it */
3212 r
= generic_array_get(f
, le64toh(f
->header
->entry_array_offset
), i
, direction
, ret_object
, &ofs
);
3216 /* Ensure our array is properly ordered. */
3217 if (p
> 0 && !check_properly_ordered(ofs
, p
, direction
))
3218 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
3219 "%s: entry array not properly ordered at entry %" PRIu64
,
3228 int journal_file_next_entry_for_data(
3231 direction_t direction
,
3232 Object
**ret_object
,
3233 uint64_t *ret_offset
) {
3240 assert(d
->object
.type
== OBJECT_DATA
);
3242 /* FIXME: fix return value assignment. */
3244 n
= le64toh(READ_NOW(d
->data
.n_entries
));
3248 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
3250 r
= generic_array_get_plus_one(f
,
3251 le64toh(d
->data
.entry_offset
),
3252 le64toh(d
->data
.entry_array_offset
),
3265 int journal_file_move_to_entry_by_offset_for_data(
3269 direction_t direction
,
3270 Object
**ret
, uint64_t *ret_offset
) {
3274 assert(d
->object
.type
== OBJECT_DATA
);
3276 return generic_array_bisect_plus_one(
3278 le64toh(d
->data
.entry_offset
),
3279 le64toh(d
->data
.entry_array_offset
),
3280 le64toh(d
->data
.n_entries
),
3284 ret
, ret_offset
, NULL
);
3287 int journal_file_move_to_entry_by_monotonic_for_data(
3292 direction_t direction
,
3293 Object
**ret_object
,
3294 uint64_t *ret_offset
) {
3296 uint64_t b
, z
, entry_offset
, entry_array_offset
, n_entries
;
3302 assert(d
->object
.type
== OBJECT_DATA
);
3304 /* Save all the required data before the data object gets invalidated. */
3305 entry_offset
= le64toh(READ_NOW(d
->data
.entry_offset
));
3306 entry_array_offset
= le64toh(READ_NOW(d
->data
.entry_array_offset
));
3307 n_entries
= le64toh(READ_NOW(d
->data
.n_entries
));
3309 /* First, seek by time */
3310 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &b
);
3316 r
= generic_array_bisect_plus_one(f
,
3317 le64toh(o
->data
.entry_offset
),
3318 le64toh(o
->data
.entry_array_offset
),
3319 le64toh(o
->data
.n_entries
),
3321 test_object_monotonic
,
3327 /* And now, continue seeking until we find an entry that
3328 * exists in both bisection arrays */
3330 r
= journal_file_move_to_object(f
, OBJECT_DATA
, b
, &o
);
3337 r
= generic_array_bisect_plus_one(f
,
3348 r
= generic_array_bisect_plus_one(f
,
3349 le64toh(o
->data
.entry_offset
),
3350 le64toh(o
->data
.entry_array_offset
),
3351 le64toh(o
->data
.n_entries
),
3362 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, q
, ret_object
);
3377 int journal_file_move_to_entry_by_seqnum_for_data(
3381 direction_t direction
,
3382 Object
**ret_object
,
3383 uint64_t *ret_offset
) {
3387 assert(d
->object
.type
== OBJECT_DATA
);
3389 return generic_array_bisect_plus_one(
3391 le64toh(d
->data
.entry_offset
),
3392 le64toh(d
->data
.entry_array_offset
),
3393 le64toh(d
->data
.n_entries
),
3397 ret_object
, ret_offset
, NULL
);
3400 int journal_file_move_to_entry_by_realtime_for_data(
3404 direction_t direction
,
3405 Object
**ret
, uint64_t *ret_offset
) {
3409 assert(d
->object
.type
== OBJECT_DATA
);
3411 return generic_array_bisect_plus_one(
3413 le64toh(d
->data
.entry_offset
),
3414 le64toh(d
->data
.entry_array_offset
),
3415 le64toh(d
->data
.n_entries
),
3417 test_object_realtime
,
3419 ret
, ret_offset
, NULL
);
3422 void journal_file_dump(JournalFile
*f
) {
3430 journal_file_print_header(f
);
3432 p
= le64toh(READ_NOW(f
->header
->header_size
));
3437 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &o
);
3441 s
= journal_object_type_to_string(o
->object
.type
);
3443 switch (o
->object
.type
) {
3448 printf("Type: %s seqnum=%"PRIu64
" monotonic=%"PRIu64
" realtime=%"PRIu64
"\n",
3450 le64toh(o
->entry
.seqnum
),
3451 le64toh(o
->entry
.monotonic
),
3452 le64toh(o
->entry
.realtime
));
3458 printf("Type: %s seqnum=%"PRIu64
" epoch=%"PRIu64
"\n",
3460 le64toh(o
->tag
.seqnum
),
3461 le64toh(o
->tag
.epoch
));
3466 printf("Type: %s \n", s
);
3468 printf("Type: unknown (%i)", o
->object
.type
);
3473 c
= COMPRESSION_FROM_OBJECT(o
);
3474 if (c
> COMPRESSION_NONE
)
3475 printf("Flags: %s\n",
3476 compression_to_string(c
));
3478 if (p
== le64toh(f
->header
->tail_object_offset
))
3481 p
+= ALIGN64(le64toh(o
->object
.size
));
3486 log_error("File corrupt");
3489 /* Note: the lifetime of the compound literal is the immediately surrounding block. */
3490 #define FORMAT_TIMESTAMP_SAFE(t) (FORMAT_TIMESTAMP(t) ?: " --- ")
3492 void journal_file_print_header(JournalFile
*f
) {
3498 printf("File path: %s\n"
3502 "Sequential number ID: %s\n"
3504 "Compatible flags:%s%s\n"
3505 "Incompatible flags:%s%s%s%s%s%s\n"
3506 "Header size: %"PRIu64
"\n"
3507 "Arena size: %"PRIu64
"\n"
3508 "Data hash table size: %"PRIu64
"\n"
3509 "Field hash table size: %"PRIu64
"\n"
3510 "Rotate suggested: %s\n"
3511 "Head sequential number: %"PRIu64
" (%"PRIx64
")\n"
3512 "Tail sequential number: %"PRIu64
" (%"PRIx64
")\n"
3513 "Head realtime timestamp: %s (%"PRIx64
")\n"
3514 "Tail realtime timestamp: %s (%"PRIx64
")\n"
3515 "Tail monotonic timestamp: %s (%"PRIx64
")\n"
3516 "Objects: %"PRIu64
"\n"
3517 "Entry objects: %"PRIu64
"\n",
3519 SD_ID128_TO_STRING(f
->header
->file_id
),
3520 SD_ID128_TO_STRING(f
->header
->machine_id
),
3521 SD_ID128_TO_STRING(f
->header
->boot_id
),
3522 SD_ID128_TO_STRING(f
->header
->seqnum_id
),
3523 f
->header
->state
== STATE_OFFLINE
? "OFFLINE" :
3524 f
->header
->state
== STATE_ONLINE
? "ONLINE" :
3525 f
->header
->state
== STATE_ARCHIVED
? "ARCHIVED" : "UNKNOWN",
3526 JOURNAL_HEADER_SEALED(f
->header
) ? " SEALED" : "",
3527 (le32toh(f
->header
->compatible_flags
) & ~HEADER_COMPATIBLE_ANY
) ? " ???" : "",
3528 JOURNAL_HEADER_COMPRESSED_XZ(f
->header
) ? " COMPRESSED-XZ" : "",
3529 JOURNAL_HEADER_COMPRESSED_LZ4(f
->header
) ? " COMPRESSED-LZ4" : "",
3530 JOURNAL_HEADER_COMPRESSED_ZSTD(f
->header
) ? " COMPRESSED-ZSTD" : "",
3531 JOURNAL_HEADER_KEYED_HASH(f
->header
) ? " KEYED-HASH" : "",
3532 JOURNAL_HEADER_COMPACT(f
->header
) ? " COMPACT" : "",
3533 (le32toh(f
->header
->incompatible_flags
) & ~HEADER_INCOMPATIBLE_ANY
) ? " ???" : "",
3534 le64toh(f
->header
->header_size
),
3535 le64toh(f
->header
->arena_size
),
3536 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
3537 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
),
3538 yes_no(journal_file_rotate_suggested(f
, 0, LOG_DEBUG
)),
3539 le64toh(f
->header
->head_entry_seqnum
), le64toh(f
->header
->head_entry_seqnum
),
3540 le64toh(f
->header
->tail_entry_seqnum
), le64toh(f
->header
->tail_entry_seqnum
),
3541 FORMAT_TIMESTAMP_SAFE(le64toh(f
->header
->head_entry_realtime
)), le64toh(f
->header
->head_entry_realtime
),
3542 FORMAT_TIMESTAMP_SAFE(le64toh(f
->header
->tail_entry_realtime
)), le64toh(f
->header
->tail_entry_realtime
),
3543 FORMAT_TIMESPAN(le64toh(f
->header
->tail_entry_monotonic
), USEC_PER_MSEC
), le64toh(f
->header
->tail_entry_monotonic
),
3544 le64toh(f
->header
->n_objects
),
3545 le64toh(f
->header
->n_entries
));
3547 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
3548 printf("Data objects: %"PRIu64
"\n"
3549 "Data hash table fill: %.1f%%\n",
3550 le64toh(f
->header
->n_data
),
3551 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))));
3553 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
3554 printf("Field objects: %"PRIu64
"\n"
3555 "Field hash table fill: %.1f%%\n",
3556 le64toh(f
->header
->n_fields
),
3557 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))));
3559 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_tags
))
3560 printf("Tag objects: %"PRIu64
"\n",
3561 le64toh(f
->header
->n_tags
));
3562 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
3563 printf("Entry array objects: %"PRIu64
"\n",
3564 le64toh(f
->header
->n_entry_arrays
));
3566 if (JOURNAL_HEADER_CONTAINS(f
->header
, field_hash_chain_depth
))
3567 printf("Deepest field hash chain: %" PRIu64
"\n",
3568 f
->header
->field_hash_chain_depth
);
3570 if (JOURNAL_HEADER_CONTAINS(f
->header
, data_hash_chain_depth
))
3571 printf("Deepest data hash chain: %" PRIu64
"\n",
3572 f
->header
->data_hash_chain_depth
);
3574 if (fstat(f
->fd
, &st
) >= 0)
3575 printf("Disk usage: %s\n", FORMAT_BYTES((uint64_t) st
.st_blocks
* 512ULL));
3578 static int journal_file_warn_btrfs(JournalFile
*f
) {
3584 /* Before we write anything, check if the COW logic is turned
3585 * off on btrfs. Given our write pattern that is quite
3586 * unfriendly to COW file systems this should greatly improve
3587 * performance on COW file systems, such as btrfs, at the
3588 * expense of data integrity features (which shouldn't be too
3589 * bad, given that we do our own checksumming). */
3591 r
= fd_is_fs_type(f
->fd
, BTRFS_SUPER_MAGIC
);
3593 return log_ratelimit_warning_errno(r
, JOURNAL_LOG_RATELIMIT
, "Failed to determine if journal is on btrfs: %m");
3597 r
= read_attr_fd(f
->fd
, &attrs
);
3599 return log_ratelimit_warning_errno(r
, JOURNAL_LOG_RATELIMIT
, "Failed to read file attributes: %m");
3601 if (attrs
& FS_NOCOW_FL
) {
3602 log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
3606 log_ratelimit_notice(JOURNAL_LOG_RATELIMIT
,
3607 "Creating journal file %s on a btrfs file system, and copy-on-write is enabled. "
3608 "This is likely to slow down journal access substantially, please consider turning "
3609 "off the copy-on-write file attribute on the journal directory, using chattr +C.",
3615 static void journal_default_metrics(JournalMetrics
*m
, int fd
, bool compact
) {
3617 uint64_t fs_size
= 0;
3622 if (fstatvfs(fd
, &ss
) >= 0)
3623 fs_size
= ss
.f_frsize
* ss
.f_blocks
;
3625 log_debug_errno(errno
, "Failed to determine disk size: %m");
3627 if (m
->max_use
== UINT64_MAX
) {
3630 m
->max_use
= CLAMP(PAGE_ALIGN(fs_size
/ 10), /* 10% of file system size */
3631 MAX_USE_LOWER
, MAX_USE_UPPER
);
3633 m
->max_use
= MAX_USE_LOWER
;
3635 m
->max_use
= PAGE_ALIGN(m
->max_use
);
3637 if (m
->max_use
!= 0 && m
->max_use
< JOURNAL_FILE_SIZE_MIN
*2)
3638 m
->max_use
= JOURNAL_FILE_SIZE_MIN
*2;
3641 if (m
->min_use
== UINT64_MAX
) {
3643 m
->min_use
= CLAMP(PAGE_ALIGN(fs_size
/ 50), /* 2% of file system size */
3644 MIN_USE_LOW
, MIN_USE_HIGH
);
3646 m
->min_use
= MIN_USE_LOW
;
3649 if (m
->min_use
> m
->max_use
)
3650 m
->min_use
= m
->max_use
;
3652 if (m
->max_size
== UINT64_MAX
)
3653 m
->max_size
= MIN(PAGE_ALIGN(m
->max_use
/ 8), /* 8 chunks */
3656 m
->max_size
= PAGE_ALIGN(m
->max_size
);
3658 if (compact
&& m
->max_size
> JOURNAL_COMPACT_SIZE_MAX
)
3659 m
->max_size
= JOURNAL_COMPACT_SIZE_MAX
;
3661 if (m
->max_size
!= 0) {
3662 if (m
->max_size
< JOURNAL_FILE_SIZE_MIN
)
3663 m
->max_size
= JOURNAL_FILE_SIZE_MIN
;
3665 if (m
->max_use
!= 0 && m
->max_size
*2 > m
->max_use
)
3666 m
->max_use
= m
->max_size
*2;
3669 if (m
->min_size
== UINT64_MAX
)
3670 m
->min_size
= JOURNAL_FILE_SIZE_MIN
;
3672 m
->min_size
= CLAMP(PAGE_ALIGN(m
->min_size
),
3673 JOURNAL_FILE_SIZE_MIN
,
3674 m
->max_size
?: UINT64_MAX
);
3676 if (m
->keep_free
== UINT64_MAX
) {
3678 m
->keep_free
= MIN(PAGE_ALIGN(fs_size
/ 20), /* 5% of file system size */
3681 m
->keep_free
= DEFAULT_KEEP_FREE
;
3684 if (m
->n_max_files
== UINT64_MAX
)
3685 m
->n_max_files
= DEFAULT_N_MAX_FILES
;
3687 log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64
,
3688 FORMAT_BYTES(m
->min_use
),
3689 FORMAT_BYTES(m
->max_use
),
3690 FORMAT_BYTES(m
->max_size
),
3691 FORMAT_BYTES(m
->min_size
),
3692 FORMAT_BYTES(m
->keep_free
),
3696 int journal_file_open(
3700 JournalFileFlags file_flags
,
3702 uint64_t compress_threshold_bytes
,
3703 JournalMetrics
*metrics
,
3704 MMapCache
*mmap_cache
,
3705 JournalFile
*template,
3706 JournalFile
**ret
) {
3708 bool newly_created
= false;
3713 assert(fd
>= 0 || fname
);
3717 if (!IN_SET((open_flags
& O_ACCMODE
), O_RDONLY
, O_RDWR
))
3720 if ((open_flags
& O_ACCMODE
) == O_RDONLY
&& FLAGS_SET(open_flags
, O_CREAT
))
3723 if (fname
&& (open_flags
& O_CREAT
) && !endswith(fname
, ".journal"))
3726 f
= new(JournalFile
, 1);
3730 *f
= (JournalFile
) {
3733 .open_flags
= open_flags
,
3734 .compress_threshold_bytes
= compress_threshold_bytes
== UINT64_MAX
?
3735 DEFAULT_COMPRESS_THRESHOLD
:
3736 MAX(MIN_COMPRESS_THRESHOLD
, compress_threshold_bytes
),
3740 f
->path
= strdup(fname
);
3748 /* If we don't know the path, fill in something explanatory and vaguely useful */
3749 if (asprintf(&f
->path
, "/proc/self/%i", fd
) < 0) {
3755 f
->chain_cache
= ordered_hashmap_new(&uint64_hash_ops
);
3756 if (!f
->chain_cache
) {
3762 /* We pass O_NONBLOCK here, so that in case somebody pointed us to some character device node or FIFO
3763 * or so, we likely fail quickly than block for long. For regular files O_NONBLOCK has no effect, hence
3764 * it doesn't hurt in that case. */
3766 f
->fd
= openat_report_new(AT_FDCWD
, f
->path
, f
->open_flags
|O_CLOEXEC
|O_NONBLOCK
, f
->mode
, &newly_created
);
3772 /* fds we opened here by us should also be closed by us. */
3775 r
= fd_nonblock(f
->fd
, false);
3779 if (!newly_created
) {
3780 r
= journal_file_fstat(f
);
3785 r
= journal_file_fstat(f
);
3789 /* If we just got the fd passed in, we don't really know if we created the file anew */
3790 newly_created
= f
->last_stat
.st_size
== 0 && journal_file_writable(f
);
3793 f
->cache_fd
= mmap_cache_add_fd(mmap_cache
, f
->fd
, mmap_prot_from_open_flags(open_flags
));
3799 if (newly_created
) {
3800 (void) journal_file_warn_btrfs(f
);
3802 /* Let's attach the creation time to the journal file, so that the vacuuming code knows the age of this
3803 * file even if the file might end up corrupted one day... Ideally we'd just use the creation time many
3804 * file systems maintain for each file, but the API to query this is very new, hence let's emulate this
3805 * via extended attributes. If extended attributes are not supported we'll just skip this, and rely
3806 * solely on mtime/atime/ctime of the file. */
3807 (void) fd_setcrtime(f
->fd
, 0);
3809 r
= journal_file_init_header(f
, file_flags
, template);
3813 r
= journal_file_fstat(f
);
3818 if (f
->last_stat
.st_size
< (off_t
) HEADER_SIZE_MIN
) {
3823 r
= mmap_cache_fd_get(f
->cache_fd
, CONTEXT_HEADER
, true, 0, PAGE_ALIGN(sizeof(Header
)), &f
->last_stat
, &h
);
3825 /* Some file systems (jffs2 or p9fs) don't support mmap() properly (or only read-only
3826 * mmap()), and return EINVAL in that case. Let's propagate that as a more recognizable error
3836 if (!newly_created
) {
3837 r
= journal_file_verify_header(f
);
3843 if (!newly_created
&& journal_file_writable(f
) && JOURNAL_HEADER_SEALED(f
->header
)) {
3844 r
= journal_file_fss_load(f
);
3850 if (journal_file_writable(f
)) {
3852 journal_default_metrics(metrics
, f
->fd
, JOURNAL_HEADER_COMPACT(f
->header
));
3853 f
->metrics
= *metrics
;
3854 } else if (template)
3855 f
->metrics
= template->metrics
;
3857 r
= journal_file_refresh_header(f
);
3863 r
= journal_file_hmac_setup(f
);
3868 if (newly_created
) {
3869 r
= journal_file_setup_field_hash_table(f
);
3873 r
= journal_file_setup_data_hash_table(f
);
3878 r
= journal_file_append_first_tag(f
);
3884 if (mmap_cache_fd_got_sigbus(f
->cache_fd
)) {
3889 if (template && template->post_change_timer
) {
3890 r
= journal_file_enable_post_change_timer(
3892 sd_event_source_get_event(template->post_change_timer
),
3893 template->post_change_timer_period
);
3899 /* The file is opened now successfully, thus we take possession of any passed in fd. */
3902 if (DEBUG_LOGGING
) {
3903 static int last_seal
= -1, last_compress
= -1, last_keyed_hash
= -1;
3904 static uint64_t last_bytes
= UINT64_MAX
;
3906 if (last_seal
!= JOURNAL_HEADER_SEALED(f
->header
) ||
3907 last_keyed_hash
!= JOURNAL_HEADER_KEYED_HASH(f
->header
) ||
3908 last_compress
!= JOURNAL_FILE_COMPRESS(f
) ||
3909 last_bytes
!= f
->compress_threshold_bytes
) {
3911 log_debug("Journal effective settings seal=%s keyed_hash=%s compress=%s compress_threshold_bytes=%s",
3912 yes_no(JOURNAL_HEADER_SEALED(f
->header
)), yes_no(JOURNAL_HEADER_KEYED_HASH(f
->header
)),
3913 yes_no(JOURNAL_FILE_COMPRESS(f
)), FORMAT_BYTES(f
->compress_threshold_bytes
));
3914 last_seal
= JOURNAL_HEADER_SEALED(f
->header
);
3915 last_keyed_hash
= JOURNAL_HEADER_KEYED_HASH(f
->header
);
3916 last_compress
= JOURNAL_FILE_COMPRESS(f
);
3917 last_bytes
= f
->compress_threshold_bytes
;
3925 if (f
->cache_fd
&& mmap_cache_fd_got_sigbus(f
->cache_fd
))
3928 (void) journal_file_close(f
);
3930 if (newly_created
&& fd
< 0)
3931 (void) unlink(fname
);
3936 int journal_file_parse_uid_from_filename(const char *path
, uid_t
*ret_uid
) {
3937 _cleanup_free_
char *buf
= NULL
, *p
= NULL
;
3938 const char *a
, *b
, *at
;
3941 /* This helper returns -EREMOTE when the filename doesn't match user online/offline journal
3942 * pattern. Hence it currently doesn't parse archived or disposed user journals. */
3947 r
= path_extract_filename(path
, &p
);
3950 if (r
== O_DIRECTORY
)
3953 a
= startswith(p
, "user-");
3956 b
= endswith(p
, ".journal");
3960 at
= strchr(a
, '@');
3964 buf
= strndup(a
, b
-a
);
3968 return parse_uid(buf
, ret_uid
);
3971 int journal_file_archive(JournalFile
*f
, char **ret_previous_path
) {
3972 _cleanup_free_
char *p
= NULL
;
3976 if (!journal_file_writable(f
))
3979 /* Is this a journal file that was passed to us as fd? If so, we synthesized a path name for it, and we refuse
3980 * rotation, since we don't know the actual path, and couldn't rename the file hence. */
3981 if (path_startswith(f
->path
, "/proc/self/fd"))
3984 if (!endswith(f
->path
, ".journal"))
3987 if (asprintf(&p
, "%.*s@" SD_ID128_FORMAT_STR
"-%016"PRIx64
"-%016"PRIx64
".journal",
3988 (int) strlen(f
->path
) - 8, f
->path
,
3989 SD_ID128_FORMAT_VAL(f
->header
->seqnum_id
),
3990 le64toh(f
->header
->head_entry_seqnum
),
3991 le64toh(f
->header
->head_entry_realtime
)) < 0)
3994 /* Try to rename the file to the archived version. If the file already was deleted, we'll get ENOENT, let's
3995 * ignore that case. */
3996 if (rename(f
->path
, p
) < 0 && errno
!= ENOENT
)
3999 /* Sync the rename to disk */
4000 (void) fsync_directory_of_file(f
->fd
);
4002 if (ret_previous_path
)
4003 *ret_previous_path
= f
->path
;
4007 f
->path
= TAKE_PTR(p
);
4009 /* Set as archive so offlining commits w/state=STATE_ARCHIVED. Previously we would set old_file->header->state
4010 * to STATE_ARCHIVED directly here, but journal_file_set_offline() short-circuits when state != STATE_ONLINE,
4011 * which would result in the rotated journal never getting fsync() called before closing. Now we simply queue
4012 * the archive state by setting an archive bit, leaving the state as STATE_ONLINE so proper offlining
4019 int journal_file_dispose(int dir_fd
, const char *fname
) {
4020 _cleanup_free_
char *p
= NULL
;
4024 /* Renames a journal file to *.journal~, i.e. to mark it as corrupted or otherwise uncleanly shutdown. Note that
4025 * this is done without looking into the file or changing any of its contents. The idea is that this is called
4026 * whenever something is suspicious and we want to move the file away and make clear that it is not accessed
4027 * for writing anymore. */
4029 if (!endswith(fname
, ".journal"))
4032 if (asprintf(&p
, "%.*s@%016" PRIx64
"-%016" PRIx64
".journal~",
4033 (int) strlen(fname
) - 8, fname
,
4034 now(CLOCK_REALTIME
),
4038 if (renameat(dir_fd
, fname
, dir_fd
, p
) < 0)
4044 int journal_file_copy_entry(JournalFile
*from
, JournalFile
*to
, Object
*o
, uint64_t p
) {
4045 _cleanup_free_ EntryItem
*items_alloc
= NULL
;
4047 uint64_t q
, n
, xor_hash
= 0;
4048 const sd_id128_t
*boot_id
;
4057 if (!journal_file_writable(to
))
4060 ts
= (dual_timestamp
) {
4061 .monotonic
= le64toh(o
->entry
.monotonic
),
4062 .realtime
= le64toh(o
->entry
.realtime
),
4064 boot_id
= &o
->entry
.boot_id
;
4066 n
= journal_file_entry_n_items(from
, o
);
4068 if (n
< ALLOCA_MAX
/ sizeof(EntryItem
) / 2)
4069 items
= newa(EntryItem
, n
);
4071 items_alloc
= new(EntryItem
, n
);
4075 items
= items_alloc
;
4078 for (uint64_t i
= 0; i
< n
; i
++) {
4084 q
= journal_file_entry_item_object_offset(from
, o
, i
);
4085 r
= journal_file_data_payload(from
, NULL
, q
, NULL
, 0, 0, &data
, &l
);
4086 if (IN_SET(r
, -EADDRNOTAVAIL
, -EBADMSG
)) {
4087 log_debug_errno(r
, "Entry item %"PRIu64
" data object is bad, skipping over it: %m", i
);
4097 r
= journal_file_append_data(to
, data
, l
, &u
, &h
);
4101 if (JOURNAL_HEADER_KEYED_HASH(to
->header
))
4102 xor_hash
^= jenkins_hash64(data
, l
);
4104 xor_hash
^= le64toh(u
->data
.hash
);
4106 items
[i
] = (EntryItem
) {
4108 .hash
= le64toh(u
->data
.hash
),
4112 /* The above journal_file_data_payload() may clear or overwrite cached object. Hence, we need
4113 * to re-read the object from the cache. */
4114 r
= journal_file_move_to_object(from
, OBJECT_ENTRY
, p
, &o
);
4119 r
= journal_file_append_entry_internal(to
, &ts
, boot_id
, xor_hash
, items
, n
, NULL
, NULL
, NULL
);
4121 if (mmap_cache_fd_got_sigbus(to
->cache_fd
))
4127 void journal_reset_metrics(JournalMetrics
*m
) {
4130 /* Set everything to "pick automatic values". */
4132 *m
= (JournalMetrics
) {
4133 .min_use
= UINT64_MAX
,
4134 .max_use
= UINT64_MAX
,
4135 .min_size
= UINT64_MAX
,
4136 .max_size
= UINT64_MAX
,
4137 .keep_free
= UINT64_MAX
,
4138 .n_max_files
= UINT64_MAX
,
4142 int journal_file_get_cutoff_realtime_usec(JournalFile
*f
, usec_t
*ret_from
, usec_t
*ret_to
) {
4145 assert(ret_from
|| ret_to
);
4148 if (f
->header
->head_entry_realtime
== 0)
4151 *ret_from
= le64toh(f
->header
->head_entry_realtime
);
4155 if (f
->header
->tail_entry_realtime
== 0)
4158 *ret_to
= le64toh(f
->header
->tail_entry_realtime
);
4164 int journal_file_get_cutoff_monotonic_usec(JournalFile
*f
, sd_id128_t boot_id
, usec_t
*ret_from
, usec_t
*ret_to
) {
4170 assert(ret_from
|| ret_to
);
4172 /* FIXME: fix return value assignment on success with 0. */
4174 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &p
);
4178 if (le64toh(o
->data
.n_entries
) <= 0)
4182 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, le64toh(o
->data
.entry_offset
), &o
);
4186 *ret_from
= le64toh(o
->entry
.monotonic
);
4190 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
4194 r
= generic_array_get_plus_one(f
,
4195 le64toh(o
->data
.entry_offset
),
4196 le64toh(o
->data
.entry_array_offset
),
4197 le64toh(o
->data
.n_entries
) - 1,
4203 *ret_to
= le64toh(o
->entry
.monotonic
);
4209 bool journal_file_rotate_suggested(JournalFile
*f
, usec_t max_file_usec
, int log_level
) {
4213 /* If we gained new header fields we gained new features,
4214 * hence suggest a rotation */
4215 if (le64toh(f
->header
->header_size
) < sizeof(Header
)) {
4216 log_ratelimit_full(log_level
, JOURNAL_LOG_RATELIMIT
,
4217 "%s uses an outdated header, suggesting rotation.", f
->path
);
4221 /* Let's check if the hash tables grew over a certain fill level (75%, borrowing this value from
4222 * Java's hash table implementation), and if so suggest a rotation. To calculate the fill level we
4223 * need the n_data field, which only exists in newer versions. */
4225 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
4226 if (le64toh(f
->header
->n_data
) * 4ULL > (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
4228 log_level
, JOURNAL_LOG_RATELIMIT
,
4229 "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.",
4231 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))),
4232 le64toh(f
->header
->n_data
),
4233 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
4234 (unsigned long long) f
->last_stat
.st_size
,
4235 f
->last_stat
.st_size
/ le64toh(f
->header
->n_data
));
4239 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
4240 if (le64toh(f
->header
->n_fields
) * 4ULL > (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
4242 log_level
, JOURNAL_LOG_RATELIMIT
,
4243 "Field hash table of %s has a fill level at %.1f (%"PRIu64
" of %"PRIu64
" items), suggesting rotation.",
4245 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))),
4246 le64toh(f
->header
->n_fields
),
4247 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
));
4251 /* If there are too many hash collisions somebody is most likely playing games with us. Hence, if our
4252 * longest chain is longer than some threshold, let's suggest rotation. */
4253 if (JOURNAL_HEADER_CONTAINS(f
->header
, data_hash_chain_depth
) &&
4254 le64toh(f
->header
->data_hash_chain_depth
) > HASH_CHAIN_DEPTH_MAX
) {
4256 log_level
, JOURNAL_LOG_RATELIMIT
,
4257 "Data hash table of %s has deepest hash chain of length %" PRIu64
", suggesting rotation.",
4258 f
->path
, le64toh(f
->header
->data_hash_chain_depth
));
4262 if (JOURNAL_HEADER_CONTAINS(f
->header
, field_hash_chain_depth
) &&
4263 le64toh(f
->header
->field_hash_chain_depth
) > HASH_CHAIN_DEPTH_MAX
) {
4265 log_level
, JOURNAL_LOG_RATELIMIT
,
4266 "Field hash table of %s has deepest hash chain of length at %" PRIu64
", suggesting rotation.",
4267 f
->path
, le64toh(f
->header
->field_hash_chain_depth
));
4271 /* Are the data objects properly indexed by field objects? */
4272 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
) &&
4273 JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
) &&
4274 le64toh(f
->header
->n_data
) > 0 &&
4275 le64toh(f
->header
->n_fields
) == 0) {
4277 log_level
, JOURNAL_LOG_RATELIMIT
,
4278 "Data objects of %s are not indexed by field objects, suggesting rotation.",
4283 if (max_file_usec
> 0) {
4286 h
= le64toh(f
->header
->head_entry_realtime
);
4287 t
= now(CLOCK_REALTIME
);
4289 if (h
> 0 && t
> h
+ max_file_usec
) {
4291 log_level
, JOURNAL_LOG_RATELIMIT
,
4292 "Oldest entry in %s is older than the configured file retention duration (%s), suggesting rotation.",
4293 f
->path
, FORMAT_TIMESPAN(max_file_usec
, USEC_PER_SEC
));
4301 static const char * const journal_object_type_table
[] = {
4302 [OBJECT_UNUSED
] = "unused",
4303 [OBJECT_DATA
] = "data",
4304 [OBJECT_FIELD
] = "field",
4305 [OBJECT_ENTRY
] = "entry",
4306 [OBJECT_DATA_HASH_TABLE
] = "data hash table",
4307 [OBJECT_FIELD_HASH_TABLE
] = "field hash table",
4308 [OBJECT_ENTRY_ARRAY
] = "entry array",
4309 [OBJECT_TAG
] = "tag",
4312 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(journal_object_type
, ObjectType
);