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 "random-util.h"
43 #include "string-util.h"
44 #include "xattr-util.h"
46 #define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem))
47 #define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem))
49 #define COMPRESSION_SIZE_THRESHOLD (512ULL)
51 /* This is the minimum journal file size */
52 #define JOURNAL_FILE_SIZE_MIN (512ULL*1024ULL) /* 512 KiB */
54 /* These are the lower and upper bounds if we deduce the max_use value
55 * from the file system size */
56 #define DEFAULT_MAX_USE_LOWER (1ULL*1024ULL*1024ULL) /* 1 MiB */
57 #define DEFAULT_MAX_USE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
59 /* This is the default minimal use limit, how much we'll use even if keep_free suggests otherwise. */
60 #define DEFAULT_MIN_USE (1ULL*1024ULL*1024ULL) /* 1 MiB */
62 /* This is the upper bound if we deduce max_size from max_use */
63 #define DEFAULT_MAX_SIZE_UPPER (128ULL*1024ULL*1024ULL) /* 128 MiB */
65 /* This is the upper bound if we deduce the keep_free value from the
67 #define DEFAULT_KEEP_FREE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
69 /* This is the keep_free value when we can't determine the system
71 #define DEFAULT_KEEP_FREE (1024ULL*1024ULL) /* 1 MB */
73 /* This is the default maximum number of journal files to keep around. */
74 #define DEFAULT_N_MAX_FILES (100)
76 /* n_data was the first entry we added after the initial file format design */
77 #define HEADER_SIZE_MIN ALIGN64(offsetof(Header, n_data))
79 /* How many entries to keep in the entry array chain cache at max */
80 #define CHAIN_CACHE_MAX 20
82 /* How much to increase the journal file size at once each time we allocate something new. */
83 #define FILE_SIZE_INCREASE (8ULL*1024ULL*1024ULL) /* 8MB */
85 /* Reread fstat() of the file for detecting deletions at least this often */
86 #define LAST_STAT_REFRESH_USEC (5*USEC_PER_SEC)
88 /* The mmap context to use for the header we pick as one above the last defined typed */
89 #define CONTEXT_HEADER _OBJECT_TYPE_MAX
91 /* This may be called from a separate thread to prevent blocking the caller for the duration of fsync().
92 * As a result we use atomic operations on f->offline_state for inter-thread communications with
93 * journal_file_set_offline() and journal_file_set_online(). */
94 static void journal_file_set_offline_internal(JournalFile
*f
) {
100 switch (f
->offline_state
) {
102 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_CANCEL
, OFFLINE_DONE
))
106 case OFFLINE_AGAIN_FROM_SYNCING
:
107 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_AGAIN_FROM_SYNCING
, OFFLINE_SYNCING
))
111 case OFFLINE_AGAIN_FROM_OFFLINING
:
112 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_AGAIN_FROM_OFFLINING
, OFFLINE_SYNCING
))
116 case OFFLINE_SYNCING
:
119 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_SYNCING
, OFFLINE_OFFLINING
))
122 f
->header
->state
= STATE_OFFLINE
;
126 case OFFLINE_OFFLINING
:
127 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_OFFLINING
, OFFLINE_DONE
))
135 log_debug("OFFLINE_JOINED unexpected offline state for journal_file_set_offline_internal()");
141 static void * journal_file_set_offline_thread(void *arg
) {
142 JournalFile
*f
= arg
;
144 journal_file_set_offline_internal(f
);
149 static int journal_file_set_offline_thread_join(JournalFile
*f
) {
154 if (f
->offline_state
== OFFLINE_JOINED
)
157 r
= pthread_join(f
->offline_thread
, NULL
);
161 f
->offline_state
= OFFLINE_JOINED
;
163 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
169 /* Trigger a restart if the offline thread is mid-flight in a restartable state. */
170 static bool journal_file_set_offline_try_restart(JournalFile
*f
) {
172 switch (f
->offline_state
) {
173 case OFFLINE_AGAIN_FROM_SYNCING
:
174 case OFFLINE_AGAIN_FROM_OFFLINING
:
178 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_CANCEL
, OFFLINE_AGAIN_FROM_SYNCING
))
182 case OFFLINE_SYNCING
:
183 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_SYNCING
, OFFLINE_AGAIN_FROM_SYNCING
))
187 case OFFLINE_OFFLINING
:
188 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_OFFLINING
, OFFLINE_AGAIN_FROM_OFFLINING
))
198 /* Sets a journal offline.
200 * If wait is false then an offline is dispatched in a separate thread for a
201 * subsequent journal_file_set_offline() or journal_file_set_online() of the
202 * same journal to synchronize with.
204 * If wait is true, then either an existing offline thread will be restarted
205 * and joined, or if none exists the offline is simply performed in this
206 * context without involving another thread.
208 int journal_file_set_offline(JournalFile
*f
, bool wait
) {
217 if (!(f
->fd
>= 0 && f
->header
))
220 if (f
->header
->state
!= STATE_ONLINE
)
223 /* Restart an in-flight offline thread and wait if needed, or join a lingering done one. */
224 restarted
= journal_file_set_offline_try_restart(f
);
225 if ((restarted
&& wait
) || !restarted
) {
226 r
= journal_file_set_offline_thread_join(f
);
234 /* Initiate a new offline. */
235 f
->offline_state
= OFFLINE_SYNCING
;
237 if (wait
) /* Without using a thread if waiting. */
238 journal_file_set_offline_internal(f
);
240 r
= pthread_create(&f
->offline_thread
, NULL
, journal_file_set_offline_thread
, f
);
248 static int journal_file_set_online(JournalFile
*f
) {
256 if (!(f
->fd
>= 0 && f
->header
))
260 switch (f
->offline_state
) {
262 /* No offline thread, no need to wait. */
266 case OFFLINE_SYNCING
:
267 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_SYNCING
, OFFLINE_CANCEL
))
269 /* Canceled syncing prior to offlining, no need to wait. */
272 case OFFLINE_AGAIN_FROM_SYNCING
:
273 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_AGAIN_FROM_SYNCING
, OFFLINE_CANCEL
))
275 /* Canceled restart from syncing, no need to wait. */
278 case OFFLINE_AGAIN_FROM_OFFLINING
:
279 if (!__sync_bool_compare_and_swap(&f
->offline_state
, OFFLINE_AGAIN_FROM_OFFLINING
, OFFLINE_CANCEL
))
281 /* Canceled restart from offlining, must wait for offlining to complete however. */
283 /* fall through to wait */
287 r
= journal_file_set_offline_thread_join(f
);
297 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
300 switch (f
->header
->state
) {
305 f
->header
->state
= STATE_ONLINE
;
314 bool journal_file_is_offlining(JournalFile
*f
) {
317 __sync_synchronize();
319 if (f
->offline_state
== OFFLINE_DONE
||
320 f
->offline_state
== OFFLINE_JOINED
)
326 JournalFile
* journal_file_close(JournalFile
*f
) {
330 /* Write the final tag */
331 if (f
->seal
&& f
->writable
)
332 journal_file_append_tag(f
);
335 if (f
->post_change_timer
) {
338 if (sd_event_source_get_enabled(f
->post_change_timer
, &enabled
) >= 0)
339 if (enabled
== SD_EVENT_ONESHOT
)
340 journal_file_post_change(f
);
342 (void) sd_event_source_set_enabled(f
->post_change_timer
, SD_EVENT_OFF
);
343 sd_event_source_unref(f
->post_change_timer
);
346 journal_file_set_offline(f
, true);
348 if (f
->mmap
&& f
->fd
>= 0)
349 mmap_cache_close_fd(f
->mmap
, f
->fd
);
351 if (f
->fd
>= 0 && f
->defrag_on_close
) {
353 /* Be friendly to btrfs: turn COW back on again now,
354 * and defragment the file. We won't write to the file
355 * ever again, hence remove all fragmentation, and
356 * reenable all the good bits COW usually provides
357 * (such as data checksumming). */
359 (void) chattr_fd(f
->fd
, 0, FS_NOCOW_FL
);
360 (void) btrfs_defrag_fd(f
->fd
);
366 mmap_cache_unref(f
->mmap
);
368 ordered_hashmap_free_free(f
->chain_cache
);
370 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
371 free(f
->compress_buffer
);
376 munmap(f
->fss_file
, PAGE_ALIGN(f
->fss_file_size
));
378 free(f
->fsprg_state
);
383 gcry_md_close(f
->hmac
);
390 void journal_file_close_set(Set
*s
) {
395 while ((f
= set_steal_first(s
)))
396 (void) journal_file_close(f
);
399 static int journal_file_init_header(JournalFile
*f
, JournalFile
*template) {
406 memcpy(h
.signature
, HEADER_SIGNATURE
, 8);
407 h
.header_size
= htole64(ALIGN64(sizeof(h
)));
409 h
.incompatible_flags
|= htole32(
410 f
->compress_xz
* HEADER_INCOMPATIBLE_COMPRESSED_XZ
|
411 f
->compress_lz4
* HEADER_INCOMPATIBLE_COMPRESSED_LZ4
);
413 h
.compatible_flags
= htole32(
414 f
->seal
* HEADER_COMPATIBLE_SEALED
);
416 r
= sd_id128_randomize(&h
.file_id
);
421 h
.seqnum_id
= template->header
->seqnum_id
;
422 h
.tail_entry_seqnum
= template->header
->tail_entry_seqnum
;
424 h
.seqnum_id
= h
.file_id
;
426 k
= pwrite(f
->fd
, &h
, sizeof(h
), 0);
436 static int journal_file_refresh_header(JournalFile
*f
) {
443 r
= sd_id128_get_machine(&f
->header
->machine_id
);
447 r
= sd_id128_get_boot(&boot_id
);
451 if (sd_id128_equal(boot_id
, f
->header
->boot_id
))
452 f
->tail_entry_monotonic_valid
= true;
454 f
->header
->boot_id
= boot_id
;
456 r
= journal_file_set_online(f
);
458 /* Sync the online state to disk */
464 static int journal_file_verify_header(JournalFile
*f
) {
470 if (memcmp(f
->header
->signature
, HEADER_SIGNATURE
, 8))
473 /* In both read and write mode we refuse to open files with
474 * incompatible flags we don't know */
475 flags
= le32toh(f
->header
->incompatible_flags
);
476 if (flags
& ~HEADER_INCOMPATIBLE_SUPPORTED
) {
477 if (flags
& ~HEADER_INCOMPATIBLE_ANY
)
478 log_debug("Journal file %s has unknown incompatible flags %"PRIx32
,
479 f
->path
, flags
& ~HEADER_INCOMPATIBLE_ANY
);
480 flags
= (flags
& HEADER_INCOMPATIBLE_ANY
) & ~HEADER_INCOMPATIBLE_SUPPORTED
;
482 log_debug("Journal file %s uses incompatible flags %"PRIx32
483 " disabled at compilation time.", f
->path
, flags
);
484 return -EPROTONOSUPPORT
;
487 /* When open for writing we refuse to open files with
488 * compatible flags, too */
489 flags
= le32toh(f
->header
->compatible_flags
);
490 if (f
->writable
&& (flags
& ~HEADER_COMPATIBLE_SUPPORTED
)) {
491 if (flags
& ~HEADER_COMPATIBLE_ANY
)
492 log_debug("Journal file %s has unknown compatible flags %"PRIx32
,
493 f
->path
, flags
& ~HEADER_COMPATIBLE_ANY
);
494 flags
= (flags
& HEADER_COMPATIBLE_ANY
) & ~HEADER_COMPATIBLE_SUPPORTED
;
496 log_debug("Journal file %s uses compatible flags %"PRIx32
497 " disabled at compilation time.", f
->path
, flags
);
498 return -EPROTONOSUPPORT
;
501 if (f
->header
->state
>= _STATE_MAX
)
504 /* The first addition was n_data, so check that we are at least this large */
505 if (le64toh(f
->header
->header_size
) < HEADER_SIZE_MIN
)
508 if (JOURNAL_HEADER_SEALED(f
->header
) && !JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
511 if ((le64toh(f
->header
->header_size
) + le64toh(f
->header
->arena_size
)) > (uint64_t) f
->last_stat
.st_size
)
514 if (le64toh(f
->header
->tail_object_offset
) > (le64toh(f
->header
->header_size
) + le64toh(f
->header
->arena_size
)))
517 if (!VALID64(le64toh(f
->header
->data_hash_table_offset
)) ||
518 !VALID64(le64toh(f
->header
->field_hash_table_offset
)) ||
519 !VALID64(le64toh(f
->header
->tail_object_offset
)) ||
520 !VALID64(le64toh(f
->header
->entry_array_offset
)))
525 sd_id128_t machine_id
;
528 r
= sd_id128_get_machine(&machine_id
);
532 if (!sd_id128_equal(machine_id
, f
->header
->machine_id
))
535 state
= f
->header
->state
;
537 if (state
== STATE_ONLINE
) {
538 log_debug("Journal file %s is already online. Assuming unclean closing.", f
->path
);
540 } else if (state
== STATE_ARCHIVED
)
542 else if (state
!= STATE_OFFLINE
) {
543 log_debug("Journal file %s has unknown state %i.", f
->path
, state
);
548 f
->compress_xz
= JOURNAL_HEADER_COMPRESSED_XZ(f
->header
);
549 f
->compress_lz4
= JOURNAL_HEADER_COMPRESSED_LZ4(f
->header
);
551 f
->seal
= JOURNAL_HEADER_SEALED(f
->header
);
556 static int journal_file_fstat(JournalFile
*f
) {
560 if (fstat(f
->fd
, &f
->last_stat
) < 0)
563 f
->last_stat_usec
= now(CLOCK_MONOTONIC
);
565 /* Refuse appending to files that are already deleted */
566 if (f
->last_stat
.st_nlink
<= 0)
572 static int journal_file_allocate(JournalFile
*f
, uint64_t offset
, uint64_t size
) {
573 uint64_t old_size
, new_size
;
579 /* We assume that this file is not sparse, and we know that
580 * for sure, since we always call posix_fallocate()
583 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
587 le64toh(f
->header
->header_size
) +
588 le64toh(f
->header
->arena_size
);
590 new_size
= PAGE_ALIGN(offset
+ size
);
591 if (new_size
< le64toh(f
->header
->header_size
))
592 new_size
= le64toh(f
->header
->header_size
);
594 if (new_size
<= old_size
) {
596 /* We already pre-allocated enough space, but before
597 * we write to it, let's check with fstat() if the
598 * file got deleted, in order make sure we don't throw
599 * away the data immediately. Don't check fstat() for
600 * all writes though, but only once ever 10s. */
602 if (f
->last_stat_usec
+ LAST_STAT_REFRESH_USEC
> now(CLOCK_MONOTONIC
))
605 return journal_file_fstat(f
);
608 /* Allocate more space. */
610 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
613 if (new_size
> f
->metrics
.min_size
&& f
->metrics
.keep_free
> 0) {
616 if (fstatvfs(f
->fd
, &svfs
) >= 0) {
619 available
= LESS_BY((uint64_t) svfs
.f_bfree
* (uint64_t) svfs
.f_bsize
, f
->metrics
.keep_free
);
621 if (new_size
- old_size
> available
)
626 /* Increase by larger blocks at once */
627 new_size
= ((new_size
+FILE_SIZE_INCREASE
-1) / FILE_SIZE_INCREASE
) * FILE_SIZE_INCREASE
;
628 if (f
->metrics
.max_size
> 0 && new_size
> f
->metrics
.max_size
)
629 new_size
= f
->metrics
.max_size
;
631 /* Note that the glibc fallocate() fallback is very
632 inefficient, hence we try to minimize the allocation area
634 r
= posix_fallocate(f
->fd
, old_size
, new_size
- old_size
);
638 f
->header
->arena_size
= htole64(new_size
- le64toh(f
->header
->header_size
));
640 return journal_file_fstat(f
);
643 static unsigned type_to_context(ObjectType type
) {
644 /* One context for each type, plus one catch-all for the rest */
645 assert_cc(_OBJECT_TYPE_MAX
<= MMAP_CACHE_MAX_CONTEXTS
);
646 assert_cc(CONTEXT_HEADER
< MMAP_CACHE_MAX_CONTEXTS
);
647 return type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
? type
: 0;
650 static int journal_file_move_to(JournalFile
*f
, ObjectType type
, bool keep_always
, uint64_t offset
, uint64_t size
, void **ret
) {
659 /* Avoid SIGBUS on invalid accesses */
660 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
) {
661 /* Hmm, out of range? Let's refresh the fstat() data
662 * first, before we trust that check. */
664 r
= journal_file_fstat(f
);
668 if (offset
+ size
> (uint64_t) f
->last_stat
.st_size
)
669 return -EADDRNOTAVAIL
;
672 return mmap_cache_get(f
->mmap
, f
->fd
, f
->prot
, type_to_context(type
), keep_always
, offset
, size
, &f
->last_stat
, ret
);
675 static uint64_t minimum_header_size(Object
*o
) {
677 static const uint64_t table
[] = {
678 [OBJECT_DATA
] = sizeof(DataObject
),
679 [OBJECT_FIELD
] = sizeof(FieldObject
),
680 [OBJECT_ENTRY
] = sizeof(EntryObject
),
681 [OBJECT_DATA_HASH_TABLE
] = sizeof(HashTableObject
),
682 [OBJECT_FIELD_HASH_TABLE
] = sizeof(HashTableObject
),
683 [OBJECT_ENTRY_ARRAY
] = sizeof(EntryArrayObject
),
684 [OBJECT_TAG
] = sizeof(TagObject
),
687 if (o
->object
.type
>= ELEMENTSOF(table
) || table
[o
->object
.type
] <= 0)
688 return sizeof(ObjectHeader
);
690 return table
[o
->object
.type
];
693 int journal_file_move_to_object(JournalFile
*f
, ObjectType type
, uint64_t offset
, Object
**ret
) {
702 /* Objects may only be located at multiple of 64 bit */
703 if (!VALID64(offset
))
706 r
= journal_file_move_to(f
, type
, false, offset
, sizeof(ObjectHeader
), &t
);
711 s
= le64toh(o
->object
.size
);
713 if (s
< sizeof(ObjectHeader
))
716 if (o
->object
.type
<= OBJECT_UNUSED
)
719 if (s
< minimum_header_size(o
))
722 if (type
> OBJECT_UNUSED
&& o
->object
.type
!= type
)
725 if (s
> sizeof(ObjectHeader
)) {
726 r
= journal_file_move_to(f
, type
, false, offset
, s
, &t
);
737 static uint64_t journal_file_entry_seqnum(JournalFile
*f
, uint64_t *seqnum
) {
743 r
= le64toh(f
->header
->tail_entry_seqnum
) + 1;
746 /* If an external seqnum counter was passed, we update
747 * both the local and the external one, and set it to
748 * the maximum of both */
756 f
->header
->tail_entry_seqnum
= htole64(r
);
758 if (f
->header
->head_entry_seqnum
== 0)
759 f
->header
->head_entry_seqnum
= htole64(r
);
764 int journal_file_append_object(JournalFile
*f
, ObjectType type
, uint64_t size
, Object
**ret
, uint64_t *offset
) {
772 assert(type
> OBJECT_UNUSED
&& type
< _OBJECT_TYPE_MAX
);
773 assert(size
>= sizeof(ObjectHeader
));
777 r
= journal_file_set_online(f
);
781 p
= le64toh(f
->header
->tail_object_offset
);
783 p
= le64toh(f
->header
->header_size
);
785 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &tail
);
789 p
+= ALIGN64(le64toh(tail
->object
.size
));
792 r
= journal_file_allocate(f
, p
, size
);
796 r
= journal_file_move_to(f
, type
, false, p
, size
, &t
);
803 o
->object
.type
= type
;
804 o
->object
.size
= htole64(size
);
806 f
->header
->tail_object_offset
= htole64(p
);
807 f
->header
->n_objects
= htole64(le64toh(f
->header
->n_objects
) + 1);
815 static int journal_file_setup_data_hash_table(JournalFile
*f
) {
823 /* We estimate that we need 1 hash table entry per 768 bytes
824 of journal file and we want to make sure we never get
825 beyond 75% fill level. Calculate the hash table size for
826 the maximum file size based on these metrics. */
828 s
= (f
->metrics
.max_size
* 4 / 768 / 3) * sizeof(HashItem
);
829 if (s
< DEFAULT_DATA_HASH_TABLE_SIZE
)
830 s
= DEFAULT_DATA_HASH_TABLE_SIZE
;
832 log_debug("Reserving %"PRIu64
" entries in hash table.", s
/ sizeof(HashItem
));
834 r
= journal_file_append_object(f
,
835 OBJECT_DATA_HASH_TABLE
,
836 offsetof(Object
, hash_table
.items
) + s
,
841 memzero(o
->hash_table
.items
, s
);
843 f
->header
->data_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
844 f
->header
->data_hash_table_size
= htole64(s
);
849 static int journal_file_setup_field_hash_table(JournalFile
*f
) {
857 /* We use a fixed size hash table for the fields as this
858 * number should grow very slowly only */
860 s
= DEFAULT_FIELD_HASH_TABLE_SIZE
;
861 r
= journal_file_append_object(f
,
862 OBJECT_FIELD_HASH_TABLE
,
863 offsetof(Object
, hash_table
.items
) + s
,
868 memzero(o
->hash_table
.items
, s
);
870 f
->header
->field_hash_table_offset
= htole64(p
+ offsetof(Object
, hash_table
.items
));
871 f
->header
->field_hash_table_size
= htole64(s
);
876 int journal_file_map_data_hash_table(JournalFile
*f
) {
884 if (f
->data_hash_table
)
887 p
= le64toh(f
->header
->data_hash_table_offset
);
888 s
= le64toh(f
->header
->data_hash_table_size
);
890 r
= journal_file_move_to(f
,
891 OBJECT_DATA_HASH_TABLE
,
898 f
->data_hash_table
= t
;
902 int journal_file_map_field_hash_table(JournalFile
*f
) {
910 if (f
->field_hash_table
)
913 p
= le64toh(f
->header
->field_hash_table_offset
);
914 s
= le64toh(f
->header
->field_hash_table_size
);
916 r
= journal_file_move_to(f
,
917 OBJECT_FIELD_HASH_TABLE
,
924 f
->field_hash_table
= t
;
928 static int journal_file_link_field(
939 assert(f
->field_hash_table
);
943 if (o
->object
.type
!= OBJECT_FIELD
)
946 m
= le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
);
950 /* This might alter the window we are looking at */
951 o
->field
.next_hash_offset
= o
->field
.head_data_offset
= 0;
954 p
= le64toh(f
->field_hash_table
[h
].tail_hash_offset
);
956 f
->field_hash_table
[h
].head_hash_offset
= htole64(offset
);
958 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
962 o
->field
.next_hash_offset
= htole64(offset
);
965 f
->field_hash_table
[h
].tail_hash_offset
= htole64(offset
);
967 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
968 f
->header
->n_fields
= htole64(le64toh(f
->header
->n_fields
) + 1);
973 static int journal_file_link_data(
984 assert(f
->data_hash_table
);
988 if (o
->object
.type
!= OBJECT_DATA
)
991 m
= le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
);
995 /* This might alter the window we are looking at */
996 o
->data
.next_hash_offset
= o
->data
.next_field_offset
= 0;
997 o
->data
.entry_offset
= o
->data
.entry_array_offset
= 0;
998 o
->data
.n_entries
= 0;
1001 p
= le64toh(f
->data_hash_table
[h
].tail_hash_offset
);
1003 /* Only entry in the hash table is easy */
1004 f
->data_hash_table
[h
].head_hash_offset
= htole64(offset
);
1006 /* Move back to the previous data object, to patch in
1009 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1013 o
->data
.next_hash_offset
= htole64(offset
);
1016 f
->data_hash_table
[h
].tail_hash_offset
= htole64(offset
);
1018 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
1019 f
->header
->n_data
= htole64(le64toh(f
->header
->n_data
) + 1);
1024 int journal_file_find_field_object_with_hash(
1026 const void *field
, uint64_t size
, uint64_t hash
,
1027 Object
**ret
, uint64_t *offset
) {
1029 uint64_t p
, osize
, h
, m
;
1034 assert(field
&& size
> 0);
1036 /* If the field hash table is empty, we can't find anything */
1037 if (le64toh(f
->header
->field_hash_table_size
) <= 0)
1040 /* Map the field hash table, if it isn't mapped yet. */
1041 r
= journal_file_map_field_hash_table(f
);
1045 osize
= offsetof(Object
, field
.payload
) + size
;
1047 m
= le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
);
1052 p
= le64toh(f
->field_hash_table
[h
].head_hash_offset
);
1057 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1061 if (le64toh(o
->field
.hash
) == hash
&&
1062 le64toh(o
->object
.size
) == osize
&&
1063 memcmp(o
->field
.payload
, field
, size
) == 0) {
1073 p
= le64toh(o
->field
.next_hash_offset
);
1079 int journal_file_find_field_object(
1081 const void *field
, uint64_t size
,
1082 Object
**ret
, uint64_t *offset
) {
1087 assert(field
&& size
> 0);
1089 hash
= hash64(field
, size
);
1091 return journal_file_find_field_object_with_hash(f
,
1096 int journal_file_find_data_object_with_hash(
1098 const void *data
, uint64_t size
, uint64_t hash
,
1099 Object
**ret
, uint64_t *offset
) {
1101 uint64_t p
, osize
, h
, m
;
1106 assert(data
|| size
== 0);
1108 /* If there's no data hash table, then there's no entry. */
1109 if (le64toh(f
->header
->data_hash_table_size
) <= 0)
1112 /* Map the data hash table, if it isn't mapped yet. */
1113 r
= journal_file_map_data_hash_table(f
);
1117 osize
= offsetof(Object
, data
.payload
) + size
;
1119 m
= le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
);
1124 p
= le64toh(f
->data_hash_table
[h
].head_hash_offset
);
1129 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1133 if (le64toh(o
->data
.hash
) != hash
)
1136 if (o
->object
.flags
& OBJECT_COMPRESSION_MASK
) {
1137 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
1141 l
= le64toh(o
->object
.size
);
1142 if (l
<= offsetof(Object
, data
.payload
))
1145 l
-= offsetof(Object
, data
.payload
);
1147 r
= decompress_blob(o
->object
.flags
& OBJECT_COMPRESSION_MASK
,
1148 o
->data
.payload
, l
, &f
->compress_buffer
, &f
->compress_buffer_size
, &rsize
, 0);
1152 if (rsize
== size
&&
1153 memcmp(f
->compress_buffer
, data
, size
) == 0) {
1164 return -EPROTONOSUPPORT
;
1166 } else if (le64toh(o
->object
.size
) == osize
&&
1167 memcmp(o
->data
.payload
, data
, size
) == 0) {
1179 p
= le64toh(o
->data
.next_hash_offset
);
1185 int journal_file_find_data_object(
1187 const void *data
, uint64_t size
,
1188 Object
**ret
, uint64_t *offset
) {
1193 assert(data
|| size
== 0);
1195 hash
= hash64(data
, size
);
1197 return journal_file_find_data_object_with_hash(f
,
1202 static int journal_file_append_field(
1204 const void *field
, uint64_t size
,
1205 Object
**ret
, uint64_t *offset
) {
1213 assert(field
&& size
> 0);
1215 hash
= hash64(field
, size
);
1217 r
= journal_file_find_field_object_with_hash(f
, field
, size
, hash
, &o
, &p
);
1231 osize
= offsetof(Object
, field
.payload
) + size
;
1232 r
= journal_file_append_object(f
, OBJECT_FIELD
, osize
, &o
, &p
);
1236 o
->field
.hash
= htole64(hash
);
1237 memcpy(o
->field
.payload
, field
, size
);
1239 r
= journal_file_link_field(f
, o
, p
, hash
);
1243 /* The linking might have altered the window, so let's
1244 * refresh our pointer */
1245 r
= journal_file_move_to_object(f
, OBJECT_FIELD
, p
, &o
);
1250 r
= journal_file_hmac_put_object(f
, OBJECT_FIELD
, o
, p
);
1264 static int journal_file_append_data(
1266 const void *data
, uint64_t size
,
1267 Object
**ret
, uint64_t *offset
) {
1272 int r
, compression
= 0;
1276 assert(data
|| size
== 0);
1278 hash
= hash64(data
, size
);
1280 r
= journal_file_find_data_object_with_hash(f
, data
, size
, hash
, &o
, &p
);
1294 osize
= offsetof(Object
, data
.payload
) + size
;
1295 r
= journal_file_append_object(f
, OBJECT_DATA
, osize
, &o
, &p
);
1299 o
->data
.hash
= htole64(hash
);
1301 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
1302 if (JOURNAL_FILE_COMPRESS(f
) && size
>= COMPRESSION_SIZE_THRESHOLD
) {
1305 compression
= compress_blob(data
, size
, o
->data
.payload
, size
- 1, &rsize
);
1307 if (compression
>= 0) {
1308 o
->object
.size
= htole64(offsetof(Object
, data
.payload
) + rsize
);
1309 o
->object
.flags
|= compression
;
1311 log_debug("Compressed data object %"PRIu64
" -> %zu using %s",
1312 size
, rsize
, object_compressed_to_string(compression
));
1314 /* Compression didn't work, we don't really care why, let's continue without compression */
1319 if (compression
== 0)
1320 memcpy_safe(o
->data
.payload
, data
, size
);
1322 r
= journal_file_link_data(f
, o
, p
, hash
);
1326 /* The linking might have altered the window, so let's
1327 * refresh our pointer */
1328 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1335 eq
= memchr(data
, '=', size
);
1336 if (eq
&& eq
> data
) {
1340 /* Create field object ... */
1341 r
= journal_file_append_field(f
, data
, (uint8_t*) eq
- (uint8_t*) data
, &fo
, &fp
);
1345 /* ... and link it in. */
1346 o
->data
.next_field_offset
= fo
->field
.head_data_offset
;
1347 fo
->field
.head_data_offset
= le64toh(p
);
1351 r
= journal_file_hmac_put_object(f
, OBJECT_DATA
, o
, p
);
1365 uint64_t journal_file_entry_n_items(Object
*o
) {
1368 if (o
->object
.type
!= OBJECT_ENTRY
)
1371 return (le64toh(o
->object
.size
) - offsetof(Object
, entry
.items
)) / sizeof(EntryItem
);
1374 uint64_t journal_file_entry_array_n_items(Object
*o
) {
1377 if (o
->object
.type
!= OBJECT_ENTRY_ARRAY
)
1380 return (le64toh(o
->object
.size
) - offsetof(Object
, entry_array
.items
)) / sizeof(uint64_t);
1383 uint64_t journal_file_hash_table_n_items(Object
*o
) {
1386 if (o
->object
.type
!= OBJECT_DATA_HASH_TABLE
&&
1387 o
->object
.type
!= OBJECT_FIELD_HASH_TABLE
)
1390 return (le64toh(o
->object
.size
) - offsetof(Object
, hash_table
.items
)) / sizeof(HashItem
);
1393 static int link_entry_into_array(JournalFile
*f
,
1398 uint64_t n
= 0, ap
= 0, q
, i
, a
, hidx
;
1407 a
= le64toh(*first
);
1408 i
= hidx
= le64toh(*idx
);
1411 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
1415 n
= journal_file_entry_array_n_items(o
);
1417 o
->entry_array
.items
[i
] = htole64(p
);
1418 *idx
= htole64(hidx
+ 1);
1424 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
1435 r
= journal_file_append_object(f
, OBJECT_ENTRY_ARRAY
,
1436 offsetof(Object
, entry_array
.items
) + n
* sizeof(uint64_t),
1442 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY_ARRAY
, o
, q
);
1447 o
->entry_array
.items
[i
] = htole64(p
);
1450 *first
= htole64(q
);
1452 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, ap
, &o
);
1456 o
->entry_array
.next_entry_array_offset
= htole64(q
);
1459 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
1460 f
->header
->n_entry_arrays
= htole64(le64toh(f
->header
->n_entry_arrays
) + 1);
1462 *idx
= htole64(hidx
+ 1);
1467 static int link_entry_into_array_plus_one(JournalFile
*f
,
1482 *extra
= htole64(p
);
1486 i
= htole64(le64toh(*idx
) - 1);
1487 r
= link_entry_into_array(f
, first
, &i
, p
);
1492 *idx
= htole64(le64toh(*idx
) + 1);
1496 static int journal_file_link_entry_item(JournalFile
*f
, Object
*o
, uint64_t offset
, uint64_t i
) {
1503 p
= le64toh(o
->entry
.items
[i
].object_offset
);
1507 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
1511 return link_entry_into_array_plus_one(f
,
1512 &o
->data
.entry_offset
,
1513 &o
->data
.entry_array_offset
,
1518 static int journal_file_link_entry(JournalFile
*f
, Object
*o
, uint64_t offset
) {
1527 if (o
->object
.type
!= OBJECT_ENTRY
)
1530 __sync_synchronize();
1532 /* Link up the entry itself */
1533 r
= link_entry_into_array(f
,
1534 &f
->header
->entry_array_offset
,
1535 &f
->header
->n_entries
,
1540 /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
1542 if (f
->header
->head_entry_realtime
== 0)
1543 f
->header
->head_entry_realtime
= o
->entry
.realtime
;
1545 f
->header
->tail_entry_realtime
= o
->entry
.realtime
;
1546 f
->header
->tail_entry_monotonic
= o
->entry
.monotonic
;
1548 f
->tail_entry_monotonic_valid
= true;
1550 /* Link up the items */
1551 n
= journal_file_entry_n_items(o
);
1552 for (i
= 0; i
< n
; i
++) {
1553 r
= journal_file_link_entry_item(f
, o
, offset
, i
);
1561 static int journal_file_append_entry_internal(
1563 const dual_timestamp
*ts
,
1565 const EntryItem items
[], unsigned n_items
,
1567 Object
**ret
, uint64_t *offset
) {
1575 assert(items
|| n_items
== 0);
1578 osize
= offsetof(Object
, entry
.items
) + (n_items
* sizeof(EntryItem
));
1580 r
= journal_file_append_object(f
, OBJECT_ENTRY
, osize
, &o
, &np
);
1584 o
->entry
.seqnum
= htole64(journal_file_entry_seqnum(f
, seqnum
));
1585 memcpy_safe(o
->entry
.items
, items
, n_items
* sizeof(EntryItem
));
1586 o
->entry
.realtime
= htole64(ts
->realtime
);
1587 o
->entry
.monotonic
= htole64(ts
->monotonic
);
1588 o
->entry
.xor_hash
= htole64(xor_hash
);
1589 o
->entry
.boot_id
= f
->header
->boot_id
;
1592 r
= journal_file_hmac_put_object(f
, OBJECT_ENTRY
, o
, np
);
1597 r
= journal_file_link_entry(f
, o
, np
);
1610 void journal_file_post_change(JournalFile
*f
) {
1613 /* inotify() does not receive IN_MODIFY events from file
1614 * accesses done via mmap(). After each access we hence
1615 * trigger IN_MODIFY by truncating the journal file to its
1616 * current size which triggers IN_MODIFY. */
1618 __sync_synchronize();
1620 if (ftruncate(f
->fd
, f
->last_stat
.st_size
) < 0)
1621 log_debug_errno(errno
, "Failed to truncate file to its own size: %m");
1624 static int post_change_thunk(sd_event_source
*timer
, uint64_t usec
, void *userdata
) {
1627 journal_file_post_change(userdata
);
1632 static void schedule_post_change(JournalFile
*f
) {
1633 sd_event_source
*timer
;
1638 assert(f
->post_change_timer
);
1640 timer
= f
->post_change_timer
;
1642 r
= sd_event_source_get_enabled(timer
, &enabled
);
1644 log_debug_errno(r
, "Failed to get ftruncate timer state: %m");
1648 if (enabled
== SD_EVENT_ONESHOT
)
1651 r
= sd_event_now(sd_event_source_get_event(timer
), CLOCK_MONOTONIC
, &now
);
1653 log_debug_errno(r
, "Failed to get clock's now for scheduling ftruncate: %m");
1657 r
= sd_event_source_set_time(timer
, now
+f
->post_change_timer_period
);
1659 log_debug_errno(r
, "Failed to set time for scheduling ftruncate: %m");
1663 r
= sd_event_source_set_enabled(timer
, SD_EVENT_ONESHOT
);
1665 log_debug_errno(r
, "Failed to enable scheduled ftruncate: %m");
1672 /* On failure, let's simply post the change immediately. */
1673 journal_file_post_change(f
);
1676 /* Enable coalesced change posting in a timer on the provided sd_event instance */
1677 int journal_file_enable_post_change_timer(JournalFile
*f
, sd_event
*e
, usec_t t
) {
1678 _cleanup_(sd_event_source_unrefp
) sd_event_source
*timer
= NULL
;
1682 assert_return(!f
->post_change_timer
, -EINVAL
);
1686 r
= sd_event_add_time(e
, &timer
, CLOCK_MONOTONIC
, 0, 0, post_change_thunk
, f
);
1690 r
= sd_event_source_set_enabled(timer
, SD_EVENT_OFF
);
1694 f
->post_change_timer
= timer
;
1696 f
->post_change_timer_period
= t
;
1701 static int entry_item_cmp(const void *_a
, const void *_b
) {
1702 const EntryItem
*a
= _a
, *b
= _b
;
1704 if (le64toh(a
->object_offset
) < le64toh(b
->object_offset
))
1706 if (le64toh(a
->object_offset
) > le64toh(b
->object_offset
))
1711 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
) {
1715 uint64_t xor_hash
= 0;
1716 struct dual_timestamp _ts
;
1720 assert(iovec
|| n_iovec
== 0);
1723 dual_timestamp_get(&_ts
);
1728 r
= journal_file_maybe_append_tag(f
, ts
->realtime
);
1733 /* alloca() can't take 0, hence let's allocate at least one */
1734 items
= alloca(sizeof(EntryItem
) * MAX(1u, n_iovec
));
1736 for (i
= 0; i
< n_iovec
; i
++) {
1740 r
= journal_file_append_data(f
, iovec
[i
].iov_base
, iovec
[i
].iov_len
, &o
, &p
);
1744 xor_hash
^= le64toh(o
->data
.hash
);
1745 items
[i
].object_offset
= htole64(p
);
1746 items
[i
].hash
= o
->data
.hash
;
1749 /* Order by the position on disk, in order to improve seek
1750 * times for rotating media. */
1751 qsort_safe(items
, n_iovec
, sizeof(EntryItem
), entry_item_cmp
);
1753 r
= journal_file_append_entry_internal(f
, ts
, xor_hash
, items
, n_iovec
, seqnum
, ret
, offset
);
1755 /* If the memory mapping triggered a SIGBUS then we return an
1756 * IO error and ignore the error code passed down to us, since
1757 * it is very likely just an effect of a nullified replacement
1760 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
1763 if (f
->post_change_timer
)
1764 schedule_post_change(f
);
1766 journal_file_post_change(f
);
1771 typedef struct ChainCacheItem
{
1772 uint64_t first
; /* the array at the beginning of the chain */
1773 uint64_t array
; /* the cached array */
1774 uint64_t begin
; /* the first item in the cached array */
1775 uint64_t total
; /* the total number of items in all arrays before this one in the chain */
1776 uint64_t last_index
; /* the last index we looked at, to optimize locality when bisecting */
1779 static void chain_cache_put(
1786 uint64_t last_index
) {
1789 /* If the chain item to cache for this chain is the
1790 * first one it's not worth caching anything */
1794 if (ordered_hashmap_size(h
) >= CHAIN_CACHE_MAX
) {
1795 ci
= ordered_hashmap_steal_first(h
);
1798 ci
= new(ChainCacheItem
, 1);
1805 if (ordered_hashmap_put(h
, &ci
->first
, ci
) < 0) {
1810 assert(ci
->first
== first
);
1815 ci
->last_index
= last_index
;
1818 static int generic_array_get(
1822 Object
**ret
, uint64_t *offset
) {
1825 uint64_t p
= 0, a
, t
= 0;
1833 /* Try the chain cache first */
1834 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
1835 if (ci
&& i
> ci
->total
) {
1844 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &o
);
1848 k
= journal_file_entry_array_n_items(o
);
1850 p
= le64toh(o
->entry_array
.items
[i
]);
1856 a
= le64toh(o
->entry_array
.next_entry_array_offset
);
1862 /* Let's cache this item for the next invocation */
1863 chain_cache_put(f
->chain_cache
, ci
, first
, a
, le64toh(o
->entry_array
.items
[0]), t
, i
);
1865 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
1878 static int generic_array_get_plus_one(
1883 Object
**ret
, uint64_t *offset
) {
1892 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, &o
);
1905 return generic_array_get(f
, first
, i
-1, ret
, offset
);
1914 static int generic_array_bisect(
1919 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
1920 direction_t direction
,
1925 uint64_t a
, p
, t
= 0, i
= 0, last_p
= 0, last_index
= (uint64_t) -1;
1926 bool subtract_one
= false;
1927 Object
*o
, *array
= NULL
;
1932 assert(test_object
);
1934 /* Start with the first array in the chain */
1937 ci
= ordered_hashmap_get(f
->chain_cache
, &first
);
1938 if (ci
&& n
> ci
->total
) {
1939 /* Ah, we have iterated this bisection array chain
1940 * previously! Let's see if we can skip ahead in the
1941 * chain, as far as the last time. But we can't jump
1942 * backwards in the chain, so let's check that
1945 r
= test_object(f
, ci
->begin
, needle
);
1949 if (r
== TEST_LEFT
) {
1950 /* OK, what we are looking for is right of the
1951 * begin of this EntryArray, so let's jump
1952 * straight to previously cached array in the
1958 last_index
= ci
->last_index
;
1963 uint64_t left
, right
, k
, lp
;
1965 r
= journal_file_move_to_object(f
, OBJECT_ENTRY_ARRAY
, a
, &array
);
1969 k
= journal_file_entry_array_n_items(array
);
1975 lp
= p
= le64toh(array
->entry_array
.items
[i
]);
1979 r
= test_object(f
, p
, needle
);
1983 if (r
== TEST_FOUND
)
1984 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
1986 if (r
== TEST_RIGHT
) {
1990 if (last_index
!= (uint64_t) -1) {
1991 assert(last_index
<= right
);
1993 /* If we cached the last index we
1994 * looked at, let's try to not to jump
1995 * too wildly around and see if we can
1996 * limit the range to look at early to
1997 * the immediate neighbors of the last
1998 * index we looked at. */
2000 if (last_index
> 0) {
2001 uint64_t x
= last_index
- 1;
2003 p
= le64toh(array
->entry_array
.items
[x
]);
2007 r
= test_object(f
, p
, needle
);
2011 if (r
== TEST_FOUND
)
2012 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2014 if (r
== TEST_RIGHT
)
2020 if (last_index
< right
) {
2021 uint64_t y
= last_index
+ 1;
2023 p
= le64toh(array
->entry_array
.items
[y
]);
2027 r
= test_object(f
, p
, needle
);
2031 if (r
== TEST_FOUND
)
2032 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2034 if (r
== TEST_RIGHT
)
2042 if (left
== right
) {
2043 if (direction
== DIRECTION_UP
)
2044 subtract_one
= true;
2050 assert(left
< right
);
2051 i
= (left
+ right
) / 2;
2053 p
= le64toh(array
->entry_array
.items
[i
]);
2057 r
= test_object(f
, p
, needle
);
2061 if (r
== TEST_FOUND
)
2062 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2064 if (r
== TEST_RIGHT
)
2072 if (direction
== DIRECTION_UP
) {
2074 subtract_one
= true;
2085 last_index
= (uint64_t) -1;
2086 a
= le64toh(array
->entry_array
.next_entry_array_offset
);
2092 if (subtract_one
&& t
== 0 && i
== 0)
2095 /* Let's cache this item for the next invocation */
2096 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
);
2098 if (subtract_one
&& i
== 0)
2100 else if (subtract_one
)
2101 p
= le64toh(array
->entry_array
.items
[i
-1]);
2103 p
= le64toh(array
->entry_array
.items
[i
]);
2105 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2116 *idx
= t
+ i
+ (subtract_one
? -1 : 0);
2121 static int generic_array_bisect_plus_one(
2127 int (*test_object
)(JournalFile
*f
, uint64_t p
, uint64_t needle
),
2128 direction_t direction
,
2134 bool step_back
= false;
2138 assert(test_object
);
2143 /* This bisects the array in object 'first', but first checks
2145 r
= test_object(f
, extra
, needle
);
2149 if (r
== TEST_FOUND
)
2150 r
= direction
== DIRECTION_DOWN
? TEST_RIGHT
: TEST_LEFT
;
2152 /* if we are looking with DIRECTION_UP then we need to first
2153 see if in the actual array there is a matching entry, and
2154 return the last one of that. But if there isn't any we need
2155 to return this one. Hence remember this, and return it
2158 step_back
= direction
== DIRECTION_UP
;
2160 if (r
== TEST_RIGHT
) {
2161 if (direction
== DIRECTION_DOWN
)
2167 r
= generic_array_bisect(f
, first
, n
-1, needle
, test_object
, direction
, ret
, offset
, idx
);
2169 if (r
== 0 && step_back
)
2178 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, extra
, &o
);
2194 _pure_
static int test_object_offset(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2200 else if (p
< needle
)
2206 static int test_object_seqnum(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2213 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2217 if (le64toh(o
->entry
.seqnum
) == needle
)
2219 else if (le64toh(o
->entry
.seqnum
) < needle
)
2225 int journal_file_move_to_entry_by_seqnum(
2228 direction_t direction
,
2234 return generic_array_bisect(f
,
2235 le64toh(f
->header
->entry_array_offset
),
2236 le64toh(f
->header
->n_entries
),
2243 static int test_object_realtime(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2250 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2254 if (le64toh(o
->entry
.realtime
) == needle
)
2256 else if (le64toh(o
->entry
.realtime
) < needle
)
2262 int journal_file_move_to_entry_by_realtime(
2265 direction_t direction
,
2271 return generic_array_bisect(f
,
2272 le64toh(f
->header
->entry_array_offset
),
2273 le64toh(f
->header
->n_entries
),
2275 test_object_realtime
,
2280 static int test_object_monotonic(JournalFile
*f
, uint64_t p
, uint64_t needle
) {
2287 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, p
, &o
);
2291 if (le64toh(o
->entry
.monotonic
) == needle
)
2293 else if (le64toh(o
->entry
.monotonic
) < needle
)
2299 static int find_data_object_by_boot_id(
2305 char t
[sizeof("_BOOT_ID=")-1 + 32 + 1] = "_BOOT_ID=";
2307 sd_id128_to_string(boot_id
, t
+ 9);
2308 return journal_file_find_data_object(f
, t
, sizeof(t
) - 1, o
, b
);
2311 int journal_file_move_to_entry_by_monotonic(
2315 direction_t direction
,
2324 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, NULL
);
2330 return generic_array_bisect_plus_one(f
,
2331 le64toh(o
->data
.entry_offset
),
2332 le64toh(o
->data
.entry_array_offset
),
2333 le64toh(o
->data
.n_entries
),
2335 test_object_monotonic
,
2340 void journal_file_reset_location(JournalFile
*f
) {
2341 f
->location_type
= LOCATION_HEAD
;
2342 f
->current_offset
= 0;
2343 f
->current_seqnum
= 0;
2344 f
->current_realtime
= 0;
2345 f
->current_monotonic
= 0;
2346 zero(f
->current_boot_id
);
2347 f
->current_xor_hash
= 0;
2350 void journal_file_save_location(JournalFile
*f
, Object
*o
, uint64_t offset
) {
2351 f
->location_type
= LOCATION_SEEK
;
2352 f
->current_offset
= offset
;
2353 f
->current_seqnum
= le64toh(o
->entry
.seqnum
);
2354 f
->current_realtime
= le64toh(o
->entry
.realtime
);
2355 f
->current_monotonic
= le64toh(o
->entry
.monotonic
);
2356 f
->current_boot_id
= o
->entry
.boot_id
;
2357 f
->current_xor_hash
= le64toh(o
->entry
.xor_hash
);
2360 int journal_file_compare_locations(JournalFile
*af
, JournalFile
*bf
) {
2365 assert(af
->location_type
== LOCATION_SEEK
);
2366 assert(bf
->location_type
== LOCATION_SEEK
);
2368 /* If contents and timestamps match, these entries are
2369 * identical, even if the seqnum does not match */
2370 if (sd_id128_equal(af
->current_boot_id
, bf
->current_boot_id
) &&
2371 af
->current_monotonic
== bf
->current_monotonic
&&
2372 af
->current_realtime
== bf
->current_realtime
&&
2373 af
->current_xor_hash
== bf
->current_xor_hash
)
2376 if (sd_id128_equal(af
->header
->seqnum_id
, bf
->header
->seqnum_id
)) {
2378 /* If this is from the same seqnum source, compare
2380 if (af
->current_seqnum
< bf
->current_seqnum
)
2382 if (af
->current_seqnum
> bf
->current_seqnum
)
2385 /* Wow! This is weird, different data but the same
2386 * seqnums? Something is borked, but let's make the
2387 * best of it and compare by time. */
2390 if (sd_id128_equal(af
->current_boot_id
, bf
->current_boot_id
)) {
2392 /* If the boot id matches, compare monotonic time */
2393 if (af
->current_monotonic
< bf
->current_monotonic
)
2395 if (af
->current_monotonic
> bf
->current_monotonic
)
2399 /* Otherwise, compare UTC time */
2400 if (af
->current_realtime
< bf
->current_realtime
)
2402 if (af
->current_realtime
> bf
->current_realtime
)
2405 /* Finally, compare by contents */
2406 if (af
->current_xor_hash
< bf
->current_xor_hash
)
2408 if (af
->current_xor_hash
> bf
->current_xor_hash
)
2414 int journal_file_next_entry(
2417 direction_t direction
,
2418 Object
**ret
, uint64_t *offset
) {
2426 n
= le64toh(f
->header
->n_entries
);
2431 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
2433 r
= generic_array_bisect(f
,
2434 le64toh(f
->header
->entry_array_offset
),
2435 le64toh(f
->header
->n_entries
),
2444 if (direction
== DIRECTION_DOWN
) {
2457 /* And jump to it */
2458 r
= generic_array_get(f
,
2459 le64toh(f
->header
->entry_array_offset
),
2466 (direction
== DIRECTION_DOWN
? ofs
<= p
: ofs
>= p
)) {
2467 log_debug("%s: entry array corrupted at entry %"PRIu64
,
2478 int journal_file_next_entry_for_data(
2480 Object
*o
, uint64_t p
,
2481 uint64_t data_offset
,
2482 direction_t direction
,
2483 Object
**ret
, uint64_t *offset
) {
2490 assert(p
> 0 || !o
);
2492 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2496 n
= le64toh(d
->data
.n_entries
);
2501 i
= direction
== DIRECTION_DOWN
? 0 : n
- 1;
2503 if (o
->object
.type
!= OBJECT_ENTRY
)
2506 r
= generic_array_bisect_plus_one(f
,
2507 le64toh(d
->data
.entry_offset
),
2508 le64toh(d
->data
.entry_array_offset
),
2509 le64toh(d
->data
.n_entries
),
2519 if (direction
== DIRECTION_DOWN
) {
2533 return generic_array_get_plus_one(f
,
2534 le64toh(d
->data
.entry_offset
),
2535 le64toh(d
->data
.entry_array_offset
),
2540 int journal_file_move_to_entry_by_offset_for_data(
2542 uint64_t data_offset
,
2544 direction_t direction
,
2545 Object
**ret
, uint64_t *offset
) {
2552 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2556 return generic_array_bisect_plus_one(f
,
2557 le64toh(d
->data
.entry_offset
),
2558 le64toh(d
->data
.entry_array_offset
),
2559 le64toh(d
->data
.n_entries
),
2566 int journal_file_move_to_entry_by_monotonic_for_data(
2568 uint64_t data_offset
,
2571 direction_t direction
,
2572 Object
**ret
, uint64_t *offset
) {
2580 /* First, seek by time */
2581 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &b
);
2587 r
= generic_array_bisect_plus_one(f
,
2588 le64toh(o
->data
.entry_offset
),
2589 le64toh(o
->data
.entry_array_offset
),
2590 le64toh(o
->data
.n_entries
),
2592 test_object_monotonic
,
2598 /* And now, continue seeking until we find an entry that
2599 * exists in both bisection arrays */
2605 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2609 r
= generic_array_bisect_plus_one(f
,
2610 le64toh(d
->data
.entry_offset
),
2611 le64toh(d
->data
.entry_array_offset
),
2612 le64toh(d
->data
.n_entries
),
2620 r
= journal_file_move_to_object(f
, OBJECT_DATA
, b
, &o
);
2624 r
= generic_array_bisect_plus_one(f
,
2625 le64toh(o
->data
.entry_offset
),
2626 le64toh(o
->data
.entry_array_offset
),
2627 le64toh(o
->data
.n_entries
),
2649 int journal_file_move_to_entry_by_seqnum_for_data(
2651 uint64_t data_offset
,
2653 direction_t direction
,
2654 Object
**ret
, uint64_t *offset
) {
2661 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2665 return generic_array_bisect_plus_one(f
,
2666 le64toh(d
->data
.entry_offset
),
2667 le64toh(d
->data
.entry_array_offset
),
2668 le64toh(d
->data
.n_entries
),
2675 int journal_file_move_to_entry_by_realtime_for_data(
2677 uint64_t data_offset
,
2679 direction_t direction
,
2680 Object
**ret
, uint64_t *offset
) {
2687 r
= journal_file_move_to_object(f
, OBJECT_DATA
, data_offset
, &d
);
2691 return generic_array_bisect_plus_one(f
,
2692 le64toh(d
->data
.entry_offset
),
2693 le64toh(d
->data
.entry_array_offset
),
2694 le64toh(d
->data
.n_entries
),
2696 test_object_realtime
,
2701 void journal_file_dump(JournalFile
*f
) {
2709 journal_file_print_header(f
);
2711 p
= le64toh(f
->header
->header_size
);
2713 r
= journal_file_move_to_object(f
, OBJECT_UNUSED
, p
, &o
);
2717 switch (o
->object
.type
) {
2720 printf("Type: OBJECT_UNUSED\n");
2724 printf("Type: OBJECT_DATA\n");
2728 printf("Type: OBJECT_FIELD\n");
2732 printf("Type: OBJECT_ENTRY seqnum=%"PRIu64
" monotonic=%"PRIu64
" realtime=%"PRIu64
"\n",
2733 le64toh(o
->entry
.seqnum
),
2734 le64toh(o
->entry
.monotonic
),
2735 le64toh(o
->entry
.realtime
));
2738 case OBJECT_FIELD_HASH_TABLE
:
2739 printf("Type: OBJECT_FIELD_HASH_TABLE\n");
2742 case OBJECT_DATA_HASH_TABLE
:
2743 printf("Type: OBJECT_DATA_HASH_TABLE\n");
2746 case OBJECT_ENTRY_ARRAY
:
2747 printf("Type: OBJECT_ENTRY_ARRAY\n");
2751 printf("Type: OBJECT_TAG seqnum=%"PRIu64
" epoch=%"PRIu64
"\n",
2752 le64toh(o
->tag
.seqnum
),
2753 le64toh(o
->tag
.epoch
));
2757 printf("Type: unknown (%i)\n", o
->object
.type
);
2761 if (o
->object
.flags
& OBJECT_COMPRESSION_MASK
)
2762 printf("Flags: %s\n",
2763 object_compressed_to_string(o
->object
.flags
& OBJECT_COMPRESSION_MASK
));
2765 if (p
== le64toh(f
->header
->tail_object_offset
))
2768 p
= p
+ ALIGN64(le64toh(o
->object
.size
));
2773 log_error("File corrupt");
2776 static const char* format_timestamp_safe(char *buf
, size_t l
, usec_t t
) {
2779 x
= format_timestamp(buf
, l
, t
);
2785 void journal_file_print_header(JournalFile
*f
) {
2786 char a
[33], b
[33], c
[33], d
[33];
2787 char x
[FORMAT_TIMESTAMP_MAX
], y
[FORMAT_TIMESTAMP_MAX
], z
[FORMAT_TIMESTAMP_MAX
];
2789 char bytes
[FORMAT_BYTES_MAX
];
2794 printf("File Path: %s\n"
2798 "Sequential Number ID: %s\n"
2800 "Compatible Flags:%s%s\n"
2801 "Incompatible Flags:%s%s%s\n"
2802 "Header size: %"PRIu64
"\n"
2803 "Arena size: %"PRIu64
"\n"
2804 "Data Hash Table Size: %"PRIu64
"\n"
2805 "Field Hash Table Size: %"PRIu64
"\n"
2806 "Rotate Suggested: %s\n"
2807 "Head Sequential Number: %"PRIu64
"\n"
2808 "Tail Sequential Number: %"PRIu64
"\n"
2809 "Head Realtime Timestamp: %s\n"
2810 "Tail Realtime Timestamp: %s\n"
2811 "Tail Monotonic Timestamp: %s\n"
2812 "Objects: %"PRIu64
"\n"
2813 "Entry Objects: %"PRIu64
"\n",
2815 sd_id128_to_string(f
->header
->file_id
, a
),
2816 sd_id128_to_string(f
->header
->machine_id
, b
),
2817 sd_id128_to_string(f
->header
->boot_id
, c
),
2818 sd_id128_to_string(f
->header
->seqnum_id
, d
),
2819 f
->header
->state
== STATE_OFFLINE
? "OFFLINE" :
2820 f
->header
->state
== STATE_ONLINE
? "ONLINE" :
2821 f
->header
->state
== STATE_ARCHIVED
? "ARCHIVED" : "UNKNOWN",
2822 JOURNAL_HEADER_SEALED(f
->header
) ? " SEALED" : "",
2823 (le32toh(f
->header
->compatible_flags
) & ~HEADER_COMPATIBLE_ANY
) ? " ???" : "",
2824 JOURNAL_HEADER_COMPRESSED_XZ(f
->header
) ? " COMPRESSED-XZ" : "",
2825 JOURNAL_HEADER_COMPRESSED_LZ4(f
->header
) ? " COMPRESSED-LZ4" : "",
2826 (le32toh(f
->header
->incompatible_flags
) & ~HEADER_INCOMPATIBLE_ANY
) ? " ???" : "",
2827 le64toh(f
->header
->header_size
),
2828 le64toh(f
->header
->arena_size
),
2829 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
2830 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
),
2831 yes_no(journal_file_rotate_suggested(f
, 0)),
2832 le64toh(f
->header
->head_entry_seqnum
),
2833 le64toh(f
->header
->tail_entry_seqnum
),
2834 format_timestamp_safe(x
, sizeof(x
), le64toh(f
->header
->head_entry_realtime
)),
2835 format_timestamp_safe(y
, sizeof(y
), le64toh(f
->header
->tail_entry_realtime
)),
2836 format_timespan(z
, sizeof(z
), le64toh(f
->header
->tail_entry_monotonic
), USEC_PER_MSEC
),
2837 le64toh(f
->header
->n_objects
),
2838 le64toh(f
->header
->n_entries
));
2840 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
2841 printf("Data Objects: %"PRIu64
"\n"
2842 "Data Hash Table Fill: %.1f%%\n",
2843 le64toh(f
->header
->n_data
),
2844 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))));
2846 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
2847 printf("Field Objects: %"PRIu64
"\n"
2848 "Field Hash Table Fill: %.1f%%\n",
2849 le64toh(f
->header
->n_fields
),
2850 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))));
2852 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_tags
))
2853 printf("Tag Objects: %"PRIu64
"\n",
2854 le64toh(f
->header
->n_tags
));
2855 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_entry_arrays
))
2856 printf("Entry Array Objects: %"PRIu64
"\n",
2857 le64toh(f
->header
->n_entry_arrays
));
2859 if (fstat(f
->fd
, &st
) >= 0)
2860 printf("Disk usage: %s\n", format_bytes(bytes
, sizeof(bytes
), (uint64_t) st
.st_blocks
* 512ULL));
2863 static int journal_file_warn_btrfs(JournalFile
*f
) {
2869 /* Before we write anything, check if the COW logic is turned
2870 * off on btrfs. Given our write pattern that is quite
2871 * unfriendly to COW file systems this should greatly improve
2872 * performance on COW file systems, such as btrfs, at the
2873 * expense of data integrity features (which shouldn't be too
2874 * bad, given that we do our own checksumming). */
2876 r
= btrfs_is_filesystem(f
->fd
);
2878 return log_warning_errno(r
, "Failed to determine if journal is on btrfs: %m");
2882 r
= read_attr_fd(f
->fd
, &attrs
);
2884 return log_warning_errno(r
, "Failed to read file attributes: %m");
2886 if (attrs
& FS_NOCOW_FL
) {
2887 log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
2891 log_notice("Creating journal file %s on a btrfs file system, and copy-on-write is enabled. "
2892 "This is likely to slow down journal access substantially, please consider turning "
2893 "off the copy-on-write file attribute on the journal directory, using chattr +C.", f
->path
);
2898 int journal_file_open(
2904 JournalMetrics
*metrics
,
2905 MMapCache
*mmap_cache
,
2906 Set
*deferred_closes
,
2907 JournalFile
*template,
2908 JournalFile
**ret
) {
2910 bool newly_created
= false;
2918 if ((flags
& O_ACCMODE
) != O_RDONLY
&&
2919 (flags
& O_ACCMODE
) != O_RDWR
)
2922 if (!endswith(fname
, ".journal") &&
2923 !endswith(fname
, ".journal~"))
2926 f
= new0(JournalFile
, 1);
2934 f
->prot
= prot_from_flags(flags
);
2935 f
->writable
= (flags
& O_ACCMODE
) != O_RDONLY
;
2936 #if defined(HAVE_LZ4)
2937 f
->compress_lz4
= compress
;
2938 #elif defined(HAVE_XZ)
2939 f
->compress_xz
= compress
;
2946 f
->mmap
= mmap_cache_ref(mmap_cache
);
2948 f
->mmap
= mmap_cache_new();
2955 f
->path
= strdup(fname
);
2961 f
->chain_cache
= ordered_hashmap_new(&uint64_hash_ops
);
2962 if (!f
->chain_cache
) {
2967 f
->fd
= open(f
->path
, f
->flags
|O_CLOEXEC
, f
->mode
);
2973 r
= journal_file_fstat(f
);
2977 if (f
->last_stat
.st_size
== 0 && f
->writable
) {
2979 (void) journal_file_warn_btrfs(f
);
2981 /* Let's attach the creation time to the journal file,
2982 * so that the vacuuming code knows the age of this
2983 * file even if the file might end up corrupted one
2984 * day... Ideally we'd just use the creation time many
2985 * file systems maintain for each file, but there is
2986 * currently no usable API to query this, hence let's
2987 * emulate this via extended attributes. If extended
2988 * attributes are not supported we'll just skip this,
2989 * and rely solely on mtime/atime/ctime of the file. */
2991 fd_setcrtime(f
->fd
, 0);
2994 /* Try to load the FSPRG state, and if we can't, then
2995 * just don't do sealing */
2997 r
= journal_file_fss_load(f
);
3003 r
= journal_file_init_header(f
, template);
3007 r
= journal_file_fstat(f
);
3011 newly_created
= true;
3014 if (f
->last_stat
.st_size
< (off_t
) HEADER_SIZE_MIN
) {
3019 r
= mmap_cache_get(f
->mmap
, f
->fd
, f
->prot
, CONTEXT_HEADER
, true, 0, PAGE_ALIGN(sizeof(Header
)), &f
->last_stat
, &h
);
3025 if (!newly_created
) {
3026 if (deferred_closes
)
3027 journal_file_close_set(deferred_closes
);
3029 r
= journal_file_verify_header(f
);
3035 if (!newly_created
&& f
->writable
) {
3036 r
= journal_file_fss_load(f
);
3044 journal_default_metrics(metrics
, f
->fd
);
3045 f
->metrics
= *metrics
;
3046 } else if (template)
3047 f
->metrics
= template->metrics
;
3049 r
= journal_file_refresh_header(f
);
3055 r
= journal_file_hmac_setup(f
);
3060 if (newly_created
) {
3061 r
= journal_file_setup_field_hash_table(f
);
3065 r
= journal_file_setup_data_hash_table(f
);
3070 r
= journal_file_append_first_tag(f
);
3076 if (mmap_cache_got_sigbus(f
->mmap
, f
->fd
)) {
3081 if (template && template->post_change_timer
) {
3082 r
= journal_file_enable_post_change_timer(
3084 sd_event_source_get_event(template->post_change_timer
),
3085 template->post_change_timer_period
);
3095 if (f
->fd
>= 0 && mmap_cache_got_sigbus(f
->mmap
, f
->fd
))
3098 (void) journal_file_close(f
);
3103 int journal_file_rotate(JournalFile
**f
, bool compress
, bool seal
, Set
*deferred_closes
) {
3104 _cleanup_free_
char *p
= NULL
;
3106 JournalFile
*old_file
, *new_file
= NULL
;
3114 if (!old_file
->writable
)
3117 if (!endswith(old_file
->path
, ".journal"))
3120 l
= strlen(old_file
->path
);
3121 r
= asprintf(&p
, "%.*s@" SD_ID128_FORMAT_STR
"-%016"PRIx64
"-%016"PRIx64
".journal",
3122 (int) l
- 8, old_file
->path
,
3123 SD_ID128_FORMAT_VAL(old_file
->header
->seqnum_id
),
3124 le64toh((*f
)->header
->head_entry_seqnum
),
3125 le64toh((*f
)->header
->head_entry_realtime
));
3129 /* Try to rename the file to the archived version. If the file
3130 * already was deleted, we'll get ENOENT, let's ignore that
3132 r
= rename(old_file
->path
, p
);
3133 if (r
< 0 && errno
!= ENOENT
)
3136 old_file
->header
->state
= STATE_ARCHIVED
;
3138 /* Currently, btrfs is not very good with out write patterns
3139 * and fragments heavily. Let's defrag our journal files when
3140 * we archive them */
3141 old_file
->defrag_on_close
= true;
3143 r
= journal_file_open(old_file
->path
, old_file
->flags
, old_file
->mode
, compress
, seal
, NULL
, old_file
->mmap
, deferred_closes
, old_file
, &new_file
);
3145 if (deferred_closes
&&
3146 set_put(deferred_closes
, old_file
) >= 0)
3147 (void) journal_file_set_offline(old_file
, false);
3149 (void) journal_file_close(old_file
);
3155 int journal_file_open_reliably(
3161 JournalMetrics
*metrics
,
3162 MMapCache
*mmap_cache
,
3163 Set
*deferred_closes
,
3164 JournalFile
*template,
3165 JournalFile
**ret
) {
3169 _cleanup_free_
char *p
= NULL
;
3171 r
= journal_file_open(fname
, flags
, mode
, compress
, seal
, metrics
, mmap_cache
, deferred_closes
, template, ret
);
3173 -EBADMSG
, /* corrupted */
3174 -ENODATA
, /* truncated */
3175 -EHOSTDOWN
, /* other machine */
3176 -EPROTONOSUPPORT
, /* incompatible feature */
3177 -EBUSY
, /* unclean shutdown */
3178 -ESHUTDOWN
, /* already archived */
3179 -EIO
, /* IO error, including SIGBUS on mmap */
3180 -EIDRM
/* File has been deleted */))
3183 if ((flags
& O_ACCMODE
) == O_RDONLY
)
3186 if (!(flags
& O_CREAT
))
3189 if (!endswith(fname
, ".journal"))
3192 /* The file is corrupted. Rotate it away and try it again (but only once) */
3195 if (asprintf(&p
, "%.*s@%016"PRIx64
"-%016"PRIx64
".journal~",
3197 now(CLOCK_REALTIME
),
3201 if (rename(fname
, p
) < 0)
3204 /* btrfs doesn't cope well with our write pattern and
3205 * fragments heavily. Let's defrag all files we rotate */
3207 (void) chattr_path(p
, false, FS_NOCOW_FL
);
3208 (void) btrfs_defrag(p
);
3210 log_warning_errno(r
, "File %s corrupted or uncleanly shut down, renaming and replacing.", fname
);
3212 return journal_file_open(fname
, flags
, mode
, compress
, seal
, metrics
, mmap_cache
, deferred_closes
, template, ret
);
3215 int journal_file_copy_entry(JournalFile
*from
, JournalFile
*to
, Object
*o
, uint64_t p
, uint64_t *seqnum
, Object
**ret
, uint64_t *offset
) {
3217 uint64_t q
, xor_hash
= 0;
3230 ts
.monotonic
= le64toh(o
->entry
.monotonic
);
3231 ts
.realtime
= le64toh(o
->entry
.realtime
);
3233 n
= journal_file_entry_n_items(o
);
3234 /* alloca() can't take 0, hence let's allocate at least one */
3235 items
= alloca(sizeof(EntryItem
) * MAX(1u, n
));
3237 for (i
= 0; i
< n
; i
++) {
3244 q
= le64toh(o
->entry
.items
[i
].object_offset
);
3245 le_hash
= o
->entry
.items
[i
].hash
;
3247 r
= journal_file_move_to_object(from
, OBJECT_DATA
, q
, &o
);
3251 if (le_hash
!= o
->data
.hash
)
3254 l
= le64toh(o
->object
.size
) - offsetof(Object
, data
.payload
);
3257 /* We hit the limit on 32bit machines */
3258 if ((uint64_t) t
!= l
)
3261 if (o
->object
.flags
& OBJECT_COMPRESSION_MASK
) {
3262 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
3265 r
= decompress_blob(o
->object
.flags
& OBJECT_COMPRESSION_MASK
,
3266 o
->data
.payload
, l
, &from
->compress_buffer
, &from
->compress_buffer_size
, &rsize
, 0);
3270 data
= from
->compress_buffer
;
3273 return -EPROTONOSUPPORT
;
3276 data
= o
->data
.payload
;
3278 r
= journal_file_append_data(to
, data
, l
, &u
, &h
);
3282 xor_hash
^= le64toh(u
->data
.hash
);
3283 items
[i
].object_offset
= htole64(h
);
3284 items
[i
].hash
= u
->data
.hash
;
3286 r
= journal_file_move_to_object(from
, OBJECT_ENTRY
, p
, &o
);
3291 r
= journal_file_append_entry_internal(to
, &ts
, xor_hash
, items
, n
, seqnum
, ret
, offset
);
3293 if (mmap_cache_got_sigbus(to
->mmap
, to
->fd
))
3299 void journal_reset_metrics(JournalMetrics
*m
) {
3302 /* Set everything to "pick automatic values". */
3304 *m
= (JournalMetrics
) {
3305 .min_use
= (uint64_t) -1,
3306 .max_use
= (uint64_t) -1,
3307 .min_size
= (uint64_t) -1,
3308 .max_size
= (uint64_t) -1,
3309 .keep_free
= (uint64_t) -1,
3310 .n_max_files
= (uint64_t) -1,
3314 void journal_default_metrics(JournalMetrics
*m
, int fd
) {
3315 char a
[FORMAT_BYTES_MAX
], b
[FORMAT_BYTES_MAX
], c
[FORMAT_BYTES_MAX
], d
[FORMAT_BYTES_MAX
], e
[FORMAT_BYTES_MAX
];
3322 if (fstatvfs(fd
, &ss
) >= 0)
3323 fs_size
= ss
.f_frsize
* ss
.f_blocks
;
3325 log_debug_errno(errno
, "Failed to detremine disk size: %m");
3329 if (m
->max_use
== (uint64_t) -1) {
3332 m
->max_use
= PAGE_ALIGN(fs_size
/ 10); /* 10% of file system size */
3334 if (m
->max_use
> DEFAULT_MAX_USE_UPPER
)
3335 m
->max_use
= DEFAULT_MAX_USE_UPPER
;
3337 if (m
->max_use
< DEFAULT_MAX_USE_LOWER
)
3338 m
->max_use
= DEFAULT_MAX_USE_LOWER
;
3340 m
->max_use
= DEFAULT_MAX_USE_LOWER
;
3342 m
->max_use
= PAGE_ALIGN(m
->max_use
);
3344 if (m
->max_use
!= 0 && m
->max_use
< JOURNAL_FILE_SIZE_MIN
*2)
3345 m
->max_use
= JOURNAL_FILE_SIZE_MIN
*2;
3348 if (m
->min_use
== (uint64_t) -1)
3349 m
->min_use
= DEFAULT_MIN_USE
;
3351 if (m
->min_use
> m
->max_use
)
3352 m
->min_use
= m
->max_use
;
3354 if (m
->max_size
== (uint64_t) -1) {
3355 m
->max_size
= PAGE_ALIGN(m
->max_use
/ 8); /* 8 chunks */
3357 if (m
->max_size
> DEFAULT_MAX_SIZE_UPPER
)
3358 m
->max_size
= DEFAULT_MAX_SIZE_UPPER
;
3360 m
->max_size
= PAGE_ALIGN(m
->max_size
);
3362 if (m
->max_size
!= 0) {
3363 if (m
->max_size
< JOURNAL_FILE_SIZE_MIN
)
3364 m
->max_size
= JOURNAL_FILE_SIZE_MIN
;
3366 if (m
->max_use
!= 0 && m
->max_size
*2 > m
->max_use
)
3367 m
->max_use
= m
->max_size
*2;
3370 if (m
->min_size
== (uint64_t) -1)
3371 m
->min_size
= JOURNAL_FILE_SIZE_MIN
;
3373 m
->min_size
= PAGE_ALIGN(m
->min_size
);
3375 if (m
->min_size
< JOURNAL_FILE_SIZE_MIN
)
3376 m
->min_size
= JOURNAL_FILE_SIZE_MIN
;
3378 if (m
->max_size
!= 0 && m
->min_size
> m
->max_size
)
3379 m
->max_size
= m
->min_size
;
3382 if (m
->keep_free
== (uint64_t) -1) {
3385 m
->keep_free
= PAGE_ALIGN(fs_size
* 3 / 20); /* 15% of file system size */
3387 if (m
->keep_free
> DEFAULT_KEEP_FREE_UPPER
)
3388 m
->keep_free
= DEFAULT_KEEP_FREE_UPPER
;
3391 m
->keep_free
= DEFAULT_KEEP_FREE
;
3394 if (m
->n_max_files
== (uint64_t) -1)
3395 m
->n_max_files
= DEFAULT_N_MAX_FILES
;
3397 log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64
,
3398 format_bytes(a
, sizeof(a
), m
->min_use
),
3399 format_bytes(b
, sizeof(b
), m
->max_use
),
3400 format_bytes(c
, sizeof(c
), m
->max_size
),
3401 format_bytes(d
, sizeof(d
), m
->min_size
),
3402 format_bytes(e
, sizeof(e
), m
->keep_free
),
3406 int journal_file_get_cutoff_realtime_usec(JournalFile
*f
, usec_t
*from
, usec_t
*to
) {
3412 if (f
->header
->head_entry_realtime
== 0)
3415 *from
= le64toh(f
->header
->head_entry_realtime
);
3419 if (f
->header
->tail_entry_realtime
== 0)
3422 *to
= le64toh(f
->header
->tail_entry_realtime
);
3428 int journal_file_get_cutoff_monotonic_usec(JournalFile
*f
, sd_id128_t boot_id
, usec_t
*from
, usec_t
*to
) {
3436 r
= find_data_object_by_boot_id(f
, boot_id
, &o
, &p
);
3440 if (le64toh(o
->data
.n_entries
) <= 0)
3444 r
= journal_file_move_to_object(f
, OBJECT_ENTRY
, le64toh(o
->data
.entry_offset
), &o
);
3448 *from
= le64toh(o
->entry
.monotonic
);
3452 r
= journal_file_move_to_object(f
, OBJECT_DATA
, p
, &o
);
3456 r
= generic_array_get_plus_one(f
,
3457 le64toh(o
->data
.entry_offset
),
3458 le64toh(o
->data
.entry_array_offset
),
3459 le64toh(o
->data
.n_entries
)-1,
3464 *to
= le64toh(o
->entry
.monotonic
);
3470 bool journal_file_rotate_suggested(JournalFile
*f
, usec_t max_file_usec
) {
3474 /* If we gained new header fields we gained new features,
3475 * hence suggest a rotation */
3476 if (le64toh(f
->header
->header_size
) < sizeof(Header
)) {
3477 log_debug("%s uses an outdated header, suggesting rotation.", f
->path
);
3481 /* Let's check if the hash tables grew over a certain fill
3482 * level (75%, borrowing this value from Java's hash table
3483 * implementation), and if so suggest a rotation. To calculate
3484 * the fill level we need the n_data field, which only exists
3485 * in newer versions. */
3487 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
))
3488 if (le64toh(f
->header
->n_data
) * 4ULL > (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
3489 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.",
3491 100.0 * (double) le64toh(f
->header
->n_data
) / ((double) (le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
))),
3492 le64toh(f
->header
->n_data
),
3493 le64toh(f
->header
->data_hash_table_size
) / sizeof(HashItem
),
3494 (unsigned long long) f
->last_stat
.st_size
,
3495 f
->last_stat
.st_size
/ le64toh(f
->header
->n_data
));
3499 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
))
3500 if (le64toh(f
->header
->n_fields
) * 4ULL > (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
)) * 3ULL) {
3501 log_debug("Field hash table of %s has a fill level at %.1f (%"PRIu64
" of %"PRIu64
" items), suggesting rotation.",
3503 100.0 * (double) le64toh(f
->header
->n_fields
) / ((double) (le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
))),
3504 le64toh(f
->header
->n_fields
),
3505 le64toh(f
->header
->field_hash_table_size
) / sizeof(HashItem
));
3509 /* Are the data objects properly indexed by field objects? */
3510 if (JOURNAL_HEADER_CONTAINS(f
->header
, n_data
) &&
3511 JOURNAL_HEADER_CONTAINS(f
->header
, n_fields
) &&
3512 le64toh(f
->header
->n_data
) > 0 &&
3513 le64toh(f
->header
->n_fields
) == 0)
3516 if (max_file_usec
> 0) {
3519 h
= le64toh(f
->header
->head_entry_realtime
);
3520 t
= now(CLOCK_REALTIME
);
3522 if (h
> 0 && t
> h
+ max_file_usec
)