2 This file is part of systemd.
4 Copyright 2011 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
26 #include <sys/statvfs.h>
30 #include "alloc-util.h"
31 #include "btrfs-util.h"
32 #include "chattr-util.h"
35 #include "journal-authenticate.h"
36 #include "journal-def.h"
37 #include "journal-file.h"
39 #include "parse-util.h"
40 #include "path-util.h"
41 #include "random-util.h"
44 #include "string-util.h"
45 #include "xattr-util.h"
47 #define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem))
48 #define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem))
50 #define COMPRESSION_SIZE_THRESHOLD (512ULL)
52 /* This is the minimum journal file size */
53 #define JOURNAL_FILE_SIZE_MIN (512ULL*1024ULL) /* 512 KiB */
55 /* These are the lower and upper bounds if we deduce the max_use value
56 * from the file system size */
57 #define DEFAULT_MAX_USE_LOWER (1ULL*1024ULL*1024ULL) /* 1 MiB */
58 #define DEFAULT_MAX_USE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
60 /* This is the default minimal use limit, how much we'll use even if keep_free suggests otherwise. */
61 #define DEFAULT_MIN_USE (1ULL*1024ULL*1024ULL) /* 1 MiB */
63 /* This is the upper bound if we deduce max_size from max_use */
64 #define DEFAULT_MAX_SIZE_UPPER (128ULL*1024ULL*1024ULL) /* 128 MiB */
66 /* This is the upper bound if we deduce the keep_free value from the
68 #define DEFAULT_KEEP_FREE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
70 /* This is the keep_free value when we can't determine the system
72 #define DEFAULT_KEEP_FREE (1024ULL*1024ULL) /* 1 MB */
74 /* This is the default maximum number of journal files to keep around. */
75 #define DEFAULT_N_MAX_FILES (100)
77 /* n_data was the first entry we added after the initial file format design */
78 #define HEADER_SIZE_MIN ALIGN64(offsetof(Header, n_data))
80 /* How many entries to keep in the entry array chain cache at max */
81 #define CHAIN_CACHE_MAX 20
83 /* How much to increase the journal file size at once each time we allocate something new. */
84 #define FILE_SIZE_INCREASE (8ULL*1024ULL*1024ULL) /* 8MB */
86 /* Reread fstat() of the file for detecting deletions at least this often */
87 #define LAST_STAT_REFRESH_USEC (5*USEC_PER_SEC)
89 /* The mmap context to use for the header we pick as one above the last defined typed */
90 #define CONTEXT_HEADER _OBJECT_TYPE_MAX
92 /* This may be called from a separate thread to prevent blocking the caller for the duration of fsync().
93 * As a result we use atomic operations on f->offline_state for inter-thread communications with
94 * journal_file_set_offline() and journal_file_set_online(). */
95 static void journal_file_set_offline_internal(JournalFile
*f
) {
101 switch (f
->offline_state
) {
103 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_CANCEL
, OFFLINE_DONE
))
107 case OFFLINE_AGAIN_FROM_SYNCING
:
108 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_AGAIN_FROM_SYNCING
, OFFLINE_SYNCING
))
112 case OFFLINE_AGAIN_FROM_OFFLINING
:
113 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_AGAIN_FROM_OFFLINING
, OFFLINE_SYNCING
))
117 case OFFLINE_SYNCING
:
120 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_SYNCING
, OFFLINE_OFFLINING
))
123 f
->header
->state
= f
->archive
? STATE_ARCHIVED
: STATE_OFFLINE
;
127 case OFFLINE_OFFLINING
:
128 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_OFFLINING
, OFFLINE_DONE
))
136 log_debug("OFFLINE_JOINED unexpected offline state for journal_file_set_offline_internal()");
142 static void * journal_file_set_offline_thread(void *arg
) {
143 JournalFile
*f
= arg
;
145 journal_file_set_offline_internal(f
);
150 static int journal_file_set_offline_thread_join(JournalFile
*f
) {
155 if (f
->offline_state
== OFFLINE_JOINED
)
158 r
= pthread_join(f
->offline_thread
, NULL
);
162 f
->offline_state
= OFFLINE_JOINED
;
164 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
170 /* Trigger a restart if the offline thread is mid-flight in a restartable state. */
171 static bool journal_file_set_offline_try_restart(JournalFile
*f
) {
173 switch (f
->offline_state
) {
174 case OFFLINE_AGAIN_FROM_SYNCING
:
175 case OFFLINE_AGAIN_FROM_OFFLINING
:
179 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_CANCEL
, OFFLINE_AGAIN_FROM_SYNCING
))
183 case OFFLINE_SYNCING
:
184 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_SYNCING
, OFFLINE_AGAIN_FROM_SYNCING
))
188 case OFFLINE_OFFLINING
:
189 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_OFFLINING
, OFFLINE_AGAIN_FROM_OFFLINING
))
199 /* Sets a journal offline.
201 * If wait is false then an offline is dispatched in a separate thread for a
202 * subsequent journal_file_set_offline() or journal_file_set_online() of the
203 * same journal to synchronize with.
205 * If wait is true, then either an existing offline thread will be restarted
206 * and joined, or if none exists the offline is simply performed in this
207 * context without involving another thread.
209 int journal_file_set_offline(JournalFile
*f
, bool wait
) {
218 if (!(f
->fd
>= 0 && f
->header
))
221 /* An offlining journal is implicitly online and may modify f->header->state,
222 * we must also join any potentially lingering offline thread when not online. */
223 if (!journal_file_is_offlining(f
) && f
->header
->state
!= STATE_ONLINE
)
224 return journal_file_set_offline_thread_join(f
);
226 /* Restart an in-flight offline thread and wait if needed, or join a lingering done one. */
227 restarted
= journal_file_set_offline_try_restart(f
);
228 if ((restarted
&& wait
) || !restarted
) {
229 r
= journal_file_set_offline_thread_join(f
);
237 /* Initiate a new offline. */
238 f
->offline_state
= OFFLINE_SYNCING
;
240 if (wait
) /* Without using a thread if waiting. */
241 journal_file_set_offline_internal(f
);
243 r
= pthread_create(&f
->offline_thread
, NULL
, journal_file_set_offline_thread
, f
);
245 f
->offline_state
= OFFLINE_JOINED
;
253 static int journal_file_set_online(JournalFile
*f
) {
261 if (!(f
->fd
>= 0 && f
->header
))
265 switch (f
->offline_state
) {
267 /* No offline thread, no need to wait. */
271 case OFFLINE_SYNCING
:
272 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_SYNCING
, OFFLINE_CANCEL
))
274 /* Canceled syncing prior to offlining, no need to wait. */
277 case OFFLINE_AGAIN_FROM_SYNCING
:
278 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_AGAIN_FROM_SYNCING
, OFFLINE_CANCEL
))
280 /* Canceled restart from syncing, no need to wait. */
283 case OFFLINE_AGAIN_FROM_OFFLINING
:
284 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_AGAIN_FROM_OFFLINING
, OFFLINE_CANCEL
))
286 /* Canceled restart from offlining, must wait for offlining to complete however. */
288 /* fall through to wait */
292 r
= journal_file_set_offline_thread_join(f
);
302 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
305 switch (f
->header
->state
) {
310 f
->header
->state
= STATE_ONLINE
;
319 bool journal_file_is_offlining(JournalFile
*f
) {
322 __sync_synchronize();
324 if (f
->offline_state
== OFFLINE_DONE
||
325 f
->offline_state
== OFFLINE_JOINED
)
331 JournalFile
* journal_file_close(JournalFile
*f
) {
335 /* Write the final tag */
336 if (f
->seal
&& f
->writable
)
337 journal_file_append_tag(f
);
340 if (f
->post_change_timer
) {
343 if (sd_event_source_get_enabled(f
->post_change_timer
, &enabled
) >= 0)
344 if (enabled
== SD_EVENT_ONESHOT
)
345 journal_file_post_change(f
);
347 (void) sd_event_source_set_enabled(f
->post_change_timer
, SD_EVENT_OFF
);
348 sd_event_source_unref(f
->post_change_timer
);
351 journal_file_set_offline(f
, true);
353 if (f
->mmap
&& f
->fd
>= 0)
354 mmap_cache_close_fd(f
->mmap
, f
->fd
);
356 if (f
->fd
>= 0 && f
->defrag_on_close
) {
358 /* Be friendly to btrfs: turn COW back on again now,
359 * and defragment the file. We won't write to the file
360 * ever again, hence remove all fragmentation, and
361 * reenable all the good bits COW usually provides
362 * (such as data checksumming). */
364 (void) chattr_fd(f
->fd
, 0, FS_NOCOW_FL
);
365 (void) btrfs_defrag_fd(f
->fd
);
372 mmap_cache_unref(f
->mmap
);
374 ordered_hashmap_free_free(f
->chain_cache
);
376 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
377 free(f
->compress_buffer
);
382 munmap(f
->fss_file
, PAGE_ALIGN(f
->fss_file_size
));
384 free(f
->fsprg_state
);
389 gcry_md_close(f
->hmac
);
396 void journal_file_close_set(Set
*s
) {
401 while ((f
= set_steal_first(s
)))
402 (void) journal_file_close(f
);
405 static int journal_file_init_header(JournalFile
*f
, JournalFile
*template) {
412 memcpy(h
.signature
, HEADER_SIGNATURE
, 8);
413 h
.header_size
= htole64(ALIGN64(sizeof(h
)));
415 h
.incompatible_flags
|= htole32(
416 f
->compress_xz
* HEADER_INCOMPATIBLE_COMPRESSED_XZ
|
417 f
->compress_lz4
* HEADER_INCOMPATIBLE_COMPRESSED_LZ4
);
419 h
.compatible_flags
= htole32(
420 f
->seal
* HEADER_COMPATIBLE_SEALED
);
422 r
= sd_id128_randomize(&h
.file_id
);
427 h
.seqnum_id
= template->header
->seqnum_id
;
428 h
.tail_entry_seqnum
= template->header
->tail_entry_seqnum
;
430 h
.seqnum_id
= h
.file_id
;
432 k
= pwrite(f
->fd
, &h
, sizeof(h
), 0);
442 static int journal_file_refresh_header(JournalFile
*f
) {
449 r
= sd_id128_get_machine(&f
->header
->machine_id
);
453 r
= sd_id128_get_boot(&boot_id
);
457 if (sd_id128_equal(boot_id
, f
->header
->boot_id
))
458 f
->tail_entry_monotonic_valid
= true;
460 f
->header
->boot_id
= boot_id
;
462 r
= journal_file_set_online(f
);
464 /* Sync the online state to disk */
470 static int journal_file_verify_header(JournalFile
*f
) {
476 if (memcmp(f
->header
->signature
, HEADER_SIGNATURE
, 8))
479 /* In both read and write mode we refuse to open files with
480 * incompatible flags we don't know */
481 flags
= le32toh(f
->header
->incompatible_flags
);
482 if (flags
& ~HEADER_INCOMPATIBLE_SUPPORTED
) {
483 if (flags
& ~HEADER_INCOMPATIBLE_ANY
)
484 log_debug("Journal file %s has unknown incompatible flags %"PRIx32
,
485 f
->path
, flags
& ~HEADER_INCOMPATIBLE_ANY
);
486 flags
= (flags
& HEADER_INCOMPATIBLE_ANY
) & ~HEADER_INCOMPATIBLE_SUPPORTED
;
488 log_debug("Journal file %s uses incompatible flags %"PRIx32
489 " disabled at compilation time.", f
->path
, flags
);
490 return -EPROTONOSUPPORT
;
493 /* When open for writing we refuse to open files with
494 * compatible flags, too */
495 flags
= le32toh(f
->header
->compatible_flags
);
496 if (f
->writable
&& (flags
& ~HEADER_COMPATIBLE_SUPPORTED
)) {
497 if (flags
& ~HEADER_COMPATIBLE_ANY
)
498 log_debug("Journal file %s has unknown compatible flags %"PRIx32
,
499 f
->path
, flags
& ~HEADER_COMPATIBLE_ANY
);
500 flags
= (flags
& HEADER_COMPATIBLE_ANY
) & ~HEADER_COMPATIBLE_SUPPORTED
;
502 log_debug("Journal file %s uses compatible flags %"PRIx32
503 " disabled at compilation time.", f
->path
, flags
);
504 return -EPROTONOSUPPORT
;
507 if (f
->header
->state
>= _STATE_MAX
)
510 /* The first addition was n_data, so check that we are at least this large */
511 if (le64toh(f
->header
->header_size
) < HEADER_SIZE_MIN
)
514 if (JOURNAL_HEADER_SEALED(f
->header
) && !JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
517 if ((le64toh(f
->header
->header_size
) + le64toh(f
->header
->arena_size
)) > (uint64_t) f
->last_stat
.st_size
)
520 if (le64toh(f
->header
->tail_object_offset
) > (le64toh(f
->header
->header_size
) + le64toh(f
->header
->arena_size
)))
523 if (!VALID64(le64toh(f
->header
->data_hash_table_offset
)) ||
524 !VALID64(le64toh(f
->header
->field_hash_table_offset
)) ||
525 !VALID64(le64toh(f
->header
->tail_object_offset
)) ||
526 !VALID64(le64toh(f
->header
->entry_array_offset
)))
531 sd_id128_t machine_id
;
534 r
= sd_id128_get_machine(&machine_id
);
538 if (!sd_id128_equal(machine_id
, f
->header
->machine_id
))
541 state
= f
->header
->state
;
543 if (state
== STATE_ONLINE
) {
544 log_debug("Journal file %s is already online. Assuming unclean closing.", f
->path
);
546 } else if (state
== STATE_ARCHIVED
)
548 else if (state
!= STATE_OFFLINE
) {
549 log_debug("Journal file %s has unknown state %i.", f
->path
, state
);
554 f
->compress_xz
= JOURNAL_HEADER_COMPRESSED_XZ(f
->header
);
555 f
->compress_lz4
= JOURNAL_HEADER_COMPRESSED_LZ4(f
->header
);
557 f
->seal
= JOURNAL_HEADER_SEALED(f
->header
);
562 static int journal_file_fstat(JournalFile
*f
) {
566 if (fstat(f
->fd
, &f
->last_stat
) < 0)
569 f
->last_stat_usec
= now(CLOCK_MONOTONIC
);
571 /* Refuse appending to files that are already deleted */
572 if (f
->last_stat
.st_nlink
<= 0)
578 static int journal_file_allocate(JournalFile
*f
, uint64_t offset
, uint64_t size
) {
579 uint64_t old_size
, new_size
;
585 /* We assume that this file is not sparse, and we know that
586 * for sure, since we always call posix_fallocate()
589 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
593 le64toh(f
->header
->header_size
) +
594 le64toh(f
->header
->arena_size
);
596 new_size
= PAGE_ALIGN(offset
+ size
);
597 if (new_size
< le64toh(f
->header
->header_size
))
598 new_size
= le64toh(f
->header
->header_size
);
600 if (new_size
<= old_size
) {
602 /* We already pre-allocated enough space, but before
603 * we write to it, let's check with fstat() if the
604 * file got deleted, in order make sure we don't throw
605 * away the data immediately. Don't check fstat() for
606 * all writes though, but only once ever 10s. */
608 if (f
->last_stat_usec
+ LAST_STAT_REFRESH_USEC
> now(CLOCK_MONOTONIC
))
611 return journal_file_fstat(f
);
614 /* Allocate more space. */
616 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
619 if (new_size
> f
->metrics
.min_size
&& f
->metrics
.keep_free
> 0) {
622 if (fstatvfs(f
->fd
, &svfs
) >= 0) {
625 available
= LESS_BY((uint64_t) svfs
.f_bfree
* (uint64_t) svfs
.f_bsize
, f
->metrics
.keep_free
);
627 if (new_size
- old_size
> available
)
632 /* Increase by larger blocks at once */
633 new_size
= ((new_size
+FILE_SIZE_INCREASE
-1) / FILE_SIZE_INCREASE
) * FILE_SIZE_INCREASE
;
634 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
635 new_size
= f
->metrics
.max_size
;
637 /* Note that the glibc fallocate() fallback is very
638 inefficient, hence we try to minimize the allocation area
640 r
= posix_fallocate(f
->fd
, old_size
, new_size
- old_size
);
644 f
->header
->arena_size
= htole64(new_size
- le64toh(f
->header
->header_size
));
646 return journal_file_fstat(f
);
649 static unsigned type_to_context(ObjectType type
) {
650 /* One context for each type, plus one catch-all for the rest */
651 assert_cc(_OBJECT_TYPE_MAX
<= MMAP_CACHE_MAX_CONTEXTS
);
652 assert_cc(CONTEXT_HEADER
< MMAP_CACHE_MAX_CONTEXTS
);
653 return type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
? type
: 0;
656 static int journal_file_move_to(JournalFile
*f
, ObjectType type
, bool keep_always
, uint64_t offset
, uint64_t size
, void **ret
) {
665 /* Avoid SIGBUS on invalid accesses */
666 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
) {
667 /* Hmm, out of range? Let's refresh the fstat() data
668 * first, before we trust that check. */
670 r
= journal_file_fstat(f
);
674 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
)
675 return -EADDRNOTAVAIL
;
678 return mmap_cache_get(f
->mmap
, f
->fd
, f
->prot
, type_to_context(type
), keep_always
, offset
, size
, &f
->last_stat
, ret
);
681 static uint64_t minimum_header_size(Object
*o
) {
683 static const uint64_t table
[] = {
684 [OBJECT_DATA
] = sizeof(DataObject
),
685 [OBJECT_FIELD
] = sizeof(FieldObject
),
686 [OBJECT_ENTRY
] = sizeof(EntryObject
),
687 [OBJECT_DATA_HASH_TABLE
] = sizeof(HashTableObject
),
688 [OBJECT_FIELD_HASH_TABLE
] = sizeof(HashTableObject
),
689 [OBJECT_ENTRY_ARRAY
] = sizeof(EntryArrayObject
),
690 [OBJECT_TAG
] = sizeof(TagObject
),
693 if (o
->object
.type
>= ELEMENTSOF(table
) || table
[o
->object
.type
] <= 0)
694 return sizeof(ObjectHeader
);
696 return table
[o
->object
.type
];
699 int journal_file_move_to_object(JournalFile
*f
, ObjectType type
, uint64_t offset
, Object
**ret
) {
708 /* Objects may only be located at multiple of 64 bit */
709 if (!VALID64(offset
))
712 /* Object may not be located in the file header */
713 if (offset
< le64toh(f
->header
->header_size
))
716 r
= journal_file_move_to(f
, type
, false, offset
, sizeof(ObjectHeader
), &t
);
721 s
= le64toh(o
->object
.size
);
723 if (s
< sizeof(ObjectHeader
))
726 if (o
->object
.type
<= OBJECT_UNUSED
)
729 if (s
< minimum_header_size(o
))
732 if (type
> OBJECT_UNUSED
&& o
->object
.type
!= type
)
735 if (s
> sizeof(ObjectHeader
)) {
736 r
= journal_file_move_to(f
, type
, false, offset
, s
, &t
);
747 static uint64_t journal_file_entry_seqnum(JournalFile
*f
, uint64_t *seqnum
) {
753 r
= le64toh(f
->header
->tail_entry_seqnum
) + 1;
756 /* If an external seqnum counter was passed, we update
757 * both the local and the external one, and set it to
758 * the maximum of both */
766 f
->header
->tail_entry_seqnum
= htole64(r
);
768 if (f
->header
->head_entry_seqnum
== 0)
769 f
->header
->head_entry_seqnum
= htole64(r
);
774 int journal_file_append_object(JournalFile
*f
, ObjectType type
, uint64_t size
, Object
**ret
, uint64_t *offset
) {
782 assert(type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
);
783 assert(size
>= sizeof(ObjectHeader
));
787 r
= journal_file_set_online(f
);
791 p
= le64toh(f
->header
->tail_object_offset
);
793 p
= le64toh(f
->header
->header_size
);
795 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &tail
);
799 p
+= ALIGN64(le64toh(tail
->object
.size
));
802 r
= journal_file_allocate(f
, p
, size
);
806 r
= journal_file_move_to(f
, type
, false, p
, size
, &t
);
813 o
->object
.type
= type
;
814 o
->object
.size
= htole64(size
);
816 f
->header
->tail_object_offset
= htole64(p
);
817 f
->header
->n_objects
= htole64(le64toh(f
->header
->n_objects
) + 1);
825 static int journal_file_setup_data_hash_table(JournalFile
*f
) {
833 /* We estimate that we need 1 hash table entry per 768 bytes
834 of journal file and we want to make sure we never get
835 beyond 75% fill level. Calculate the hash table size for
836 the maximum file size based on these metrics. */
838 s
= (f
->metrics
.max_size
* 4 / 768 / 3) * sizeof(HashItem
);
839 if (s
< DEFAULT_DATA_HASH_TABLE_SIZE
)
840 s
= DEFAULT_DATA_HASH_TABLE_SIZE
;
842 log_debug("Reserving %"PRIu64
" entries in hash table.", s
/ sizeof(HashItem
));
844 r
= journal_file_append_object(f
,
845 OBJECT_DATA_HASH_TABLE
,
846 offsetof(Object
, hash_table
.items
) + s
,
851 memzero(o
->hash_table
.items
, s
);
853 f
->header
->data_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
854 f
->header
->data_hash_table_size
= htole64(s
);
859 static int journal_file_setup_field_hash_table(JournalFile
*f
) {
867 /* We use a fixed size hash table for the fields as this
868 * number should grow very slowly only */
870 s
= DEFAULT_FIELD_HASH_TABLE_SIZE
;
871 r
= journal_file_append_object(f
,
872 OBJECT_FIELD_HASH_TABLE
,
873 offsetof(Object
, hash_table
.items
) + s
,
878 memzero(o
->hash_table
.items
, s
);
880 f
->header
->field_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
881 f
->header
->field_hash_table_size
= htole64(s
);
886 int journal_file_map_data_hash_table(JournalFile
*f
) {
894 if (f
->data_hash_table
)
897 p
= le64toh(f
->header
->data_hash_table_offset
);
898 s
= le64toh(f
->header
->data_hash_table_size
);
900 r
= journal_file_move_to(f
,
901 OBJECT_DATA_HASH_TABLE
,
908 f
->data_hash_table
= t
;
912 int journal_file_map_field_hash_table(JournalFile
*f
) {
920 if (f
->field_hash_table
)
923 p
= le64toh(f
->header
->field_hash_table_offset
);
924 s
= le64toh(f
->header
->field_hash_table_size
);
926 r
= journal_file_move_to(f
,
927 OBJECT_FIELD_HASH_TABLE
,
934 f
->field_hash_table
= t
;
938 static int journal_file_link_field(
949 assert(f
->field_hash_table
);
953 if (o
->object
.type
!= OBJECT_FIELD
)
956 m
= le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
);
960 /* This might alter the window we are looking at */
961 o
->field
.next_hash_offset
= o
->field
.head_data_offset
= 0;
964 p
= le64toh(f
->field_hash_table
[h
].tail_hash_offset
);
966 f
->field_hash_table
[h
].head_hash_offset
= htole64(offset
);
968 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
972 o
->field
.next_hash_offset
= htole64(offset
);
975 f
->field_hash_table
[h
].tail_hash_offset
= htole64(offset
);
977 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
978 f
->header
->n_fields
= htole64(le64toh(f
->header
->n_fields
) + 1);
983 static int journal_file_link_data(
994 assert(f
->data_hash_table
);
998 if (o
->object
.type
!= OBJECT_DATA
)
1001 m
= le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
);
1005 /* This might alter the window we are looking at */
1006 o
->data
.next_hash_offset
= o
->data
.next_field_offset
= 0;
1007 o
->data
.entry_offset
= o
->data
.entry_array_offset
= 0;
1008 o
->data
.n_entries
= 0;
1011 p
= le64toh(f
->data_hash_table
[h
].tail_hash_offset
);
1013 /* Only entry in the hash table is easy */
1014 f
->data_hash_table
[h
].head_hash_offset
= htole64(offset
);
1016 /* Move back to the previous data object, to patch in
1019 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1023 o
->data
.next_hash_offset
= htole64(offset
);
1026 f
->data_hash_table
[h
].tail_hash_offset
= htole64(offset
);
1028 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
1029 f
->header
->n_data
= htole64(le64toh(f
->header
->n_data
) + 1);
1034 int journal_file_find_field_object_with_hash(
1036 const void *field
, uint64_t size
, uint64_t hash
,
1037 Object
**ret
, uint64_t *offset
) {
1039 uint64_t p
, osize
, h
, m
;
1044 assert(field
&& size
> 0);
1046 /* If the field hash table is empty, we can't find anything */
1047 if (le64toh(f
->header
->field_hash_table_size
) <= 0)
1050 /* Map the field hash table, if it isn't mapped yet. */
1051 r
= journal_file_map_field_hash_table(f
);
1055 osize
= offsetof(Object
, field
.payload
) + size
;
1057 m
= le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
);
1062 p
= le64toh(f
->field_hash_table
[h
].head_hash_offset
);
1067 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1071 if (le64toh(o
->field
.hash
) == hash
&&
1072 le64toh(o
->object
.size
) == osize
&&
1073 memcmp(o
->field
.payload
, field
, size
) == 0) {
1083 p
= le64toh(o
->field
.next_hash_offset
);
1089 int journal_file_find_field_object(
1091 const void *field
, uint64_t size
,
1092 Object
**ret
, uint64_t *offset
) {
1097 assert(field
&& size
> 0);
1099 hash
= hash64(field
, size
);
1101 return journal_file_find_field_object_with_hash(f
,
1106 int journal_file_find_data_object_with_hash(
1108 const void *data
, uint64_t size
, uint64_t hash
,
1109 Object
**ret
, uint64_t *offset
) {
1111 uint64_t p
, osize
, h
, m
;
1116 assert(data
|| size
== 0);
1118 /* If there's no data hash table, then there's no entry. */
1119 if (le64toh(f
->header
->data_hash_table_size
) <= 0)
1122 /* Map the data hash table, if it isn't mapped yet. */
1123 r
= journal_file_map_data_hash_table(f
);
1127 osize
= offsetof(Object
, data
.payload
) + size
;
1129 m
= le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
);
1134 p
= le64toh(f
->data_hash_table
[h
].head_hash_offset
);
1139 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1143 if (le64toh(o
->data
.hash
) != hash
)
1146 if (o
->object
.flags
& OBJECT_COMPRESSION_MASK
) {
1147 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
1151 l
= le64toh(o
->object
.size
);
1152 if (l
<= offsetof(Object
, data
.payload
))
1155 l
-= offsetof(Object
, data
.payload
);
1157 r
= decompress_blob(o
->object
.flags
& OBJECT_COMPRESSION_MASK
,
1158 o
->data
.payload
, l
, &f
->compress_buffer
, &f
->compress_buffer_size
, &rsize
, 0);
1162 if (rsize
== size
&&
1163 memcmp(f
->compress_buffer
, data
, size
) == 0) {
1174 return -EPROTONOSUPPORT
;
1176 } else if (le64toh(o
->object
.size
) == osize
&&
1177 memcmp(o
->data
.payload
, data
, size
) == 0) {
1189 p
= le64toh(o
->data
.next_hash_offset
);
1195 int journal_file_find_data_object(
1197 const void *data
, uint64_t size
,
1198 Object
**ret
, uint64_t *offset
) {
1203 assert(data
|| size
== 0);
1205 hash
= hash64(data
, size
);
1207 return journal_file_find_data_object_with_hash(f
,
1212 static int journal_file_append_field(
1214 const void *field
, uint64_t size
,
1215 Object
**ret
, uint64_t *offset
) {
1223 assert(field
&& size
> 0);
1225 hash
= hash64(field
, size
);
1227 r
= journal_file_find_field_object_with_hash(f
, field
, size
, hash
, &o
, &p
);
1241 osize
= offsetof(Object
, field
.payload
) + size
;
1242 r
= journal_file_append_object(f
, OBJECT_FIELD
, osize
, &o
, &p
);
1246 o
->field
.hash
= htole64(hash
);
1247 memcpy(o
->field
.payload
, field
, size
);
1249 r
= journal_file_link_field(f
, o
, p
, hash
);
1253 /* The linking might have altered the window, so let's
1254 * refresh our pointer */
1255 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1260 r
= journal_file_hmac_put_object(f
, OBJECT_FIELD
, o
, p
);
1274 static int journal_file_append_data(
1276 const void *data
, uint64_t size
,
1277 Object
**ret
, uint64_t *offset
) {
1282 int r
, compression
= 0;
1286 assert(data
|| size
== 0);
1288 hash
= hash64(data
, size
);
1290 r
= journal_file_find_data_object_with_hash(f
, data
, size
, hash
, &o
, &p
);
1304 osize
= offsetof(Object
, data
.payload
) + size
;
1305 r
= journal_file_append_object(f
, OBJECT_DATA
, osize
, &o
, &p
);
1309 o
->data
.hash
= htole64(hash
);
1311 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
1312 if (JOURNAL_FILE_COMPRESS(f
) && size
>= COMPRESSION_SIZE_THRESHOLD
) {
1315 compression
= compress_blob(data
, size
, o
->data
.payload
, size
- 1, &rsize
);
1317 if (compression
>= 0) {
1318 o
->object
.size
= htole64(offsetof(Object
, data
.payload
) + rsize
);
1319 o
->object
.flags
|= compression
;
1321 log_debug("Compressed data object %"PRIu64
" -> %zu using %s",
1322 size
, rsize
, object_compressed_to_string(compression
));
1324 /* Compression didn't work, we don't really care why, let's continue without compression */
1329 if (compression
== 0)
1330 memcpy_safe(o
->data
.payload
, data
, size
);
1332 r
= journal_file_link_data(f
, o
, p
, hash
);
1336 /* The linking might have altered the window, so let's
1337 * refresh our pointer */
1338 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1345 eq
= memchr(data
, '=', size
);
1346 if (eq
&& eq
> data
) {
1350 /* Create field object ... */
1351 r
= journal_file_append_field(f
, data
, (uint8_t*) eq
- (uint8_t*) data
, &fo
, &fp
);
1355 /* ... and link it in. */
1356 o
->data
.next_field_offset
= fo
->field
.head_data_offset
;
1357 fo
->field
.head_data_offset
= le64toh(p
);
1361 r
= journal_file_hmac_put_object(f
, OBJECT_DATA
, o
, p
);
1375 uint64_t journal_file_entry_n_items(Object
*o
) {
1378 if (o
->object
.type
!= OBJECT_ENTRY
)
1381 return (le64toh(o
->object
.size
) - offsetof(Object
, entry
.items
)) / sizeof(EntryItem
);
1384 uint64_t journal_file_entry_array_n_items(Object
*o
) {
1387 if (o
->object
.type
!= OBJECT_ENTRY_ARRAY
)
1390 return (le64toh(o
->object
.size
) - offsetof(Object
, entry_array
.items
)) / sizeof(uint64_t);
1393 uint64_t journal_file_hash_table_n_items(Object
*o
) {
1396 if (o
->object
.type
!= OBJECT_DATA_HASH_TABLE
&&
1397 o
->object
.type
!= OBJECT_FIELD_HASH_TABLE
)
1400 return (le64toh(o
->object
.size
) - offsetof(Object
, hash_table
.items
)) / sizeof(HashItem
);
1403 static int link_entry_into_array(JournalFile
*f
,
1408 uint64_t n
= 0, ap
= 0, q
, i
, a
, hidx
;
1417 a
= le64toh(*first
);
1418 i
= hidx
= le64toh(*idx
);
1421 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
1425 n
= journal_file_entry_array_n_items(o
);
1427 o
->entry_array
.items
[i
] = htole64(p
);
1428 *idx
= htole64(hidx
+ 1);
1434 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
1445 r
= journal_file_append_object(f
, OBJECT_ENTRY_ARRAY
,
1446 offsetof(Object
, entry_array
.items
) + n
* sizeof(uint64_t),
1452 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY_ARRAY
, o
, q
);
1457 o
->entry_array
.items
[i
] = htole64(p
);
1460 *first
= htole64(q
);
1462 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, ap
, &o
);
1466 o
->entry_array
.next_entry_array_offset
= htole64(q
);
1469 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
1470 f
->header
->n_entry_arrays
= htole64(le64toh(f
->header
->n_entry_arrays
) + 1);
1472 *idx
= htole64(hidx
+ 1);
1477 static int link_entry_into_array_plus_one(JournalFile
*f
,
1492 *extra
= htole64(p
);
1496 i
= htole64(le64toh(*idx
) - 1);
1497 r
= link_entry_into_array(f
, first
, &i
, p
);
1502 *idx
= htole64(le64toh(*idx
) + 1);
1506 static int journal_file_link_entry_item(JournalFile
*f
, Object
*o
, uint64_t offset
, uint64_t i
) {
1513 p
= le64toh(o
->entry
.items
[i
].object_offset
);
1517 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1521 return link_entry_into_array_plus_one(f
,
1522 &o
->data
.entry_offset
,
1523 &o
->data
.entry_array_offset
,
1528 static int journal_file_link_entry(JournalFile
*f
, Object
*o
, uint64_t offset
) {
1537 if (o
->object
.type
!= OBJECT_ENTRY
)
1540 __sync_synchronize();
1542 /* Link up the entry itself */
1543 r
= link_entry_into_array(f
,
1544 &f
->header
->entry_array_offset
,
1545 &f
->header
->n_entries
,
1550 /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
1552 if (f
->header
->head_entry_realtime
== 0)
1553 f
->header
->head_entry_realtime
= o
->entry
.realtime
;
1555 f
->header
->tail_entry_realtime
= o
->entry
.realtime
;
1556 f
->header
->tail_entry_monotonic
= o
->entry
.monotonic
;
1558 f
->tail_entry_monotonic_valid
= true;
1560 /* Link up the items */
1561 n
= journal_file_entry_n_items(o
);
1562 for (i
= 0; i
< n
; i
++) {
1563 r
= journal_file_link_entry_item(f
, o
, offset
, i
);
1571 static int journal_file_append_entry_internal(
1573 const dual_timestamp
*ts
,
1575 const EntryItem items
[], unsigned n_items
,
1577 Object
**ret
, uint64_t *offset
) {
1585 assert(items
|| n_items
== 0);
1588 osize
= offsetof(Object
, entry
.items
) + (n_items
* sizeof(EntryItem
));
1590 r
= journal_file_append_object(f
, OBJECT_ENTRY
, osize
, &o
, &np
);
1594 o
->entry
.seqnum
= htole64(journal_file_entry_seqnum(f
, seqnum
));
1595 memcpy_safe(o
->entry
.items
, items
, n_items
* sizeof(EntryItem
));
1596 o
->entry
.realtime
= htole64(ts
->realtime
);
1597 o
->entry
.monotonic
= htole64(ts
->monotonic
);
1598 o
->entry
.xor_hash
= htole64(xor_hash
);
1599 o
->entry
.boot_id
= f
->header
->boot_id
;
1602 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY
, o
, np
);
1607 r
= journal_file_link_entry(f
, o
, np
);
1620 void journal_file_post_change(JournalFile
*f
) {
1623 /* inotify() does not receive IN_MODIFY events from file
1624 * accesses done via mmap(). After each access we hence
1625 * trigger IN_MODIFY by truncating the journal file to its
1626 * current size which triggers IN_MODIFY. */
1628 __sync_synchronize();
1630 if (ftruncate(f
->fd
, f
->last_stat
.st_size
) < 0)
1631 log_debug_errno(errno
, "Failed to truncate file to its own size: %m");
1634 static int post_change_thunk(sd_event_source
*timer
, uint64_t usec
, void *userdata
) {
1637 journal_file_post_change(userdata
);
1642 static void schedule_post_change(JournalFile
*f
) {
1643 sd_event_source
*timer
;
1648 assert(f
->post_change_timer
);
1650 timer
= f
->post_change_timer
;
1652 r
= sd_event_source_get_enabled(timer
, &enabled
);
1654 log_debug_errno(r
, "Failed to get ftruncate timer state: %m");
1658 if (enabled
== SD_EVENT_ONESHOT
)
1661 r
= sd_event_now(sd_event_source_get_event(timer
), CLOCK_MONOTONIC
, &now
);
1663 log_debug_errno(r
, "Failed to get clock's now for scheduling ftruncate: %m");
1667 r
= sd_event_source_set_time(timer
, now
+f
->post_change_timer_period
);
1669 log_debug_errno(r
, "Failed to set time for scheduling ftruncate: %m");
1673 r
= sd_event_source_set_enabled(timer
, SD_EVENT_ONESHOT
);
1675 log_debug_errno(r
, "Failed to enable scheduled ftruncate: %m");
1682 /* On failure, let's simply post the change immediately. */
1683 journal_file_post_change(f
);
1686 /* Enable coalesced change posting in a timer on the provided sd_event instance */
1687 int journal_file_enable_post_change_timer(JournalFile
*f
, sd_event
*e
, usec_t t
) {
1688 _cleanup_(sd_event_source_unrefp
) sd_event_source
*timer
= NULL
;
1692 assert_return(!f
->post_change_timer
, -EINVAL
);
1696 r
= sd_event_add_time(e
, &timer
, CLOCK_MONOTONIC
, 0, 0, post_change_thunk
, f
);
1700 r
= sd_event_source_set_enabled(timer
, SD_EVENT_OFF
);
1704 f
->post_change_timer
= timer
;
1706 f
->post_change_timer_period
= t
;
1711 static int entry_item_cmp(const void *_a
, const void *_b
) {
1712 const EntryItem
*a
= _a
, *b
= _b
;
1714 if (le64toh(a
->object_offset
) < le64toh(b
->object_offset
))
1716 if (le64toh(a
->object_offset
) > le64toh(b
->object_offset
))
1721 int journal_file_append_entry(JournalFile
*f
, const dual_timestamp
*ts
, const struct iovec iovec
[], unsigned n_iovec
, uint64_t *seqnum
, Object
**ret
, uint64_t *offset
) {
1725 uint64_t xor_hash
= 0;
1726 struct dual_timestamp _ts
;
1730 assert(iovec
|| n_iovec
== 0);
1733 dual_timestamp_get(&_ts
);
1738 r
= journal_file_maybe_append_tag(f
, ts
->realtime
);
1743 /* alloca() can't take 0, hence let's allocate at least one */
1744 items
= alloca(sizeof(EntryItem
) * MAX(1u, n_iovec
));
1746 for (i
= 0; i
< n_iovec
; i
++) {
1750 r
= journal_file_append_data(f
, iovec
[i
].iov_base
, iovec
[i
].iov_len
, &o
, &p
);
1754 xor_hash
^= le64toh(o
->data
.hash
);
1755 items
[i
].object_offset
= htole64(p
);
1756 items
[i
].hash
= o
->data
.hash
;
1759 /* Order by the position on disk, in order to improve seek
1760 * times for rotating media. */
1761 qsort_safe(items
, n_iovec
, sizeof(EntryItem
), entry_item_cmp
);
1763 r
= journal_file_append_entry_internal(f
, ts
, xor_hash
, items
, n_iovec
, seqnum
, ret
, offset
);
1765 /* If the memory mapping triggered a SIGBUS then we return an
1766 * IO error and ignore the error code passed down to us, since
1767 * it is very likely just an effect of a nullified replacement
1770 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
1773 if (f
->post_change_timer
)
1774 schedule_post_change(f
);
1776 journal_file_post_change(f
);
1781 typedef struct ChainCacheItem
{
1782 uint64_t first
; /* the array at the beginning of the chain */
1783 uint64_t array
; /* the cached array */
1784 uint64_t begin
; /* the first item in the cached array */
1785 uint64_t total
; /* the total number of items in all arrays before this one in the chain */
1786 uint64_t last_index
; /* the last index we looked at, to optimize locality when bisecting */
1789 static void chain_cache_put(
1796 uint64_t last_index
) {
1799 /* If the chain item to cache for this chain is the
1800 * first one it's not worth caching anything */
1804 if (ordered_hashmap_size(h
) >= CHAIN_CACHE_MAX
) {
1805 ci
= ordered_hashmap_steal_first(h
);
1808 ci
= new(ChainCacheItem
, 1);
1815 if (ordered_hashmap_put(h
, &ci
->first
, ci
) < 0) {
1820 assert(ci
->first
== first
);
1825 ci
->last_index
= last_index
;
1828 static int generic_array_get(
1832 Object
**ret
, uint64_t *offset
) {
1835 uint64_t p
= 0, a
, t
= 0;
1843 /* Try the chain cache first */
1844 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
1845 if (ci
&& i
> ci
->total
) {
1854 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
1858 k
= journal_file_entry_array_n_items(o
);
1860 p
= le64toh(o
->entry_array
.items
[i
]);
1866 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
1872 /* Let's cache this item for the next invocation */
1873 chain_cache_put(f
->chain_cache
, ci
, first
, a
, le64toh(o
->entry_array
.items
[0]), t
, i
);
1875 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
1888 static int generic_array_get_plus_one(
1893 Object
**ret
, uint64_t *offset
) {
1902 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, &o
);
1915 return generic_array_get(f
, first
, i
-1, ret
, offset
);
1924 static int generic_array_bisect(
1929 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
1930 direction_t direction
,
1935 uint64_t a
, p
, t
= 0, i
= 0, last_p
= 0, last_index
= (uint64_t) -1;
1936 bool subtract_one
= false;
1937 Object
*o
, *array
= NULL
;
1942 assert(test_object
);
1944 /* Start with the first array in the chain */
1947 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
1948 if (ci
&& n
> ci
->total
) {
1949 /* Ah, we have iterated this bisection array chain
1950 * previously! Let's see if we can skip ahead in the
1951 * chain, as far as the last time. But we can't jump
1952 * backwards in the chain, so let's check that
1955 r
= test_object(f
, ci
->begin
, needle
);
1959 if (r
== TEST_LEFT
) {
1960 /* OK, what we are looking for is right of the
1961 * begin of this EntryArray, so let's jump
1962 * straight to previously cached array in the
1968 last_index
= ci
->last_index
;
1973 uint64_t left
, right
, k
, lp
;
1975 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &array
);
1979 k
= journal_file_entry_array_n_items(array
);
1985 lp
= p
= le64toh(array
->entry_array
.items
[i
]);
1989 r
= test_object(f
, p
, needle
);
1990 if (r
== -EBADMSG
) {
1991 log_debug_errno(r
, "Encountered invalid entry while bisecting, cutting algorithm short. (1)");
1998 if (r
== TEST_FOUND
)
1999 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2001 if (r
== TEST_RIGHT
) {
2005 if (last_index
!= (uint64_t) -1) {
2006 assert(last_index
<= right
);
2008 /* If we cached the last index we
2009 * looked at, let's try to not to jump
2010 * too wildly around and see if we can
2011 * limit the range to look at early to
2012 * the immediate neighbors of the last
2013 * index we looked at. */
2015 if (last_index
> 0) {
2016 uint64_t x
= last_index
- 1;
2018 p
= le64toh(array
->entry_array
.items
[x
]);
2022 r
= test_object(f
, p
, needle
);
2026 if (r
== TEST_FOUND
)
2027 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2029 if (r
== TEST_RIGHT
)
2035 if (last_index
< right
) {
2036 uint64_t y
= last_index
+ 1;
2038 p
= le64toh(array
->entry_array
.items
[y
]);
2042 r
= test_object(f
, p
, needle
);
2046 if (r
== TEST_FOUND
)
2047 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2049 if (r
== TEST_RIGHT
)
2057 if (left
== right
) {
2058 if (direction
== DIRECTION_UP
)
2059 subtract_one
= true;
2065 assert(left
< right
);
2066 i
= (left
+ right
) / 2;
2068 p
= le64toh(array
->entry_array
.items
[i
]);
2072 r
= test_object(f
, p
, needle
);
2073 if (r
== -EBADMSG
) {
2074 log_debug_errno(r
, "Encountered invalid entry while bisecting, cutting algorithm short. (2)");
2081 if (r
== TEST_FOUND
)
2082 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2084 if (r
== TEST_RIGHT
)
2092 if (direction
== DIRECTION_UP
) {
2094 subtract_one
= true;
2105 last_index
= (uint64_t) -1;
2106 a
= le64toh(array
->entry_array
.next_entry_array_offset
);
2112 if (subtract_one
&& t
== 0 && i
== 0)
2115 /* Let's cache this item for the next invocation */
2116 chain_cache_put(f
->chain_cache
, ci
, first
, a
, le64toh(array
->entry_array
.items
[0]), t
, subtract_one
? (i
> 0 ? i
-1 : (uint64_t) -1) : i
);
2118 if (subtract_one
&& i
== 0)
2120 else if (subtract_one
)
2121 p
= le64toh(array
->entry_array
.items
[i
-1]);
2123 p
= le64toh(array
->entry_array
.items
[i
]);
2125 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2136 *idx
= t
+ i
+ (subtract_one
? -1 : 0);
2141 static int generic_array_bisect_plus_one(
2147 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
2148 direction_t direction
,
2154 bool step_back
= false;
2158 assert(test_object
);
2163 /* This bisects the array in object 'first', but first checks
2165 r
= test_object(f
, extra
, needle
);
2169 if (r
== TEST_FOUND
)
2170 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2172 /* if we are looking with DIRECTION_UP then we need to first
2173 see if in the actual array there is a matching entry, and
2174 return the last one of that. But if there isn't any we need
2175 to return this one. Hence remember this, and return it
2178 step_back
= direction
== DIRECTION_UP
;
2180 if (r
== TEST_RIGHT
) {
2181 if (direction
== DIRECTION_DOWN
)
2187 r
= generic_array_bisect(f
, first
, n
-1, needle
, test_object
, direction
, ret
, offset
, idx
);
2189 if (r
== 0 && step_back
)
2198 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, &o
);
2214 _pure_
static int test_object_offset(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2220 else if (p
< needle
)
2226 static int test_object_seqnum(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2233 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2237 if (le64toh(o
->entry
.seqnum
) == needle
)
2239 else if (le64toh(o
->entry
.seqnum
) < needle
)
2245 int journal_file_move_to_entry_by_seqnum(
2248 direction_t direction
,
2254 return generic_array_bisect(f
,
2255 le64toh(f
->header
->entry_array_offset
),
2256 le64toh(f
->header
->n_entries
),
2263 static int test_object_realtime(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2270 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2274 if (le64toh(o
->entry
.realtime
) == needle
)
2276 else if (le64toh(o
->entry
.realtime
) < needle
)
2282 int journal_file_move_to_entry_by_realtime(
2285 direction_t direction
,
2291 return generic_array_bisect(f
,
2292 le64toh(f
->header
->entry_array_offset
),
2293 le64toh(f
->header
->n_entries
),
2295 test_object_realtime
,
2300 static int test_object_monotonic(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2307 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2311 if (le64toh(o
->entry
.monotonic
) == needle
)
2313 else if (le64toh(o
->entry
.monotonic
) < needle
)
2319 static int find_data_object_by_boot_id(
2325 char t
[sizeof("_BOOT_ID=")-1 + 32 + 1] = "_BOOT_ID=";
2327 sd_id128_to_string(boot_id
, t
+ 9);
2328 return journal_file_find_data_object(f
, t
, sizeof(t
) - 1, o
, b
);
2331 int journal_file_move_to_entry_by_monotonic(
2335 direction_t direction
,
2344 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, NULL
);
2350 return generic_array_bisect_plus_one(f
,
2351 le64toh(o
->data
.entry_offset
),
2352 le64toh(o
->data
.entry_array_offset
),
2353 le64toh(o
->data
.n_entries
),
2355 test_object_monotonic
,
2360 void journal_file_reset_location(JournalFile
*f
) {
2361 f
->location_type
= LOCATION_HEAD
;
2362 f
->current_offset
= 0;
2363 f
->current_seqnum
= 0;
2364 f
->current_realtime
= 0;
2365 f
->current_monotonic
= 0;
2366 zero(f
->current_boot_id
);
2367 f
->current_xor_hash
= 0;
2370 void journal_file_save_location(JournalFile
*f
, Object
*o
, uint64_t offset
) {
2371 f
->location_type
= LOCATION_SEEK
;
2372 f
->current_offset
= offset
;
2373 f
->current_seqnum
= le64toh(o
->entry
.seqnum
);
2374 f
->current_realtime
= le64toh(o
->entry
.realtime
);
2375 f
->current_monotonic
= le64toh(o
->entry
.monotonic
);
2376 f
->current_boot_id
= o
->entry
.boot_id
;
2377 f
->current_xor_hash
= le64toh(o
->entry
.xor_hash
);
2380 int journal_file_compare_locations(JournalFile
*af
, JournalFile
*bf
) {
2385 assert(af
->location_type
== LOCATION_SEEK
);
2386 assert(bf
->location_type
== LOCATION_SEEK
);
2388 /* If contents and timestamps match, these entries are
2389 * identical, even if the seqnum does not match */
2390 if (sd_id128_equal(af
->current_boot_id
, bf
->current_boot_id
) &&
2391 af
->current_monotonic
== bf
->current_monotonic
&&
2392 af
->current_realtime
== bf
->current_realtime
&&
2393 af
->current_xor_hash
== bf
->current_xor_hash
)
2396 if (sd_id128_equal(af
->header
->seqnum_id
, bf
->header
->seqnum_id
)) {
2398 /* If this is from the same seqnum source, compare
2400 if (af
->current_seqnum
< bf
->current_seqnum
)
2402 if (af
->current_seqnum
> bf
->current_seqnum
)
2405 /* Wow! This is weird, different data but the same
2406 * seqnums? Something is borked, but let's make the
2407 * best of it and compare by time. */
2410 if (sd_id128_equal(af
->current_boot_id
, bf
->current_boot_id
)) {
2412 /* If the boot id matches, compare monotonic time */
2413 if (af
->current_monotonic
< bf
->current_monotonic
)
2415 if (af
->current_monotonic
> bf
->current_monotonic
)
2419 /* Otherwise, compare UTC time */
2420 if (af
->current_realtime
< bf
->current_realtime
)
2422 if (af
->current_realtime
> bf
->current_realtime
)
2425 /* Finally, compare by contents */
2426 if (af
->current_xor_hash
< bf
->current_xor_hash
)
2428 if (af
->current_xor_hash
> bf
->current_xor_hash
)
2434 int journal_file_next_entry(
2437 direction_t direction
,
2438 Object
**ret
, uint64_t *offset
) {
2446 n
= le64toh(f
->header
->n_entries
);
2451 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
2453 r
= generic_array_bisect(f
,
2454 le64toh(f
->header
->entry_array_offset
),
2455 le64toh(f
->header
->n_entries
),
2464 if (direction
== DIRECTION_DOWN
) {
2477 /* And jump to it */
2478 r
= generic_array_get(f
,
2479 le64toh(f
->header
->entry_array_offset
),
2482 if (r
== -EBADMSG
&& direction
== DIRECTION_DOWN
) {
2483 /* Special case: when we iterate throught the journal file linearly, and hit an entry we can't read,
2484 * consider this the end of the journal file. */
2485 log_debug_errno(r
, "Encountered entry we can't read while iterating through journal file. Considering this the end of the file.");
2492 (direction
== DIRECTION_DOWN
? ofs
<= p
: ofs
>= p
)) {
2493 log_debug("%s: entry array corrupted at entry %" PRIu64
, f
->path
, i
);
2503 int journal_file_next_entry_for_data(
2505 Object
*o
, uint64_t p
,
2506 uint64_t data_offset
,
2507 direction_t direction
,
2508 Object
**ret
, uint64_t *offset
) {
2515 assert(p
> 0 || !o
);
2517 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2521 n
= le64toh(d
->data
.n_entries
);
2526 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
2528 if (o
->object
.type
!= OBJECT_ENTRY
)
2531 r
= generic_array_bisect_plus_one(f
,
2532 le64toh(d
->data
.entry_offset
),
2533 le64toh(d
->data
.entry_array_offset
),
2534 le64toh(d
->data
.n_entries
),
2544 if (direction
== DIRECTION_DOWN
) {
2558 return generic_array_get_plus_one(f
,
2559 le64toh(d
->data
.entry_offset
),
2560 le64toh(d
->data
.entry_array_offset
),
2565 int journal_file_move_to_entry_by_offset_for_data(
2567 uint64_t data_offset
,
2569 direction_t direction
,
2570 Object
**ret
, uint64_t *offset
) {
2577 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2581 return generic_array_bisect_plus_one(f
,
2582 le64toh(d
->data
.entry_offset
),
2583 le64toh(d
->data
.entry_array_offset
),
2584 le64toh(d
->data
.n_entries
),
2591 int journal_file_move_to_entry_by_monotonic_for_data(
2593 uint64_t data_offset
,
2596 direction_t direction
,
2597 Object
**ret
, uint64_t *offset
) {
2605 /* First, seek by time */
2606 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &b
);
2612 r
= generic_array_bisect_plus_one(f
,
2613 le64toh(o
->data
.entry_offset
),
2614 le64toh(o
->data
.entry_array_offset
),
2615 le64toh(o
->data
.n_entries
),
2617 test_object_monotonic
,
2623 /* And now, continue seeking until we find an entry that
2624 * exists in both bisection arrays */
2630 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2634 r
= generic_array_bisect_plus_one(f
,
2635 le64toh(d
->data
.entry_offset
),
2636 le64toh(d
->data
.entry_array_offset
),
2637 le64toh(d
->data
.n_entries
),
2645 r
= journal_file_move_to_object(f
, OBJECT_DATA
, b
, &o
);
2649 r
= generic_array_bisect_plus_one(f
,
2650 le64toh(o
->data
.entry_offset
),
2651 le64toh(o
->data
.entry_array_offset
),
2652 le64toh(o
->data
.n_entries
),
2674 int journal_file_move_to_entry_by_seqnum_for_data(
2676 uint64_t data_offset
,
2678 direction_t direction
,
2679 Object
**ret
, uint64_t *offset
) {
2686 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2690 return generic_array_bisect_plus_one(f
,
2691 le64toh(d
->data
.entry_offset
),
2692 le64toh(d
->data
.entry_array_offset
),
2693 le64toh(d
->data
.n_entries
),
2700 int journal_file_move_to_entry_by_realtime_for_data(
2702 uint64_t data_offset
,
2704 direction_t direction
,
2705 Object
**ret
, uint64_t *offset
) {
2712 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2716 return generic_array_bisect_plus_one(f
,
2717 le64toh(d
->data
.entry_offset
),
2718 le64toh(d
->data
.entry_array_offset
),
2719 le64toh(d
->data
.n_entries
),
2721 test_object_realtime
,
2726 void journal_file_dump(JournalFile
*f
) {
2734 journal_file_print_header(f
);
2736 p
= le64toh(f
->header
->header_size
);
2738 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &o
);
2742 switch (o
->object
.type
) {
2745 printf("Type: OBJECT_UNUSED\n");
2749 printf("Type: OBJECT_DATA\n");
2753 printf("Type: OBJECT_FIELD\n");
2757 printf("Type: OBJECT_ENTRY seqnum=%"PRIu64
" monotonic=%"PRIu64
" realtime=%"PRIu64
"\n",
2758 le64toh(o
->entry
.seqnum
),
2759 le64toh(o
->entry
.monotonic
),
2760 le64toh(o
->entry
.realtime
));
2763 case OBJECT_FIELD_HASH_TABLE
:
2764 printf("Type: OBJECT_FIELD_HASH_TABLE\n");
2767 case OBJECT_DATA_HASH_TABLE
:
2768 printf("Type: OBJECT_DATA_HASH_TABLE\n");
2771 case OBJECT_ENTRY_ARRAY
:
2772 printf("Type: OBJECT_ENTRY_ARRAY\n");
2776 printf("Type: OBJECT_TAG seqnum=%"PRIu64
" epoch=%"PRIu64
"\n",
2777 le64toh(o
->tag
.seqnum
),
2778 le64toh(o
->tag
.epoch
));
2782 printf("Type: unknown (%i)\n", o
->object
.type
);
2786 if (o
->object
.flags
& OBJECT_COMPRESSION_MASK
)
2787 printf("Flags: %s\n",
2788 object_compressed_to_string(o
->object
.flags
& OBJECT_COMPRESSION_MASK
));
2790 if (p
== le64toh(f
->header
->tail_object_offset
))
2793 p
= p
+ ALIGN64(le64toh(o
->object
.size
));
2798 log_error("File corrupt");
2801 static const char* format_timestamp_safe(char *buf
, size_t l
, usec_t t
) {
2804 x
= format_timestamp(buf
, l
, t
);
2810 void journal_file_print_header(JournalFile
*f
) {
2811 char a
[33], b
[33], c
[33], d
[33];
2812 char x
[FORMAT_TIMESTAMP_MAX
], y
[FORMAT_TIMESTAMP_MAX
], z
[FORMAT_TIMESTAMP_MAX
];
2814 char bytes
[FORMAT_BYTES_MAX
];
2819 printf("File Path: %s\n"
2823 "Sequential Number ID: %s\n"
2825 "Compatible Flags:%s%s\n"
2826 "Incompatible Flags:%s%s%s\n"
2827 "Header size: %"PRIu64
"\n"
2828 "Arena size: %"PRIu64
"\n"
2829 "Data Hash Table Size: %"PRIu64
"\n"
2830 "Field Hash Table Size: %"PRIu64
"\n"
2831 "Rotate Suggested: %s\n"
2832 "Head Sequential Number: %"PRIu64
" (%"PRIx64
")\n"
2833 "Tail Sequential Number: %"PRIu64
" (%"PRIx64
")\n"
2834 "Head Realtime Timestamp: %s (%"PRIx64
")\n"
2835 "Tail Realtime Timestamp: %s (%"PRIx64
")\n"
2836 "Tail Monotonic Timestamp: %s (%"PRIx64
")\n"
2837 "Objects: %"PRIu64
"\n"
2838 "Entry Objects: %"PRIu64
"\n",
2840 sd_id128_to_string(f
->header
->file_id
, a
),
2841 sd_id128_to_string(f
->header
->machine_id
, b
),
2842 sd_id128_to_string(f
->header
->boot_id
, c
),
2843 sd_id128_to_string(f
->header
->seqnum_id
, d
),
2844 f
->header
->state
== STATE_OFFLINE
? "OFFLINE" :
2845 f
->header
->state
== STATE_ONLINE
? "ONLINE" :
2846 f
->header
->state
== STATE_ARCHIVED
? "ARCHIVED" : "UNKNOWN",
2847 JOURNAL_HEADER_SEALED(f
->header
) ? " SEALED" : "",
2848 (le32toh(f
->header
->compatible_flags
) & ~HEADER_COMPATIBLE_ANY
) ? " ???" : "",
2849 JOURNAL_HEADER_COMPRESSED_XZ(f
->header
) ? " COMPRESSED-XZ" : "",
2850 JOURNAL_HEADER_COMPRESSED_LZ4(f
->header
) ? " COMPRESSED-LZ4" : "",
2851 (le32toh(f
->header
->incompatible_flags
) & ~HEADER_INCOMPATIBLE_ANY
) ? " ???" : "",
2852 le64toh(f
->header
->header_size
),
2853 le64toh(f
->header
->arena_size
),
2854 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
2855 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
),
2856 yes_no(journal_file_rotate_suggested(f
, 0)),
2857 le64toh(f
->header
->head_entry_seqnum
), le64toh(f
->header
->head_entry_seqnum
),
2858 le64toh(f
->header
->tail_entry_seqnum
), le64toh(f
->header
->tail_entry_seqnum
),
2859 format_timestamp_safe(x
, sizeof(x
), le64toh(f
->header
->head_entry_realtime
)), le64toh(f
->header
->head_entry_realtime
),
2860 format_timestamp_safe(y
, sizeof(y
), le64toh(f
->header
->tail_entry_realtime
)), le64toh(f
->header
->tail_entry_realtime
),
2861 format_timespan(z
, sizeof(z
), le64toh(f
->header
->tail_entry_monotonic
), USEC_PER_MSEC
), le64toh(f
->header
->tail_entry_monotonic
),
2862 le64toh(f
->header
->n_objects
),
2863 le64toh(f
->header
->n_entries
));
2865 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
2866 printf("Data Objects: %"PRIu64
"\n"
2867 "Data Hash Table Fill: %.1f%%\n",
2868 le64toh(f
->header
->n_data
),
2869 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))));
2871 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
2872 printf("Field Objects: %"PRIu64
"\n"
2873 "Field Hash Table Fill: %.1f%%\n",
2874 le64toh(f
->header
->n_fields
),
2875 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))));
2877 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_tags
))
2878 printf("Tag Objects: %"PRIu64
"\n",
2879 le64toh(f
->header
->n_tags
));
2880 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
2881 printf("Entry Array Objects: %"PRIu64
"\n",
2882 le64toh(f
->header
->n_entry_arrays
));
2884 if (fstat(f
->fd
, &st
) >= 0)
2885 printf("Disk usage: %s\n", format_bytes(bytes
, sizeof(bytes
), (uint64_t) st
.st_blocks
* 512ULL));
2888 static int journal_file_warn_btrfs(JournalFile
*f
) {
2894 /* Before we write anything, check if the COW logic is turned
2895 * off on btrfs. Given our write pattern that is quite
2896 * unfriendly to COW file systems this should greatly improve
2897 * performance on COW file systems, such as btrfs, at the
2898 * expense of data integrity features (which shouldn't be too
2899 * bad, given that we do our own checksumming). */
2901 r
= btrfs_is_filesystem(f
->fd
);
2903 return log_warning_errno(r
, "Failed to determine if journal is on btrfs: %m");
2907 r
= read_attr_fd(f
->fd
, &attrs
);
2909 return log_warning_errno(r
, "Failed to read file attributes: %m");
2911 if (attrs
& FS_NOCOW_FL
) {
2912 log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
2916 log_notice("Creating journal file %s on a btrfs file system, and copy-on-write is enabled. "
2917 "This is likely to slow down journal access substantially, please consider turning "
2918 "off the copy-on-write file attribute on the journal directory, using chattr +C.", f
->path
);
2923 int journal_file_open(
2930 JournalMetrics
*metrics
,
2931 MMapCache
*mmap_cache
,
2932 Set
*deferred_closes
,
2933 JournalFile
*template,
2934 JournalFile
**ret
) {
2936 bool newly_created
= false;
2942 assert(fd
>= 0 || fname
);
2944 if ((flags
& O_ACCMODE
) != O_RDONLY
&&
2945 (flags
& O_ACCMODE
) != O_RDWR
)
2949 if (!endswith(fname
, ".journal") &&
2950 !endswith(fname
, ".journal~"))
2954 f
= new0(JournalFile
, 1);
2962 f
->prot
= prot_from_flags(flags
);
2963 f
->writable
= (flags
& O_ACCMODE
) != O_RDONLY
;
2964 #if defined(HAVE_LZ4)
2965 f
->compress_lz4
= compress
;
2966 #elif defined(HAVE_XZ)
2967 f
->compress_xz
= compress
;
2974 f
->mmap
= mmap_cache_ref(mmap_cache
);
2976 f
->mmap
= mmap_cache_new();
2984 f
->path
= strdup(fname
);
2985 else /* If we don't know the path, fill in something explanatory and vaguely useful */
2986 asprintf(&f
->path
, "/proc/self/%i", fd
);
2992 f
->chain_cache
= ordered_hashmap_new(&uint64_hash_ops
);
2993 if (!f
->chain_cache
) {
2999 f
->fd
= open(f
->path
, f
->flags
|O_CLOEXEC
, f
->mode
);
3005 /* fds we opened here by us should also be closed by us. */
3009 r
= journal_file_fstat(f
);
3013 if (f
->last_stat
.st_size
== 0 && f
->writable
) {
3015 (void) journal_file_warn_btrfs(f
);
3017 /* Let's attach the creation time to the journal file,
3018 * so that the vacuuming code knows the age of this
3019 * file even if the file might end up corrupted one
3020 * day... Ideally we'd just use the creation time many
3021 * file systems maintain for each file, but there is
3022 * currently no usable API to query this, hence let's
3023 * emulate this via extended attributes. If extended
3024 * attributes are not supported we'll just skip this,
3025 * and rely solely on mtime/atime/ctime of the file. */
3027 fd_setcrtime(f
->fd
, 0);
3030 /* Try to load the FSPRG state, and if we can't, then
3031 * just don't do sealing */
3033 r
= journal_file_fss_load(f
);
3039 r
= journal_file_init_header(f
, template);
3043 r
= journal_file_fstat(f
);
3047 newly_created
= true;
3050 if (f
->last_stat
.st_size
< (off_t
) HEADER_SIZE_MIN
) {
3055 r
= mmap_cache_get(f
->mmap
, f
->fd
, f
->prot
, CONTEXT_HEADER
, true, 0, PAGE_ALIGN(sizeof(Header
)), &f
->last_stat
, &h
);
3061 if (!newly_created
) {
3062 if (deferred_closes
)
3063 journal_file_close_set(deferred_closes
);
3065 r
= journal_file_verify_header(f
);
3071 if (!newly_created
&& f
->writable
) {
3072 r
= journal_file_fss_load(f
);
3080 journal_default_metrics(metrics
, f
->fd
);
3081 f
->metrics
= *metrics
;
3082 } else if (template)
3083 f
->metrics
= template->metrics
;
3085 r
= journal_file_refresh_header(f
);
3091 r
= journal_file_hmac_setup(f
);
3096 if (newly_created
) {
3097 r
= journal_file_setup_field_hash_table(f
);
3101 r
= journal_file_setup_data_hash_table(f
);
3106 r
= journal_file_append_first_tag(f
);
3112 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
)) {
3117 if (template && template->post_change_timer
) {
3118 r
= journal_file_enable_post_change_timer(
3120 sd_event_source_get_event(template->post_change_timer
),
3121 template->post_change_timer_period
);
3127 /* The file is opened now successfully, thus we take possesion of any passed in fd. */
3134 if (f
->fd
>= 0 && mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
3137 (void) journal_file_close(f
);
3142 int journal_file_rotate(JournalFile
**f
, bool compress
, bool seal
, Set
*deferred_closes
) {
3143 _cleanup_free_
char *p
= NULL
;
3145 JournalFile
*old_file
, *new_file
= NULL
;
3153 if (!old_file
->writable
)
3156 /* Is this a journal file that was passed to us as fd? If so, we synthesized a path name for it, and we refuse
3157 * rotation, since we don't know the actual path, and couldn't rename the file hence.*/
3158 if (path_startswith(old_file
->path
, "/proc/self/fd"))
3161 if (!endswith(old_file
->path
, ".journal"))
3164 l
= strlen(old_file
->path
);
3165 r
= asprintf(&p
, "%.*s@" SD_ID128_FORMAT_STR
"-%016"PRIx64
"-%016"PRIx64
".journal",
3166 (int) l
- 8, old_file
->path
,
3167 SD_ID128_FORMAT_VAL(old_file
->header
->seqnum_id
),
3168 le64toh((*f
)->header
->head_entry_seqnum
),
3169 le64toh((*f
)->header
->head_entry_realtime
));
3173 /* Try to rename the file to the archived version. If the file
3174 * already was deleted, we'll get ENOENT, let's ignore that
3176 r
= rename(old_file
->path
, p
);
3177 if (r
< 0 && errno
!= ENOENT
)
3180 /* Set as archive so offlining commits w/state=STATE_ARCHIVED.
3181 * Previously we would set old_file->header->state to STATE_ARCHIVED directly here,
3182 * but journal_file_set_offline() short-circuits when state != STATE_ONLINE, which
3183 * would result in the rotated journal never getting fsync() called before closing.
3184 * Now we simply queue the archive state by setting an archive bit, leaving the state
3185 * as STATE_ONLINE so proper offlining occurs. */
3186 old_file
->archive
= true;
3188 /* Currently, btrfs is not very good with out write patterns
3189 * and fragments heavily. Let's defrag our journal files when
3190 * we archive them */
3191 old_file
->defrag_on_close
= true;
3193 r
= journal_file_open(-1, old_file
->path
, old_file
->flags
, old_file
->mode
, compress
, seal
, NULL
, old_file
->mmap
, deferred_closes
, old_file
, &new_file
);
3195 if (deferred_closes
&&
3196 set_put(deferred_closes
, old_file
) >= 0)
3197 (void) journal_file_set_offline(old_file
, false);
3199 (void) journal_file_close(old_file
);
3205 int journal_file_open_reliably(
3211 JournalMetrics
*metrics
,
3212 MMapCache
*mmap_cache
,
3213 Set
*deferred_closes
,
3214 JournalFile
*template,
3215 JournalFile
**ret
) {
3219 _cleanup_free_
char *p
= NULL
;
3221 r
= journal_file_open(-1, fname
, flags
, mode
, compress
, seal
, metrics
, mmap_cache
, deferred_closes
, template, ret
);
3223 -EBADMSG
, /* corrupted */
3224 -ENODATA
, /* truncated */
3225 -EHOSTDOWN
, /* other machine */
3226 -EPROTONOSUPPORT
, /* incompatible feature */
3227 -EBUSY
, /* unclean shutdown */
3228 -ESHUTDOWN
, /* already archived */
3229 -EIO
, /* IO error, including SIGBUS on mmap */
3230 -EIDRM
/* File has been deleted */))
3233 if ((flags
& O_ACCMODE
) == O_RDONLY
)
3236 if (!(flags
& O_CREAT
))
3239 if (!endswith(fname
, ".journal"))
3242 /* The file is corrupted. Rotate it away and try it again (but only once) */
3245 if (asprintf(&p
, "%.*s@%016"PRIx64
"-%016"PRIx64
".journal~",
3247 now(CLOCK_REALTIME
),
3251 if (rename(fname
, p
) < 0)
3254 /* btrfs doesn't cope well with our write pattern and
3255 * fragments heavily. Let's defrag all files we rotate */
3257 (void) chattr_path(p
, false, FS_NOCOW_FL
);
3258 (void) btrfs_defrag(p
);
3260 log_warning_errno(r
, "File %s corrupted or uncleanly shut down, renaming and replacing.", fname
);
3262 return journal_file_open(-1, fname
, flags
, mode
, compress
, seal
, metrics
, mmap_cache
, deferred_closes
, template, ret
);
3265 int journal_file_copy_entry(JournalFile
*from
, JournalFile
*to
, Object
*o
, uint64_t p
, uint64_t *seqnum
, Object
**ret
, uint64_t *offset
) {
3267 uint64_t q
, xor_hash
= 0;
3280 ts
.monotonic
= le64toh(o
->entry
.monotonic
);
3281 ts
.realtime
= le64toh(o
->entry
.realtime
);
3283 n
= journal_file_entry_n_items(o
);
3284 /* alloca() can't take 0, hence let's allocate at least one */
3285 items
= alloca(sizeof(EntryItem
) * MAX(1u, n
));
3287 for (i
= 0; i
< n
; i
++) {
3294 q
= le64toh(o
->entry
.items
[i
].object_offset
);
3295 le_hash
= o
->entry
.items
[i
].hash
;
3297 r
= journal_file_move_to_object(from
, OBJECT_DATA
, q
, &o
);
3301 if (le_hash
!= o
->data
.hash
)
3304 l
= le64toh(o
->object
.size
) - offsetof(Object
, data
.payload
);
3307 /* We hit the limit on 32bit machines */
3308 if ((uint64_t) t
!= l
)
3311 if (o
->object
.flags
& OBJECT_COMPRESSION_MASK
) {
3312 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
3315 r
= decompress_blob(o
->object
.flags
& OBJECT_COMPRESSION_MASK
,
3316 o
->data
.payload
, l
, &from
->compress_buffer
, &from
->compress_buffer_size
, &rsize
, 0);
3320 data
= from
->compress_buffer
;
3323 return -EPROTONOSUPPORT
;
3326 data
= o
->data
.payload
;
3328 r
= journal_file_append_data(to
, data
, l
, &u
, &h
);
3332 xor_hash
^= le64toh(u
->data
.hash
);
3333 items
[i
].object_offset
= htole64(h
);
3334 items
[i
].hash
= u
->data
.hash
;
3336 r
= journal_file_move_to_object(from
, OBJECT_ENTRY
, p
, &o
);
3341 r
= journal_file_append_entry_internal(to
, &ts
, xor_hash
, items
, n
, seqnum
, ret
, offset
);
3343 if (mmap_cache_got_sigbus(to
->mmap
, to
->fd
))
3349 void journal_reset_metrics(JournalMetrics
*m
) {
3352 /* Set everything to "pick automatic values". */
3354 *m
= (JournalMetrics
) {
3355 .min_use
= (uint64_t) -1,
3356 .max_use
= (uint64_t) -1,
3357 .min_size
= (uint64_t) -1,
3358 .max_size
= (uint64_t) -1,
3359 .keep_free
= (uint64_t) -1,
3360 .n_max_files
= (uint64_t) -1,
3364 void journal_default_metrics(JournalMetrics
*m
, int fd
) {
3365 char a
[FORMAT_BYTES_MAX
], b
[FORMAT_BYTES_MAX
], c
[FORMAT_BYTES_MAX
], d
[FORMAT_BYTES_MAX
], e
[FORMAT_BYTES_MAX
];
3372 if (fstatvfs(fd
, &ss
) >= 0)
3373 fs_size
= ss
.f_frsize
* ss
.f_blocks
;
3375 log_debug_errno(errno
, "Failed to detremine disk size: %m");
3379 if (m
->max_use
== (uint64_t) -1) {
3382 m
->max_use
= PAGE_ALIGN(fs_size
/ 10); /* 10% of file system size */
3384 if (m
->max_use
> DEFAULT_MAX_USE_UPPER
)
3385 m
->max_use
= DEFAULT_MAX_USE_UPPER
;
3387 if (m
->max_use
< DEFAULT_MAX_USE_LOWER
)
3388 m
->max_use
= DEFAULT_MAX_USE_LOWER
;
3390 m
->max_use
= DEFAULT_MAX_USE_LOWER
;
3392 m
->max_use
= PAGE_ALIGN(m
->max_use
);
3394 if (m
->max_use
!= 0 && m
->max_use
< JOURNAL_FILE_SIZE_MIN
*2)
3395 m
->max_use
= JOURNAL_FILE_SIZE_MIN
*2;
3398 if (m
->min_use
== (uint64_t) -1)
3399 m
->min_use
= DEFAULT_MIN_USE
;
3401 if (m
->min_use
> m
->max_use
)
3402 m
->min_use
= m
->max_use
;
3404 if (m
->max_size
== (uint64_t) -1) {
3405 m
->max_size
= PAGE_ALIGN(m
->max_use
/ 8); /* 8 chunks */
3407 if (m
->max_size
> DEFAULT_MAX_SIZE_UPPER
)
3408 m
->max_size
= DEFAULT_MAX_SIZE_UPPER
;
3410 m
->max_size
= PAGE_ALIGN(m
->max_size
);
3412 if (m
->max_size
!= 0) {
3413 if (m
->max_size
< JOURNAL_FILE_SIZE_MIN
)
3414 m
->max_size
= JOURNAL_FILE_SIZE_MIN
;
3416 if (m
->max_use
!= 0 && m
->max_size
*2 > m
->max_use
)
3417 m
->max_use
= m
->max_size
*2;
3420 if (m
->min_size
== (uint64_t) -1)
3421 m
->min_size
= JOURNAL_FILE_SIZE_MIN
;
3423 m
->min_size
= PAGE_ALIGN(m
->min_size
);
3425 if (m
->min_size
< JOURNAL_FILE_SIZE_MIN
)
3426 m
->min_size
= JOURNAL_FILE_SIZE_MIN
;
3428 if (m
->max_size
!= 0 && m
->min_size
> m
->max_size
)
3429 m
->max_size
= m
->min_size
;
3432 if (m
->keep_free
== (uint64_t) -1) {
3435 m
->keep_free
= PAGE_ALIGN(fs_size
* 3 / 20); /* 15% of file system size */
3437 if (m
->keep_free
> DEFAULT_KEEP_FREE_UPPER
)
3438 m
->keep_free
= DEFAULT_KEEP_FREE_UPPER
;
3441 m
->keep_free
= DEFAULT_KEEP_FREE
;
3444 if (m
->n_max_files
== (uint64_t) -1)
3445 m
->n_max_files
= DEFAULT_N_MAX_FILES
;
3447 log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64
,
3448 format_bytes(a
, sizeof(a
), m
->min_use
),
3449 format_bytes(b
, sizeof(b
), m
->max_use
),
3450 format_bytes(c
, sizeof(c
), m
->max_size
),
3451 format_bytes(d
, sizeof(d
), m
->min_size
),
3452 format_bytes(e
, sizeof(e
), m
->keep_free
),
3456 int journal_file_get_cutoff_realtime_usec(JournalFile
*f
, usec_t
*from
, usec_t
*to
) {
3462 if (f
->header
->head_entry_realtime
== 0)
3465 *from
= le64toh(f
->header
->head_entry_realtime
);
3469 if (f
->header
->tail_entry_realtime
== 0)
3472 *to
= le64toh(f
->header
->tail_entry_realtime
);
3478 int journal_file_get_cutoff_monotonic_usec(JournalFile
*f
, sd_id128_t boot_id
, usec_t
*from
, usec_t
*to
) {
3486 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &p
);
3490 if (le64toh(o
->data
.n_entries
) <= 0)
3494 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, le64toh(o
->data
.entry_offset
), &o
);
3498 *from
= le64toh(o
->entry
.monotonic
);
3502 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
3506 r
= generic_array_get_plus_one(f
,
3507 le64toh(o
->data
.entry_offset
),
3508 le64toh(o
->data
.entry_array_offset
),
3509 le64toh(o
->data
.n_entries
)-1,
3514 *to
= le64toh(o
->entry
.monotonic
);
3520 bool journal_file_rotate_suggested(JournalFile
*f
, usec_t max_file_usec
) {
3524 /* If we gained new header fields we gained new features,
3525 * hence suggest a rotation */
3526 if (le64toh(f
->header
->header_size
) < sizeof(Header
)) {
3527 log_debug("%s uses an outdated header, suggesting rotation.", f
->path
);
3531 /* Let's check if the hash tables grew over a certain fill
3532 * level (75%, borrowing this value from Java's hash table
3533 * implementation), and if so suggest a rotation. To calculate
3534 * the fill level we need the n_data field, which only exists
3535 * in newer versions. */
3537 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
3538 if (le64toh(f
->header
->n_data
) * 4ULL > (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
3539 log_debug("Data hash table of %s has a fill level at %.1f (%"PRIu64
" of %"PRIu64
" items, %llu file size, %"PRIu64
" bytes per hash table item), suggesting rotation.",
3541 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))),
3542 le64toh(f
->header
->n_data
),
3543 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
3544 (unsigned long long) f
->last_stat
.st_size
,
3545 f
->last_stat
.st_size
/ le64toh(f
->header
->n_data
));
3549 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
3550 if (le64toh(f
->header
->n_fields
) * 4ULL > (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
3551 log_debug("Field hash table of %s has a fill level at %.1f (%"PRIu64
" of %"PRIu64
" items), suggesting rotation.",
3553 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))),
3554 le64toh(f
->header
->n_fields
),
3555 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
));
3559 /* Are the data objects properly indexed by field objects? */
3560 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
) &&
3561 JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
) &&
3562 le64toh(f
->header
->n_data
) > 0 &&
3563 le64toh(f
->header
->n_fields
) == 0)
3566 if (max_file_usec
> 0) {
3569 h
= le64toh(f
->header
->head_entry_realtime
);
3570 t
= now(CLOCK_REALTIME
);
3572 if (h
> 0 && t
> h
+ max_file_usec
)