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 fsync_directory_of_file(int fd
) {
443 _cleanup_free_
char *path
= NULL
, *dn
= NULL
;
444 _cleanup_close_
int dfd
= -1;
448 if (fstat(fd
, &st
) < 0)
451 if (!S_ISREG(st
.st_mode
))
454 r
= fd_get_path(fd
, &path
);
458 if (!path_is_absolute(path
))
461 dn
= dirname_malloc(path
);
465 dfd
= open(dn
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
);
475 static int journal_file_refresh_header(JournalFile
*f
) {
482 r
= sd_id128_get_machine(&f
->header
->machine_id
);
486 r
= sd_id128_get_boot(&boot_id
);
490 if (sd_id128_equal(boot_id
, f
->header
->boot_id
))
491 f
->tail_entry_monotonic_valid
= true;
493 f
->header
->boot_id
= boot_id
;
495 r
= journal_file_set_online(f
);
497 /* Sync the online state to disk */
500 /* We likely just created a new file, also sync the directory this file is located in. */
501 (void) fsync_directory_of_file(f
->fd
);
506 static int journal_file_verify_header(JournalFile
*f
) {
512 if (memcmp(f
->header
->signature
, HEADER_SIGNATURE
, 8))
515 /* In both read and write mode we refuse to open files with
516 * incompatible flags we don't know */
517 flags
= le32toh(f
->header
->incompatible_flags
);
518 if (flags
& ~HEADER_INCOMPATIBLE_SUPPORTED
) {
519 if (flags
& ~HEADER_INCOMPATIBLE_ANY
)
520 log_debug("Journal file %s has unknown incompatible flags %"PRIx32
,
521 f
->path
, flags
& ~HEADER_INCOMPATIBLE_ANY
);
522 flags
= (flags
& HEADER_INCOMPATIBLE_ANY
) & ~HEADER_INCOMPATIBLE_SUPPORTED
;
524 log_debug("Journal file %s uses incompatible flags %"PRIx32
525 " disabled at compilation time.", f
->path
, flags
);
526 return -EPROTONOSUPPORT
;
529 /* When open for writing we refuse to open files with
530 * compatible flags, too */
531 flags
= le32toh(f
->header
->compatible_flags
);
532 if (f
->writable
&& (flags
& ~HEADER_COMPATIBLE_SUPPORTED
)) {
533 if (flags
& ~HEADER_COMPATIBLE_ANY
)
534 log_debug("Journal file %s has unknown compatible flags %"PRIx32
,
535 f
->path
, flags
& ~HEADER_COMPATIBLE_ANY
);
536 flags
= (flags
& HEADER_COMPATIBLE_ANY
) & ~HEADER_COMPATIBLE_SUPPORTED
;
538 log_debug("Journal file %s uses compatible flags %"PRIx32
539 " disabled at compilation time.", f
->path
, flags
);
540 return -EPROTONOSUPPORT
;
543 if (f
->header
->state
>= _STATE_MAX
)
546 /* The first addition was n_data, so check that we are at least this large */
547 if (le64toh(f
->header
->header_size
) < HEADER_SIZE_MIN
)
550 if (JOURNAL_HEADER_SEALED(f
->header
) && !JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
553 if ((le64toh(f
->header
->header_size
) + le64toh(f
->header
->arena_size
)) > (uint64_t) f
->last_stat
.st_size
)
556 if (le64toh(f
->header
->tail_object_offset
) > (le64toh(f
->header
->header_size
) + le64toh(f
->header
->arena_size
)))
559 if (!VALID64(le64toh(f
->header
->data_hash_table_offset
)) ||
560 !VALID64(le64toh(f
->header
->field_hash_table_offset
)) ||
561 !VALID64(le64toh(f
->header
->tail_object_offset
)) ||
562 !VALID64(le64toh(f
->header
->entry_array_offset
)))
567 sd_id128_t machine_id
;
570 r
= sd_id128_get_machine(&machine_id
);
574 if (!sd_id128_equal(machine_id
, f
->header
->machine_id
))
577 state
= f
->header
->state
;
579 if (state
== STATE_ONLINE
) {
580 log_debug("Journal file %s is already online. Assuming unclean closing.", f
->path
);
582 } else if (state
== STATE_ARCHIVED
)
584 else if (state
!= STATE_OFFLINE
) {
585 log_debug("Journal file %s has unknown state %i.", f
->path
, state
);
590 f
->compress_xz
= JOURNAL_HEADER_COMPRESSED_XZ(f
->header
);
591 f
->compress_lz4
= JOURNAL_HEADER_COMPRESSED_LZ4(f
->header
);
593 f
->seal
= JOURNAL_HEADER_SEALED(f
->header
);
598 static int journal_file_fstat(JournalFile
*f
) {
602 if (fstat(f
->fd
, &f
->last_stat
) < 0)
605 f
->last_stat_usec
= now(CLOCK_MONOTONIC
);
607 /* Refuse appending to files that are already deleted */
608 if (f
->last_stat
.st_nlink
<= 0)
614 static int journal_file_allocate(JournalFile
*f
, uint64_t offset
, uint64_t size
) {
615 uint64_t old_size
, new_size
;
621 /* We assume that this file is not sparse, and we know that
622 * for sure, since we always call posix_fallocate()
625 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
629 le64toh(f
->header
->header_size
) +
630 le64toh(f
->header
->arena_size
);
632 new_size
= PAGE_ALIGN(offset
+ size
);
633 if (new_size
< le64toh(f
->header
->header_size
))
634 new_size
= le64toh(f
->header
->header_size
);
636 if (new_size
<= old_size
) {
638 /* We already pre-allocated enough space, but before
639 * we write to it, let's check with fstat() if the
640 * file got deleted, in order make sure we don't throw
641 * away the data immediately. Don't check fstat() for
642 * all writes though, but only once ever 10s. */
644 if (f
->last_stat_usec
+ LAST_STAT_REFRESH_USEC
> now(CLOCK_MONOTONIC
))
647 return journal_file_fstat(f
);
650 /* Allocate more space. */
652 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
655 if (new_size
> f
->metrics
.min_size
&& f
->metrics
.keep_free
> 0) {
658 if (fstatvfs(f
->fd
, &svfs
) >= 0) {
661 available
= LESS_BY((uint64_t) svfs
.f_bfree
* (uint64_t) svfs
.f_bsize
, f
->metrics
.keep_free
);
663 if (new_size
- old_size
> available
)
668 /* Increase by larger blocks at once */
669 new_size
= ((new_size
+FILE_SIZE_INCREASE
-1) / FILE_SIZE_INCREASE
) * FILE_SIZE_INCREASE
;
670 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
671 new_size
= f
->metrics
.max_size
;
673 /* Note that the glibc fallocate() fallback is very
674 inefficient, hence we try to minimize the allocation area
676 r
= posix_fallocate(f
->fd
, old_size
, new_size
- old_size
);
680 f
->header
->arena_size
= htole64(new_size
- le64toh(f
->header
->header_size
));
682 return journal_file_fstat(f
);
685 static unsigned type_to_context(ObjectType type
) {
686 /* One context for each type, plus one catch-all for the rest */
687 assert_cc(_OBJECT_TYPE_MAX
<= MMAP_CACHE_MAX_CONTEXTS
);
688 assert_cc(CONTEXT_HEADER
< MMAP_CACHE_MAX_CONTEXTS
);
689 return type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
? type
: 0;
692 static int journal_file_move_to(JournalFile
*f
, ObjectType type
, bool keep_always
, uint64_t offset
, uint64_t size
, void **ret
) {
701 /* Avoid SIGBUS on invalid accesses */
702 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
) {
703 /* Hmm, out of range? Let's refresh the fstat() data
704 * first, before we trust that check. */
706 r
= journal_file_fstat(f
);
710 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
)
711 return -EADDRNOTAVAIL
;
714 return mmap_cache_get(f
->mmap
, f
->fd
, f
->prot
, type_to_context(type
), keep_always
, offset
, size
, &f
->last_stat
, ret
);
717 static uint64_t minimum_header_size(Object
*o
) {
719 static const uint64_t table
[] = {
720 [OBJECT_DATA
] = sizeof(DataObject
),
721 [OBJECT_FIELD
] = sizeof(FieldObject
),
722 [OBJECT_ENTRY
] = sizeof(EntryObject
),
723 [OBJECT_DATA_HASH_TABLE
] = sizeof(HashTableObject
),
724 [OBJECT_FIELD_HASH_TABLE
] = sizeof(HashTableObject
),
725 [OBJECT_ENTRY_ARRAY
] = sizeof(EntryArrayObject
),
726 [OBJECT_TAG
] = sizeof(TagObject
),
729 if (o
->object
.type
>= ELEMENTSOF(table
) || table
[o
->object
.type
] <= 0)
730 return sizeof(ObjectHeader
);
732 return table
[o
->object
.type
];
735 int journal_file_move_to_object(JournalFile
*f
, ObjectType type
, uint64_t offset
, Object
**ret
) {
744 /* Objects may only be located at multiple of 64 bit */
745 if (!VALID64(offset
))
748 /* Object may not be located in the file header */
749 if (offset
< le64toh(f
->header
->header_size
))
752 r
= journal_file_move_to(f
, type
, false, offset
, sizeof(ObjectHeader
), &t
);
757 s
= le64toh(o
->object
.size
);
759 if (s
< sizeof(ObjectHeader
))
762 if (o
->object
.type
<= OBJECT_UNUSED
)
765 if (s
< minimum_header_size(o
))
768 if (type
> OBJECT_UNUSED
&& o
->object
.type
!= type
)
771 if (s
> sizeof(ObjectHeader
)) {
772 r
= journal_file_move_to(f
, type
, false, offset
, s
, &t
);
783 static uint64_t journal_file_entry_seqnum(JournalFile
*f
, uint64_t *seqnum
) {
789 r
= le64toh(f
->header
->tail_entry_seqnum
) + 1;
792 /* If an external seqnum counter was passed, we update
793 * both the local and the external one, and set it to
794 * the maximum of both */
802 f
->header
->tail_entry_seqnum
= htole64(r
);
804 if (f
->header
->head_entry_seqnum
== 0)
805 f
->header
->head_entry_seqnum
= htole64(r
);
810 int journal_file_append_object(JournalFile
*f
, ObjectType type
, uint64_t size
, Object
**ret
, uint64_t *offset
) {
818 assert(type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
);
819 assert(size
>= sizeof(ObjectHeader
));
823 r
= journal_file_set_online(f
);
827 p
= le64toh(f
->header
->tail_object_offset
);
829 p
= le64toh(f
->header
->header_size
);
831 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &tail
);
835 p
+= ALIGN64(le64toh(tail
->object
.size
));
838 r
= journal_file_allocate(f
, p
, size
);
842 r
= journal_file_move_to(f
, type
, false, p
, size
, &t
);
849 o
->object
.type
= type
;
850 o
->object
.size
= htole64(size
);
852 f
->header
->tail_object_offset
= htole64(p
);
853 f
->header
->n_objects
= htole64(le64toh(f
->header
->n_objects
) + 1);
861 static int journal_file_setup_data_hash_table(JournalFile
*f
) {
869 /* We estimate that we need 1 hash table entry per 768 bytes
870 of journal file and we want to make sure we never get
871 beyond 75% fill level. Calculate the hash table size for
872 the maximum file size based on these metrics. */
874 s
= (f
->metrics
.max_size
* 4 / 768 / 3) * sizeof(HashItem
);
875 if (s
< DEFAULT_DATA_HASH_TABLE_SIZE
)
876 s
= DEFAULT_DATA_HASH_TABLE_SIZE
;
878 log_debug("Reserving %"PRIu64
" entries in hash table.", s
/ sizeof(HashItem
));
880 r
= journal_file_append_object(f
,
881 OBJECT_DATA_HASH_TABLE
,
882 offsetof(Object
, hash_table
.items
) + s
,
887 memzero(o
->hash_table
.items
, s
);
889 f
->header
->data_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
890 f
->header
->data_hash_table_size
= htole64(s
);
895 static int journal_file_setup_field_hash_table(JournalFile
*f
) {
903 /* We use a fixed size hash table for the fields as this
904 * number should grow very slowly only */
906 s
= DEFAULT_FIELD_HASH_TABLE_SIZE
;
907 r
= journal_file_append_object(f
,
908 OBJECT_FIELD_HASH_TABLE
,
909 offsetof(Object
, hash_table
.items
) + s
,
914 memzero(o
->hash_table
.items
, s
);
916 f
->header
->field_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
917 f
->header
->field_hash_table_size
= htole64(s
);
922 int journal_file_map_data_hash_table(JournalFile
*f
) {
930 if (f
->data_hash_table
)
933 p
= le64toh(f
->header
->data_hash_table_offset
);
934 s
= le64toh(f
->header
->data_hash_table_size
);
936 r
= journal_file_move_to(f
,
937 OBJECT_DATA_HASH_TABLE
,
944 f
->data_hash_table
= t
;
948 int journal_file_map_field_hash_table(JournalFile
*f
) {
956 if (f
->field_hash_table
)
959 p
= le64toh(f
->header
->field_hash_table_offset
);
960 s
= le64toh(f
->header
->field_hash_table_size
);
962 r
= journal_file_move_to(f
,
963 OBJECT_FIELD_HASH_TABLE
,
970 f
->field_hash_table
= t
;
974 static int journal_file_link_field(
985 assert(f
->field_hash_table
);
989 if (o
->object
.type
!= OBJECT_FIELD
)
992 m
= le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
);
996 /* This might alter the window we are looking at */
997 o
->field
.next_hash_offset
= o
->field
.head_data_offset
= 0;
1000 p
= le64toh(f
->field_hash_table
[h
].tail_hash_offset
);
1002 f
->field_hash_table
[h
].head_hash_offset
= htole64(offset
);
1004 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1008 o
->field
.next_hash_offset
= htole64(offset
);
1011 f
->field_hash_table
[h
].tail_hash_offset
= htole64(offset
);
1013 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
1014 f
->header
->n_fields
= htole64(le64toh(f
->header
->n_fields
) + 1);
1019 static int journal_file_link_data(
1030 assert(f
->data_hash_table
);
1034 if (o
->object
.type
!= OBJECT_DATA
)
1037 m
= le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
);
1041 /* This might alter the window we are looking at */
1042 o
->data
.next_hash_offset
= o
->data
.next_field_offset
= 0;
1043 o
->data
.entry_offset
= o
->data
.entry_array_offset
= 0;
1044 o
->data
.n_entries
= 0;
1047 p
= le64toh(f
->data_hash_table
[h
].tail_hash_offset
);
1049 /* Only entry in the hash table is easy */
1050 f
->data_hash_table
[h
].head_hash_offset
= htole64(offset
);
1052 /* Move back to the previous data object, to patch in
1055 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1059 o
->data
.next_hash_offset
= htole64(offset
);
1062 f
->data_hash_table
[h
].tail_hash_offset
= htole64(offset
);
1064 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
1065 f
->header
->n_data
= htole64(le64toh(f
->header
->n_data
) + 1);
1070 int journal_file_find_field_object_with_hash(
1072 const void *field
, uint64_t size
, uint64_t hash
,
1073 Object
**ret
, uint64_t *offset
) {
1075 uint64_t p
, osize
, h
, m
;
1080 assert(field
&& size
> 0);
1082 /* If the field hash table is empty, we can't find anything */
1083 if (le64toh(f
->header
->field_hash_table_size
) <= 0)
1086 /* Map the field hash table, if it isn't mapped yet. */
1087 r
= journal_file_map_field_hash_table(f
);
1091 osize
= offsetof(Object
, field
.payload
) + size
;
1093 m
= le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
);
1098 p
= le64toh(f
->field_hash_table
[h
].head_hash_offset
);
1103 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1107 if (le64toh(o
->field
.hash
) == hash
&&
1108 le64toh(o
->object
.size
) == osize
&&
1109 memcmp(o
->field
.payload
, field
, size
) == 0) {
1119 p
= le64toh(o
->field
.next_hash_offset
);
1125 int journal_file_find_field_object(
1127 const void *field
, uint64_t size
,
1128 Object
**ret
, uint64_t *offset
) {
1133 assert(field
&& size
> 0);
1135 hash
= hash64(field
, size
);
1137 return journal_file_find_field_object_with_hash(f
,
1142 int journal_file_find_data_object_with_hash(
1144 const void *data
, uint64_t size
, uint64_t hash
,
1145 Object
**ret
, uint64_t *offset
) {
1147 uint64_t p
, osize
, h
, m
;
1152 assert(data
|| size
== 0);
1154 /* If there's no data hash table, then there's no entry. */
1155 if (le64toh(f
->header
->data_hash_table_size
) <= 0)
1158 /* Map the data hash table, if it isn't mapped yet. */
1159 r
= journal_file_map_data_hash_table(f
);
1163 osize
= offsetof(Object
, data
.payload
) + size
;
1165 m
= le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
);
1170 p
= le64toh(f
->data_hash_table
[h
].head_hash_offset
);
1175 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1179 if (le64toh(o
->data
.hash
) != hash
)
1182 if (o
->object
.flags
& OBJECT_COMPRESSION_MASK
) {
1183 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
1187 l
= le64toh(o
->object
.size
);
1188 if (l
<= offsetof(Object
, data
.payload
))
1191 l
-= offsetof(Object
, data
.payload
);
1193 r
= decompress_blob(o
->object
.flags
& OBJECT_COMPRESSION_MASK
,
1194 o
->data
.payload
, l
, &f
->compress_buffer
, &f
->compress_buffer_size
, &rsize
, 0);
1198 if (rsize
== size
&&
1199 memcmp(f
->compress_buffer
, data
, size
) == 0) {
1210 return -EPROTONOSUPPORT
;
1212 } else if (le64toh(o
->object
.size
) == osize
&&
1213 memcmp(o
->data
.payload
, data
, size
) == 0) {
1225 p
= le64toh(o
->data
.next_hash_offset
);
1231 int journal_file_find_data_object(
1233 const void *data
, uint64_t size
,
1234 Object
**ret
, uint64_t *offset
) {
1239 assert(data
|| size
== 0);
1241 hash
= hash64(data
, size
);
1243 return journal_file_find_data_object_with_hash(f
,
1248 static int journal_file_append_field(
1250 const void *field
, uint64_t size
,
1251 Object
**ret
, uint64_t *offset
) {
1259 assert(field
&& size
> 0);
1261 hash
= hash64(field
, size
);
1263 r
= journal_file_find_field_object_with_hash(f
, field
, size
, hash
, &o
, &p
);
1277 osize
= offsetof(Object
, field
.payload
) + size
;
1278 r
= journal_file_append_object(f
, OBJECT_FIELD
, osize
, &o
, &p
);
1282 o
->field
.hash
= htole64(hash
);
1283 memcpy(o
->field
.payload
, field
, size
);
1285 r
= journal_file_link_field(f
, o
, p
, hash
);
1289 /* The linking might have altered the window, so let's
1290 * refresh our pointer */
1291 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1296 r
= journal_file_hmac_put_object(f
, OBJECT_FIELD
, o
, p
);
1310 static int journal_file_append_data(
1312 const void *data
, uint64_t size
,
1313 Object
**ret
, uint64_t *offset
) {
1318 int r
, compression
= 0;
1322 assert(data
|| size
== 0);
1324 hash
= hash64(data
, size
);
1326 r
= journal_file_find_data_object_with_hash(f
, data
, size
, hash
, &o
, &p
);
1340 osize
= offsetof(Object
, data
.payload
) + size
;
1341 r
= journal_file_append_object(f
, OBJECT_DATA
, osize
, &o
, &p
);
1345 o
->data
.hash
= htole64(hash
);
1347 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
1348 if (JOURNAL_FILE_COMPRESS(f
) && size
>= COMPRESSION_SIZE_THRESHOLD
) {
1351 compression
= compress_blob(data
, size
, o
->data
.payload
, size
- 1, &rsize
);
1353 if (compression
>= 0) {
1354 o
->object
.size
= htole64(offsetof(Object
, data
.payload
) + rsize
);
1355 o
->object
.flags
|= compression
;
1357 log_debug("Compressed data object %"PRIu64
" -> %zu using %s",
1358 size
, rsize
, object_compressed_to_string(compression
));
1360 /* Compression didn't work, we don't really care why, let's continue without compression */
1365 if (compression
== 0)
1366 memcpy_safe(o
->data
.payload
, data
, size
);
1368 r
= journal_file_link_data(f
, o
, p
, hash
);
1372 /* The linking might have altered the window, so let's
1373 * refresh our pointer */
1374 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1381 eq
= memchr(data
, '=', size
);
1382 if (eq
&& eq
> data
) {
1386 /* Create field object ... */
1387 r
= journal_file_append_field(f
, data
, (uint8_t*) eq
- (uint8_t*) data
, &fo
, &fp
);
1391 /* ... and link it in. */
1392 o
->data
.next_field_offset
= fo
->field
.head_data_offset
;
1393 fo
->field
.head_data_offset
= le64toh(p
);
1397 r
= journal_file_hmac_put_object(f
, OBJECT_DATA
, o
, p
);
1411 uint64_t journal_file_entry_n_items(Object
*o
) {
1414 if (o
->object
.type
!= OBJECT_ENTRY
)
1417 return (le64toh(o
->object
.size
) - offsetof(Object
, entry
.items
)) / sizeof(EntryItem
);
1420 uint64_t journal_file_entry_array_n_items(Object
*o
) {
1423 if (o
->object
.type
!= OBJECT_ENTRY_ARRAY
)
1426 return (le64toh(o
->object
.size
) - offsetof(Object
, entry_array
.items
)) / sizeof(uint64_t);
1429 uint64_t journal_file_hash_table_n_items(Object
*o
) {
1432 if (o
->object
.type
!= OBJECT_DATA_HASH_TABLE
&&
1433 o
->object
.type
!= OBJECT_FIELD_HASH_TABLE
)
1436 return (le64toh(o
->object
.size
) - offsetof(Object
, hash_table
.items
)) / sizeof(HashItem
);
1439 static int link_entry_into_array(JournalFile
*f
,
1444 uint64_t n
= 0, ap
= 0, q
, i
, a
, hidx
;
1453 a
= le64toh(*first
);
1454 i
= hidx
= le64toh(*idx
);
1457 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
1461 n
= journal_file_entry_array_n_items(o
);
1463 o
->entry_array
.items
[i
] = htole64(p
);
1464 *idx
= htole64(hidx
+ 1);
1470 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
1481 r
= journal_file_append_object(f
, OBJECT_ENTRY_ARRAY
,
1482 offsetof(Object
, entry_array
.items
) + n
* sizeof(uint64_t),
1488 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY_ARRAY
, o
, q
);
1493 o
->entry_array
.items
[i
] = htole64(p
);
1496 *first
= htole64(q
);
1498 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, ap
, &o
);
1502 o
->entry_array
.next_entry_array_offset
= htole64(q
);
1505 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
1506 f
->header
->n_entry_arrays
= htole64(le64toh(f
->header
->n_entry_arrays
) + 1);
1508 *idx
= htole64(hidx
+ 1);
1513 static int link_entry_into_array_plus_one(JournalFile
*f
,
1528 *extra
= htole64(p
);
1532 i
= htole64(le64toh(*idx
) - 1);
1533 r
= link_entry_into_array(f
, first
, &i
, p
);
1538 *idx
= htole64(le64toh(*idx
) + 1);
1542 static int journal_file_link_entry_item(JournalFile
*f
, Object
*o
, uint64_t offset
, uint64_t i
) {
1549 p
= le64toh(o
->entry
.items
[i
].object_offset
);
1553 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1557 return link_entry_into_array_plus_one(f
,
1558 &o
->data
.entry_offset
,
1559 &o
->data
.entry_array_offset
,
1564 static int journal_file_link_entry(JournalFile
*f
, Object
*o
, uint64_t offset
) {
1573 if (o
->object
.type
!= OBJECT_ENTRY
)
1576 __sync_synchronize();
1578 /* Link up the entry itself */
1579 r
= link_entry_into_array(f
,
1580 &f
->header
->entry_array_offset
,
1581 &f
->header
->n_entries
,
1586 /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
1588 if (f
->header
->head_entry_realtime
== 0)
1589 f
->header
->head_entry_realtime
= o
->entry
.realtime
;
1591 f
->header
->tail_entry_realtime
= o
->entry
.realtime
;
1592 f
->header
->tail_entry_monotonic
= o
->entry
.monotonic
;
1594 f
->tail_entry_monotonic_valid
= true;
1596 /* Link up the items */
1597 n
= journal_file_entry_n_items(o
);
1598 for (i
= 0; i
< n
; i
++) {
1599 r
= journal_file_link_entry_item(f
, o
, offset
, i
);
1607 static int journal_file_append_entry_internal(
1609 const dual_timestamp
*ts
,
1611 const EntryItem items
[], unsigned n_items
,
1613 Object
**ret
, uint64_t *offset
) {
1621 assert(items
|| n_items
== 0);
1624 osize
= offsetof(Object
, entry
.items
) + (n_items
* sizeof(EntryItem
));
1626 r
= journal_file_append_object(f
, OBJECT_ENTRY
, osize
, &o
, &np
);
1630 o
->entry
.seqnum
= htole64(journal_file_entry_seqnum(f
, seqnum
));
1631 memcpy_safe(o
->entry
.items
, items
, n_items
* sizeof(EntryItem
));
1632 o
->entry
.realtime
= htole64(ts
->realtime
);
1633 o
->entry
.monotonic
= htole64(ts
->monotonic
);
1634 o
->entry
.xor_hash
= htole64(xor_hash
);
1635 o
->entry
.boot_id
= f
->header
->boot_id
;
1638 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY
, o
, np
);
1643 r
= journal_file_link_entry(f
, o
, np
);
1656 void journal_file_post_change(JournalFile
*f
) {
1659 /* inotify() does not receive IN_MODIFY events from file
1660 * accesses done via mmap(). After each access we hence
1661 * trigger IN_MODIFY by truncating the journal file to its
1662 * current size which triggers IN_MODIFY. */
1664 __sync_synchronize();
1666 if (ftruncate(f
->fd
, f
->last_stat
.st_size
) < 0)
1667 log_debug_errno(errno
, "Failed to truncate file to its own size: %m");
1670 static int post_change_thunk(sd_event_source
*timer
, uint64_t usec
, void *userdata
) {
1673 journal_file_post_change(userdata
);
1678 static void schedule_post_change(JournalFile
*f
) {
1679 sd_event_source
*timer
;
1684 assert(f
->post_change_timer
);
1686 timer
= f
->post_change_timer
;
1688 r
= sd_event_source_get_enabled(timer
, &enabled
);
1690 log_debug_errno(r
, "Failed to get ftruncate timer state: %m");
1694 if (enabled
== SD_EVENT_ONESHOT
)
1697 r
= sd_event_now(sd_event_source_get_event(timer
), CLOCK_MONOTONIC
, &now
);
1699 log_debug_errno(r
, "Failed to get clock's now for scheduling ftruncate: %m");
1703 r
= sd_event_source_set_time(timer
, now
+f
->post_change_timer_period
);
1705 log_debug_errno(r
, "Failed to set time for scheduling ftruncate: %m");
1709 r
= sd_event_source_set_enabled(timer
, SD_EVENT_ONESHOT
);
1711 log_debug_errno(r
, "Failed to enable scheduled ftruncate: %m");
1718 /* On failure, let's simply post the change immediately. */
1719 journal_file_post_change(f
);
1722 /* Enable coalesced change posting in a timer on the provided sd_event instance */
1723 int journal_file_enable_post_change_timer(JournalFile
*f
, sd_event
*e
, usec_t t
) {
1724 _cleanup_(sd_event_source_unrefp
) sd_event_source
*timer
= NULL
;
1728 assert_return(!f
->post_change_timer
, -EINVAL
);
1732 r
= sd_event_add_time(e
, &timer
, CLOCK_MONOTONIC
, 0, 0, post_change_thunk
, f
);
1736 r
= sd_event_source_set_enabled(timer
, SD_EVENT_OFF
);
1740 f
->post_change_timer
= timer
;
1742 f
->post_change_timer_period
= t
;
1747 static int entry_item_cmp(const void *_a
, const void *_b
) {
1748 const EntryItem
*a
= _a
, *b
= _b
;
1750 if (le64toh(a
->object_offset
) < le64toh(b
->object_offset
))
1752 if (le64toh(a
->object_offset
) > le64toh(b
->object_offset
))
1757 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
) {
1761 uint64_t xor_hash
= 0;
1762 struct dual_timestamp _ts
;
1766 assert(iovec
|| n_iovec
== 0);
1769 dual_timestamp_get(&_ts
);
1774 r
= journal_file_maybe_append_tag(f
, ts
->realtime
);
1779 /* alloca() can't take 0, hence let's allocate at least one */
1780 items
= alloca(sizeof(EntryItem
) * MAX(1u, n_iovec
));
1782 for (i
= 0; i
< n_iovec
; i
++) {
1786 r
= journal_file_append_data(f
, iovec
[i
].iov_base
, iovec
[i
].iov_len
, &o
, &p
);
1790 xor_hash
^= le64toh(o
->data
.hash
);
1791 items
[i
].object_offset
= htole64(p
);
1792 items
[i
].hash
= o
->data
.hash
;
1795 /* Order by the position on disk, in order to improve seek
1796 * times for rotating media. */
1797 qsort_safe(items
, n_iovec
, sizeof(EntryItem
), entry_item_cmp
);
1799 r
= journal_file_append_entry_internal(f
, ts
, xor_hash
, items
, n_iovec
, seqnum
, ret
, offset
);
1801 /* If the memory mapping triggered a SIGBUS then we return an
1802 * IO error and ignore the error code passed down to us, since
1803 * it is very likely just an effect of a nullified replacement
1806 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
1809 if (f
->post_change_timer
)
1810 schedule_post_change(f
);
1812 journal_file_post_change(f
);
1817 typedef struct ChainCacheItem
{
1818 uint64_t first
; /* the array at the beginning of the chain */
1819 uint64_t array
; /* the cached array */
1820 uint64_t begin
; /* the first item in the cached array */
1821 uint64_t total
; /* the total number of items in all arrays before this one in the chain */
1822 uint64_t last_index
; /* the last index we looked at, to optimize locality when bisecting */
1825 static void chain_cache_put(
1832 uint64_t last_index
) {
1835 /* If the chain item to cache for this chain is the
1836 * first one it's not worth caching anything */
1840 if (ordered_hashmap_size(h
) >= CHAIN_CACHE_MAX
) {
1841 ci
= ordered_hashmap_steal_first(h
);
1844 ci
= new(ChainCacheItem
, 1);
1851 if (ordered_hashmap_put(h
, &ci
->first
, ci
) < 0) {
1856 assert(ci
->first
== first
);
1861 ci
->last_index
= last_index
;
1864 static int generic_array_get(
1868 Object
**ret
, uint64_t *offset
) {
1871 uint64_t p
= 0, a
, t
= 0;
1879 /* Try the chain cache first */
1880 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
1881 if (ci
&& i
> ci
->total
) {
1890 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
1894 k
= journal_file_entry_array_n_items(o
);
1896 p
= le64toh(o
->entry_array
.items
[i
]);
1902 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
1908 /* Let's cache this item for the next invocation */
1909 chain_cache_put(f
->chain_cache
, ci
, first
, a
, le64toh(o
->entry_array
.items
[0]), t
, i
);
1911 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
1924 static int generic_array_get_plus_one(
1929 Object
**ret
, uint64_t *offset
) {
1938 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, &o
);
1951 return generic_array_get(f
, first
, i
-1, ret
, offset
);
1960 static int generic_array_bisect(
1965 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
1966 direction_t direction
,
1971 uint64_t a
, p
, t
= 0, i
= 0, last_p
= 0, last_index
= (uint64_t) -1;
1972 bool subtract_one
= false;
1973 Object
*o
, *array
= NULL
;
1978 assert(test_object
);
1980 /* Start with the first array in the chain */
1983 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
1984 if (ci
&& n
> ci
->total
) {
1985 /* Ah, we have iterated this bisection array chain
1986 * previously! Let's see if we can skip ahead in the
1987 * chain, as far as the last time. But we can't jump
1988 * backwards in the chain, so let's check that
1991 r
= test_object(f
, ci
->begin
, needle
);
1995 if (r
== TEST_LEFT
) {
1996 /* OK, what we are looking for is right of the
1997 * begin of this EntryArray, so let's jump
1998 * straight to previously cached array in the
2004 last_index
= ci
->last_index
;
2009 uint64_t left
, right
, k
, lp
;
2011 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &array
);
2015 k
= journal_file_entry_array_n_items(array
);
2021 lp
= p
= le64toh(array
->entry_array
.items
[i
]);
2025 r
= test_object(f
, p
, needle
);
2026 if (r
== -EBADMSG
) {
2027 log_debug_errno(r
, "Encountered invalid entry while bisecting, cutting algorithm short. (1)");
2034 if (r
== TEST_FOUND
)
2035 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2037 if (r
== TEST_RIGHT
) {
2041 if (last_index
!= (uint64_t) -1) {
2042 assert(last_index
<= right
);
2044 /* If we cached the last index we
2045 * looked at, let's try to not to jump
2046 * too wildly around and see if we can
2047 * limit the range to look at early to
2048 * the immediate neighbors of the last
2049 * index we looked at. */
2051 if (last_index
> 0) {
2052 uint64_t x
= last_index
- 1;
2054 p
= le64toh(array
->entry_array
.items
[x
]);
2058 r
= test_object(f
, p
, needle
);
2062 if (r
== TEST_FOUND
)
2063 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2065 if (r
== TEST_RIGHT
)
2071 if (last_index
< right
) {
2072 uint64_t y
= last_index
+ 1;
2074 p
= le64toh(array
->entry_array
.items
[y
]);
2078 r
= test_object(f
, p
, needle
);
2082 if (r
== TEST_FOUND
)
2083 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2085 if (r
== TEST_RIGHT
)
2093 if (left
== right
) {
2094 if (direction
== DIRECTION_UP
)
2095 subtract_one
= true;
2101 assert(left
< right
);
2102 i
= (left
+ right
) / 2;
2104 p
= le64toh(array
->entry_array
.items
[i
]);
2108 r
= test_object(f
, p
, needle
);
2109 if (r
== -EBADMSG
) {
2110 log_debug_errno(r
, "Encountered invalid entry while bisecting, cutting algorithm short. (2)");
2117 if (r
== TEST_FOUND
)
2118 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2120 if (r
== TEST_RIGHT
)
2128 if (direction
== DIRECTION_UP
) {
2130 subtract_one
= true;
2141 last_index
= (uint64_t) -1;
2142 a
= le64toh(array
->entry_array
.next_entry_array_offset
);
2148 if (subtract_one
&& t
== 0 && i
== 0)
2151 /* Let's cache this item for the next invocation */
2152 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
);
2154 if (subtract_one
&& i
== 0)
2156 else if (subtract_one
)
2157 p
= le64toh(array
->entry_array
.items
[i
-1]);
2159 p
= le64toh(array
->entry_array
.items
[i
]);
2161 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2172 *idx
= t
+ i
+ (subtract_one
? -1 : 0);
2177 static int generic_array_bisect_plus_one(
2183 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
2184 direction_t direction
,
2190 bool step_back
= false;
2194 assert(test_object
);
2199 /* This bisects the array in object 'first', but first checks
2201 r
= test_object(f
, extra
, needle
);
2205 if (r
== TEST_FOUND
)
2206 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2208 /* if we are looking with DIRECTION_UP then we need to first
2209 see if in the actual array there is a matching entry, and
2210 return the last one of that. But if there isn't any we need
2211 to return this one. Hence remember this, and return it
2214 step_back
= direction
== DIRECTION_UP
;
2216 if (r
== TEST_RIGHT
) {
2217 if (direction
== DIRECTION_DOWN
)
2223 r
= generic_array_bisect(f
, first
, n
-1, needle
, test_object
, direction
, ret
, offset
, idx
);
2225 if (r
== 0 && step_back
)
2234 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, &o
);
2250 _pure_
static int test_object_offset(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2256 else if (p
< needle
)
2262 static int test_object_seqnum(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2269 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2273 if (le64toh(o
->entry
.seqnum
) == needle
)
2275 else if (le64toh(o
->entry
.seqnum
) < needle
)
2281 int journal_file_move_to_entry_by_seqnum(
2284 direction_t direction
,
2290 return generic_array_bisect(f
,
2291 le64toh(f
->header
->entry_array_offset
),
2292 le64toh(f
->header
->n_entries
),
2299 static int test_object_realtime(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2306 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2310 if (le64toh(o
->entry
.realtime
) == needle
)
2312 else if (le64toh(o
->entry
.realtime
) < needle
)
2318 int journal_file_move_to_entry_by_realtime(
2321 direction_t direction
,
2327 return generic_array_bisect(f
,
2328 le64toh(f
->header
->entry_array_offset
),
2329 le64toh(f
->header
->n_entries
),
2331 test_object_realtime
,
2336 static int test_object_monotonic(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2343 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2347 if (le64toh(o
->entry
.monotonic
) == needle
)
2349 else if (le64toh(o
->entry
.monotonic
) < needle
)
2355 static int find_data_object_by_boot_id(
2361 char t
[sizeof("_BOOT_ID=")-1 + 32 + 1] = "_BOOT_ID=";
2363 sd_id128_to_string(boot_id
, t
+ 9);
2364 return journal_file_find_data_object(f
, t
, sizeof(t
) - 1, o
, b
);
2367 int journal_file_move_to_entry_by_monotonic(
2371 direction_t direction
,
2380 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, NULL
);
2386 return generic_array_bisect_plus_one(f
,
2387 le64toh(o
->data
.entry_offset
),
2388 le64toh(o
->data
.entry_array_offset
),
2389 le64toh(o
->data
.n_entries
),
2391 test_object_monotonic
,
2396 void journal_file_reset_location(JournalFile
*f
) {
2397 f
->location_type
= LOCATION_HEAD
;
2398 f
->current_offset
= 0;
2399 f
->current_seqnum
= 0;
2400 f
->current_realtime
= 0;
2401 f
->current_monotonic
= 0;
2402 zero(f
->current_boot_id
);
2403 f
->current_xor_hash
= 0;
2406 void journal_file_save_location(JournalFile
*f
, Object
*o
, uint64_t offset
) {
2407 f
->location_type
= LOCATION_SEEK
;
2408 f
->current_offset
= offset
;
2409 f
->current_seqnum
= le64toh(o
->entry
.seqnum
);
2410 f
->current_realtime
= le64toh(o
->entry
.realtime
);
2411 f
->current_monotonic
= le64toh(o
->entry
.monotonic
);
2412 f
->current_boot_id
= o
->entry
.boot_id
;
2413 f
->current_xor_hash
= le64toh(o
->entry
.xor_hash
);
2416 int journal_file_compare_locations(JournalFile
*af
, JournalFile
*bf
) {
2421 assert(af
->location_type
== LOCATION_SEEK
);
2422 assert(bf
->location_type
== LOCATION_SEEK
);
2424 /* If contents and timestamps match, these entries are
2425 * identical, even if the seqnum does not match */
2426 if (sd_id128_equal(af
->current_boot_id
, bf
->current_boot_id
) &&
2427 af
->current_monotonic
== bf
->current_monotonic
&&
2428 af
->current_realtime
== bf
->current_realtime
&&
2429 af
->current_xor_hash
== bf
->current_xor_hash
)
2432 if (sd_id128_equal(af
->header
->seqnum_id
, bf
->header
->seqnum_id
)) {
2434 /* If this is from the same seqnum source, compare
2436 if (af
->current_seqnum
< bf
->current_seqnum
)
2438 if (af
->current_seqnum
> bf
->current_seqnum
)
2441 /* Wow! This is weird, different data but the same
2442 * seqnums? Something is borked, but let's make the
2443 * best of it and compare by time. */
2446 if (sd_id128_equal(af
->current_boot_id
, bf
->current_boot_id
)) {
2448 /* If the boot id matches, compare monotonic time */
2449 if (af
->current_monotonic
< bf
->current_monotonic
)
2451 if (af
->current_monotonic
> bf
->current_monotonic
)
2455 /* Otherwise, compare UTC time */
2456 if (af
->current_realtime
< bf
->current_realtime
)
2458 if (af
->current_realtime
> bf
->current_realtime
)
2461 /* Finally, compare by contents */
2462 if (af
->current_xor_hash
< bf
->current_xor_hash
)
2464 if (af
->current_xor_hash
> bf
->current_xor_hash
)
2470 int journal_file_next_entry(
2473 direction_t direction
,
2474 Object
**ret
, uint64_t *offset
) {
2482 n
= le64toh(f
->header
->n_entries
);
2487 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
2489 r
= generic_array_bisect(f
,
2490 le64toh(f
->header
->entry_array_offset
),
2491 le64toh(f
->header
->n_entries
),
2500 if (direction
== DIRECTION_DOWN
) {
2513 /* And jump to it */
2514 r
= generic_array_get(f
,
2515 le64toh(f
->header
->entry_array_offset
),
2518 if (r
== -EBADMSG
&& direction
== DIRECTION_DOWN
) {
2519 /* Special case: when we iterate throught the journal file linearly, and hit an entry we can't read,
2520 * consider this the end of the journal file. */
2521 log_debug_errno(r
, "Encountered entry we can't read while iterating through journal file. Considering this the end of the file.");
2528 (direction
== DIRECTION_DOWN
? ofs
<= p
: ofs
>= p
)) {
2529 log_debug("%s: entry array corrupted at entry %" PRIu64
, f
->path
, i
);
2539 int journal_file_next_entry_for_data(
2541 Object
*o
, uint64_t p
,
2542 uint64_t data_offset
,
2543 direction_t direction
,
2544 Object
**ret
, uint64_t *offset
) {
2551 assert(p
> 0 || !o
);
2553 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2557 n
= le64toh(d
->data
.n_entries
);
2562 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
2564 if (o
->object
.type
!= OBJECT_ENTRY
)
2567 r
= generic_array_bisect_plus_one(f
,
2568 le64toh(d
->data
.entry_offset
),
2569 le64toh(d
->data
.entry_array_offset
),
2570 le64toh(d
->data
.n_entries
),
2580 if (direction
== DIRECTION_DOWN
) {
2594 return generic_array_get_plus_one(f
,
2595 le64toh(d
->data
.entry_offset
),
2596 le64toh(d
->data
.entry_array_offset
),
2601 int journal_file_move_to_entry_by_offset_for_data(
2603 uint64_t data_offset
,
2605 direction_t direction
,
2606 Object
**ret
, uint64_t *offset
) {
2613 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2617 return generic_array_bisect_plus_one(f
,
2618 le64toh(d
->data
.entry_offset
),
2619 le64toh(d
->data
.entry_array_offset
),
2620 le64toh(d
->data
.n_entries
),
2627 int journal_file_move_to_entry_by_monotonic_for_data(
2629 uint64_t data_offset
,
2632 direction_t direction
,
2633 Object
**ret
, uint64_t *offset
) {
2641 /* First, seek by time */
2642 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &b
);
2648 r
= generic_array_bisect_plus_one(f
,
2649 le64toh(o
->data
.entry_offset
),
2650 le64toh(o
->data
.entry_array_offset
),
2651 le64toh(o
->data
.n_entries
),
2653 test_object_monotonic
,
2659 /* And now, continue seeking until we find an entry that
2660 * exists in both bisection arrays */
2666 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2670 r
= generic_array_bisect_plus_one(f
,
2671 le64toh(d
->data
.entry_offset
),
2672 le64toh(d
->data
.entry_array_offset
),
2673 le64toh(d
->data
.n_entries
),
2681 r
= journal_file_move_to_object(f
, OBJECT_DATA
, b
, &o
);
2685 r
= generic_array_bisect_plus_one(f
,
2686 le64toh(o
->data
.entry_offset
),
2687 le64toh(o
->data
.entry_array_offset
),
2688 le64toh(o
->data
.n_entries
),
2710 int journal_file_move_to_entry_by_seqnum_for_data(
2712 uint64_t data_offset
,
2714 direction_t direction
,
2715 Object
**ret
, uint64_t *offset
) {
2722 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2726 return generic_array_bisect_plus_one(f
,
2727 le64toh(d
->data
.entry_offset
),
2728 le64toh(d
->data
.entry_array_offset
),
2729 le64toh(d
->data
.n_entries
),
2736 int journal_file_move_to_entry_by_realtime_for_data(
2738 uint64_t data_offset
,
2740 direction_t direction
,
2741 Object
**ret
, uint64_t *offset
) {
2748 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2752 return generic_array_bisect_plus_one(f
,
2753 le64toh(d
->data
.entry_offset
),
2754 le64toh(d
->data
.entry_array_offset
),
2755 le64toh(d
->data
.n_entries
),
2757 test_object_realtime
,
2762 void journal_file_dump(JournalFile
*f
) {
2770 journal_file_print_header(f
);
2772 p
= le64toh(f
->header
->header_size
);
2774 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &o
);
2778 switch (o
->object
.type
) {
2781 printf("Type: OBJECT_UNUSED\n");
2785 printf("Type: OBJECT_DATA\n");
2789 printf("Type: OBJECT_FIELD\n");
2793 printf("Type: OBJECT_ENTRY seqnum=%"PRIu64
" monotonic=%"PRIu64
" realtime=%"PRIu64
"\n",
2794 le64toh(o
->entry
.seqnum
),
2795 le64toh(o
->entry
.monotonic
),
2796 le64toh(o
->entry
.realtime
));
2799 case OBJECT_FIELD_HASH_TABLE
:
2800 printf("Type: OBJECT_FIELD_HASH_TABLE\n");
2803 case OBJECT_DATA_HASH_TABLE
:
2804 printf("Type: OBJECT_DATA_HASH_TABLE\n");
2807 case OBJECT_ENTRY_ARRAY
:
2808 printf("Type: OBJECT_ENTRY_ARRAY\n");
2812 printf("Type: OBJECT_TAG seqnum=%"PRIu64
" epoch=%"PRIu64
"\n",
2813 le64toh(o
->tag
.seqnum
),
2814 le64toh(o
->tag
.epoch
));
2818 printf("Type: unknown (%i)\n", o
->object
.type
);
2822 if (o
->object
.flags
& OBJECT_COMPRESSION_MASK
)
2823 printf("Flags: %s\n",
2824 object_compressed_to_string(o
->object
.flags
& OBJECT_COMPRESSION_MASK
));
2826 if (p
== le64toh(f
->header
->tail_object_offset
))
2829 p
= p
+ ALIGN64(le64toh(o
->object
.size
));
2834 log_error("File corrupt");
2837 static const char* format_timestamp_safe(char *buf
, size_t l
, usec_t t
) {
2840 x
= format_timestamp(buf
, l
, t
);
2846 void journal_file_print_header(JournalFile
*f
) {
2847 char a
[33], b
[33], c
[33], d
[33];
2848 char x
[FORMAT_TIMESTAMP_MAX
], y
[FORMAT_TIMESTAMP_MAX
], z
[FORMAT_TIMESTAMP_MAX
];
2850 char bytes
[FORMAT_BYTES_MAX
];
2855 printf("File Path: %s\n"
2859 "Sequential Number ID: %s\n"
2861 "Compatible Flags:%s%s\n"
2862 "Incompatible Flags:%s%s%s\n"
2863 "Header size: %"PRIu64
"\n"
2864 "Arena size: %"PRIu64
"\n"
2865 "Data Hash Table Size: %"PRIu64
"\n"
2866 "Field Hash Table Size: %"PRIu64
"\n"
2867 "Rotate Suggested: %s\n"
2868 "Head Sequential Number: %"PRIu64
" (%"PRIx64
")\n"
2869 "Tail Sequential Number: %"PRIu64
" (%"PRIx64
")\n"
2870 "Head Realtime Timestamp: %s (%"PRIx64
")\n"
2871 "Tail Realtime Timestamp: %s (%"PRIx64
")\n"
2872 "Tail Monotonic Timestamp: %s (%"PRIx64
")\n"
2873 "Objects: %"PRIu64
"\n"
2874 "Entry Objects: %"PRIu64
"\n",
2876 sd_id128_to_string(f
->header
->file_id
, a
),
2877 sd_id128_to_string(f
->header
->machine_id
, b
),
2878 sd_id128_to_string(f
->header
->boot_id
, c
),
2879 sd_id128_to_string(f
->header
->seqnum_id
, d
),
2880 f
->header
->state
== STATE_OFFLINE
? "OFFLINE" :
2881 f
->header
->state
== STATE_ONLINE
? "ONLINE" :
2882 f
->header
->state
== STATE_ARCHIVED
? "ARCHIVED" : "UNKNOWN",
2883 JOURNAL_HEADER_SEALED(f
->header
) ? " SEALED" : "",
2884 (le32toh(f
->header
->compatible_flags
) & ~HEADER_COMPATIBLE_ANY
) ? " ???" : "",
2885 JOURNAL_HEADER_COMPRESSED_XZ(f
->header
) ? " COMPRESSED-XZ" : "",
2886 JOURNAL_HEADER_COMPRESSED_LZ4(f
->header
) ? " COMPRESSED-LZ4" : "",
2887 (le32toh(f
->header
->incompatible_flags
) & ~HEADER_INCOMPATIBLE_ANY
) ? " ???" : "",
2888 le64toh(f
->header
->header_size
),
2889 le64toh(f
->header
->arena_size
),
2890 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
2891 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
),
2892 yes_no(journal_file_rotate_suggested(f
, 0)),
2893 le64toh(f
->header
->head_entry_seqnum
), le64toh(f
->header
->head_entry_seqnum
),
2894 le64toh(f
->header
->tail_entry_seqnum
), le64toh(f
->header
->tail_entry_seqnum
),
2895 format_timestamp_safe(x
, sizeof(x
), le64toh(f
->header
->head_entry_realtime
)), le64toh(f
->header
->head_entry_realtime
),
2896 format_timestamp_safe(y
, sizeof(y
), le64toh(f
->header
->tail_entry_realtime
)), le64toh(f
->header
->tail_entry_realtime
),
2897 format_timespan(z
, sizeof(z
), le64toh(f
->header
->tail_entry_monotonic
), USEC_PER_MSEC
), le64toh(f
->header
->tail_entry_monotonic
),
2898 le64toh(f
->header
->n_objects
),
2899 le64toh(f
->header
->n_entries
));
2901 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
2902 printf("Data Objects: %"PRIu64
"\n"
2903 "Data Hash Table Fill: %.1f%%\n",
2904 le64toh(f
->header
->n_data
),
2905 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))));
2907 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
2908 printf("Field Objects: %"PRIu64
"\n"
2909 "Field Hash Table Fill: %.1f%%\n",
2910 le64toh(f
->header
->n_fields
),
2911 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))));
2913 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_tags
))
2914 printf("Tag Objects: %"PRIu64
"\n",
2915 le64toh(f
->header
->n_tags
));
2916 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
2917 printf("Entry Array Objects: %"PRIu64
"\n",
2918 le64toh(f
->header
->n_entry_arrays
));
2920 if (fstat(f
->fd
, &st
) >= 0)
2921 printf("Disk usage: %s\n", format_bytes(bytes
, sizeof(bytes
), (uint64_t) st
.st_blocks
* 512ULL));
2924 static int journal_file_warn_btrfs(JournalFile
*f
) {
2930 /* Before we write anything, check if the COW logic is turned
2931 * off on btrfs. Given our write pattern that is quite
2932 * unfriendly to COW file systems this should greatly improve
2933 * performance on COW file systems, such as btrfs, at the
2934 * expense of data integrity features (which shouldn't be too
2935 * bad, given that we do our own checksumming). */
2937 r
= btrfs_is_filesystem(f
->fd
);
2939 return log_warning_errno(r
, "Failed to determine if journal is on btrfs: %m");
2943 r
= read_attr_fd(f
->fd
, &attrs
);
2945 return log_warning_errno(r
, "Failed to read file attributes: %m");
2947 if (attrs
& FS_NOCOW_FL
) {
2948 log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
2952 log_notice("Creating journal file %s on a btrfs file system, and copy-on-write is enabled. "
2953 "This is likely to slow down journal access substantially, please consider turning "
2954 "off the copy-on-write file attribute on the journal directory, using chattr +C.", f
->path
);
2959 int journal_file_open(
2966 JournalMetrics
*metrics
,
2967 MMapCache
*mmap_cache
,
2968 Set
*deferred_closes
,
2969 JournalFile
*template,
2970 JournalFile
**ret
) {
2972 bool newly_created
= false;
2978 assert(fd
>= 0 || fname
);
2980 if ((flags
& O_ACCMODE
) != O_RDONLY
&&
2981 (flags
& O_ACCMODE
) != O_RDWR
)
2985 if (!endswith(fname
, ".journal") &&
2986 !endswith(fname
, ".journal~"))
2990 f
= new0(JournalFile
, 1);
2998 f
->prot
= prot_from_flags(flags
);
2999 f
->writable
= (flags
& O_ACCMODE
) != O_RDONLY
;
3000 #if defined(HAVE_LZ4)
3001 f
->compress_lz4
= compress
;
3002 #elif defined(HAVE_XZ)
3003 f
->compress_xz
= compress
;
3010 f
->mmap
= mmap_cache_ref(mmap_cache
);
3012 f
->mmap
= mmap_cache_new();
3020 f
->path
= strdup(fname
);
3021 else /* If we don't know the path, fill in something explanatory and vaguely useful */
3022 asprintf(&f
->path
, "/proc/self/%i", fd
);
3028 f
->chain_cache
= ordered_hashmap_new(&uint64_hash_ops
);
3029 if (!f
->chain_cache
) {
3035 f
->fd
= open(f
->path
, f
->flags
|O_CLOEXEC
, f
->mode
);
3041 /* fds we opened here by us should also be closed by us. */
3045 r
= journal_file_fstat(f
);
3049 if (f
->last_stat
.st_size
== 0 && f
->writable
) {
3051 (void) journal_file_warn_btrfs(f
);
3053 /* Let's attach the creation time to the journal file,
3054 * so that the vacuuming code knows the age of this
3055 * file even if the file might end up corrupted one
3056 * day... Ideally we'd just use the creation time many
3057 * file systems maintain for each file, but there is
3058 * currently no usable API to query this, hence let's
3059 * emulate this via extended attributes. If extended
3060 * attributes are not supported we'll just skip this,
3061 * and rely solely on mtime/atime/ctime of the file. */
3063 fd_setcrtime(f
->fd
, 0);
3066 /* Try to load the FSPRG state, and if we can't, then
3067 * just don't do sealing */
3069 r
= journal_file_fss_load(f
);
3075 r
= journal_file_init_header(f
, template);
3079 r
= journal_file_fstat(f
);
3083 newly_created
= true;
3086 if (f
->last_stat
.st_size
< (off_t
) HEADER_SIZE_MIN
) {
3091 r
= mmap_cache_get(f
->mmap
, f
->fd
, f
->prot
, CONTEXT_HEADER
, true, 0, PAGE_ALIGN(sizeof(Header
)), &f
->last_stat
, &h
);
3097 if (!newly_created
) {
3098 if (deferred_closes
)
3099 journal_file_close_set(deferred_closes
);
3101 r
= journal_file_verify_header(f
);
3107 if (!newly_created
&& f
->writable
) {
3108 r
= journal_file_fss_load(f
);
3116 journal_default_metrics(metrics
, f
->fd
);
3117 f
->metrics
= *metrics
;
3118 } else if (template)
3119 f
->metrics
= template->metrics
;
3121 r
= journal_file_refresh_header(f
);
3127 r
= journal_file_hmac_setup(f
);
3132 if (newly_created
) {
3133 r
= journal_file_setup_field_hash_table(f
);
3137 r
= journal_file_setup_data_hash_table(f
);
3142 r
= journal_file_append_first_tag(f
);
3148 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
)) {
3153 if (template && template->post_change_timer
) {
3154 r
= journal_file_enable_post_change_timer(
3156 sd_event_source_get_event(template->post_change_timer
),
3157 template->post_change_timer_period
);
3163 /* The file is opened now successfully, thus we take possesion of any passed in fd. */
3170 if (f
->fd
>= 0 && mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
3173 (void) journal_file_close(f
);
3178 int journal_file_rotate(JournalFile
**f
, bool compress
, bool seal
, Set
*deferred_closes
) {
3179 _cleanup_free_
char *p
= NULL
;
3181 JournalFile
*old_file
, *new_file
= NULL
;
3189 if (!old_file
->writable
)
3192 /* Is this a journal file that was passed to us as fd? If so, we synthesized a path name for it, and we refuse
3193 * rotation, since we don't know the actual path, and couldn't rename the file hence.*/
3194 if (path_startswith(old_file
->path
, "/proc/self/fd"))
3197 if (!endswith(old_file
->path
, ".journal"))
3200 l
= strlen(old_file
->path
);
3201 r
= asprintf(&p
, "%.*s@" SD_ID128_FORMAT_STR
"-%016"PRIx64
"-%016"PRIx64
".journal",
3202 (int) l
- 8, old_file
->path
,
3203 SD_ID128_FORMAT_VAL(old_file
->header
->seqnum_id
),
3204 le64toh((*f
)->header
->head_entry_seqnum
),
3205 le64toh((*f
)->header
->head_entry_realtime
));
3209 /* Try to rename the file to the archived version. If the file
3210 * already was deleted, we'll get ENOENT, let's ignore that
3212 r
= rename(old_file
->path
, p
);
3213 if (r
< 0 && errno
!= ENOENT
)
3216 /* Sync the rename to disk */
3217 (void) fsync_directory_of_file(old_file
->fd
);
3219 /* Set as archive so offlining commits w/state=STATE_ARCHIVED.
3220 * Previously we would set old_file->header->state to STATE_ARCHIVED directly here,
3221 * but journal_file_set_offline() short-circuits when state != STATE_ONLINE, which
3222 * would result in the rotated journal never getting fsync() called before closing.
3223 * Now we simply queue the archive state by setting an archive bit, leaving the state
3224 * as STATE_ONLINE so proper offlining occurs. */
3225 old_file
->archive
= true;
3227 /* Currently, btrfs is not very good with out write patterns
3228 * and fragments heavily. Let's defrag our journal files when
3229 * we archive them */
3230 old_file
->defrag_on_close
= true;
3232 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
);
3234 if (deferred_closes
&&
3235 set_put(deferred_closes
, old_file
) >= 0)
3236 (void) journal_file_set_offline(old_file
, false);
3238 (void) journal_file_close(old_file
);
3244 int journal_file_open_reliably(
3250 JournalMetrics
*metrics
,
3251 MMapCache
*mmap_cache
,
3252 Set
*deferred_closes
,
3253 JournalFile
*template,
3254 JournalFile
**ret
) {
3258 _cleanup_free_
char *p
= NULL
;
3260 r
= journal_file_open(-1, fname
, flags
, mode
, compress
, seal
, metrics
, mmap_cache
, deferred_closes
, template, ret
);
3262 -EBADMSG
, /* corrupted */
3263 -ENODATA
, /* truncated */
3264 -EHOSTDOWN
, /* other machine */
3265 -EPROTONOSUPPORT
, /* incompatible feature */
3266 -EBUSY
, /* unclean shutdown */
3267 -ESHUTDOWN
, /* already archived */
3268 -EIO
, /* IO error, including SIGBUS on mmap */
3269 -EIDRM
/* File has been deleted */))
3272 if ((flags
& O_ACCMODE
) == O_RDONLY
)
3275 if (!(flags
& O_CREAT
))
3278 if (!endswith(fname
, ".journal"))
3281 /* The file is corrupted. Rotate it away and try it again (but only once) */
3284 if (asprintf(&p
, "%.*s@%016"PRIx64
"-%016"PRIx64
".journal~",
3286 now(CLOCK_REALTIME
),
3290 if (rename(fname
, p
) < 0)
3293 /* btrfs doesn't cope well with our write pattern and
3294 * fragments heavily. Let's defrag all files we rotate */
3296 (void) chattr_path(p
, 0, FS_NOCOW_FL
);
3297 (void) btrfs_defrag(p
);
3299 log_warning_errno(r
, "File %s corrupted or uncleanly shut down, renaming and replacing.", fname
);
3301 return journal_file_open(-1, fname
, flags
, mode
, compress
, seal
, metrics
, mmap_cache
, deferred_closes
, template, ret
);
3304 int journal_file_copy_entry(JournalFile
*from
, JournalFile
*to
, Object
*o
, uint64_t p
, uint64_t *seqnum
, Object
**ret
, uint64_t *offset
) {
3306 uint64_t q
, xor_hash
= 0;
3319 ts
.monotonic
= le64toh(o
->entry
.monotonic
);
3320 ts
.realtime
= le64toh(o
->entry
.realtime
);
3322 n
= journal_file_entry_n_items(o
);
3323 /* alloca() can't take 0, hence let's allocate at least one */
3324 items
= alloca(sizeof(EntryItem
) * MAX(1u, n
));
3326 for (i
= 0; i
< n
; i
++) {
3333 q
= le64toh(o
->entry
.items
[i
].object_offset
);
3334 le_hash
= o
->entry
.items
[i
].hash
;
3336 r
= journal_file_move_to_object(from
, OBJECT_DATA
, q
, &o
);
3340 if (le_hash
!= o
->data
.hash
)
3343 l
= le64toh(o
->object
.size
) - offsetof(Object
, data
.payload
);
3346 /* We hit the limit on 32bit machines */
3347 if ((uint64_t) t
!= l
)
3350 if (o
->object
.flags
& OBJECT_COMPRESSION_MASK
) {
3351 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
3354 r
= decompress_blob(o
->object
.flags
& OBJECT_COMPRESSION_MASK
,
3355 o
->data
.payload
, l
, &from
->compress_buffer
, &from
->compress_buffer_size
, &rsize
, 0);
3359 data
= from
->compress_buffer
;
3362 return -EPROTONOSUPPORT
;
3365 data
= o
->data
.payload
;
3367 r
= journal_file_append_data(to
, data
, l
, &u
, &h
);
3371 xor_hash
^= le64toh(u
->data
.hash
);
3372 items
[i
].object_offset
= htole64(h
);
3373 items
[i
].hash
= u
->data
.hash
;
3375 r
= journal_file_move_to_object(from
, OBJECT_ENTRY
, p
, &o
);
3380 r
= journal_file_append_entry_internal(to
, &ts
, xor_hash
, items
, n
, seqnum
, ret
, offset
);
3382 if (mmap_cache_got_sigbus(to
->mmap
, to
->fd
))
3388 void journal_reset_metrics(JournalMetrics
*m
) {
3391 /* Set everything to "pick automatic values". */
3393 *m
= (JournalMetrics
) {
3394 .min_use
= (uint64_t) -1,
3395 .max_use
= (uint64_t) -1,
3396 .min_size
= (uint64_t) -1,
3397 .max_size
= (uint64_t) -1,
3398 .keep_free
= (uint64_t) -1,
3399 .n_max_files
= (uint64_t) -1,
3403 void journal_default_metrics(JournalMetrics
*m
, int fd
) {
3404 char a
[FORMAT_BYTES_MAX
], b
[FORMAT_BYTES_MAX
], c
[FORMAT_BYTES_MAX
], d
[FORMAT_BYTES_MAX
], e
[FORMAT_BYTES_MAX
];
3411 if (fstatvfs(fd
, &ss
) >= 0)
3412 fs_size
= ss
.f_frsize
* ss
.f_blocks
;
3414 log_debug_errno(errno
, "Failed to detremine disk size: %m");
3418 if (m
->max_use
== (uint64_t) -1) {
3421 m
->max_use
= PAGE_ALIGN(fs_size
/ 10); /* 10% of file system size */
3423 if (m
->max_use
> DEFAULT_MAX_USE_UPPER
)
3424 m
->max_use
= DEFAULT_MAX_USE_UPPER
;
3426 if (m
->max_use
< DEFAULT_MAX_USE_LOWER
)
3427 m
->max_use
= DEFAULT_MAX_USE_LOWER
;
3429 m
->max_use
= DEFAULT_MAX_USE_LOWER
;
3431 m
->max_use
= PAGE_ALIGN(m
->max_use
);
3433 if (m
->max_use
!= 0 && m
->max_use
< JOURNAL_FILE_SIZE_MIN
*2)
3434 m
->max_use
= JOURNAL_FILE_SIZE_MIN
*2;
3437 if (m
->min_use
== (uint64_t) -1)
3438 m
->min_use
= DEFAULT_MIN_USE
;
3440 if (m
->min_use
> m
->max_use
)
3441 m
->min_use
= m
->max_use
;
3443 if (m
->max_size
== (uint64_t) -1) {
3444 m
->max_size
= PAGE_ALIGN(m
->max_use
/ 8); /* 8 chunks */
3446 if (m
->max_size
> DEFAULT_MAX_SIZE_UPPER
)
3447 m
->max_size
= DEFAULT_MAX_SIZE_UPPER
;
3449 m
->max_size
= PAGE_ALIGN(m
->max_size
);
3451 if (m
->max_size
!= 0) {
3452 if (m
->max_size
< JOURNAL_FILE_SIZE_MIN
)
3453 m
->max_size
= JOURNAL_FILE_SIZE_MIN
;
3455 if (m
->max_use
!= 0 && m
->max_size
*2 > m
->max_use
)
3456 m
->max_use
= m
->max_size
*2;
3459 if (m
->min_size
== (uint64_t) -1)
3460 m
->min_size
= JOURNAL_FILE_SIZE_MIN
;
3462 m
->min_size
= PAGE_ALIGN(m
->min_size
);
3464 if (m
->min_size
< JOURNAL_FILE_SIZE_MIN
)
3465 m
->min_size
= JOURNAL_FILE_SIZE_MIN
;
3467 if (m
->max_size
!= 0 && m
->min_size
> m
->max_size
)
3468 m
->max_size
= m
->min_size
;
3471 if (m
->keep_free
== (uint64_t) -1) {
3474 m
->keep_free
= PAGE_ALIGN(fs_size
* 3 / 20); /* 15% of file system size */
3476 if (m
->keep_free
> DEFAULT_KEEP_FREE_UPPER
)
3477 m
->keep_free
= DEFAULT_KEEP_FREE_UPPER
;
3480 m
->keep_free
= DEFAULT_KEEP_FREE
;
3483 if (m
->n_max_files
== (uint64_t) -1)
3484 m
->n_max_files
= DEFAULT_N_MAX_FILES
;
3486 log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64
,
3487 format_bytes(a
, sizeof(a
), m
->min_use
),
3488 format_bytes(b
, sizeof(b
), m
->max_use
),
3489 format_bytes(c
, sizeof(c
), m
->max_size
),
3490 format_bytes(d
, sizeof(d
), m
->min_size
),
3491 format_bytes(e
, sizeof(e
), m
->keep_free
),
3495 int journal_file_get_cutoff_realtime_usec(JournalFile
*f
, usec_t
*from
, usec_t
*to
) {
3501 if (f
->header
->head_entry_realtime
== 0)
3504 *from
= le64toh(f
->header
->head_entry_realtime
);
3508 if (f
->header
->tail_entry_realtime
== 0)
3511 *to
= le64toh(f
->header
->tail_entry_realtime
);
3517 int journal_file_get_cutoff_monotonic_usec(JournalFile
*f
, sd_id128_t boot_id
, usec_t
*from
, usec_t
*to
) {
3525 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &p
);
3529 if (le64toh(o
->data
.n_entries
) <= 0)
3533 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, le64toh(o
->data
.entry_offset
), &o
);
3537 *from
= le64toh(o
->entry
.monotonic
);
3541 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
3545 r
= generic_array_get_plus_one(f
,
3546 le64toh(o
->data
.entry_offset
),
3547 le64toh(o
->data
.entry_array_offset
),
3548 le64toh(o
->data
.n_entries
)-1,
3553 *to
= le64toh(o
->entry
.monotonic
);
3559 bool journal_file_rotate_suggested(JournalFile
*f
, usec_t max_file_usec
) {
3563 /* If we gained new header fields we gained new features,
3564 * hence suggest a rotation */
3565 if (le64toh(f
->header
->header_size
) < sizeof(Header
)) {
3566 log_debug("%s uses an outdated header, suggesting rotation.", f
->path
);
3570 /* Let's check if the hash tables grew over a certain fill
3571 * level (75%, borrowing this value from Java's hash table
3572 * implementation), and if so suggest a rotation. To calculate
3573 * the fill level we need the n_data field, which only exists
3574 * in newer versions. */
3576 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
3577 if (le64toh(f
->header
->n_data
) * 4ULL > (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
3578 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.",
3580 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))),
3581 le64toh(f
->header
->n_data
),
3582 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
3583 (unsigned long long) f
->last_stat
.st_size
,
3584 f
->last_stat
.st_size
/ le64toh(f
->header
->n_data
));
3588 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
3589 if (le64toh(f
->header
->n_fields
) * 4ULL > (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
3590 log_debug("Field hash table of %s has a fill level at %.1f (%"PRIu64
" of %"PRIu64
" items), suggesting rotation.",
3592 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))),
3593 le64toh(f
->header
->n_fields
),
3594 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
));
3598 /* Are the data objects properly indexed by field objects? */
3599 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
) &&
3600 JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
) &&
3601 le64toh(f
->header
->n_data
) > 0 &&
3602 le64toh(f
->header
->n_fields
) == 0)
3605 if (max_file_usec
> 0) {
3608 h
= le64toh(f
->header
->head_entry_realtime
);
3609 t
= now(CLOCK_REALTIME
);
3611 if (h
> 0 && t
> h
+ max_file_usec
)