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 "id128-util.h"
24 #include "journal-authenticate.h"
25 #include "journal-def.h"
26 #include "journal-file.h"
27 #include "journal-internal.h"
29 #include "memory-util.h"
30 #include "missing_threads.h"
31 #include "path-util.h"
33 #include "random-util.h"
35 #include "sort-util.h"
36 #include "stat-util.h"
37 #include "string-table.h"
38 #include "string-util.h"
40 #include "sync-util.h"
41 #include "user-util.h"
42 #include "xattr-util.h"
44 #define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem))
45 #define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem))
47 #define DEFAULT_COMPRESS_THRESHOLD (512ULL)
48 #define MIN_COMPRESS_THRESHOLD (8ULL)
50 /* This is the minimum journal file size */
51 #define JOURNAL_FILE_SIZE_MIN (512 * 1024ULL) /* 512 KiB */
52 #define JOURNAL_COMPACT_SIZE_MAX UINT32_MAX /* 4 GiB */
54 /* These are the lower and upper bounds if we deduce the max_use value
55 * from the file system size */
56 #define MAX_USE_LOWER (1 * 1024 * 1024ULL) /* 1 MiB */
57 #define MAX_USE_UPPER (4 * 1024 * 1024 * 1024ULL) /* 4 GiB */
59 /* Those are the lower and upper bounds for the minimal use limit,
60 * i.e. how much we'll use even if keep_free suggests otherwise. */
61 #define MIN_USE_LOW (1 * 1024 * 1024ULL) /* 1 MiB */
62 #define MIN_USE_HIGH (16 * 1024 * 1024ULL) /* 16 MiB */
64 /* This is the upper bound if we deduce max_size from max_use */
65 #define MAX_SIZE_UPPER (128 * 1024 * 1024ULL) /* 128 MiB */
67 /* This is the upper bound if we deduce the keep_free value from the
69 #define KEEP_FREE_UPPER (4 * 1024 * 1024 * 1024ULL) /* 4 GiB */
71 /* This is the keep_free value when we can't determine the system
73 #define DEFAULT_KEEP_FREE (1024 * 1024ULL) /* 1 MB */
75 /* This is the default maximum number of journal files to keep around. */
76 #define DEFAULT_N_MAX_FILES 100
78 /* n_data was the first entry we added after the initial file format design */
79 #define HEADER_SIZE_MIN ALIGN64(offsetof(Header, n_data))
81 /* How many entries to keep in the entry array chain cache at max */
82 #define CHAIN_CACHE_MAX 20
84 /* How much to increase the journal file size at once each time we allocate something new. */
85 #define FILE_SIZE_INCREASE (8 * 1024 * 1024ULL) /* 8MB */
87 /* Reread fstat() of the file for detecting deletions at least this often */
88 #define LAST_STAT_REFRESH_USEC (5*USEC_PER_SEC)
90 /* The mmap context to use for the header we pick as one above the last defined typed */
91 #define CONTEXT_HEADER _OBJECT_TYPE_MAX
93 /* Longest hash chain to rotate after */
94 #define HASH_CHAIN_DEPTH_MAX 100
97 # pragma GCC diagnostic ignored "-Waddress-of-packed-member"
100 static int mmap_prot_from_open_flags(int flags
) {
101 switch (flags
& O_ACCMODE
) {
107 return PROT_READ
|PROT_WRITE
;
109 assert_not_reached();
113 int journal_file_tail_end_by_pread(JournalFile
*f
, uint64_t *ret_offset
) {
121 /* Same as journal_file_tail_end_by_mmap() below, but operates with pread() to avoid the mmap cache
122 * (and thus is thread safe) */
124 p
= le64toh(f
->header
->tail_object_offset
);
126 p
= le64toh(f
->header
->header_size
);
131 r
= journal_file_read_object_header(f
, OBJECT_UNUSED
, p
, &tail
);
135 sz
= le64toh(tail
.object
.size
);
136 if (sz
> UINT64_MAX
- sizeof(uint64_t) + 1)
140 if (p
> UINT64_MAX
- sz
)
151 int journal_file_tail_end_by_mmap(JournalFile
*f
, uint64_t *ret_offset
) {
159 /* Same as journal_file_tail_end_by_pread() above, but operates with the usual mmap logic */
161 p
= le64toh(f
->header
->tail_object_offset
);
163 p
= le64toh(f
->header
->header_size
);
168 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &tail
);
172 sz
= le64toh(READ_NOW(tail
->object
.size
));
173 if (sz
> UINT64_MAX
- sizeof(uint64_t) + 1)
177 if (p
> UINT64_MAX
- sz
)
188 int journal_file_set_offline_thread_join(JournalFile
*f
) {
193 if (f
->offline_state
== OFFLINE_JOINED
)
196 r
= pthread_join(f
->offline_thread
, NULL
);
200 f
->offline_state
= OFFLINE_JOINED
;
202 if (mmap_cache_fd_got_sigbus(f
->cache_fd
))
208 static int journal_file_set_online(JournalFile
*f
) {
213 if (!journal_file_writable(f
))
216 if (f
->fd
< 0 || !f
->header
)
220 switch (f
->offline_state
) {
222 /* No offline thread, no need to wait. */
226 case OFFLINE_SYNCING
: {
227 OfflineState tmp_state
= OFFLINE_SYNCING
;
228 if (!__atomic_compare_exchange_n(&f
->offline_state
, &tmp_state
, OFFLINE_CANCEL
,
229 false, __ATOMIC_SEQ_CST
, __ATOMIC_SEQ_CST
))
232 /* Canceled syncing prior to offlining, no need to wait. */
236 case OFFLINE_AGAIN_FROM_SYNCING
: {
237 OfflineState tmp_state
= OFFLINE_AGAIN_FROM_SYNCING
;
238 if (!__atomic_compare_exchange_n(&f
->offline_state
, &tmp_state
, OFFLINE_CANCEL
,
239 false, __ATOMIC_SEQ_CST
, __ATOMIC_SEQ_CST
))
242 /* Canceled restart from syncing, no need to wait. */
246 case OFFLINE_AGAIN_FROM_OFFLINING
: {
247 OfflineState tmp_state
= OFFLINE_AGAIN_FROM_OFFLINING
;
248 if (!__atomic_compare_exchange_n(&f
->offline_state
, &tmp_state
, OFFLINE_CANCEL
,
249 false, __ATOMIC_SEQ_CST
, __ATOMIC_SEQ_CST
))
252 /* Canceled restart from offlining, must wait for offlining to complete however. */
257 r
= journal_file_set_offline_thread_join(f
);
267 if (mmap_cache_fd_got_sigbus(f
->cache_fd
))
270 switch (f
->header
->state
) {
275 f
->header
->state
= STATE_ONLINE
;
284 JournalFile
* journal_file_close(JournalFile
*f
) {
288 assert(f
->newest_boot_id_prioq_idx
== PRIOQ_IDX_NULL
);
291 mmap_cache_fd_free(f
->cache_fd
);
297 ordered_hashmap_free_free(f
->chain_cache
);
300 free(f
->compress_buffer
);
305 munmap(f
->fss_file
, PAGE_ALIGN(f
->fss_file_size
));
307 free(f
->fsprg_state
);
312 gcry_md_close(f
->hmac
);
318 static bool keyed_hash_requested(void) {
319 static thread_local
int cached
= -1;
323 r
= getenv_bool("SYSTEMD_JOURNAL_KEYED_HASH");
326 log_debug_errno(r
, "Failed to parse $SYSTEMD_JOURNAL_KEYED_HASH environment variable, ignoring: %m");
335 static bool compact_mode_requested(void) {
336 static thread_local
int cached
= -1;
340 r
= getenv_bool("SYSTEMD_JOURNAL_COMPACT");
343 log_debug_errno(r
, "Failed to parse $SYSTEMD_JOURNAL_COMPACT environment variable, ignoring: %m");
353 static Compression
getenv_compression(void) {
358 e
= getenv("SYSTEMD_JOURNAL_COMPRESS");
360 return DEFAULT_COMPRESSION
;
362 r
= parse_boolean(e
);
364 return r
? DEFAULT_COMPRESSION
: COMPRESSION_NONE
;
366 c
= compression_from_string(e
);
368 log_debug_errno(c
, "Failed to parse SYSTEMD_JOURNAL_COMPRESS value, ignoring: %s", e
);
369 return DEFAULT_COMPRESSION
;
372 if (!compression_supported(c
)) {
373 log_debug("Unsupported compression algorithm specified, ignoring: %s", e
);
374 return DEFAULT_COMPRESSION
;
381 static Compression
compression_requested(void) {
383 static thread_local Compression cached
= _COMPRESSION_INVALID
;
386 cached
= getenv_compression();
390 return COMPRESSION_NONE
;
394 static int journal_file_init_header(
396 JournalFileFlags file_flags
,
397 JournalFile
*template) {
406 /* Try to load the FSPRG state, and if we can't, then just don't do sealing */
407 seal
= FLAGS_SET(file_flags
, JOURNAL_SEAL
) && journal_file_fss_load(f
) >= 0;
411 .header_size
= htole64(ALIGN64(sizeof(h
))),
412 .incompatible_flags
= htole32(
413 FLAGS_SET(file_flags
, JOURNAL_COMPRESS
) * COMPRESSION_TO_HEADER_INCOMPATIBLE_FLAG(compression_requested()) |
414 keyed_hash_requested() * HEADER_INCOMPATIBLE_KEYED_HASH
|
415 compact_mode_requested() * HEADER_INCOMPATIBLE_COMPACT
),
416 .compatible_flags
= htole32(
417 (seal
* HEADER_COMPATIBLE_SEALED
) |
418 HEADER_COMPATIBLE_TAIL_ENTRY_BOOT_ID
),
421 assert_cc(sizeof(h
.signature
) == sizeof(HEADER_SIGNATURE
));
422 memcpy(h
.signature
, HEADER_SIGNATURE
, sizeof(HEADER_SIGNATURE
));
424 r
= sd_id128_randomize(&h
.file_id
);
428 r
= sd_id128_get_machine(&h
.machine_id
);
429 if (r
< 0 && !ERRNO_IS_MACHINE_ID_UNSET(r
))
430 return r
; /* If we have no valid machine ID (test environment?), let's simply leave the
431 * machine ID field all zeroes. */
434 h
.seqnum_id
= template->header
->seqnum_id
;
435 h
.tail_entry_seqnum
= template->header
->tail_entry_seqnum
;
437 h
.seqnum_id
= h
.file_id
;
439 k
= pwrite(f
->fd
, &h
, sizeof(h
), 0);
448 static int journal_file_refresh_header(JournalFile
*f
) {
454 /* We used to update the header's boot ID field here, but we don't do that anymore, as per
455 * HEADER_COMPATIBLE_TAIL_ENTRY_BOOT_ID */
457 r
= journal_file_set_online(f
);
459 /* Sync the online state to disk; likely just created a new file, also sync the directory this file
461 (void) fsync_full(f
->fd
);
466 static bool warn_wrong_flags(const JournalFile
*f
, bool compatible
) {
467 const uint32_t any
= compatible
? HEADER_COMPATIBLE_ANY
: HEADER_INCOMPATIBLE_ANY
,
468 supported
= compatible
? HEADER_COMPATIBLE_SUPPORTED
: HEADER_INCOMPATIBLE_SUPPORTED
;
469 const char *type
= compatible
? "compatible" : "incompatible";
475 flags
= le32toh(compatible
? f
->header
->compatible_flags
: f
->header
->incompatible_flags
);
477 if (flags
& ~supported
) {
479 log_debug("Journal file %s has unknown %s flags 0x%"PRIx32
,
480 f
->path
, type
, flags
& ~any
);
481 flags
= (flags
& any
) & ~supported
;
485 _cleanup_free_
char *t
= NULL
;
488 if (flags
& HEADER_COMPATIBLE_SEALED
)
489 strv
[n
++] = "sealed";
491 if (flags
& HEADER_INCOMPATIBLE_COMPRESSED_XZ
)
492 strv
[n
++] = "xz-compressed";
493 if (flags
& HEADER_INCOMPATIBLE_COMPRESSED_LZ4
)
494 strv
[n
++] = "lz4-compressed";
495 if (flags
& HEADER_INCOMPATIBLE_COMPRESSED_ZSTD
)
496 strv
[n
++] = "zstd-compressed";
497 if (flags
& HEADER_INCOMPATIBLE_KEYED_HASH
)
498 strv
[n
++] = "keyed-hash";
499 if (flags
& HEADER_INCOMPATIBLE_COMPACT
)
500 strv
[n
++] = "compact";
503 assert(n
< ELEMENTSOF(strv
));
505 t
= strv_join((char**) strv
, ", ");
506 log_debug("Journal file %s uses %s %s %s disabled at compilation time.",
507 f
->path
, type
, n
> 1 ? "flags" : "flag", strnull(t
));
515 static int journal_file_verify_header(JournalFile
*f
) {
516 uint64_t arena_size
, header_size
;
521 if (memcmp(f
->header
->signature
, HEADER_SIGNATURE
, 8))
524 /* In both read and write mode we refuse to open files with incompatible
525 * flags we don't know. */
526 if (warn_wrong_flags(f
, false))
527 return -EPROTONOSUPPORT
;
529 /* When open for writing we refuse to open files with compatible flags, too. */
530 if (journal_file_writable(f
) && warn_wrong_flags(f
, true))
531 return -EPROTONOSUPPORT
;
533 if (f
->header
->state
>= _STATE_MAX
)
536 header_size
= le64toh(READ_NOW(f
->header
->header_size
));
538 /* The first addition was n_data, so check that we are at least this large */
539 if (header_size
< HEADER_SIZE_MIN
)
542 /* When open for writing we refuse to open files with a mismatch of the header size, i.e. writing to
543 * files implementing older or new header structures. */
544 if (journal_file_writable(f
) && header_size
!= sizeof(Header
))
545 return -EPROTONOSUPPORT
;
547 if (JOURNAL_HEADER_SEALED(f
->header
) && !JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
550 arena_size
= le64toh(READ_NOW(f
->header
->arena_size
));
552 if (UINT64_MAX
- header_size
< arena_size
|| header_size
+ arena_size
> (uint64_t) f
->last_stat
.st_size
)
555 if (le64toh(f
->header
->tail_object_offset
) > header_size
+ arena_size
)
558 if (!VALID64(le64toh(f
->header
->data_hash_table_offset
)) ||
559 !VALID64(le64toh(f
->header
->field_hash_table_offset
)) ||
560 !VALID64(le64toh(f
->header
->tail_object_offset
)) ||
561 !VALID64(le64toh(f
->header
->entry_array_offset
)))
564 if (JOURNAL_HEADER_CONTAINS(f
->header
, tail_entry_offset
) &&
565 le64toh(f
->header
->tail_entry_offset
) != 0 &&
566 !VALID64(le64toh(f
->header
->tail_entry_offset
)))
569 if (journal_file_writable(f
)) {
570 sd_id128_t machine_id
;
574 r
= sd_id128_get_machine(&machine_id
);
576 if (!ERRNO_IS_MACHINE_ID_UNSET(r
)) /* handle graceful if machine ID is not initialized yet */
579 machine_id
= SD_ID128_NULL
;
582 if (!sd_id128_equal(machine_id
, f
->header
->machine_id
))
583 return log_debug_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
584 "Trying to open journal file from different host for writing, refusing.");
586 state
= f
->header
->state
;
588 if (state
== STATE_ARCHIVED
)
589 return -ESHUTDOWN
; /* Already archived */
590 if (state
== STATE_ONLINE
)
591 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
),
592 "Journal file %s is already online. Assuming unclean closing.",
594 if (state
!= STATE_OFFLINE
)
595 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
),
596 "Journal file %s has unknown state %i.",
599 if (f
->header
->field_hash_table_size
== 0 || f
->header
->data_hash_table_size
== 0)
606 int journal_file_fstat(JournalFile
*f
) {
612 if (fstat(f
->fd
, &f
->last_stat
) < 0)
615 f
->last_stat_usec
= now(CLOCK_MONOTONIC
);
617 /* Refuse dealing with files that aren't regular */
618 r
= stat_verify_regular(&f
->last_stat
);
622 /* Refuse appending to files that are already deleted */
623 if (f
->last_stat
.st_nlink
<= 0)
629 static int journal_file_allocate(JournalFile
*f
, uint64_t offset
, uint64_t size
) {
630 uint64_t old_size
, new_size
, old_header_size
, old_arena_size
;
636 /* We assume that this file is not sparse, and we know that for sure, since we always call
637 * posix_fallocate() ourselves */
639 if (size
> PAGE_ALIGN_DOWN(UINT64_MAX
) - offset
)
642 if (mmap_cache_fd_got_sigbus(f
->cache_fd
))
645 old_header_size
= le64toh(READ_NOW(f
->header
->header_size
));
646 old_arena_size
= le64toh(READ_NOW(f
->header
->arena_size
));
647 if (old_arena_size
> PAGE_ALIGN_DOWN(UINT64_MAX
) - old_header_size
)
650 old_size
= old_header_size
+ old_arena_size
;
652 new_size
= MAX(PAGE_ALIGN(offset
+ size
), old_header_size
);
654 if (new_size
<= old_size
) {
656 /* We already pre-allocated enough space, but before
657 * we write to it, let's check with fstat() if the
658 * file got deleted, in order make sure we don't throw
659 * away the data immediately. Don't check fstat() for
660 * all writes though, but only once ever 10s. */
662 if (f
->last_stat_usec
+ LAST_STAT_REFRESH_USEC
> now(CLOCK_MONOTONIC
))
665 return journal_file_fstat(f
);
668 /* Allocate more space. */
670 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
673 /* Refuse to go over 4G in compact mode so offsets can be stored in 32-bit. */
674 if (JOURNAL_HEADER_COMPACT(f
->header
) && new_size
> UINT32_MAX
)
677 if (new_size
> f
->metrics
.min_size
&& f
->metrics
.keep_free
> 0) {
680 if (fstatvfs(f
->fd
, &svfs
) >= 0) {
683 available
= LESS_BY((uint64_t) svfs
.f_bfree
* (uint64_t) svfs
.f_bsize
, f
->metrics
.keep_free
);
685 if (new_size
- old_size
> available
)
690 /* Increase by larger blocks at once */
691 new_size
= DIV_ROUND_UP(new_size
, FILE_SIZE_INCREASE
) * FILE_SIZE_INCREASE
;
692 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
693 new_size
= f
->metrics
.max_size
;
695 /* Note that the glibc fallocate() fallback is very
696 inefficient, hence we try to minimize the allocation area
698 r
= posix_fallocate_loop(f
->fd
, old_size
, new_size
- old_size
);
702 f
->header
->arena_size
= htole64(new_size
- old_header_size
);
704 return journal_file_fstat(f
);
707 static unsigned type_to_context(ObjectType type
) {
708 /* One context for each type, plus one catch-all for the rest */
709 assert_cc(_OBJECT_TYPE_MAX
<= MMAP_CACHE_MAX_CONTEXTS
);
710 assert_cc(CONTEXT_HEADER
< MMAP_CACHE_MAX_CONTEXTS
);
711 return type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
? type
: 0;
714 static int journal_file_move_to(
727 /* This function may clear, overwrite, or alter previously cached entries. After this function has
728 * been called, all objects except for one obtained by this function are invalidated and must be
729 * re-read before use. */
734 if (size
> UINT64_MAX
- offset
)
737 /* Avoid SIGBUS on invalid accesses */
738 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
) {
739 /* Hmm, out of range? Let's refresh the fstat() data
740 * first, before we trust that check. */
742 r
= journal_file_fstat(f
);
746 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
)
747 return -EADDRNOTAVAIL
;
750 return mmap_cache_fd_get(f
->cache_fd
, type_to_context(type
), keep_always
, offset
, size
, &f
->last_stat
, ret
);
753 static uint64_t minimum_header_size(JournalFile
*f
, Object
*o
) {
755 static const uint64_t table
[] = {
756 [OBJECT_DATA
] = sizeof(DataObject
),
757 [OBJECT_FIELD
] = sizeof(FieldObject
),
758 [OBJECT_ENTRY
] = sizeof(EntryObject
),
759 [OBJECT_DATA_HASH_TABLE
] = sizeof(HashTableObject
),
760 [OBJECT_FIELD_HASH_TABLE
] = sizeof(HashTableObject
),
761 [OBJECT_ENTRY_ARRAY
] = sizeof(EntryArrayObject
),
762 [OBJECT_TAG
] = sizeof(TagObject
),
768 if (o
->object
.type
== OBJECT_DATA
)
769 return journal_file_data_payload_offset(f
);
771 if (o
->object
.type
>= ELEMENTSOF(table
) || table
[o
->object
.type
] <= 0)
772 return sizeof(ObjectHeader
);
774 return table
[o
->object
.type
];
777 static int check_object_header(JournalFile
*f
, Object
*o
, ObjectType type
, uint64_t offset
) {
783 s
= le64toh(READ_NOW(o
->object
.size
));
785 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
786 "Attempt to move to uninitialized object: %" PRIu64
,
789 if (s
< sizeof(ObjectHeader
))
790 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
791 "Attempt to move to overly short object with size %"PRIu64
": %" PRIu64
,
794 if (o
->object
.type
<= OBJECT_UNUSED
|| o
->object
.type
>= _OBJECT_TYPE_MAX
)
795 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
796 "Attempt to move to object with invalid type (%u): %" PRIu64
,
797 o
->object
.type
, offset
);
799 if (type
> OBJECT_UNUSED
&& o
->object
.type
!= type
)
800 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
801 "Found %s object while expecting %s object: %" PRIu64
,
802 journal_object_type_to_string(o
->object
.type
),
803 journal_object_type_to_string(type
),
806 if (s
< minimum_header_size(f
, o
))
807 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
808 "Size of %s object (%"PRIu64
") is smaller than the minimum object size (%"PRIu64
"): %" PRIu64
,
809 journal_object_type_to_string(o
->object
.type
),
811 minimum_header_size(f
, o
),
817 /* Lightweight object checks. We want this to be fast, so that we won't
818 * slowdown every journal_file_move_to_object() call too much. */
819 static int check_object(JournalFile
*f
, Object
*o
, uint64_t offset
) {
823 switch (o
->object
.type
) {
826 if ((le64toh(o
->data
.entry_offset
) == 0) ^ (le64toh(o
->data
.n_entries
) == 0))
827 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
828 "Bad data n_entries: %" PRIu64
": %" PRIu64
,
829 le64toh(o
->data
.n_entries
),
832 if (le64toh(o
->object
.size
) <= journal_file_data_payload_offset(f
))
833 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
834 "Bad data size (<= %zu): %" PRIu64
": %" PRIu64
,
835 journal_file_data_payload_offset(f
),
836 le64toh(o
->object
.size
),
839 if (!VALID64(le64toh(o
->data
.next_hash_offset
)) ||
840 !VALID64(le64toh(o
->data
.next_field_offset
)) ||
841 !VALID64(le64toh(o
->data
.entry_offset
)) ||
842 !VALID64(le64toh(o
->data
.entry_array_offset
)))
843 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
844 "Invalid offset, next_hash_offset=" OFSfmt
", next_field_offset=" OFSfmt
", entry_offset=" OFSfmt
", entry_array_offset=" OFSfmt
": %" PRIu64
,
845 le64toh(o
->data
.next_hash_offset
),
846 le64toh(o
->data
.next_field_offset
),
847 le64toh(o
->data
.entry_offset
),
848 le64toh(o
->data
.entry_array_offset
),
854 if (le64toh(o
->object
.size
) <= offsetof(Object
, field
.payload
))
855 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
856 "Bad field size (<= %zu): %" PRIu64
": %" PRIu64
,
857 offsetof(Object
, field
.payload
),
858 le64toh(o
->object
.size
),
861 if (!VALID64(le64toh(o
->field
.next_hash_offset
)) ||
862 !VALID64(le64toh(o
->field
.head_data_offset
)))
863 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
864 "Invalid offset, next_hash_offset=" OFSfmt
", head_data_offset=" OFSfmt
": %" PRIu64
,
865 le64toh(o
->field
.next_hash_offset
),
866 le64toh(o
->field
.head_data_offset
),
873 sz
= le64toh(READ_NOW(o
->object
.size
));
874 if (sz
< offsetof(Object
, entry
.items
) ||
875 (sz
- offsetof(Object
, entry
.items
)) % journal_file_entry_item_size(f
) != 0)
876 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
877 "Bad entry size (<= %zu): %" PRIu64
": %" PRIu64
,
878 offsetof(Object
, entry
.items
),
882 if ((sz
- offsetof(Object
, entry
.items
)) / journal_file_entry_item_size(f
) <= 0)
883 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
884 "Invalid number items in entry: %" PRIu64
": %" PRIu64
,
885 (sz
- offsetof(Object
, entry
.items
)) / journal_file_entry_item_size(f
),
888 if (le64toh(o
->entry
.seqnum
) <= 0)
889 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
890 "Invalid entry seqnum: %" PRIx64
": %" PRIu64
,
891 le64toh(o
->entry
.seqnum
),
894 if (!VALID_REALTIME(le64toh(o
->entry
.realtime
)))
895 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
896 "Invalid entry realtime timestamp: %" PRIu64
": %" PRIu64
,
897 le64toh(o
->entry
.realtime
),
900 if (!VALID_MONOTONIC(le64toh(o
->entry
.monotonic
)))
901 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
902 "Invalid entry monotonic timestamp: %" PRIu64
": %" PRIu64
,
903 le64toh(o
->entry
.monotonic
),
909 case OBJECT_DATA_HASH_TABLE
:
910 case OBJECT_FIELD_HASH_TABLE
: {
913 sz
= le64toh(READ_NOW(o
->object
.size
));
914 if (sz
< offsetof(Object
, hash_table
.items
) ||
915 (sz
- offsetof(Object
, hash_table
.items
)) % sizeof(HashItem
) != 0 ||
916 (sz
- offsetof(Object
, hash_table
.items
)) / sizeof(HashItem
) <= 0)
917 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
918 "Invalid %s hash table size: %" PRIu64
": %" PRIu64
,
919 journal_object_type_to_string(o
->object
.type
),
926 case OBJECT_ENTRY_ARRAY
: {
929 sz
= le64toh(READ_NOW(o
->object
.size
));
930 if (sz
< offsetof(Object
, entry_array
.items
) ||
931 (sz
- offsetof(Object
, entry_array
.items
)) % journal_file_entry_array_item_size(f
) != 0 ||
932 (sz
- offsetof(Object
, entry_array
.items
)) / journal_file_entry_array_item_size(f
) <= 0)
933 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
934 "Invalid object entry array size: %" PRIu64
": %" PRIu64
,
937 /* Here, we request that the offset of each entry array object is in strictly increasing order. */
938 next
= le64toh(o
->entry_array
.next_entry_array_offset
);
939 if (!VALID64(next
) || (next
> 0 && next
<= offset
))
940 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
941 "Invalid object entry array next_entry_array_offset: %" PRIu64
": %" PRIu64
,
949 if (le64toh(o
->object
.size
) != sizeof(TagObject
))
950 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
951 "Invalid object tag size: %" PRIu64
": %" PRIu64
,
952 le64toh(o
->object
.size
),
955 if (!VALID_EPOCH(le64toh(o
->tag
.epoch
)))
956 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
957 "Invalid object tag epoch: %" PRIu64
": %" PRIu64
,
958 le64toh(o
->tag
.epoch
), offset
);
966 int journal_file_move_to_object(JournalFile
*f
, ObjectType type
, uint64_t offset
, Object
**ret
) {
972 /* Even if this function fails, it may clear, overwrite, or alter previously cached entries. After
973 * this function has been called, all objects except for one obtained by this function are
974 * invalidated and must be re-read before use.. */
976 /* Objects may only be located at multiple of 64 bit */
977 if (!VALID64(offset
))
978 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
979 "Attempt to move to %s object at non-64bit boundary: %" PRIu64
,
980 journal_object_type_to_string(type
),
983 /* Object may not be located in the file header */
984 if (offset
< le64toh(f
->header
->header_size
))
985 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
986 "Attempt to move to %s object located in file header: %" PRIu64
,
987 journal_object_type_to_string(type
),
990 r
= journal_file_move_to(f
, type
, false, offset
, sizeof(ObjectHeader
), (void**) &o
);
994 r
= check_object_header(f
, o
, type
, offset
);
998 r
= journal_file_move_to(f
, type
, false, offset
, le64toh(READ_NOW(o
->object
.size
)), (void**) &o
);
1002 r
= check_object_header(f
, o
, type
, offset
);
1006 r
= check_object(f
, o
, offset
);
1016 int journal_file_read_object_header(JournalFile
*f
, ObjectType type
, uint64_t offset
, Object
*ret
) {
1023 /* Objects may only be located at multiple of 64 bit */
1024 if (!VALID64(offset
))
1025 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
1026 "Attempt to read %s object at non-64bit boundary: %" PRIu64
,
1027 journal_object_type_to_string(type
), offset
);
1029 /* Object may not be located in the file header */
1030 if (offset
< le64toh(f
->header
->header_size
))
1031 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
1032 "Attempt to read %s object located in file header: %" PRIu64
,
1033 journal_object_type_to_string(type
), offset
);
1035 /* This will likely read too much data but it avoids having to call pread() twice. */
1036 n
= pread(f
->fd
, &o
, sizeof(o
), offset
);
1038 return log_debug_errno(errno
, "Failed to read journal %s object at offset: %" PRIu64
,
1039 journal_object_type_to_string(type
), offset
);
1041 if ((size_t) n
< sizeof(o
.object
))
1042 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
1043 "Failed to read short %s object at offset: %" PRIu64
,
1044 journal_object_type_to_string(type
), offset
);
1046 r
= check_object_header(f
, &o
, type
, offset
);
1050 if ((size_t) n
< minimum_header_size(f
, &o
))
1051 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
1052 "Short read while reading %s object: %" PRIu64
,
1053 journal_object_type_to_string(type
), offset
);
1055 r
= check_object(f
, &o
, offset
);
1065 static uint64_t inc_seqnum(uint64_t seqnum
) {
1066 if (seqnum
< UINT64_MAX
-1)
1069 return 1; /* skip over UINT64_MAX and 0 when we run out of seqnums and start again */
1072 static uint64_t journal_file_entry_seqnum(
1076 uint64_t next_seqnum
;
1081 /* Picks a new sequence number for the entry we are about to add and returns it. */
1083 next_seqnum
= inc_seqnum(le64toh(f
->header
->tail_entry_seqnum
));
1085 /* If an external seqnum counter was passed, we update both the local and the external one, and set
1086 * it to the maximum of both */
1088 *seqnum
= next_seqnum
= MAX(inc_seqnum(*seqnum
), next_seqnum
);
1090 f
->header
->tail_entry_seqnum
= htole64(next_seqnum
);
1092 if (f
->header
->head_entry_seqnum
== 0)
1093 f
->header
->head_entry_seqnum
= htole64(next_seqnum
);
1098 int journal_file_append_object(
1102 Object
**ret_object
,
1103 uint64_t *ret_offset
) {
1111 assert(type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
);
1112 assert(size
>= sizeof(ObjectHeader
));
1114 r
= journal_file_set_online(f
);
1118 r
= journal_file_tail_end_by_mmap(f
, &p
);
1122 r
= journal_file_allocate(f
, p
, size
);
1126 r
= journal_file_move_to(f
, type
, false, p
, size
, (void**) &o
);
1130 o
->object
= (ObjectHeader
) {
1132 .size
= htole64(size
),
1135 f
->header
->tail_object_offset
= htole64(p
);
1136 f
->header
->n_objects
= htole64(le64toh(f
->header
->n_objects
) + 1);
1147 static int journal_file_setup_data_hash_table(JournalFile
*f
) {
1155 /* We estimate that we need 1 hash table entry per 768 bytes
1156 of journal file and we want to make sure we never get
1157 beyond 75% fill level. Calculate the hash table size for
1158 the maximum file size based on these metrics. */
1160 s
= (f
->metrics
.max_size
* 4 / 768 / 3) * sizeof(HashItem
);
1161 if (s
< DEFAULT_DATA_HASH_TABLE_SIZE
)
1162 s
= DEFAULT_DATA_HASH_TABLE_SIZE
;
1164 log_debug("Reserving %"PRIu64
" entries in data hash table.", s
/ sizeof(HashItem
));
1166 r
= journal_file_append_object(f
,
1167 OBJECT_DATA_HASH_TABLE
,
1168 offsetof(Object
, hash_table
.items
) + s
,
1173 memzero(o
->hash_table
.items
, s
);
1175 f
->header
->data_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
1176 f
->header
->data_hash_table_size
= htole64(s
);
1181 static int journal_file_setup_field_hash_table(JournalFile
*f
) {
1189 /* We use a fixed size hash table for the fields as this
1190 * number should grow very slowly only */
1192 s
= DEFAULT_FIELD_HASH_TABLE_SIZE
;
1193 log_debug("Reserving %"PRIu64
" entries in field hash table.", s
/ sizeof(HashItem
));
1195 r
= journal_file_append_object(f
,
1196 OBJECT_FIELD_HASH_TABLE
,
1197 offsetof(Object
, hash_table
.items
) + s
,
1202 memzero(o
->hash_table
.items
, s
);
1204 f
->header
->field_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
1205 f
->header
->field_hash_table_size
= htole64(s
);
1210 int journal_file_map_data_hash_table(JournalFile
*f
) {
1218 if (f
->data_hash_table
)
1221 p
= le64toh(f
->header
->data_hash_table_offset
);
1222 s
= le64toh(f
->header
->data_hash_table_size
);
1224 r
= journal_file_move_to(f
,
1225 OBJECT_DATA_HASH_TABLE
,
1232 f
->data_hash_table
= t
;
1236 int journal_file_map_field_hash_table(JournalFile
*f
) {
1244 if (f
->field_hash_table
)
1247 p
= le64toh(f
->header
->field_hash_table_offset
);
1248 s
= le64toh(f
->header
->field_hash_table_size
);
1250 r
= journal_file_move_to(f
,
1251 OBJECT_FIELD_HASH_TABLE
,
1258 f
->field_hash_table
= t
;
1262 static int journal_file_link_field(
1273 assert(f
->field_hash_table
);
1277 if (o
->object
.type
!= OBJECT_FIELD
)
1280 m
= le64toh(READ_NOW(f
->header
->field_hash_table_size
)) / sizeof(HashItem
);
1284 /* This might alter the window we are looking at */
1285 o
->field
.next_hash_offset
= o
->field
.head_data_offset
= 0;
1288 p
= le64toh(f
->field_hash_table
[h
].tail_hash_offset
);
1290 f
->field_hash_table
[h
].head_hash_offset
= htole64(offset
);
1292 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1296 o
->field
.next_hash_offset
= htole64(offset
);
1299 f
->field_hash_table
[h
].tail_hash_offset
= htole64(offset
);
1301 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
1302 f
->header
->n_fields
= htole64(le64toh(f
->header
->n_fields
) + 1);
1307 static int journal_file_link_data(
1318 assert(f
->data_hash_table
);
1322 if (o
->object
.type
!= OBJECT_DATA
)
1325 m
= le64toh(READ_NOW(f
->header
->data_hash_table_size
)) / sizeof(HashItem
);
1329 /* This might alter the window we are looking at */
1330 o
->data
.next_hash_offset
= o
->data
.next_field_offset
= 0;
1331 o
->data
.entry_offset
= o
->data
.entry_array_offset
= 0;
1332 o
->data
.n_entries
= 0;
1335 p
= le64toh(f
->data_hash_table
[h
].tail_hash_offset
);
1337 /* Only entry in the hash table is easy */
1338 f
->data_hash_table
[h
].head_hash_offset
= htole64(offset
);
1340 /* Move back to the previous data object, to patch in
1343 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1347 o
->data
.next_hash_offset
= htole64(offset
);
1350 f
->data_hash_table
[h
].tail_hash_offset
= htole64(offset
);
1352 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
1353 f
->header
->n_data
= htole64(le64toh(f
->header
->n_data
) + 1);
1358 static int get_next_hash_offset(
1361 le64_t
*next_hash_offset
,
1363 le64_t
*header_max_depth
) {
1369 assert(next_hash_offset
);
1372 nextp
= le64toh(READ_NOW(*next_hash_offset
));
1374 if (nextp
<= *p
) /* Refuse going in loops */
1375 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
1376 "Detected hash item loop in %s, refusing.", f
->path
);
1380 /* If the depth of this hash chain is larger than all others we have seen so far, record it */
1381 if (header_max_depth
&& journal_file_writable(f
))
1382 *header_max_depth
= htole64(MAX(*depth
, le64toh(*header_max_depth
)));
1389 int journal_file_find_field_object_with_hash(
1394 Object
**ret_object
,
1395 uint64_t *ret_offset
) {
1397 uint64_t p
, osize
, h
, m
, depth
= 0;
1405 /* If the field hash table is empty, we can't find anything */
1406 if (le64toh(f
->header
->field_hash_table_size
) <= 0)
1409 /* Map the field hash table, if it isn't mapped yet. */
1410 r
= journal_file_map_field_hash_table(f
);
1414 osize
= offsetof(Object
, field
.payload
) + size
;
1416 m
= le64toh(READ_NOW(f
->header
->field_hash_table_size
)) / sizeof(HashItem
);
1421 p
= le64toh(f
->field_hash_table
[h
].head_hash_offset
);
1425 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1429 if (le64toh(o
->field
.hash
) == hash
&&
1430 le64toh(o
->object
.size
) == osize
&&
1431 memcmp(o
->field
.payload
, field
, size
) == 0) {
1441 r
= get_next_hash_offset(
1444 &o
->field
.next_hash_offset
,
1446 JOURNAL_HEADER_CONTAINS(f
->header
, field_hash_chain_depth
) ? &f
->header
->field_hash_chain_depth
: NULL
);
1454 uint64_t journal_file_hash_data(
1461 assert(data
|| sz
== 0);
1463 /* We try to unify our codebase on siphash, hence new-styled journal files utilizing the keyed hash
1464 * function use siphash. Old journal files use the Jenkins hash. */
1466 if (JOURNAL_HEADER_KEYED_HASH(f
->header
))
1467 return siphash24(data
, sz
, f
->header
->file_id
.bytes
);
1469 return jenkins_hash64(data
, sz
);
1472 int journal_file_find_field_object(
1476 Object
**ret_object
,
1477 uint64_t *ret_offset
) {
1483 return journal_file_find_field_object_with_hash(
1486 journal_file_hash_data(f
, field
, size
),
1487 ret_object
, ret_offset
);
1490 int journal_file_find_data_object_with_hash(
1495 Object
**ret_object
,
1496 uint64_t *ret_offset
) {
1498 uint64_t p
, h
, m
, depth
= 0;
1503 assert(data
|| size
== 0);
1505 /* If there's no data hash table, then there's no entry. */
1506 if (le64toh(f
->header
->data_hash_table_size
) <= 0)
1509 /* Map the data hash table, if it isn't mapped yet. */
1510 r
= journal_file_map_data_hash_table(f
);
1514 m
= le64toh(READ_NOW(f
->header
->data_hash_table_size
)) / sizeof(HashItem
);
1519 p
= le64toh(f
->data_hash_table
[h
].head_hash_offset
);
1526 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1530 if (le64toh(o
->data
.hash
) != hash
)
1533 r
= journal_file_data_payload(f
, o
, p
, NULL
, 0, 0, &d
, &rsize
);
1536 assert(r
> 0); /* journal_file_data_payload() always returns > 0 if no field is provided. */
1538 if (memcmp_nn(data
, size
, d
, rsize
) == 0) {
1549 r
= get_next_hash_offset(
1552 &o
->data
.next_hash_offset
,
1554 JOURNAL_HEADER_CONTAINS(f
->header
, data_hash_chain_depth
) ? &f
->header
->data_hash_chain_depth
: NULL
);
1562 int journal_file_find_data_object(
1566 Object
**ret_object
,
1567 uint64_t *ret_offset
) {
1570 assert(data
|| size
== 0);
1572 return journal_file_find_data_object_with_hash(
1575 journal_file_hash_data(f
, data
, size
),
1576 ret_object
, ret_offset
);
1579 bool journal_field_valid(const char *p
, size_t l
, bool allow_protected
) {
1580 /* We kinda enforce POSIX syntax recommendations for
1581 environment variables here, but make a couple of additional
1584 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1591 /* No empty field names */
1595 /* Don't allow names longer than 64 chars */
1599 /* Variables starting with an underscore are protected */
1600 if (!allow_protected
&& p
[0] == '_')
1603 /* Don't allow digits as first character */
1604 if (ascii_isdigit(p
[0]))
1607 /* Only allow A-Z0-9 and '_' */
1608 for (const char *a
= p
; a
< p
+ l
; a
++)
1609 if ((*a
< 'A' || *a
> 'Z') &&
1610 !ascii_isdigit(*a
) &&
1617 static int journal_file_append_field(
1621 Object
**ret_object
,
1622 uint64_t *ret_offset
) {
1633 if (!journal_field_valid(field
, size
, true))
1636 hash
= journal_file_hash_data(f
, field
, size
);
1638 r
= journal_file_find_field_object_with_hash(f
, field
, size
, hash
, ret_object
, ret_offset
);
1644 osize
= offsetof(Object
, field
.payload
) + size
;
1645 r
= journal_file_append_object(f
, OBJECT_FIELD
, osize
, &o
, &p
);
1649 o
->field
.hash
= htole64(hash
);
1650 memcpy(o
->field
.payload
, field
, size
);
1652 r
= journal_file_link_field(f
, o
, p
, hash
);
1656 /* The linking might have altered the window, so let's only pass the offset to hmac which will
1657 * move to the object again if needed. */
1660 r
= journal_file_hmac_put_object(f
, OBJECT_FIELD
, NULL
, p
);
1666 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, ret_object
);
1677 static int maybe_compress_payload(JournalFile
*f
, uint8_t *dst
, const uint8_t *src
, uint64_t size
, size_t *rsize
) {
1681 #if HAVE_COMPRESSION
1685 c
= JOURNAL_FILE_COMPRESSION(f
);
1686 if (c
== COMPRESSION_NONE
|| size
< f
->compress_threshold_bytes
)
1689 r
= compress_blob(c
, src
, size
, dst
, size
- 1, rsize
);
1691 return log_debug_errno(r
, "Failed to compress data object using %s, ignoring: %m", compression_to_string(c
));
1693 log_debug("Compressed data object %"PRIu64
" -> %zu using %s", size
, *rsize
, compression_to_string(c
));
1695 return 1; /* compressed */
1701 static int journal_file_append_data(
1705 Object
**ret_object
,
1706 uint64_t *ret_offset
) {
1708 uint64_t hash
, p
, osize
;
1716 if (!data
|| size
== 0)
1719 hash
= journal_file_hash_data(f
, data
, size
);
1721 r
= journal_file_find_data_object_with_hash(f
, data
, size
, hash
, ret_object
, ret_offset
);
1727 eq
= memchr(data
, '=', size
);
1731 osize
= journal_file_data_payload_offset(f
) + size
;
1732 r
= journal_file_append_object(f
, OBJECT_DATA
, osize
, &o
, &p
);
1736 o
->data
.hash
= htole64(hash
);
1738 r
= maybe_compress_payload(f
, journal_file_data_payload_field(f
, o
), data
, size
, &rsize
);
1740 /* We don't really care failures, let's continue without compression */
1741 memcpy_safe(journal_file_data_payload_field(f
, o
), data
, size
);
1743 Compression c
= JOURNAL_FILE_COMPRESSION(f
);
1745 assert(c
>= 0 && c
< _COMPRESSION_MAX
&& c
!= COMPRESSION_NONE
);
1747 o
->object
.size
= htole64(journal_file_data_payload_offset(f
) + rsize
);
1748 o
->object
.flags
|= COMPRESSION_TO_OBJECT_FLAG(c
);
1751 r
= journal_file_link_data(f
, o
, p
, hash
);
1755 /* The linking might have altered the window, so let's refresh our pointer. */
1756 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1761 r
= journal_file_hmac_put_object(f
, OBJECT_DATA
, o
, p
);
1766 /* Create field object ... */
1767 r
= journal_file_append_field(f
, data
, (uint8_t*) eq
- (uint8_t*) data
, &fo
, NULL
);
1771 /* ... and link it in. */
1772 o
->data
.next_field_offset
= fo
->field
.head_data_offset
;
1773 fo
->field
.head_data_offset
= le64toh(p
);
1784 static int maybe_decompress_payload(
1788 Compression compression
,
1790 size_t field_length
,
1791 size_t data_threshold
,
1797 /* We can't read objects larger than 4G on a 32bit machine */
1798 if ((uint64_t) (size_t) size
!= size
)
1801 if (compression
!= COMPRESSION_NONE
) {
1802 #if HAVE_COMPRESSION
1807 r
= decompress_startswith(compression
, payload
, size
, &f
->compress_buffer
, field
,
1810 return log_debug_errno(r
,
1811 "Cannot decompress %s object of length %" PRIu64
": %m",
1812 compression_to_string(compression
),
1823 r
= decompress_blob(compression
, payload
, size
, &f
->compress_buffer
, &rsize
, 0);
1828 *ret_data
= f
->compress_buffer
;
1832 return -EPROTONOSUPPORT
;
1835 if (field
&& (size
< field_length
+ 1 || memcmp(payload
, field
, field_length
) != 0 || payload
[field_length
] != '=')) {
1844 *ret_data
= payload
;
1846 *ret_size
= (size_t) size
;
1852 int journal_file_data_payload(
1857 size_t field_length
,
1858 size_t data_threshold
,
1867 assert(!field
== (field_length
== 0)); /* These must be specified together. */
1870 r
= journal_file_move_to_object(f
, OBJECT_DATA
, offset
, &o
);
1875 size
= le64toh(READ_NOW(o
->object
.size
));
1876 if (size
< journal_file_data_payload_offset(f
))
1879 size
-= journal_file_data_payload_offset(f
);
1881 c
= COMPRESSION_FROM_OBJECT(o
);
1883 return -EPROTONOSUPPORT
;
1885 return maybe_decompress_payload(f
, journal_file_data_payload_field(f
, o
), size
, c
, field
,
1886 field_length
, data_threshold
, ret_data
, ret_size
);
1889 uint64_t journal_file_entry_n_items(JournalFile
*f
, Object
*o
) {
1895 if (o
->object
.type
!= OBJECT_ENTRY
)
1898 sz
= le64toh(READ_NOW(o
->object
.size
));
1899 if (sz
< offsetof(Object
, entry
.items
))
1902 return (sz
- offsetof(Object
, entry
.items
)) / journal_file_entry_item_size(f
);
1905 uint64_t journal_file_entry_array_n_items(JournalFile
*f
, Object
*o
) {
1911 if (o
->object
.type
!= OBJECT_ENTRY_ARRAY
)
1914 sz
= le64toh(READ_NOW(o
->object
.size
));
1915 if (sz
< offsetof(Object
, entry_array
.items
))
1918 return (sz
- offsetof(Object
, entry_array
.items
)) / journal_file_entry_array_item_size(f
);
1921 uint64_t journal_file_hash_table_n_items(Object
*o
) {
1926 if (!IN_SET(o
->object
.type
, OBJECT_DATA_HASH_TABLE
, OBJECT_FIELD_HASH_TABLE
))
1929 sz
= le64toh(READ_NOW(o
->object
.size
));
1930 if (sz
< offsetof(Object
, hash_table
.items
))
1933 return (sz
- offsetof(Object
, hash_table
.items
)) / sizeof(HashItem
);
1936 static void write_entry_array_item(JournalFile
*f
, Object
*o
, uint64_t i
, uint64_t p
) {
1940 if (JOURNAL_HEADER_COMPACT(f
->header
)) {
1941 assert(p
<= UINT32_MAX
);
1942 o
->entry_array
.items
.compact
[i
] = htole32(p
);
1944 o
->entry_array
.items
.regular
[i
] = htole64(p
);
1947 static int link_entry_into_array(
1955 uint64_t n
= 0, ap
= 0, q
, i
, a
, hidx
;
1965 a
= tail
? le32toh(*tail
) : le64toh(*first
);
1966 hidx
= le64toh(READ_NOW(*idx
));
1967 i
= tidx
? le32toh(READ_NOW(*tidx
)) : hidx
;
1970 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
1974 n
= journal_file_entry_array_n_items(f
, o
);
1976 write_entry_array_item(f
, o
, i
, p
);
1977 *idx
= htole64(hidx
+ 1);
1979 *tidx
= htole32(le32toh(*tidx
) + 1);
1985 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
1996 r
= journal_file_append_object(f
, OBJECT_ENTRY_ARRAY
,
1997 offsetof(Object
, entry_array
.items
) + n
* journal_file_entry_array_item_size(f
),
2003 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY_ARRAY
, o
, q
);
2008 write_entry_array_item(f
, o
, i
, p
);
2011 *first
= htole64(q
);
2013 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, ap
, &o
);
2017 o
->entry_array
.next_entry_array_offset
= htole64(q
);
2023 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
2024 f
->header
->n_entry_arrays
= htole64(le64toh(f
->header
->n_entry_arrays
) + 1);
2026 *idx
= htole64(hidx
+ 1);
2033 static int link_entry_into_array_plus_one(
2051 hidx
= le64toh(READ_NOW(*idx
));
2052 if (hidx
== UINT64_MAX
)
2055 *extra
= htole64(p
);
2059 i
= htole64(hidx
- 1);
2060 r
= link_entry_into_array(f
, first
, &i
, tail
, tidx
, p
);
2065 *idx
= htole64(hidx
+ 1);
2069 static int journal_file_link_entry_item(JournalFile
*f
, uint64_t offset
, uint64_t p
) {
2076 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
2080 return link_entry_into_array_plus_one(f
,
2081 &o
->data
.entry_offset
,
2082 &o
->data
.entry_array_offset
,
2084 JOURNAL_HEADER_COMPACT(f
->header
) ? &o
->data
.compact
.tail_entry_array_offset
: NULL
,
2085 JOURNAL_HEADER_COMPACT(f
->header
) ? &o
->data
.compact
.tail_entry_array_n_entries
: NULL
,
2089 static int journal_file_link_entry(
2093 const EntryItem items
[],
2103 if (o
->object
.type
!= OBJECT_ENTRY
)
2106 __atomic_thread_fence(__ATOMIC_SEQ_CST
);
2108 /* Link up the entry itself */
2109 r
= link_entry_into_array(f
,
2110 &f
->header
->entry_array_offset
,
2111 &f
->header
->n_entries
,
2112 JOURNAL_HEADER_CONTAINS(f
->header
, tail_entry_array_offset
) ? &f
->header
->tail_entry_array_offset
: NULL
,
2113 JOURNAL_HEADER_CONTAINS(f
->header
, tail_entry_array_n_entries
) ? &f
->header
->tail_entry_array_n_entries
: NULL
,
2118 /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
2120 if (f
->header
->head_entry_realtime
== 0)
2121 f
->header
->head_entry_realtime
= o
->entry
.realtime
;
2123 f
->header
->tail_entry_realtime
= o
->entry
.realtime
;
2124 f
->header
->tail_entry_monotonic
= o
->entry
.monotonic
;
2125 f
->header
->tail_entry_offset
= offset
;
2126 f
->newest_mtime
= 0; /* we have a new tail entry now, explicitly invalidate newest boot id/timestamp info */
2128 /* Link up the items */
2129 for (uint64_t i
= 0; i
< n_items
; i
++) {
2132 /* If we fail to link an entry item because we can't allocate a new entry array, don't fail
2133 * immediately but try to link the other entry items since it might still be possible to link
2134 * those if they don't require a new entry array to be allocated. */
2136 k
= journal_file_link_entry_item(f
, offset
, items
[i
].object_offset
);
2146 static void write_entry_item(JournalFile
*f
, Object
*o
, uint64_t i
, const EntryItem
*item
) {
2151 if (JOURNAL_HEADER_COMPACT(f
->header
)) {
2152 assert(item
->object_offset
<= UINT32_MAX
);
2153 o
->entry
.items
.compact
[i
].object_offset
= htole32(item
->object_offset
);
2155 o
->entry
.items
.regular
[i
].object_offset
= htole64(item
->object_offset
);
2156 o
->entry
.items
.regular
[i
].hash
= htole64(item
->hash
);
2160 static int journal_file_append_entry_internal(
2162 const dual_timestamp
*ts
,
2163 const sd_id128_t
*boot_id
,
2164 const sd_id128_t
*machine_id
,
2166 const EntryItem items
[],
2169 sd_id128_t
*seqnum_id
,
2170 Object
**ret_object
,
2171 uint64_t *ret_offset
) {
2181 assert(items
|| n_items
== 0);
2183 if (f
->strict_order
) {
2184 /* If requested be stricter with ordering in this journal file, to make searching via
2185 * bisection fully deterministic. This is an optional feature, so that if desired journal
2186 * files can be written where the ordering is not strictly enforced (in which case bisection
2187 * will yield *a* result, but not the *only* result, when searching for points in
2188 * time). Strict ordering mode is enabled when journald originally writes the files, but
2189 * might not necessarily be if other tools (the remoting tools for example) write journal
2190 * files from combined sources.
2192 * Typically, if any of the errors generated here are seen journald will just rotate the
2193 * journal files and start anew. */
2195 if (ts
->realtime
< le64toh(f
->header
->tail_entry_realtime
))
2196 return log_debug_errno(SYNTHETIC_ERRNO(EREMCHG
),
2197 "Realtime timestamp %" PRIu64
" smaller than previous realtime "
2198 "timestamp %" PRIu64
", refusing entry.",
2199 ts
->realtime
, le64toh(f
->header
->tail_entry_realtime
));
2201 if (!sd_id128_is_null(f
->header
->tail_entry_boot_id
) && boot_id
) {
2203 if (!sd_id128_equal(f
->header
->tail_entry_boot_id
, *boot_id
))
2204 return log_debug_errno(SYNTHETIC_ERRNO(EREMOTE
),
2205 "Boot ID to write is different from previous boot id, refusing entry.");
2207 if (ts
->monotonic
< le64toh(f
->header
->tail_entry_monotonic
))
2208 return log_debug_errno(SYNTHETIC_ERRNO(ENOTNAM
),
2209 "Monotonic timestamp %" PRIu64
" smaller than previous monotonic "
2210 "timestamp %" PRIu64
", refusing entry.",
2211 ts
->monotonic
, le64toh(f
->header
->tail_entry_monotonic
));
2216 /* Settle the passed in sequence number ID */
2218 if (sd_id128_is_null(*seqnum_id
))
2219 *seqnum_id
= f
->header
->seqnum_id
; /* Caller has none assigned, then copy the one from the file */
2220 else if (!sd_id128_equal(*seqnum_id
, f
->header
->seqnum_id
)) {
2221 /* Different seqnum IDs? We can't allow entries from multiple IDs end up in the same journal.*/
2222 if (le64toh(f
->header
->n_entries
) == 0)
2223 f
->header
->seqnum_id
= *seqnum_id
; /* Caller has one, and file so far has no entries, then copy the one from the caller */
2225 return log_debug_errno(SYNTHETIC_ERRNO(EILSEQ
),
2226 "Sequence number IDs don't match, refusing entry.");
2230 if (machine_id
&& sd_id128_is_null(f
->header
->machine_id
))
2231 /* Initialize machine ID when not set yet */
2232 f
->header
->machine_id
= *machine_id
;
2234 osize
= offsetof(Object
, entry
.items
) + (n_items
* journal_file_entry_item_size(f
));
2236 r
= journal_file_append_object(f
, OBJECT_ENTRY
, osize
, &o
, &np
);
2240 o
->entry
.seqnum
= htole64(journal_file_entry_seqnum(f
, seqnum
));
2241 o
->entry
.realtime
= htole64(ts
->realtime
);
2242 o
->entry
.monotonic
= htole64(ts
->monotonic
);
2243 o
->entry
.xor_hash
= htole64(xor_hash
);
2245 f
->header
->tail_entry_boot_id
= *boot_id
;
2246 o
->entry
.boot_id
= f
->header
->tail_entry_boot_id
;
2248 for (size_t i
= 0; i
< n_items
; i
++)
2249 write_entry_item(f
, o
, i
, &items
[i
]);
2252 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY
, o
, np
);
2257 r
= journal_file_link_entry(f
, o
, np
, items
, n_items
);
2270 void journal_file_post_change(JournalFile
*f
) {
2276 /* inotify() does not receive IN_MODIFY events from file
2277 * accesses done via mmap(). After each access we hence
2278 * trigger IN_MODIFY by truncating the journal file to its
2279 * current size which triggers IN_MODIFY. */
2281 __atomic_thread_fence(__ATOMIC_SEQ_CST
);
2283 if (ftruncate(f
->fd
, f
->last_stat
.st_size
) < 0)
2284 log_debug_errno(errno
, "Failed to truncate file to its own size: %m");
2287 static int post_change_thunk(sd_event_source
*timer
, uint64_t usec
, void *userdata
) {
2290 journal_file_post_change(userdata
);
2295 static void schedule_post_change(JournalFile
*f
) {
2300 assert(f
->post_change_timer
);
2302 assert_se(e
= sd_event_source_get_event(f
->post_change_timer
));
2304 /* If we are already going down, post the change immediately. */
2305 if (IN_SET(sd_event_get_state(e
), SD_EVENT_EXITING
, SD_EVENT_FINISHED
))
2308 r
= sd_event_source_get_enabled(f
->post_change_timer
, NULL
);
2310 log_debug_errno(r
, "Failed to get ftruncate timer state: %m");
2316 r
= sd_event_source_set_time_relative(f
->post_change_timer
, f
->post_change_timer_period
);
2318 log_debug_errno(r
, "Failed to set time for scheduling ftruncate: %m");
2322 r
= sd_event_source_set_enabled(f
->post_change_timer
, SD_EVENT_ONESHOT
);
2324 log_debug_errno(r
, "Failed to enable scheduled ftruncate: %m");
2331 /* On failure, let's simply post the change immediately. */
2332 journal_file_post_change(f
);
2335 /* Enable coalesced change posting in a timer on the provided sd_event instance */
2336 int journal_file_enable_post_change_timer(JournalFile
*f
, sd_event
*e
, usec_t t
) {
2337 _cleanup_(sd_event_source_unrefp
) sd_event_source
*timer
= NULL
;
2341 assert_return(!f
->post_change_timer
, -EINVAL
);
2345 r
= sd_event_add_time(e
, &timer
, CLOCK_MONOTONIC
, 0, 0, post_change_thunk
, f
);
2349 r
= sd_event_source_set_enabled(timer
, SD_EVENT_OFF
);
2353 f
->post_change_timer
= TAKE_PTR(timer
);
2354 f
->post_change_timer_period
= t
;
2359 static int entry_item_cmp(const EntryItem
*a
, const EntryItem
*b
) {
2360 return CMP(ASSERT_PTR(a
)->object_offset
, ASSERT_PTR(b
)->object_offset
);
2363 static size_t remove_duplicate_entry_items(EntryItem items
[], size_t n
) {
2366 assert(items
|| n
== 0);
2371 for (size_t i
= 1; i
< n
; i
++)
2372 if (items
[i
].object_offset
!= items
[j
- 1].object_offset
)
2373 items
[j
++] = items
[i
];
2378 int journal_file_append_entry(
2380 const dual_timestamp
*ts
,
2381 const sd_id128_t
*boot_id
,
2382 const struct iovec iovec
[],
2385 sd_id128_t
*seqnum_id
,
2386 Object
**ret_object
,
2387 uint64_t *ret_offset
) {
2389 _cleanup_free_ EntryItem
*items_alloc
= NULL
;
2391 uint64_t xor_hash
= 0;
2392 struct dual_timestamp _ts
;
2393 sd_id128_t _boot_id
, _machine_id
, *machine_id
;
2399 assert(n_iovec
> 0);
2402 if (!VALID_REALTIME(ts
->realtime
))
2403 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
2404 "Invalid realtime timestamp %" PRIu64
", refusing entry.",
2406 if (!VALID_MONOTONIC(ts
->monotonic
))
2407 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
2408 "Invalid monotomic timestamp %" PRIu64
", refusing entry.",
2411 dual_timestamp_get(&_ts
);
2416 r
= sd_id128_get_boot(&_boot_id
);
2420 boot_id
= &_boot_id
;
2423 r
= sd_id128_get_machine(&_machine_id
);
2425 if (!ERRNO_IS_MACHINE_ID_UNSET(r
))
2428 /* If the machine ID is not initialized yet, handle gracefully */
2431 machine_id
= &_machine_id
;
2434 r
= journal_file_maybe_append_tag(f
, ts
->realtime
);
2439 if (n_iovec
< ALLOCA_MAX
/ sizeof(EntryItem
) / 2)
2440 items
= newa(EntryItem
, n_iovec
);
2442 items_alloc
= new(EntryItem
, n_iovec
);
2446 items
= items_alloc
;
2449 for (size_t i
= 0; i
< n_iovec
; i
++) {
2453 r
= journal_file_append_data(f
, iovec
[i
].iov_base
, iovec
[i
].iov_len
, &o
, &p
);
2457 /* When calculating the XOR hash field, we need to take special care if the "keyed-hash"
2458 * journal file flag is on. We use the XOR hash field to quickly determine the identity of a
2459 * specific record, and give records with otherwise identical position (i.e. match in seqno,
2460 * timestamp, …) a stable ordering. But for that we can't have it that the hash of the
2461 * objects in each file is different since they are keyed. Hence let's calculate the Jenkins
2462 * hash here for that. This also has the benefit that cursors for old and new journal files
2463 * are completely identical (they include the XOR hash after all). For classic Jenkins-hash
2464 * files things are easier, we can just take the value from the stored record directly. */
2466 if (JOURNAL_HEADER_KEYED_HASH(f
->header
))
2467 xor_hash
^= jenkins_hash64(iovec
[i
].iov_base
, iovec
[i
].iov_len
);
2469 xor_hash
^= le64toh(o
->data
.hash
);
2471 items
[i
] = (EntryItem
) {
2473 .hash
= le64toh(o
->data
.hash
),
2477 /* Order by the position on disk, in order to improve seek
2478 * times for rotating media. */
2479 typesafe_qsort(items
, n_iovec
, entry_item_cmp
);
2480 n_iovec
= remove_duplicate_entry_items(items
, n_iovec
);
2482 r
= journal_file_append_entry_internal(
2495 /* If the memory mapping triggered a SIGBUS then we return an
2496 * IO error and ignore the error code passed down to us, since
2497 * it is very likely just an effect of a nullified replacement
2500 if (mmap_cache_fd_got_sigbus(f
->cache_fd
))
2503 if (f
->post_change_timer
)
2504 schedule_post_change(f
);
2506 journal_file_post_change(f
);
2511 typedef struct ChainCacheItem
{
2512 uint64_t first
; /* the array at the beginning of the chain */
2513 uint64_t array
; /* the cached array */
2514 uint64_t begin
; /* the first item in the cached array */
2515 uint64_t total
; /* the total number of items in all arrays before this one in the chain */
2516 uint64_t last_index
; /* the last index we looked at, to optimize locality when bisecting */
2519 static void chain_cache_put(
2526 uint64_t last_index
) {
2531 /* If the chain item to cache for this chain is the
2532 * first one it's not worth caching anything */
2536 if (ordered_hashmap_size(h
) >= CHAIN_CACHE_MAX
) {
2537 ci
= ordered_hashmap_steal_first(h
);
2540 ci
= new(ChainCacheItem
, 1);
2547 if (ordered_hashmap_put(h
, &ci
->first
, ci
) < 0) {
2552 assert(ci
->first
== first
);
2557 ci
->last_index
= last_index
;
2560 static int bump_array_index(uint64_t *i
, direction_t direction
, uint64_t n
) {
2563 /* Increase or decrease the specified index, in the right direction. */
2565 if (direction
== DIRECTION_DOWN
) {
2580 static int bump_entry_array(
2585 direction_t direction
,
2595 if (direction
== DIRECTION_DOWN
) {
2597 *ret
= le64toh(o
->entry_array
.next_entry_array_offset
);
2601 /* Entry array chains are a singly linked list, so to find the previous array in the chain, we have
2602 * to start iterating from the top. */
2606 while (p
> 0 && p
!= offset
) {
2607 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, p
, &o
);
2612 p
= le64toh(o
->entry_array
.next_entry_array_offset
);
2615 /* If we can't find the previous entry array in the entry array chain, we're likely dealing with a
2616 * corrupted journal file. */
2625 static int generic_array_get(
2629 direction_t direction
,
2630 Object
**ret_object
,
2631 uint64_t *ret_offset
) {
2633 uint64_t a
, t
= 0, k
;
2640 /* FIXME: fix return value assignment on success. */
2644 /* Try the chain cache first */
2645 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
2646 if (ci
&& i
> ci
->total
) {
2653 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
2654 if (IN_SET(r
, -EBADMSG
, -EADDRNOTAVAIL
)) {
2655 /* If there's corruption and we're going downwards, let's pretend we reached the
2656 * final entry in the entry array chain. */
2658 if (direction
== DIRECTION_DOWN
)
2661 /* If there's corruption and we're going upwards, move back to the previous entry
2662 * array and start iterating entries from there. */
2664 r
= bump_entry_array(f
, NULL
, a
, first
, DIRECTION_UP
, &a
);
2675 k
= journal_file_entry_array_n_items(f
, o
);
2681 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
2684 /* If we've found the right location, now look for the first non-corrupt entry object (in the right
2688 /* In the first iteration of the while loop, we reuse i, k and o from the previous while
2690 if (i
== UINT64_MAX
) {
2691 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
2695 k
= journal_file_entry_array_n_items(f
, o
);
2699 i
= direction
== DIRECTION_DOWN
? 0 : k
- 1;
2705 p
= journal_file_entry_array_item(f
, o
, i
);
2707 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, ret_object
);
2709 /* Let's cache this item for the next invocation */
2710 chain_cache_put(f
->chain_cache
, ci
, first
, a
, journal_file_entry_array_item(f
, o
, 0), t
, i
);
2717 if (!IN_SET(r
, -EADDRNOTAVAIL
, -EBADMSG
))
2720 /* OK, so this entry is borked. Most likely some entry didn't get synced to
2721 * disk properly, let's see if the next one might work for us instead. */
2722 log_debug_errno(r
, "Entry item %" PRIu64
" is bad, skipping over it.", i
);
2724 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
2728 } while (bump_array_index(&i
, direction
, k
) > 0);
2730 r
= bump_entry_array(f
, o
, a
, first
, direction
, &a
);
2741 static int generic_array_get_plus_one(
2746 direction_t direction
,
2747 Object
**ret_object
,
2748 uint64_t *ret_offset
) {
2754 /* FIXME: fix return value assignment on success. */
2757 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, ret_object
);
2758 if (IN_SET(r
, -EADDRNOTAVAIL
, -EBADMSG
))
2759 return generic_array_get(f
, first
, 0, direction
, ret_object
, ret_offset
);
2764 *ret_offset
= extra
;
2769 return generic_array_get(f
, first
, i
- 1, direction
, ret_object
, ret_offset
);
2778 static int generic_array_bisect(
2783 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
2784 direction_t direction
,
2785 Object
**ret_object
,
2786 uint64_t *ret_offset
,
2787 uint64_t *ret_idx
) {
2789 /* Given an entry array chain, this function finds the object "closest" to the given needle in the
2790 * chain, taking into account the provided direction. A function can be provided to determine how
2791 * an object is matched against the given needle.
2793 * Given a journal file, the offset of an object and the needle, the test_object() function should
2794 * return TEST_LEFT if the needle is located earlier in the entry array chain, TEST_LEFT if the
2795 * needle is located later in the entry array chain and TEST_FOUND if the object matches the needle.
2796 * If test_object() returns TEST_FOUND for a specific object, that object's information will be used
2797 * to populate the return values of this function. If test_object() never returns TEST_FOUND, the
2798 * return values are populated with the details of one of the objects closest to the needle. If the
2799 * direction is DIRECTION_UP, the earlier object is used. Otherwise, the later object is used.
2802 uint64_t a
, p
, t
= 0, i
= 0, last_p
= 0, last_index
= UINT64_MAX
;
2803 bool subtract_one
= false;
2809 assert(test_object
);
2811 /* Start with the first array in the chain */
2814 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
2815 if (ci
&& n
> ci
->total
&& ci
->begin
!= 0) {
2816 /* Ah, we have iterated this bisection array chain previously! Let's see if we can skip ahead
2817 * in the chain, as far as the last time. But we can't jump backwards in the chain, so let's
2818 * check that first. */
2820 r
= test_object(f
, ci
->begin
, needle
);
2824 if (r
== TEST_LEFT
) {
2825 /* OK, what we are looking for is right of the begin of this EntryArray, so let's
2826 * jump straight to previously cached array in the chain */
2831 last_index
= ci
->last_index
;
2836 uint64_t left
, right
, k
, lp
;
2838 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &array
);
2842 k
= journal_file_entry_array_n_items(f
, array
);
2848 lp
= p
= journal_file_entry_array_item(f
, array
, i
);
2852 r
= test_object(f
, p
, needle
);
2853 if (IN_SET(r
, -EBADMSG
, -EADDRNOTAVAIL
)) {
2854 log_debug_errno(r
, "Encountered invalid entry while bisecting, cutting algorithm short. (1)");
2861 if (r
== TEST_FOUND
)
2862 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2864 if (r
== TEST_RIGHT
) {
2868 if (last_index
!= UINT64_MAX
) {
2869 assert(last_index
<= right
);
2871 /* If we cached the last index we
2872 * looked at, let's try to not to jump
2873 * too wildly around and see if we can
2874 * limit the range to look at early to
2875 * the immediate neighbors of the last
2876 * index we looked at. */
2878 if (last_index
> 0) {
2879 uint64_t x
= last_index
- 1;
2881 p
= journal_file_entry_array_item(f
, array
, x
);
2885 r
= test_object(f
, p
, needle
);
2889 if (r
== TEST_FOUND
)
2890 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2892 if (r
== TEST_RIGHT
)
2898 if (last_index
< right
) {
2899 uint64_t y
= last_index
+ 1;
2901 p
= journal_file_entry_array_item(f
, array
, y
);
2905 r
= test_object(f
, p
, needle
);
2909 if (r
== TEST_FOUND
)
2910 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2912 if (r
== TEST_RIGHT
)
2920 if (left
== right
) {
2921 if (direction
== DIRECTION_UP
)
2922 subtract_one
= true;
2928 assert(left
< right
);
2929 i
= (left
+ right
) / 2;
2931 p
= journal_file_entry_array_item(f
, array
, i
);
2935 r
= test_object(f
, p
, needle
);
2936 if (IN_SET(r
, -EBADMSG
, -EADDRNOTAVAIL
)) {
2937 log_debug_errno(r
, "Encountered invalid entry while bisecting, cutting algorithm short. (2)");
2944 if (r
== TEST_FOUND
)
2945 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2947 if (r
== TEST_RIGHT
)
2955 if (direction
== DIRECTION_UP
) {
2957 subtract_one
= true;
2968 last_index
= UINT64_MAX
;
2969 a
= le64toh(array
->entry_array
.next_entry_array_offset
);
2975 if (subtract_one
&& t
== 0 && i
== 0)
2978 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &array
);
2982 p
= journal_file_entry_array_item(f
, array
, 0);
2986 /* Let's cache this item for the next invocation */
2987 chain_cache_put(f
->chain_cache
, ci
, first
, a
, p
, t
, subtract_one
? (i
> 0 ? i
-1 : UINT64_MAX
) : i
);
2989 if (subtract_one
&& i
== 0)
2991 else if (subtract_one
)
2992 p
= journal_file_entry_array_item(f
, array
, i
- 1);
2994 p
= journal_file_entry_array_item(f
, array
, i
);
2997 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, ret_object
);
3006 *ret_idx
= t
+ i
+ (subtract_one
? -1 : 0);
3011 static int generic_array_bisect_plus_one(
3017 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
3018 direction_t direction
,
3019 Object
**ret_object
,
3020 uint64_t *ret_offset
,
3021 uint64_t *ret_idx
) {
3024 bool step_back
= false;
3027 assert(test_object
);
3032 /* This bisects the array in object 'first', but first checks
3034 r
= test_object(f
, extra
, needle
);
3038 if (r
== TEST_FOUND
)
3039 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
3041 /* if we are looking with DIRECTION_UP then we need to first
3042 see if in the actual array there is a matching entry, and
3043 return the last one of that. But if there isn't any we need
3044 to return this one. Hence remember this, and return it
3047 step_back
= direction
== DIRECTION_UP
;
3049 if (r
== TEST_RIGHT
) {
3050 if (direction
== DIRECTION_DOWN
)
3056 r
= generic_array_bisect(f
, first
, n
-1, needle
, test_object
, direction
, ret_object
, ret_offset
, ret_idx
);
3058 if (r
== 0 && step_back
)
3061 if (r
> 0 && ret_idx
)
3068 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, ret_object
);
3074 *ret_offset
= extra
;
3082 _pure_
static int test_object_offset(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
3088 else if (p
< needle
)
3094 int journal_file_move_to_entry_by_offset(
3097 direction_t direction
,
3098 Object
**ret_object
,
3099 uint64_t *ret_offset
) {
3104 return generic_array_bisect(
3106 le64toh(f
->header
->entry_array_offset
),
3107 le64toh(f
->header
->n_entries
),
3111 ret_object
, ret_offset
, NULL
);
3114 static int test_object_seqnum(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
3122 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
3126 sq
= le64toh(READ_NOW(o
->entry
.seqnum
));
3129 else if (sq
< needle
)
3135 int journal_file_move_to_entry_by_seqnum(
3138 direction_t direction
,
3139 Object
**ret_object
,
3140 uint64_t *ret_offset
) {
3145 return generic_array_bisect(
3147 le64toh(f
->header
->entry_array_offset
),
3148 le64toh(f
->header
->n_entries
),
3152 ret_object
, ret_offset
, NULL
);
3155 static int test_object_realtime(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
3163 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
3167 rt
= le64toh(READ_NOW(o
->entry
.realtime
));
3170 else if (rt
< needle
)
3176 int journal_file_move_to_entry_by_realtime(
3179 direction_t direction
,
3180 Object
**ret_object
,
3181 uint64_t *ret_offset
) {
3186 return generic_array_bisect(
3188 le64toh(f
->header
->entry_array_offset
),
3189 le64toh(f
->header
->n_entries
),
3191 test_object_realtime
,
3193 ret_object
, ret_offset
, NULL
);
3196 static int test_object_monotonic(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
3204 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
3208 m
= le64toh(READ_NOW(o
->entry
.monotonic
));
3211 else if (m
< needle
)
3217 static int find_data_object_by_boot_id(
3220 Object
**ret_object
,
3221 uint64_t *ret_offset
) {
3223 char t
[STRLEN("_BOOT_ID=") + 32 + 1] = "_BOOT_ID=";
3227 sd_id128_to_string(boot_id
, t
+ 9);
3228 return journal_file_find_data_object(f
, t
, sizeof(t
) - 1, ret_object
, ret_offset
);
3231 int journal_file_move_to_entry_by_monotonic(
3235 direction_t direction
,
3236 Object
**ret_object
,
3237 uint64_t *ret_offset
) {
3244 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, NULL
);
3250 return generic_array_bisect_plus_one(
3252 le64toh(o
->data
.entry_offset
),
3253 le64toh(o
->data
.entry_array_offset
),
3254 le64toh(o
->data
.n_entries
),
3256 test_object_monotonic
,
3258 ret_object
, ret_offset
, NULL
);
3261 void journal_file_reset_location(JournalFile
*f
) {
3264 f
->location_type
= LOCATION_HEAD
;
3265 f
->current_offset
= 0;
3266 f
->current_seqnum
= 0;
3267 f
->current_realtime
= 0;
3268 f
->current_monotonic
= 0;
3269 zero(f
->current_boot_id
);
3270 f
->current_xor_hash
= 0;
3273 void journal_file_save_location(JournalFile
*f
, Object
*o
, uint64_t offset
) {
3277 f
->location_type
= LOCATION_SEEK
;
3278 f
->current_offset
= offset
;
3279 f
->current_seqnum
= le64toh(o
->entry
.seqnum
);
3280 f
->current_realtime
= le64toh(o
->entry
.realtime
);
3281 f
->current_monotonic
= le64toh(o
->entry
.monotonic
);
3282 f
->current_boot_id
= o
->entry
.boot_id
;
3283 f
->current_xor_hash
= le64toh(o
->entry
.xor_hash
);
3286 static bool check_properly_ordered(uint64_t new_offset
, uint64_t old_offset
, direction_t direction
) {
3288 /* Consider it an error if any of the two offsets is uninitialized */
3289 if (old_offset
== 0 || new_offset
== 0)
3292 /* If we go down, the new offset must be larger than the old one. */
3293 return direction
== DIRECTION_DOWN
?
3294 new_offset
> old_offset
:
3295 new_offset
< old_offset
;
3298 int journal_file_next_entry(
3301 direction_t direction
,
3302 Object
**ret_object
,
3303 uint64_t *ret_offset
) {
3311 /* FIXME: fix return value assignment. */
3313 n
= le64toh(READ_NOW(f
->header
->n_entries
));
3318 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
3320 r
= generic_array_bisect(f
,
3321 le64toh(f
->header
->entry_array_offset
),
3322 le64toh(f
->header
->n_entries
),
3331 r
= bump_array_index(&i
, direction
, n
);
3336 /* And jump to it */
3337 r
= generic_array_get(f
, le64toh(f
->header
->entry_array_offset
), i
, direction
, ret_object
, &ofs
);
3341 /* Ensure our array is properly ordered. */
3342 if (p
> 0 && !check_properly_ordered(ofs
, p
, direction
))
3343 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
3344 "%s: entry array not properly ordered at entry %" PRIu64
,
3353 int journal_file_next_entry_for_data(
3356 direction_t direction
,
3357 Object
**ret_object
,
3358 uint64_t *ret_offset
) {
3365 assert(d
->object
.type
== OBJECT_DATA
);
3367 /* FIXME: fix return value assignment. */
3369 n
= le64toh(READ_NOW(d
->data
.n_entries
));
3373 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
3375 r
= generic_array_get_plus_one(f
,
3376 le64toh(d
->data
.entry_offset
),
3377 le64toh(d
->data
.entry_array_offset
),
3390 int journal_file_move_to_entry_by_offset_for_data(
3394 direction_t direction
,
3395 Object
**ret
, uint64_t *ret_offset
) {
3399 assert(d
->object
.type
== OBJECT_DATA
);
3401 return generic_array_bisect_plus_one(
3403 le64toh(d
->data
.entry_offset
),
3404 le64toh(d
->data
.entry_array_offset
),
3405 le64toh(d
->data
.n_entries
),
3409 ret
, ret_offset
, NULL
);
3412 int journal_file_move_to_entry_by_monotonic_for_data(
3417 direction_t direction
,
3418 Object
**ret_object
,
3419 uint64_t *ret_offset
) {
3421 uint64_t b
, z
, entry_offset
, entry_array_offset
, n_entries
;
3427 assert(d
->object
.type
== OBJECT_DATA
);
3429 /* Save all the required data before the data object gets invalidated. */
3430 entry_offset
= le64toh(READ_NOW(d
->data
.entry_offset
));
3431 entry_array_offset
= le64toh(READ_NOW(d
->data
.entry_array_offset
));
3432 n_entries
= le64toh(READ_NOW(d
->data
.n_entries
));
3434 /* First, seek by time */
3435 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &b
);
3441 r
= generic_array_bisect_plus_one(f
,
3442 le64toh(o
->data
.entry_offset
),
3443 le64toh(o
->data
.entry_array_offset
),
3444 le64toh(o
->data
.n_entries
),
3446 test_object_monotonic
,
3452 /* And now, continue seeking until we find an entry that
3453 * exists in both bisection arrays */
3455 r
= journal_file_move_to_object(f
, OBJECT_DATA
, b
, &o
);
3462 r
= generic_array_bisect_plus_one(f
,
3473 r
= generic_array_bisect_plus_one(f
,
3474 le64toh(o
->data
.entry_offset
),
3475 le64toh(o
->data
.entry_array_offset
),
3476 le64toh(o
->data
.n_entries
),
3487 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, q
, ret_object
);
3502 int journal_file_move_to_entry_by_seqnum_for_data(
3506 direction_t direction
,
3507 Object
**ret_object
,
3508 uint64_t *ret_offset
) {
3512 assert(d
->object
.type
== OBJECT_DATA
);
3514 return generic_array_bisect_plus_one(
3516 le64toh(d
->data
.entry_offset
),
3517 le64toh(d
->data
.entry_array_offset
),
3518 le64toh(d
->data
.n_entries
),
3522 ret_object
, ret_offset
, NULL
);
3525 int journal_file_move_to_entry_by_realtime_for_data(
3529 direction_t direction
,
3530 Object
**ret
, uint64_t *ret_offset
) {
3534 assert(d
->object
.type
== OBJECT_DATA
);
3536 return generic_array_bisect_plus_one(
3538 le64toh(d
->data
.entry_offset
),
3539 le64toh(d
->data
.entry_array_offset
),
3540 le64toh(d
->data
.n_entries
),
3542 test_object_realtime
,
3544 ret
, ret_offset
, NULL
);
3547 void journal_file_dump(JournalFile
*f
) {
3555 journal_file_print_header(f
);
3557 p
= le64toh(READ_NOW(f
->header
->header_size
));
3562 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &o
);
3566 s
= journal_object_type_to_string(o
->object
.type
);
3568 switch (o
->object
.type
) {
3573 printf("Type: %s seqnum=%"PRIu64
" monotonic=%"PRIu64
" realtime=%"PRIu64
"\n",
3575 le64toh(o
->entry
.seqnum
),
3576 le64toh(o
->entry
.monotonic
),
3577 le64toh(o
->entry
.realtime
));
3583 printf("Type: %s seqnum=%"PRIu64
" epoch=%"PRIu64
"\n",
3585 le64toh(o
->tag
.seqnum
),
3586 le64toh(o
->tag
.epoch
));
3591 printf("Type: %s \n", s
);
3593 printf("Type: unknown (%i)", o
->object
.type
);
3598 c
= COMPRESSION_FROM_OBJECT(o
);
3599 if (c
> COMPRESSION_NONE
)
3600 printf("Flags: %s\n",
3601 compression_to_string(c
));
3603 if (p
== le64toh(f
->header
->tail_object_offset
))
3606 p
+= ALIGN64(le64toh(o
->object
.size
));
3611 log_error("File corrupt");
3614 /* Note: the lifetime of the compound literal is the immediately surrounding block. */
3615 #define FORMAT_TIMESTAMP_SAFE(t) (FORMAT_TIMESTAMP(t) ?: " --- ")
3617 void journal_file_print_header(JournalFile
*f
) {
3623 printf("File path: %s\n"
3627 "Sequential number ID: %s\n"
3629 "Compatible flags:%s%s%s\n"
3630 "Incompatible flags:%s%s%s%s%s%s\n"
3631 "Header size: %"PRIu64
"\n"
3632 "Arena size: %"PRIu64
"\n"
3633 "Data hash table size: %"PRIu64
"\n"
3634 "Field hash table size: %"PRIu64
"\n"
3635 "Rotate suggested: %s\n"
3636 "Head sequential number: %"PRIu64
" (%"PRIx64
")\n"
3637 "Tail sequential number: %"PRIu64
" (%"PRIx64
")\n"
3638 "Head realtime timestamp: %s (%"PRIx64
")\n"
3639 "Tail realtime timestamp: %s (%"PRIx64
")\n"
3640 "Tail monotonic timestamp: %s (%"PRIx64
")\n"
3641 "Objects: %"PRIu64
"\n"
3642 "Entry objects: %"PRIu64
"\n",
3644 SD_ID128_TO_STRING(f
->header
->file_id
),
3645 SD_ID128_TO_STRING(f
->header
->machine_id
),
3646 SD_ID128_TO_STRING(f
->header
->tail_entry_boot_id
),
3647 SD_ID128_TO_STRING(f
->header
->seqnum_id
),
3648 f
->header
->state
== STATE_OFFLINE
? "OFFLINE" :
3649 f
->header
->state
== STATE_ONLINE
? "ONLINE" :
3650 f
->header
->state
== STATE_ARCHIVED
? "ARCHIVED" : "UNKNOWN",
3651 JOURNAL_HEADER_SEALED(f
->header
) ? " SEALED" : "",
3652 JOURNAL_HEADER_TAIL_ENTRY_BOOT_ID(f
->header
) ? " TAIL_ENTRY_BOOT_ID" : "",
3653 (le32toh(f
->header
->compatible_flags
) & ~HEADER_COMPATIBLE_ANY
) ? " ???" : "",
3654 JOURNAL_HEADER_COMPRESSED_XZ(f
->header
) ? " COMPRESSED-XZ" : "",
3655 JOURNAL_HEADER_COMPRESSED_LZ4(f
->header
) ? " COMPRESSED-LZ4" : "",
3656 JOURNAL_HEADER_COMPRESSED_ZSTD(f
->header
) ? " COMPRESSED-ZSTD" : "",
3657 JOURNAL_HEADER_KEYED_HASH(f
->header
) ? " KEYED-HASH" : "",
3658 JOURNAL_HEADER_COMPACT(f
->header
) ? " COMPACT" : "",
3659 (le32toh(f
->header
->incompatible_flags
) & ~HEADER_INCOMPATIBLE_ANY
) ? " ???" : "",
3660 le64toh(f
->header
->header_size
),
3661 le64toh(f
->header
->arena_size
),
3662 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
3663 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
),
3664 yes_no(journal_file_rotate_suggested(f
, 0, LOG_DEBUG
)),
3665 le64toh(f
->header
->head_entry_seqnum
), le64toh(f
->header
->head_entry_seqnum
),
3666 le64toh(f
->header
->tail_entry_seqnum
), le64toh(f
->header
->tail_entry_seqnum
),
3667 FORMAT_TIMESTAMP_SAFE(le64toh(f
->header
->head_entry_realtime
)), le64toh(f
->header
->head_entry_realtime
),
3668 FORMAT_TIMESTAMP_SAFE(le64toh(f
->header
->tail_entry_realtime
)), le64toh(f
->header
->tail_entry_realtime
),
3669 FORMAT_TIMESPAN(le64toh(f
->header
->tail_entry_monotonic
), USEC_PER_MSEC
), le64toh(f
->header
->tail_entry_monotonic
),
3670 le64toh(f
->header
->n_objects
),
3671 le64toh(f
->header
->n_entries
));
3673 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
3674 printf("Data objects: %"PRIu64
"\n"
3675 "Data hash table fill: %.1f%%\n",
3676 le64toh(f
->header
->n_data
),
3677 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))));
3679 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
3680 printf("Field objects: %"PRIu64
"\n"
3681 "Field hash table fill: %.1f%%\n",
3682 le64toh(f
->header
->n_fields
),
3683 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))));
3685 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_tags
))
3686 printf("Tag objects: %"PRIu64
"\n",
3687 le64toh(f
->header
->n_tags
));
3688 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
3689 printf("Entry array objects: %"PRIu64
"\n",
3690 le64toh(f
->header
->n_entry_arrays
));
3692 if (JOURNAL_HEADER_CONTAINS(f
->header
, field_hash_chain_depth
))
3693 printf("Deepest field hash chain: %" PRIu64
"\n",
3694 f
->header
->field_hash_chain_depth
);
3696 if (JOURNAL_HEADER_CONTAINS(f
->header
, data_hash_chain_depth
))
3697 printf("Deepest data hash chain: %" PRIu64
"\n",
3698 f
->header
->data_hash_chain_depth
);
3700 if (fstat(f
->fd
, &st
) >= 0)
3701 printf("Disk usage: %s\n", FORMAT_BYTES((uint64_t) st
.st_blocks
* 512ULL));
3704 static int journal_file_warn_btrfs(JournalFile
*f
) {
3710 /* Before we write anything, check if the COW logic is turned
3711 * off on btrfs. Given our write pattern that is quite
3712 * unfriendly to COW file systems this should greatly improve
3713 * performance on COW file systems, such as btrfs, at the
3714 * expense of data integrity features (which shouldn't be too
3715 * bad, given that we do our own checksumming). */
3717 r
= fd_is_fs_type(f
->fd
, BTRFS_SUPER_MAGIC
);
3719 return log_ratelimit_warning_errno(r
, JOURNAL_LOG_RATELIMIT
, "Failed to determine if journal is on btrfs: %m");
3723 r
= read_attr_fd(f
->fd
, &attrs
);
3725 return log_ratelimit_warning_errno(r
, JOURNAL_LOG_RATELIMIT
, "Failed to read file attributes: %m");
3727 if (attrs
& FS_NOCOW_FL
) {
3728 log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
3732 log_ratelimit_notice(JOURNAL_LOG_RATELIMIT
,
3733 "Creating journal file %s on a btrfs file system, and copy-on-write is enabled. "
3734 "This is likely to slow down journal access substantially, please consider turning "
3735 "off the copy-on-write file attribute on the journal directory, using chattr +C.",
3741 static void journal_default_metrics(JournalMetrics
*m
, int fd
, bool compact
) {
3743 uint64_t fs_size
= 0;
3748 if (fstatvfs(fd
, &ss
) >= 0)
3749 fs_size
= ss
.f_frsize
* ss
.f_blocks
;
3751 log_debug_errno(errno
, "Failed to determine disk size: %m");
3753 if (m
->max_use
== UINT64_MAX
) {
3756 m
->max_use
= CLAMP(PAGE_ALIGN(fs_size
/ 10), /* 10% of file system size */
3757 MAX_USE_LOWER
, MAX_USE_UPPER
);
3759 m
->max_use
= MAX_USE_LOWER
;
3761 m
->max_use
= PAGE_ALIGN(m
->max_use
);
3763 if (m
->max_use
!= 0 && m
->max_use
< JOURNAL_FILE_SIZE_MIN
*2)
3764 m
->max_use
= JOURNAL_FILE_SIZE_MIN
*2;
3767 if (m
->min_use
== UINT64_MAX
) {
3769 m
->min_use
= CLAMP(PAGE_ALIGN(fs_size
/ 50), /* 2% of file system size */
3770 MIN_USE_LOW
, MIN_USE_HIGH
);
3772 m
->min_use
= MIN_USE_LOW
;
3775 if (m
->min_use
> m
->max_use
)
3776 m
->min_use
= m
->max_use
;
3778 if (m
->max_size
== UINT64_MAX
)
3779 m
->max_size
= MIN(PAGE_ALIGN(m
->max_use
/ 8), /* 8 chunks */
3782 m
->max_size
= PAGE_ALIGN(m
->max_size
);
3784 if (compact
&& m
->max_size
> JOURNAL_COMPACT_SIZE_MAX
)
3785 m
->max_size
= JOURNAL_COMPACT_SIZE_MAX
;
3787 if (m
->max_size
!= 0) {
3788 if (m
->max_size
< JOURNAL_FILE_SIZE_MIN
)
3789 m
->max_size
= JOURNAL_FILE_SIZE_MIN
;
3791 if (m
->max_use
!= 0 && m
->max_size
*2 > m
->max_use
)
3792 m
->max_use
= m
->max_size
*2;
3795 if (m
->min_size
== UINT64_MAX
)
3796 m
->min_size
= JOURNAL_FILE_SIZE_MIN
;
3798 m
->min_size
= CLAMP(PAGE_ALIGN(m
->min_size
),
3799 JOURNAL_FILE_SIZE_MIN
,
3800 m
->max_size
?: UINT64_MAX
);
3802 if (m
->keep_free
== UINT64_MAX
) {
3804 m
->keep_free
= MIN(PAGE_ALIGN(fs_size
/ 20), /* 5% of file system size */
3807 m
->keep_free
= DEFAULT_KEEP_FREE
;
3810 if (m
->n_max_files
== UINT64_MAX
)
3811 m
->n_max_files
= DEFAULT_N_MAX_FILES
;
3813 log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64
,
3814 FORMAT_BYTES(m
->min_use
),
3815 FORMAT_BYTES(m
->max_use
),
3816 FORMAT_BYTES(m
->max_size
),
3817 FORMAT_BYTES(m
->min_size
),
3818 FORMAT_BYTES(m
->keep_free
),
3822 int journal_file_open(
3826 JournalFileFlags file_flags
,
3828 uint64_t compress_threshold_bytes
,
3829 JournalMetrics
*metrics
,
3830 MMapCache
*mmap_cache
,
3831 JournalFile
*template,
3832 JournalFile
**ret
) {
3834 bool newly_created
= false;
3839 assert(fd
>= 0 || fname
);
3840 assert(file_flags
>= 0);
3841 assert(file_flags
<= _JOURNAL_FILE_FLAGS_MAX
);
3845 if (!IN_SET((open_flags
& O_ACCMODE
), O_RDONLY
, O_RDWR
))
3848 if ((open_flags
& O_ACCMODE
) == O_RDONLY
&& FLAGS_SET(open_flags
, O_CREAT
))
3851 if (fname
&& (open_flags
& O_CREAT
) && !endswith(fname
, ".journal"))
3854 f
= new(JournalFile
, 1);
3858 *f
= (JournalFile
) {
3861 .open_flags
= open_flags
,
3862 .compress_threshold_bytes
= compress_threshold_bytes
== UINT64_MAX
?
3863 DEFAULT_COMPRESS_THRESHOLD
:
3864 MAX(MIN_COMPRESS_THRESHOLD
, compress_threshold_bytes
),
3865 .strict_order
= FLAGS_SET(file_flags
, JOURNAL_STRICT_ORDER
),
3866 .newest_boot_id_prioq_idx
= PRIOQ_IDX_NULL
,
3870 f
->path
= strdup(fname
);
3878 /* If we don't know the path, fill in something explanatory and vaguely useful */
3879 if (asprintf(&f
->path
, "/proc/self/%i", fd
) < 0) {
3885 f
->chain_cache
= ordered_hashmap_new(&uint64_hash_ops
);
3886 if (!f
->chain_cache
) {
3892 /* We pass O_NONBLOCK here, so that in case somebody pointed us to some character device node or FIFO
3893 * or so, we likely fail quickly than block for long. For regular files O_NONBLOCK has no effect, hence
3894 * it doesn't hurt in that case. */
3896 f
->fd
= openat_report_new(AT_FDCWD
, f
->path
, f
->open_flags
|O_CLOEXEC
|O_NONBLOCK
, f
->mode
, &newly_created
);
3902 /* fds we opened here by us should also be closed by us. */
3905 r
= fd_nonblock(f
->fd
, false);
3909 if (!newly_created
) {
3910 r
= journal_file_fstat(f
);
3915 r
= journal_file_fstat(f
);
3919 /* If we just got the fd passed in, we don't really know if we created the file anew */
3920 newly_created
= f
->last_stat
.st_size
== 0 && journal_file_writable(f
);
3923 f
->cache_fd
= mmap_cache_add_fd(mmap_cache
, f
->fd
, mmap_prot_from_open_flags(open_flags
));
3929 if (newly_created
) {
3930 (void) journal_file_warn_btrfs(f
);
3932 /* Let's attach the creation time to the journal file, so that the vacuuming code knows the age of this
3933 * file even if the file might end up corrupted one day... Ideally we'd just use the creation time many
3934 * file systems maintain for each file, but the API to query this is very new, hence let's emulate this
3935 * via extended attributes. If extended attributes are not supported we'll just skip this, and rely
3936 * solely on mtime/atime/ctime of the file. */
3937 (void) fd_setcrtime(f
->fd
, 0);
3939 r
= journal_file_init_header(f
, file_flags
, template);
3943 r
= journal_file_fstat(f
);
3948 if (f
->last_stat
.st_size
< (off_t
) HEADER_SIZE_MIN
) {
3953 r
= mmap_cache_fd_get(f
->cache_fd
, CONTEXT_HEADER
, true, 0, PAGE_ALIGN(sizeof(Header
)), &f
->last_stat
, &h
);
3955 /* Some file systems (jffs2 or p9fs) don't support mmap() properly (or only read-only
3956 * mmap()), and return EINVAL in that case. Let's propagate that as a more recognizable error
3966 if (!newly_created
) {
3967 r
= journal_file_verify_header(f
);
3973 if (!newly_created
&& journal_file_writable(f
) && JOURNAL_HEADER_SEALED(f
->header
)) {
3974 r
= journal_file_fss_load(f
);
3980 if (journal_file_writable(f
)) {
3982 journal_default_metrics(metrics
, f
->fd
, JOURNAL_HEADER_COMPACT(f
->header
));
3983 f
->metrics
= *metrics
;
3984 } else if (template)
3985 f
->metrics
= template->metrics
;
3987 r
= journal_file_refresh_header(f
);
3993 r
= journal_file_hmac_setup(f
);
3998 if (newly_created
) {
3999 r
= journal_file_setup_field_hash_table(f
);
4003 r
= journal_file_setup_data_hash_table(f
);
4008 r
= journal_file_append_first_tag(f
);
4014 if (mmap_cache_fd_got_sigbus(f
->cache_fd
)) {
4019 if (template && template->post_change_timer
) {
4020 r
= journal_file_enable_post_change_timer(
4022 sd_event_source_get_event(template->post_change_timer
),
4023 template->post_change_timer_period
);
4029 /* The file is opened now successfully, thus we take possession of any passed in fd. */
4032 if (DEBUG_LOGGING
) {
4033 static int last_seal
= -1, last_keyed_hash
= -1;
4034 static Compression last_compression
= _COMPRESSION_INVALID
;
4035 static uint64_t last_bytes
= UINT64_MAX
;
4037 if (last_seal
!= JOURNAL_HEADER_SEALED(f
->header
) ||
4038 last_keyed_hash
!= JOURNAL_HEADER_KEYED_HASH(f
->header
) ||
4039 last_compression
!= JOURNAL_FILE_COMPRESSION(f
) ||
4040 last_bytes
!= f
->compress_threshold_bytes
) {
4042 log_debug("Journal effective settings seal=%s keyed_hash=%s compress=%s compress_threshold_bytes=%s",
4043 yes_no(JOURNAL_HEADER_SEALED(f
->header
)), yes_no(JOURNAL_HEADER_KEYED_HASH(f
->header
)),
4044 compression_to_string(JOURNAL_FILE_COMPRESSION(f
)), FORMAT_BYTES(f
->compress_threshold_bytes
));
4045 last_seal
= JOURNAL_HEADER_SEALED(f
->header
);
4046 last_keyed_hash
= JOURNAL_HEADER_KEYED_HASH(f
->header
);
4047 last_compression
= JOURNAL_FILE_COMPRESSION(f
);
4048 last_bytes
= f
->compress_threshold_bytes
;
4056 if (f
->cache_fd
&& mmap_cache_fd_got_sigbus(f
->cache_fd
))
4059 (void) journal_file_close(f
);
4061 if (newly_created
&& fd
< 0)
4062 (void) unlink(fname
);
4067 int journal_file_parse_uid_from_filename(const char *path
, uid_t
*ret_uid
) {
4068 _cleanup_free_
char *buf
= NULL
, *p
= NULL
;
4069 const char *a
, *b
, *at
;
4072 /* This helper returns -EREMOTE when the filename doesn't match user online/offline journal
4073 * pattern. Hence it currently doesn't parse archived or disposed user journals. */
4078 r
= path_extract_filename(path
, &p
);
4081 if (r
== O_DIRECTORY
)
4084 a
= startswith(p
, "user-");
4087 b
= endswith(p
, ".journal");
4091 at
= strchr(a
, '@');
4095 buf
= strndup(a
, b
-a
);
4099 return parse_uid(buf
, ret_uid
);
4102 int journal_file_archive(JournalFile
*f
, char **ret_previous_path
) {
4103 _cleanup_free_
char *p
= NULL
;
4107 if (!journal_file_writable(f
))
4110 /* Is this a journal file that was passed to us as fd? If so, we synthesized a path name for it, and we refuse
4111 * rotation, since we don't know the actual path, and couldn't rename the file hence. */
4112 if (path_startswith(f
->path
, "/proc/self/fd"))
4115 if (!endswith(f
->path
, ".journal"))
4118 if (asprintf(&p
, "%.*s@" SD_ID128_FORMAT_STR
"-%016"PRIx64
"-%016"PRIx64
".journal",
4119 (int) strlen(f
->path
) - 8, f
->path
,
4120 SD_ID128_FORMAT_VAL(f
->header
->seqnum_id
),
4121 le64toh(f
->header
->head_entry_seqnum
),
4122 le64toh(f
->header
->head_entry_realtime
)) < 0)
4125 /* Try to rename the file to the archived version. If the file already was deleted, we'll get ENOENT, let's
4126 * ignore that case. */
4127 if (rename(f
->path
, p
) < 0 && errno
!= ENOENT
)
4130 /* Sync the rename to disk */
4131 (void) fsync_directory_of_file(f
->fd
);
4133 if (ret_previous_path
)
4134 *ret_previous_path
= f
->path
;
4138 f
->path
= TAKE_PTR(p
);
4140 /* Set as archive so offlining commits w/state=STATE_ARCHIVED. Previously we would set old_file->header->state
4141 * to STATE_ARCHIVED directly here, but journal_file_set_offline() short-circuits when state != STATE_ONLINE,
4142 * which would result in the rotated journal never getting fsync() called before closing. Now we simply queue
4143 * the archive state by setting an archive bit, leaving the state as STATE_ONLINE so proper offlining
4150 int journal_file_dispose(int dir_fd
, const char *fname
) {
4151 _cleanup_free_
char *p
= NULL
;
4155 /* Renames a journal file to *.journal~, i.e. to mark it as corrupted or otherwise uncleanly shutdown. Note that
4156 * this is done without looking into the file or changing any of its contents. The idea is that this is called
4157 * whenever something is suspicious and we want to move the file away and make clear that it is not accessed
4158 * for writing anymore. */
4160 if (!endswith(fname
, ".journal"))
4163 if (asprintf(&p
, "%.*s@%016" PRIx64
"-%016" PRIx64
".journal~",
4164 (int) strlen(fname
) - 8, fname
,
4165 now(CLOCK_REALTIME
),
4169 if (renameat(dir_fd
, fname
, dir_fd
, p
) < 0)
4175 int journal_file_copy_entry(
4181 sd_id128_t
*seqnum_id
) {
4183 _cleanup_free_ EntryItem
*items_alloc
= NULL
;
4185 uint64_t n
, m
= 0, xor_hash
= 0;
4195 if (!journal_file_writable(to
))
4198 ts
= (dual_timestamp
) {
4199 .monotonic
= le64toh(o
->entry
.monotonic
),
4200 .realtime
= le64toh(o
->entry
.realtime
),
4202 boot_id
= o
->entry
.boot_id
;
4204 n
= journal_file_entry_n_items(from
, o
);
4208 if (n
< ALLOCA_MAX
/ sizeof(EntryItem
) / 2)
4209 items
= newa(EntryItem
, n
);
4211 items_alloc
= new(EntryItem
, n
);
4215 items
= items_alloc
;
4218 for (uint64_t i
= 0; i
< n
; i
++) {
4224 q
= journal_file_entry_item_object_offset(from
, o
, i
);
4225 r
= journal_file_data_payload(from
, NULL
, q
, NULL
, 0, 0, &data
, &l
);
4226 if (IN_SET(r
, -EADDRNOTAVAIL
, -EBADMSG
)) {
4227 log_debug_errno(r
, "Entry item %"PRIu64
" data object is bad, skipping over it: %m", i
);
4237 r
= journal_file_append_data(to
, data
, l
, &u
, &h
);
4241 if (JOURNAL_HEADER_KEYED_HASH(to
->header
))
4242 xor_hash
^= jenkins_hash64(data
, l
);
4244 xor_hash
^= le64toh(u
->data
.hash
);
4246 items
[m
++] = (EntryItem
) {
4248 .hash
= le64toh(u
->data
.hash
),
4252 /* The above journal_file_data_payload() may clear or overwrite cached object. Hence, we need
4253 * to re-read the object from the cache. */
4254 r
= journal_file_move_to_object(from
, OBJECT_ENTRY
, p
, &o
);
4262 r
= journal_file_append_entry_internal(
4266 &from
->header
->machine_id
,
4272 /* ret_object= */ NULL
,
4273 /* ret_offset= */ NULL
);
4275 if (mmap_cache_fd_got_sigbus(to
->cache_fd
))
4281 void journal_reset_metrics(JournalMetrics
*m
) {
4284 /* Set everything to "pick automatic values". */
4286 *m
= (JournalMetrics
) {
4287 .min_use
= UINT64_MAX
,
4288 .max_use
= UINT64_MAX
,
4289 .min_size
= UINT64_MAX
,
4290 .max_size
= UINT64_MAX
,
4291 .keep_free
= UINT64_MAX
,
4292 .n_max_files
= UINT64_MAX
,
4296 int journal_file_get_cutoff_realtime_usec(JournalFile
*f
, usec_t
*ret_from
, usec_t
*ret_to
) {
4299 assert(ret_from
|| ret_to
);
4302 if (f
->header
->head_entry_realtime
== 0)
4305 *ret_from
= le64toh(f
->header
->head_entry_realtime
);
4309 if (f
->header
->tail_entry_realtime
== 0)
4312 *ret_to
= le64toh(f
->header
->tail_entry_realtime
);
4318 int journal_file_get_cutoff_monotonic_usec(JournalFile
*f
, sd_id128_t boot_id
, usec_t
*ret_from
, usec_t
*ret_to
) {
4324 assert(ret_from
|| ret_to
);
4326 /* FIXME: fix return value assignment on success with 0. */
4328 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &p
);
4332 if (le64toh(o
->data
.n_entries
) <= 0)
4336 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, le64toh(o
->data
.entry_offset
), &o
);
4340 *ret_from
= le64toh(o
->entry
.monotonic
);
4344 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
4348 r
= generic_array_get_plus_one(f
,
4349 le64toh(o
->data
.entry_offset
),
4350 le64toh(o
->data
.entry_array_offset
),
4351 le64toh(o
->data
.n_entries
) - 1,
4357 *ret_to
= le64toh(o
->entry
.monotonic
);
4363 bool journal_file_rotate_suggested(JournalFile
*f
, usec_t max_file_usec
, int log_level
) {
4367 /* If we gained new header fields we gained new features,
4368 * hence suggest a rotation */
4369 if (le64toh(f
->header
->header_size
) < sizeof(Header
)) {
4370 log_ratelimit_full(log_level
, JOURNAL_LOG_RATELIMIT
,
4371 "%s uses an outdated header, suggesting rotation.", f
->path
);
4375 /* Let's check if the hash tables grew over a certain fill level (75%, borrowing this value from
4376 * Java's hash table implementation), and if so suggest a rotation. To calculate the fill level we
4377 * need the n_data field, which only exists in newer versions. */
4379 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
4380 if (le64toh(f
->header
->n_data
) * 4ULL > (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
4382 log_level
, JOURNAL_LOG_RATELIMIT
,
4383 "Data hash table of %s has a fill level at %.1f (%"PRIu64
" of %"PRIu64
" items, %"PRIu64
" file size, %"PRIu64
" bytes per hash table item), suggesting rotation.",
4385 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))),
4386 le64toh(f
->header
->n_data
),
4387 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
4388 (uint64_t) f
->last_stat
.st_size
,
4389 f
->last_stat
.st_size
/ le64toh(f
->header
->n_data
));
4393 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
4394 if (le64toh(f
->header
->n_fields
) * 4ULL > (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
4396 log_level
, JOURNAL_LOG_RATELIMIT
,
4397 "Field hash table of %s has a fill level at %.1f (%"PRIu64
" of %"PRIu64
" items), suggesting rotation.",
4399 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))),
4400 le64toh(f
->header
->n_fields
),
4401 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
));
4405 /* If there are too many hash collisions somebody is most likely playing games with us. Hence, if our
4406 * longest chain is longer than some threshold, let's suggest rotation. */
4407 if (JOURNAL_HEADER_CONTAINS(f
->header
, data_hash_chain_depth
) &&
4408 le64toh(f
->header
->data_hash_chain_depth
) > HASH_CHAIN_DEPTH_MAX
) {
4410 log_level
, JOURNAL_LOG_RATELIMIT
,
4411 "Data hash table of %s has deepest hash chain of length %" PRIu64
", suggesting rotation.",
4412 f
->path
, le64toh(f
->header
->data_hash_chain_depth
));
4416 if (JOURNAL_HEADER_CONTAINS(f
->header
, field_hash_chain_depth
) &&
4417 le64toh(f
->header
->field_hash_chain_depth
) > HASH_CHAIN_DEPTH_MAX
) {
4419 log_level
, JOURNAL_LOG_RATELIMIT
,
4420 "Field hash table of %s has deepest hash chain of length at %" PRIu64
", suggesting rotation.",
4421 f
->path
, le64toh(f
->header
->field_hash_chain_depth
));
4425 /* Are the data objects properly indexed by field objects? */
4426 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
) &&
4427 JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
) &&
4428 le64toh(f
->header
->n_data
) > 0 &&
4429 le64toh(f
->header
->n_fields
) == 0) {
4431 log_level
, JOURNAL_LOG_RATELIMIT
,
4432 "Data objects of %s are not indexed by field objects, suggesting rotation.",
4437 if (max_file_usec
> 0) {
4440 h
= le64toh(f
->header
->head_entry_realtime
);
4441 t
= now(CLOCK_REALTIME
);
4443 if (h
> 0 && t
> h
+ max_file_usec
) {
4445 log_level
, JOURNAL_LOG_RATELIMIT
,
4446 "Oldest entry in %s is older than the configured file retention duration (%s), suggesting rotation.",
4447 f
->path
, FORMAT_TIMESPAN(max_file_usec
, USEC_PER_SEC
));
4455 static const char * const journal_object_type_table
[] = {
4456 [OBJECT_UNUSED
] = "unused",
4457 [OBJECT_DATA
] = "data",
4458 [OBJECT_FIELD
] = "field",
4459 [OBJECT_ENTRY
] = "entry",
4460 [OBJECT_DATA_HASH_TABLE
] = "data hash table",
4461 [OBJECT_FIELD_HASH_TABLE
] = "field hash table",
4462 [OBJECT_ENTRY_ARRAY
] = "entry array",
4463 [OBJECT_TAG
] = "tag",
4466 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(journal_object_type
, ObjectType
);