]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/journal/journal-file.c
tree-wide: fix invocations of chattr_path()
[thirdparty/systemd.git] / src / journal / journal-file.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2011 Lennart Poettering
5
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.
10
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.
15
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/>.
18 ***/
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <linux/fs.h>
23 #include <pthread.h>
24 #include <stddef.h>
25 #include <sys/mman.h>
26 #include <sys/statvfs.h>
27 #include <sys/uio.h>
28 #include <unistd.h>
29
30 #include "alloc-util.h"
31 #include "btrfs-util.h"
32 #include "chattr-util.h"
33 #include "compress.h"
34 #include "fd-util.h"
35 #include "journal-authenticate.h"
36 #include "journal-def.h"
37 #include "journal-file.h"
38 #include "lookup3.h"
39 #include "parse-util.h"
40 #include "path-util.h"
41 #include "random-util.h"
42 #include "sd-event.h"
43 #include "set.h"
44 #include "string-util.h"
45 #include "xattr-util.h"
46
47 #define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem))
48 #define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem))
49
50 #define COMPRESSION_SIZE_THRESHOLD (512ULL)
51
52 /* This is the minimum journal file size */
53 #define JOURNAL_FILE_SIZE_MIN (512ULL*1024ULL) /* 512 KiB */
54
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 */
59
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 */
62
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 */
65
66 /* This is the upper bound if we deduce the keep_free value from the
67 * file system size */
68 #define DEFAULT_KEEP_FREE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
69
70 /* This is the keep_free value when we can't determine the system
71 * size */
72 #define DEFAULT_KEEP_FREE (1024ULL*1024ULL) /* 1 MB */
73
74 /* This is the default maximum number of journal files to keep around. */
75 #define DEFAULT_N_MAX_FILES (100)
76
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))
79
80 /* How many entries to keep in the entry array chain cache at max */
81 #define CHAIN_CACHE_MAX 20
82
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 */
85
86 /* Reread fstat() of the file for detecting deletions at least this often */
87 #define LAST_STAT_REFRESH_USEC (5*USEC_PER_SEC)
88
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
91
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) {
96 assert(f);
97 assert(f->fd >= 0);
98 assert(f->header);
99
100 for (;;) {
101 switch (f->offline_state) {
102 case OFFLINE_CANCEL:
103 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_CANCEL, OFFLINE_DONE))
104 continue;
105 return;
106
107 case OFFLINE_AGAIN_FROM_SYNCING:
108 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_SYNCING, OFFLINE_SYNCING))
109 continue;
110 break;
111
112 case OFFLINE_AGAIN_FROM_OFFLINING:
113 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_OFFLINING, OFFLINE_SYNCING))
114 continue;
115 break;
116
117 case OFFLINE_SYNCING:
118 (void) fsync(f->fd);
119
120 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_SYNCING, OFFLINE_OFFLINING))
121 continue;
122
123 f->header->state = f->archive ? STATE_ARCHIVED : STATE_OFFLINE;
124 (void) fsync(f->fd);
125 break;
126
127 case OFFLINE_OFFLINING:
128 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_OFFLINING, OFFLINE_DONE))
129 continue;
130 /* fall through */
131
132 case OFFLINE_DONE:
133 return;
134
135 case OFFLINE_JOINED:
136 log_debug("OFFLINE_JOINED unexpected offline state for journal_file_set_offline_internal()");
137 return;
138 }
139 }
140 }
141
142 static void * journal_file_set_offline_thread(void *arg) {
143 JournalFile *f = arg;
144
145 journal_file_set_offline_internal(f);
146
147 return NULL;
148 }
149
150 static int journal_file_set_offline_thread_join(JournalFile *f) {
151 int r;
152
153 assert(f);
154
155 if (f->offline_state == OFFLINE_JOINED)
156 return 0;
157
158 r = pthread_join(f->offline_thread, NULL);
159 if (r)
160 return -r;
161
162 f->offline_state = OFFLINE_JOINED;
163
164 if (mmap_cache_got_sigbus(f->mmap, f->fd))
165 return -EIO;
166
167 return 0;
168 }
169
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) {
172 for (;;) {
173 switch (f->offline_state) {
174 case OFFLINE_AGAIN_FROM_SYNCING:
175 case OFFLINE_AGAIN_FROM_OFFLINING:
176 return true;
177
178 case OFFLINE_CANCEL:
179 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_CANCEL, OFFLINE_AGAIN_FROM_SYNCING))
180 continue;
181 return true;
182
183 case OFFLINE_SYNCING:
184 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_SYNCING, OFFLINE_AGAIN_FROM_SYNCING))
185 continue;
186 return true;
187
188 case OFFLINE_OFFLINING:
189 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_OFFLINING, OFFLINE_AGAIN_FROM_OFFLINING))
190 continue;
191 return true;
192
193 default:
194 return false;
195 }
196 }
197 }
198
199 /* Sets a journal offline.
200 *
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.
204 *
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.
208 */
209 int journal_file_set_offline(JournalFile *f, bool wait) {
210 bool restarted;
211 int r;
212
213 assert(f);
214
215 if (!f->writable)
216 return -EPERM;
217
218 if (!(f->fd >= 0 && f->header))
219 return -EINVAL;
220
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);
225
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);
230 if (r < 0)
231 return r;
232 }
233
234 if (restarted)
235 return 0;
236
237 /* Initiate a new offline. */
238 f->offline_state = OFFLINE_SYNCING;
239
240 if (wait) /* Without using a thread if waiting. */
241 journal_file_set_offline_internal(f);
242 else {
243 r = pthread_create(&f->offline_thread, NULL, journal_file_set_offline_thread, f);
244 if (r > 0) {
245 f->offline_state = OFFLINE_JOINED;
246 return -r;
247 }
248 }
249
250 return 0;
251 }
252
253 static int journal_file_set_online(JournalFile *f) {
254 bool joined = false;
255
256 assert(f);
257
258 if (!f->writable)
259 return -EPERM;
260
261 if (!(f->fd >= 0 && f->header))
262 return -EINVAL;
263
264 while (!joined) {
265 switch (f->offline_state) {
266 case OFFLINE_JOINED:
267 /* No offline thread, no need to wait. */
268 joined = true;
269 break;
270
271 case OFFLINE_SYNCING:
272 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_SYNCING, OFFLINE_CANCEL))
273 continue;
274 /* Canceled syncing prior to offlining, no need to wait. */
275 break;
276
277 case OFFLINE_AGAIN_FROM_SYNCING:
278 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_SYNCING, OFFLINE_CANCEL))
279 continue;
280 /* Canceled restart from syncing, no need to wait. */
281 break;
282
283 case OFFLINE_AGAIN_FROM_OFFLINING:
284 if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_OFFLINING, OFFLINE_CANCEL))
285 continue;
286 /* Canceled restart from offlining, must wait for offlining to complete however. */
287
288 /* fall through to wait */
289 default: {
290 int r;
291
292 r = journal_file_set_offline_thread_join(f);
293 if (r < 0)
294 return r;
295
296 joined = true;
297 break;
298 }
299 }
300 }
301
302 if (mmap_cache_got_sigbus(f->mmap, f->fd))
303 return -EIO;
304
305 switch (f->header->state) {
306 case STATE_ONLINE:
307 return 0;
308
309 case STATE_OFFLINE:
310 f->header->state = STATE_ONLINE;
311 (void) fsync(f->fd);
312 return 0;
313
314 default:
315 return -EINVAL;
316 }
317 }
318
319 bool journal_file_is_offlining(JournalFile *f) {
320 assert(f);
321
322 __sync_synchronize();
323
324 if (f->offline_state == OFFLINE_DONE ||
325 f->offline_state == OFFLINE_JOINED)
326 return false;
327
328 return true;
329 }
330
331 JournalFile* journal_file_close(JournalFile *f) {
332 assert(f);
333
334 #ifdef HAVE_GCRYPT
335 /* Write the final tag */
336 if (f->seal && f->writable)
337 journal_file_append_tag(f);
338 #endif
339
340 if (f->post_change_timer) {
341 int enabled;
342
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);
346
347 (void) sd_event_source_set_enabled(f->post_change_timer, SD_EVENT_OFF);
348 sd_event_source_unref(f->post_change_timer);
349 }
350
351 journal_file_set_offline(f, true);
352
353 if (f->mmap && f->fd >= 0)
354 mmap_cache_close_fd(f->mmap, f->fd);
355
356 if (f->fd >= 0 && f->defrag_on_close) {
357
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). */
363
364 (void) chattr_fd(f->fd, 0, FS_NOCOW_FL);
365 (void) btrfs_defrag_fd(f->fd);
366 }
367
368 if (f->close_fd)
369 safe_close(f->fd);
370 free(f->path);
371
372 mmap_cache_unref(f->mmap);
373
374 ordered_hashmap_free_free(f->chain_cache);
375
376 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
377 free(f->compress_buffer);
378 #endif
379
380 #ifdef HAVE_GCRYPT
381 if (f->fss_file)
382 munmap(f->fss_file, PAGE_ALIGN(f->fss_file_size));
383 else
384 free(f->fsprg_state);
385
386 free(f->fsprg_seed);
387
388 if (f->hmac)
389 gcry_md_close(f->hmac);
390 #endif
391
392 free(f);
393 return NULL;
394 }
395
396 void journal_file_close_set(Set *s) {
397 JournalFile *f;
398
399 assert(s);
400
401 while ((f = set_steal_first(s)))
402 (void) journal_file_close(f);
403 }
404
405 static int journal_file_init_header(JournalFile *f, JournalFile *template) {
406 Header h = {};
407 ssize_t k;
408 int r;
409
410 assert(f);
411
412 memcpy(h.signature, HEADER_SIGNATURE, 8);
413 h.header_size = htole64(ALIGN64(sizeof(h)));
414
415 h.incompatible_flags |= htole32(
416 f->compress_xz * HEADER_INCOMPATIBLE_COMPRESSED_XZ |
417 f->compress_lz4 * HEADER_INCOMPATIBLE_COMPRESSED_LZ4);
418
419 h.compatible_flags = htole32(
420 f->seal * HEADER_COMPATIBLE_SEALED);
421
422 r = sd_id128_randomize(&h.file_id);
423 if (r < 0)
424 return r;
425
426 if (template) {
427 h.seqnum_id = template->header->seqnum_id;
428 h.tail_entry_seqnum = template->header->tail_entry_seqnum;
429 } else
430 h.seqnum_id = h.file_id;
431
432 k = pwrite(f->fd, &h, sizeof(h), 0);
433 if (k < 0)
434 return -errno;
435
436 if (k != sizeof(h))
437 return -EIO;
438
439 return 0;
440 }
441
442 static int fsync_directory_of_file(int fd) {
443 _cleanup_free_ char *path = NULL, *dn = NULL;
444 _cleanup_close_ int dfd = -1;
445 struct stat st;
446 int r;
447
448 if (fstat(fd, &st) < 0)
449 return -errno;
450
451 if (!S_ISREG(st.st_mode))
452 return -EBADFD;
453
454 r = fd_get_path(fd, &path);
455 if (r < 0)
456 return r;
457
458 if (!path_is_absolute(path))
459 return -EINVAL;
460
461 dn = dirname_malloc(path);
462 if (!dn)
463 return -ENOMEM;
464
465 dfd = open(dn, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
466 if (dfd < 0)
467 return -errno;
468
469 if (fsync(dfd) < 0)
470 return -errno;
471
472 return 0;
473 }
474
475 static int journal_file_refresh_header(JournalFile *f) {
476 sd_id128_t boot_id;
477 int r;
478
479 assert(f);
480 assert(f->header);
481
482 r = sd_id128_get_machine(&f->header->machine_id);
483 if (r < 0)
484 return r;
485
486 r = sd_id128_get_boot(&boot_id);
487 if (r < 0)
488 return r;
489
490 if (sd_id128_equal(boot_id, f->header->boot_id))
491 f->tail_entry_monotonic_valid = true;
492
493 f->header->boot_id = boot_id;
494
495 r = journal_file_set_online(f);
496
497 /* Sync the online state to disk */
498 (void) fsync(f->fd);
499
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);
502
503 return r;
504 }
505
506 static int journal_file_verify_header(JournalFile *f) {
507 uint32_t flags;
508
509 assert(f);
510 assert(f->header);
511
512 if (memcmp(f->header->signature, HEADER_SIGNATURE, 8))
513 return -EBADMSG;
514
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;
523 if (flags)
524 log_debug("Journal file %s uses incompatible flags %"PRIx32
525 " disabled at compilation time.", f->path, flags);
526 return -EPROTONOSUPPORT;
527 }
528
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;
537 if (flags)
538 log_debug("Journal file %s uses compatible flags %"PRIx32
539 " disabled at compilation time.", f->path, flags);
540 return -EPROTONOSUPPORT;
541 }
542
543 if (f->header->state >= _STATE_MAX)
544 return -EBADMSG;
545
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)
548 return -EBADMSG;
549
550 if (JOURNAL_HEADER_SEALED(f->header) && !JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
551 return -EBADMSG;
552
553 if ((le64toh(f->header->header_size) + le64toh(f->header->arena_size)) > (uint64_t) f->last_stat.st_size)
554 return -ENODATA;
555
556 if (le64toh(f->header->tail_object_offset) > (le64toh(f->header->header_size) + le64toh(f->header->arena_size)))
557 return -ENODATA;
558
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)))
563 return -ENODATA;
564
565 if (f->writable) {
566 uint8_t state;
567 sd_id128_t machine_id;
568 int r;
569
570 r = sd_id128_get_machine(&machine_id);
571 if (r < 0)
572 return r;
573
574 if (!sd_id128_equal(machine_id, f->header->machine_id))
575 return -EHOSTDOWN;
576
577 state = f->header->state;
578
579 if (state == STATE_ONLINE) {
580 log_debug("Journal file %s is already online. Assuming unclean closing.", f->path);
581 return -EBUSY;
582 } else if (state == STATE_ARCHIVED)
583 return -ESHUTDOWN;
584 else if (state != STATE_OFFLINE) {
585 log_debug("Journal file %s has unknown state %i.", f->path, state);
586 return -EBUSY;
587 }
588 }
589
590 f->compress_xz = JOURNAL_HEADER_COMPRESSED_XZ(f->header);
591 f->compress_lz4 = JOURNAL_HEADER_COMPRESSED_LZ4(f->header);
592
593 f->seal = JOURNAL_HEADER_SEALED(f->header);
594
595 return 0;
596 }
597
598 static int journal_file_fstat(JournalFile *f) {
599 assert(f);
600 assert(f->fd >= 0);
601
602 if (fstat(f->fd, &f->last_stat) < 0)
603 return -errno;
604
605 f->last_stat_usec = now(CLOCK_MONOTONIC);
606
607 /* Refuse appending to files that are already deleted */
608 if (f->last_stat.st_nlink <= 0)
609 return -EIDRM;
610
611 return 0;
612 }
613
614 static int journal_file_allocate(JournalFile *f, uint64_t offset, uint64_t size) {
615 uint64_t old_size, new_size;
616 int r;
617
618 assert(f);
619 assert(f->header);
620
621 /* We assume that this file is not sparse, and we know that
622 * for sure, since we always call posix_fallocate()
623 * ourselves */
624
625 if (mmap_cache_got_sigbus(f->mmap, f->fd))
626 return -EIO;
627
628 old_size =
629 le64toh(f->header->header_size) +
630 le64toh(f->header->arena_size);
631
632 new_size = PAGE_ALIGN(offset + size);
633 if (new_size < le64toh(f->header->header_size))
634 new_size = le64toh(f->header->header_size);
635
636 if (new_size <= old_size) {
637
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. */
643
644 if (f->last_stat_usec + LAST_STAT_REFRESH_USEC > now(CLOCK_MONOTONIC))
645 return 0;
646
647 return journal_file_fstat(f);
648 }
649
650 /* Allocate more space. */
651
652 if (f->metrics.max_size > 0 && new_size > f->metrics.max_size)
653 return -E2BIG;
654
655 if (new_size > f->metrics.min_size && f->metrics.keep_free > 0) {
656 struct statvfs svfs;
657
658 if (fstatvfs(f->fd, &svfs) >= 0) {
659 uint64_t available;
660
661 available = LESS_BY((uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize, f->metrics.keep_free);
662
663 if (new_size - old_size > available)
664 return -E2BIG;
665 }
666 }
667
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;
672
673 /* Note that the glibc fallocate() fallback is very
674 inefficient, hence we try to minimize the allocation area
675 as we can. */
676 r = posix_fallocate(f->fd, old_size, new_size - old_size);
677 if (r != 0)
678 return -r;
679
680 f->header->arena_size = htole64(new_size - le64toh(f->header->header_size));
681
682 return journal_file_fstat(f);
683 }
684
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;
690 }
691
692 static int journal_file_move_to(JournalFile *f, ObjectType type, bool keep_always, uint64_t offset, uint64_t size, void **ret) {
693 int r;
694
695 assert(f);
696 assert(ret);
697
698 if (size <= 0)
699 return -EINVAL;
700
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. */
705
706 r = journal_file_fstat(f);
707 if (r < 0)
708 return r;
709
710 if (offset + size > (uint64_t) f->last_stat.st_size)
711 return -EADDRNOTAVAIL;
712 }
713
714 return mmap_cache_get(f->mmap, f->fd, f->prot, type_to_context(type), keep_always, offset, size, &f->last_stat, ret);
715 }
716
717 static uint64_t minimum_header_size(Object *o) {
718
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),
727 };
728
729 if (o->object.type >= ELEMENTSOF(table) || table[o->object.type] <= 0)
730 return sizeof(ObjectHeader);
731
732 return table[o->object.type];
733 }
734
735 int journal_file_move_to_object(JournalFile *f, ObjectType type, uint64_t offset, Object **ret) {
736 int r;
737 void *t;
738 Object *o;
739 uint64_t s;
740
741 assert(f);
742 assert(ret);
743
744 /* Objects may only be located at multiple of 64 bit */
745 if (!VALID64(offset))
746 return -EBADMSG;
747
748 /* Object may not be located in the file header */
749 if (offset < le64toh(f->header->header_size))
750 return -EBADMSG;
751
752 r = journal_file_move_to(f, type, false, offset, sizeof(ObjectHeader), &t);
753 if (r < 0)
754 return r;
755
756 o = (Object*) t;
757 s = le64toh(o->object.size);
758
759 if (s < sizeof(ObjectHeader))
760 return -EBADMSG;
761
762 if (o->object.type <= OBJECT_UNUSED)
763 return -EBADMSG;
764
765 if (s < minimum_header_size(o))
766 return -EBADMSG;
767
768 if (type > OBJECT_UNUSED && o->object.type != type)
769 return -EBADMSG;
770
771 if (s > sizeof(ObjectHeader)) {
772 r = journal_file_move_to(f, type, false, offset, s, &t);
773 if (r < 0)
774 return r;
775
776 o = (Object*) t;
777 }
778
779 *ret = o;
780 return 0;
781 }
782
783 static uint64_t journal_file_entry_seqnum(JournalFile *f, uint64_t *seqnum) {
784 uint64_t r;
785
786 assert(f);
787 assert(f->header);
788
789 r = le64toh(f->header->tail_entry_seqnum) + 1;
790
791 if (seqnum) {
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 */
795
796 if (*seqnum + 1 > r)
797 r = *seqnum + 1;
798
799 *seqnum = r;
800 }
801
802 f->header->tail_entry_seqnum = htole64(r);
803
804 if (f->header->head_entry_seqnum == 0)
805 f->header->head_entry_seqnum = htole64(r);
806
807 return r;
808 }
809
810 int journal_file_append_object(JournalFile *f, ObjectType type, uint64_t size, Object **ret, uint64_t *offset) {
811 int r;
812 uint64_t p;
813 Object *tail, *o;
814 void *t;
815
816 assert(f);
817 assert(f->header);
818 assert(type > OBJECT_UNUSED && type < _OBJECT_TYPE_MAX);
819 assert(size >= sizeof(ObjectHeader));
820 assert(offset);
821 assert(ret);
822
823 r = journal_file_set_online(f);
824 if (r < 0)
825 return r;
826
827 p = le64toh(f->header->tail_object_offset);
828 if (p == 0)
829 p = le64toh(f->header->header_size);
830 else {
831 r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &tail);
832 if (r < 0)
833 return r;
834
835 p += ALIGN64(le64toh(tail->object.size));
836 }
837
838 r = journal_file_allocate(f, p, size);
839 if (r < 0)
840 return r;
841
842 r = journal_file_move_to(f, type, false, p, size, &t);
843 if (r < 0)
844 return r;
845
846 o = (Object*) t;
847
848 zero(o->object);
849 o->object.type = type;
850 o->object.size = htole64(size);
851
852 f->header->tail_object_offset = htole64(p);
853 f->header->n_objects = htole64(le64toh(f->header->n_objects) + 1);
854
855 *ret = o;
856 *offset = p;
857
858 return 0;
859 }
860
861 static int journal_file_setup_data_hash_table(JournalFile *f) {
862 uint64_t s, p;
863 Object *o;
864 int r;
865
866 assert(f);
867 assert(f->header);
868
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. */
873
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;
877
878 log_debug("Reserving %"PRIu64" entries in hash table.", s / sizeof(HashItem));
879
880 r = journal_file_append_object(f,
881 OBJECT_DATA_HASH_TABLE,
882 offsetof(Object, hash_table.items) + s,
883 &o, &p);
884 if (r < 0)
885 return r;
886
887 memzero(o->hash_table.items, s);
888
889 f->header->data_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
890 f->header->data_hash_table_size = htole64(s);
891
892 return 0;
893 }
894
895 static int journal_file_setup_field_hash_table(JournalFile *f) {
896 uint64_t s, p;
897 Object *o;
898 int r;
899
900 assert(f);
901 assert(f->header);
902
903 /* We use a fixed size hash table for the fields as this
904 * number should grow very slowly only */
905
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,
910 &o, &p);
911 if (r < 0)
912 return r;
913
914 memzero(o->hash_table.items, s);
915
916 f->header->field_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
917 f->header->field_hash_table_size = htole64(s);
918
919 return 0;
920 }
921
922 int journal_file_map_data_hash_table(JournalFile *f) {
923 uint64_t s, p;
924 void *t;
925 int r;
926
927 assert(f);
928 assert(f->header);
929
930 if (f->data_hash_table)
931 return 0;
932
933 p = le64toh(f->header->data_hash_table_offset);
934 s = le64toh(f->header->data_hash_table_size);
935
936 r = journal_file_move_to(f,
937 OBJECT_DATA_HASH_TABLE,
938 true,
939 p, s,
940 &t);
941 if (r < 0)
942 return r;
943
944 f->data_hash_table = t;
945 return 0;
946 }
947
948 int journal_file_map_field_hash_table(JournalFile *f) {
949 uint64_t s, p;
950 void *t;
951 int r;
952
953 assert(f);
954 assert(f->header);
955
956 if (f->field_hash_table)
957 return 0;
958
959 p = le64toh(f->header->field_hash_table_offset);
960 s = le64toh(f->header->field_hash_table_size);
961
962 r = journal_file_move_to(f,
963 OBJECT_FIELD_HASH_TABLE,
964 true,
965 p, s,
966 &t);
967 if (r < 0)
968 return r;
969
970 f->field_hash_table = t;
971 return 0;
972 }
973
974 static int journal_file_link_field(
975 JournalFile *f,
976 Object *o,
977 uint64_t offset,
978 uint64_t hash) {
979
980 uint64_t p, h, m;
981 int r;
982
983 assert(f);
984 assert(f->header);
985 assert(f->field_hash_table);
986 assert(o);
987 assert(offset > 0);
988
989 if (o->object.type != OBJECT_FIELD)
990 return -EINVAL;
991
992 m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem);
993 if (m <= 0)
994 return -EBADMSG;
995
996 /* This might alter the window we are looking at */
997 o->field.next_hash_offset = o->field.head_data_offset = 0;
998
999 h = hash % m;
1000 p = le64toh(f->field_hash_table[h].tail_hash_offset);
1001 if (p == 0)
1002 f->field_hash_table[h].head_hash_offset = htole64(offset);
1003 else {
1004 r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
1005 if (r < 0)
1006 return r;
1007
1008 o->field.next_hash_offset = htole64(offset);
1009 }
1010
1011 f->field_hash_table[h].tail_hash_offset = htole64(offset);
1012
1013 if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
1014 f->header->n_fields = htole64(le64toh(f->header->n_fields) + 1);
1015
1016 return 0;
1017 }
1018
1019 static int journal_file_link_data(
1020 JournalFile *f,
1021 Object *o,
1022 uint64_t offset,
1023 uint64_t hash) {
1024
1025 uint64_t p, h, m;
1026 int r;
1027
1028 assert(f);
1029 assert(f->header);
1030 assert(f->data_hash_table);
1031 assert(o);
1032 assert(offset > 0);
1033
1034 if (o->object.type != OBJECT_DATA)
1035 return -EINVAL;
1036
1037 m = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
1038 if (m <= 0)
1039 return -EBADMSG;
1040
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;
1045
1046 h = hash % m;
1047 p = le64toh(f->data_hash_table[h].tail_hash_offset);
1048 if (p == 0)
1049 /* Only entry in the hash table is easy */
1050 f->data_hash_table[h].head_hash_offset = htole64(offset);
1051 else {
1052 /* Move back to the previous data object, to patch in
1053 * pointer */
1054
1055 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
1056 if (r < 0)
1057 return r;
1058
1059 o->data.next_hash_offset = htole64(offset);
1060 }
1061
1062 f->data_hash_table[h].tail_hash_offset = htole64(offset);
1063
1064 if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
1065 f->header->n_data = htole64(le64toh(f->header->n_data) + 1);
1066
1067 return 0;
1068 }
1069
1070 int journal_file_find_field_object_with_hash(
1071 JournalFile *f,
1072 const void *field, uint64_t size, uint64_t hash,
1073 Object **ret, uint64_t *offset) {
1074
1075 uint64_t p, osize, h, m;
1076 int r;
1077
1078 assert(f);
1079 assert(f->header);
1080 assert(field && size > 0);
1081
1082 /* If the field hash table is empty, we can't find anything */
1083 if (le64toh(f->header->field_hash_table_size) <= 0)
1084 return 0;
1085
1086 /* Map the field hash table, if it isn't mapped yet. */
1087 r = journal_file_map_field_hash_table(f);
1088 if (r < 0)
1089 return r;
1090
1091 osize = offsetof(Object, field.payload) + size;
1092
1093 m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem);
1094 if (m <= 0)
1095 return -EBADMSG;
1096
1097 h = hash % m;
1098 p = le64toh(f->field_hash_table[h].head_hash_offset);
1099
1100 while (p > 0) {
1101 Object *o;
1102
1103 r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
1104 if (r < 0)
1105 return r;
1106
1107 if (le64toh(o->field.hash) == hash &&
1108 le64toh(o->object.size) == osize &&
1109 memcmp(o->field.payload, field, size) == 0) {
1110
1111 if (ret)
1112 *ret = o;
1113 if (offset)
1114 *offset = p;
1115
1116 return 1;
1117 }
1118
1119 p = le64toh(o->field.next_hash_offset);
1120 }
1121
1122 return 0;
1123 }
1124
1125 int journal_file_find_field_object(
1126 JournalFile *f,
1127 const void *field, uint64_t size,
1128 Object **ret, uint64_t *offset) {
1129
1130 uint64_t hash;
1131
1132 assert(f);
1133 assert(field && size > 0);
1134
1135 hash = hash64(field, size);
1136
1137 return journal_file_find_field_object_with_hash(f,
1138 field, size, hash,
1139 ret, offset);
1140 }
1141
1142 int journal_file_find_data_object_with_hash(
1143 JournalFile *f,
1144 const void *data, uint64_t size, uint64_t hash,
1145 Object **ret, uint64_t *offset) {
1146
1147 uint64_t p, osize, h, m;
1148 int r;
1149
1150 assert(f);
1151 assert(f->header);
1152 assert(data || size == 0);
1153
1154 /* If there's no data hash table, then there's no entry. */
1155 if (le64toh(f->header->data_hash_table_size) <= 0)
1156 return 0;
1157
1158 /* Map the data hash table, if it isn't mapped yet. */
1159 r = journal_file_map_data_hash_table(f);
1160 if (r < 0)
1161 return r;
1162
1163 osize = offsetof(Object, data.payload) + size;
1164
1165 m = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
1166 if (m <= 0)
1167 return -EBADMSG;
1168
1169 h = hash % m;
1170 p = le64toh(f->data_hash_table[h].head_hash_offset);
1171
1172 while (p > 0) {
1173 Object *o;
1174
1175 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
1176 if (r < 0)
1177 return r;
1178
1179 if (le64toh(o->data.hash) != hash)
1180 goto next;
1181
1182 if (o->object.flags & OBJECT_COMPRESSION_MASK) {
1183 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
1184 uint64_t l;
1185 size_t rsize = 0;
1186
1187 l = le64toh(o->object.size);
1188 if (l <= offsetof(Object, data.payload))
1189 return -EBADMSG;
1190
1191 l -= offsetof(Object, data.payload);
1192
1193 r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK,
1194 o->data.payload, l, &f->compress_buffer, &f->compress_buffer_size, &rsize, 0);
1195 if (r < 0)
1196 return r;
1197
1198 if (rsize == size &&
1199 memcmp(f->compress_buffer, data, size) == 0) {
1200
1201 if (ret)
1202 *ret = o;
1203
1204 if (offset)
1205 *offset = p;
1206
1207 return 1;
1208 }
1209 #else
1210 return -EPROTONOSUPPORT;
1211 #endif
1212 } else if (le64toh(o->object.size) == osize &&
1213 memcmp(o->data.payload, data, size) == 0) {
1214
1215 if (ret)
1216 *ret = o;
1217
1218 if (offset)
1219 *offset = p;
1220
1221 return 1;
1222 }
1223
1224 next:
1225 p = le64toh(o->data.next_hash_offset);
1226 }
1227
1228 return 0;
1229 }
1230
1231 int journal_file_find_data_object(
1232 JournalFile *f,
1233 const void *data, uint64_t size,
1234 Object **ret, uint64_t *offset) {
1235
1236 uint64_t hash;
1237
1238 assert(f);
1239 assert(data || size == 0);
1240
1241 hash = hash64(data, size);
1242
1243 return journal_file_find_data_object_with_hash(f,
1244 data, size, hash,
1245 ret, offset);
1246 }
1247
1248 static int journal_file_append_field(
1249 JournalFile *f,
1250 const void *field, uint64_t size,
1251 Object **ret, uint64_t *offset) {
1252
1253 uint64_t hash, p;
1254 uint64_t osize;
1255 Object *o;
1256 int r;
1257
1258 assert(f);
1259 assert(field && size > 0);
1260
1261 hash = hash64(field, size);
1262
1263 r = journal_file_find_field_object_with_hash(f, field, size, hash, &o, &p);
1264 if (r < 0)
1265 return r;
1266 else if (r > 0) {
1267
1268 if (ret)
1269 *ret = o;
1270
1271 if (offset)
1272 *offset = p;
1273
1274 return 0;
1275 }
1276
1277 osize = offsetof(Object, field.payload) + size;
1278 r = journal_file_append_object(f, OBJECT_FIELD, osize, &o, &p);
1279 if (r < 0)
1280 return r;
1281
1282 o->field.hash = htole64(hash);
1283 memcpy(o->field.payload, field, size);
1284
1285 r = journal_file_link_field(f, o, p, hash);
1286 if (r < 0)
1287 return r;
1288
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);
1292 if (r < 0)
1293 return r;
1294
1295 #ifdef HAVE_GCRYPT
1296 r = journal_file_hmac_put_object(f, OBJECT_FIELD, o, p);
1297 if (r < 0)
1298 return r;
1299 #endif
1300
1301 if (ret)
1302 *ret = o;
1303
1304 if (offset)
1305 *offset = p;
1306
1307 return 0;
1308 }
1309
1310 static int journal_file_append_data(
1311 JournalFile *f,
1312 const void *data, uint64_t size,
1313 Object **ret, uint64_t *offset) {
1314
1315 uint64_t hash, p;
1316 uint64_t osize;
1317 Object *o;
1318 int r, compression = 0;
1319 const void *eq;
1320
1321 assert(f);
1322 assert(data || size == 0);
1323
1324 hash = hash64(data, size);
1325
1326 r = journal_file_find_data_object_with_hash(f, data, size, hash, &o, &p);
1327 if (r < 0)
1328 return r;
1329 if (r > 0) {
1330
1331 if (ret)
1332 *ret = o;
1333
1334 if (offset)
1335 *offset = p;
1336
1337 return 0;
1338 }
1339
1340 osize = offsetof(Object, data.payload) + size;
1341 r = journal_file_append_object(f, OBJECT_DATA, osize, &o, &p);
1342 if (r < 0)
1343 return r;
1344
1345 o->data.hash = htole64(hash);
1346
1347 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
1348 if (JOURNAL_FILE_COMPRESS(f) && size >= COMPRESSION_SIZE_THRESHOLD) {
1349 size_t rsize = 0;
1350
1351 compression = compress_blob(data, size, o->data.payload, size - 1, &rsize);
1352
1353 if (compression >= 0) {
1354 o->object.size = htole64(offsetof(Object, data.payload) + rsize);
1355 o->object.flags |= compression;
1356
1357 log_debug("Compressed data object %"PRIu64" -> %zu using %s",
1358 size, rsize, object_compressed_to_string(compression));
1359 } else
1360 /* Compression didn't work, we don't really care why, let's continue without compression */
1361 compression = 0;
1362 }
1363 #endif
1364
1365 if (compression == 0)
1366 memcpy_safe(o->data.payload, data, size);
1367
1368 r = journal_file_link_data(f, o, p, hash);
1369 if (r < 0)
1370 return r;
1371
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);
1375 if (r < 0)
1376 return r;
1377
1378 if (!data)
1379 eq = NULL;
1380 else
1381 eq = memchr(data, '=', size);
1382 if (eq && eq > data) {
1383 Object *fo = NULL;
1384 uint64_t fp;
1385
1386 /* Create field object ... */
1387 r = journal_file_append_field(f, data, (uint8_t*) eq - (uint8_t*) data, &fo, &fp);
1388 if (r < 0)
1389 return r;
1390
1391 /* ... and link it in. */
1392 o->data.next_field_offset = fo->field.head_data_offset;
1393 fo->field.head_data_offset = le64toh(p);
1394 }
1395
1396 #ifdef HAVE_GCRYPT
1397 r = journal_file_hmac_put_object(f, OBJECT_DATA, o, p);
1398 if (r < 0)
1399 return r;
1400 #endif
1401
1402 if (ret)
1403 *ret = o;
1404
1405 if (offset)
1406 *offset = p;
1407
1408 return 0;
1409 }
1410
1411 uint64_t journal_file_entry_n_items(Object *o) {
1412 assert(o);
1413
1414 if (o->object.type != OBJECT_ENTRY)
1415 return 0;
1416
1417 return (le64toh(o->object.size) - offsetof(Object, entry.items)) / sizeof(EntryItem);
1418 }
1419
1420 uint64_t journal_file_entry_array_n_items(Object *o) {
1421 assert(o);
1422
1423 if (o->object.type != OBJECT_ENTRY_ARRAY)
1424 return 0;
1425
1426 return (le64toh(o->object.size) - offsetof(Object, entry_array.items)) / sizeof(uint64_t);
1427 }
1428
1429 uint64_t journal_file_hash_table_n_items(Object *o) {
1430 assert(o);
1431
1432 if (o->object.type != OBJECT_DATA_HASH_TABLE &&
1433 o->object.type != OBJECT_FIELD_HASH_TABLE)
1434 return 0;
1435
1436 return (le64toh(o->object.size) - offsetof(Object, hash_table.items)) / sizeof(HashItem);
1437 }
1438
1439 static int link_entry_into_array(JournalFile *f,
1440 le64_t *first,
1441 le64_t *idx,
1442 uint64_t p) {
1443 int r;
1444 uint64_t n = 0, ap = 0, q, i, a, hidx;
1445 Object *o;
1446
1447 assert(f);
1448 assert(f->header);
1449 assert(first);
1450 assert(idx);
1451 assert(p > 0);
1452
1453 a = le64toh(*first);
1454 i = hidx = le64toh(*idx);
1455 while (a > 0) {
1456
1457 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
1458 if (r < 0)
1459 return r;
1460
1461 n = journal_file_entry_array_n_items(o);
1462 if (i < n) {
1463 o->entry_array.items[i] = htole64(p);
1464 *idx = htole64(hidx + 1);
1465 return 0;
1466 }
1467
1468 i -= n;
1469 ap = a;
1470 a = le64toh(o->entry_array.next_entry_array_offset);
1471 }
1472
1473 if (hidx > n)
1474 n = (hidx+1) * 2;
1475 else
1476 n = n * 2;
1477
1478 if (n < 4)
1479 n = 4;
1480
1481 r = journal_file_append_object(f, OBJECT_ENTRY_ARRAY,
1482 offsetof(Object, entry_array.items) + n * sizeof(uint64_t),
1483 &o, &q);
1484 if (r < 0)
1485 return r;
1486
1487 #ifdef HAVE_GCRYPT
1488 r = journal_file_hmac_put_object(f, OBJECT_ENTRY_ARRAY, o, q);
1489 if (r < 0)
1490 return r;
1491 #endif
1492
1493 o->entry_array.items[i] = htole64(p);
1494
1495 if (ap == 0)
1496 *first = htole64(q);
1497 else {
1498 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, ap, &o);
1499 if (r < 0)
1500 return r;
1501
1502 o->entry_array.next_entry_array_offset = htole64(q);
1503 }
1504
1505 if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
1506 f->header->n_entry_arrays = htole64(le64toh(f->header->n_entry_arrays) + 1);
1507
1508 *idx = htole64(hidx + 1);
1509
1510 return 0;
1511 }
1512
1513 static int link_entry_into_array_plus_one(JournalFile *f,
1514 le64_t *extra,
1515 le64_t *first,
1516 le64_t *idx,
1517 uint64_t p) {
1518
1519 int r;
1520
1521 assert(f);
1522 assert(extra);
1523 assert(first);
1524 assert(idx);
1525 assert(p > 0);
1526
1527 if (*idx == 0)
1528 *extra = htole64(p);
1529 else {
1530 le64_t i;
1531
1532 i = htole64(le64toh(*idx) - 1);
1533 r = link_entry_into_array(f, first, &i, p);
1534 if (r < 0)
1535 return r;
1536 }
1537
1538 *idx = htole64(le64toh(*idx) + 1);
1539 return 0;
1540 }
1541
1542 static int journal_file_link_entry_item(JournalFile *f, Object *o, uint64_t offset, uint64_t i) {
1543 uint64_t p;
1544 int r;
1545 assert(f);
1546 assert(o);
1547 assert(offset > 0);
1548
1549 p = le64toh(o->entry.items[i].object_offset);
1550 if (p == 0)
1551 return -EINVAL;
1552
1553 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
1554 if (r < 0)
1555 return r;
1556
1557 return link_entry_into_array_plus_one(f,
1558 &o->data.entry_offset,
1559 &o->data.entry_array_offset,
1560 &o->data.n_entries,
1561 offset);
1562 }
1563
1564 static int journal_file_link_entry(JournalFile *f, Object *o, uint64_t offset) {
1565 uint64_t n, i;
1566 int r;
1567
1568 assert(f);
1569 assert(f->header);
1570 assert(o);
1571 assert(offset > 0);
1572
1573 if (o->object.type != OBJECT_ENTRY)
1574 return -EINVAL;
1575
1576 __sync_synchronize();
1577
1578 /* Link up the entry itself */
1579 r = link_entry_into_array(f,
1580 &f->header->entry_array_offset,
1581 &f->header->n_entries,
1582 offset);
1583 if (r < 0)
1584 return r;
1585
1586 /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
1587
1588 if (f->header->head_entry_realtime == 0)
1589 f->header->head_entry_realtime = o->entry.realtime;
1590
1591 f->header->tail_entry_realtime = o->entry.realtime;
1592 f->header->tail_entry_monotonic = o->entry.monotonic;
1593
1594 f->tail_entry_monotonic_valid = true;
1595
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);
1600 if (r < 0)
1601 return r;
1602 }
1603
1604 return 0;
1605 }
1606
1607 static int journal_file_append_entry_internal(
1608 JournalFile *f,
1609 const dual_timestamp *ts,
1610 uint64_t xor_hash,
1611 const EntryItem items[], unsigned n_items,
1612 uint64_t *seqnum,
1613 Object **ret, uint64_t *offset) {
1614 uint64_t np;
1615 uint64_t osize;
1616 Object *o;
1617 int r;
1618
1619 assert(f);
1620 assert(f->header);
1621 assert(items || n_items == 0);
1622 assert(ts);
1623
1624 osize = offsetof(Object, entry.items) + (n_items * sizeof(EntryItem));
1625
1626 r = journal_file_append_object(f, OBJECT_ENTRY, osize, &o, &np);
1627 if (r < 0)
1628 return r;
1629
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;
1636
1637 #ifdef HAVE_GCRYPT
1638 r = journal_file_hmac_put_object(f, OBJECT_ENTRY, o, np);
1639 if (r < 0)
1640 return r;
1641 #endif
1642
1643 r = journal_file_link_entry(f, o, np);
1644 if (r < 0)
1645 return r;
1646
1647 if (ret)
1648 *ret = o;
1649
1650 if (offset)
1651 *offset = np;
1652
1653 return 0;
1654 }
1655
1656 void journal_file_post_change(JournalFile *f) {
1657 assert(f);
1658
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. */
1663
1664 __sync_synchronize();
1665
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");
1668 }
1669
1670 static int post_change_thunk(sd_event_source *timer, uint64_t usec, void *userdata) {
1671 assert(userdata);
1672
1673 journal_file_post_change(userdata);
1674
1675 return 1;
1676 }
1677
1678 static void schedule_post_change(JournalFile *f) {
1679 sd_event_source *timer;
1680 int enabled, r;
1681 uint64_t now;
1682
1683 assert(f);
1684 assert(f->post_change_timer);
1685
1686 timer = f->post_change_timer;
1687
1688 r = sd_event_source_get_enabled(timer, &enabled);
1689 if (r < 0) {
1690 log_debug_errno(r, "Failed to get ftruncate timer state: %m");
1691 goto fail;
1692 }
1693
1694 if (enabled == SD_EVENT_ONESHOT)
1695 return;
1696
1697 r = sd_event_now(sd_event_source_get_event(timer), CLOCK_MONOTONIC, &now);
1698 if (r < 0) {
1699 log_debug_errno(r, "Failed to get clock's now for scheduling ftruncate: %m");
1700 goto fail;
1701 }
1702
1703 r = sd_event_source_set_time(timer, now+f->post_change_timer_period);
1704 if (r < 0) {
1705 log_debug_errno(r, "Failed to set time for scheduling ftruncate: %m");
1706 goto fail;
1707 }
1708
1709 r = sd_event_source_set_enabled(timer, SD_EVENT_ONESHOT);
1710 if (r < 0) {
1711 log_debug_errno(r, "Failed to enable scheduled ftruncate: %m");
1712 goto fail;
1713 }
1714
1715 return;
1716
1717 fail:
1718 /* On failure, let's simply post the change immediately. */
1719 journal_file_post_change(f);
1720 }
1721
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;
1725 int r;
1726
1727 assert(f);
1728 assert_return(!f->post_change_timer, -EINVAL);
1729 assert(e);
1730 assert(t);
1731
1732 r = sd_event_add_time(e, &timer, CLOCK_MONOTONIC, 0, 0, post_change_thunk, f);
1733 if (r < 0)
1734 return r;
1735
1736 r = sd_event_source_set_enabled(timer, SD_EVENT_OFF);
1737 if (r < 0)
1738 return r;
1739
1740 f->post_change_timer = timer;
1741 timer = NULL;
1742 f->post_change_timer_period = t;
1743
1744 return r;
1745 }
1746
1747 static int entry_item_cmp(const void *_a, const void *_b) {
1748 const EntryItem *a = _a, *b = _b;
1749
1750 if (le64toh(a->object_offset) < le64toh(b->object_offset))
1751 return -1;
1752 if (le64toh(a->object_offset) > le64toh(b->object_offset))
1753 return 1;
1754 return 0;
1755 }
1756
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) {
1758 unsigned i;
1759 EntryItem *items;
1760 int r;
1761 uint64_t xor_hash = 0;
1762 struct dual_timestamp _ts;
1763
1764 assert(f);
1765 assert(f->header);
1766 assert(iovec || n_iovec == 0);
1767
1768 if (!ts) {
1769 dual_timestamp_get(&_ts);
1770 ts = &_ts;
1771 }
1772
1773 #ifdef HAVE_GCRYPT
1774 r = journal_file_maybe_append_tag(f, ts->realtime);
1775 if (r < 0)
1776 return r;
1777 #endif
1778
1779 /* alloca() can't take 0, hence let's allocate at least one */
1780 items = alloca(sizeof(EntryItem) * MAX(1u, n_iovec));
1781
1782 for (i = 0; i < n_iovec; i++) {
1783 uint64_t p;
1784 Object *o;
1785
1786 r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p);
1787 if (r < 0)
1788 return r;
1789
1790 xor_hash ^= le64toh(o->data.hash);
1791 items[i].object_offset = htole64(p);
1792 items[i].hash = o->data.hash;
1793 }
1794
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);
1798
1799 r = journal_file_append_entry_internal(f, ts, xor_hash, items, n_iovec, seqnum, ret, offset);
1800
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
1804 * mapping page */
1805
1806 if (mmap_cache_got_sigbus(f->mmap, f->fd))
1807 r = -EIO;
1808
1809 if (f->post_change_timer)
1810 schedule_post_change(f);
1811 else
1812 journal_file_post_change(f);
1813
1814 return r;
1815 }
1816
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 */
1823 } ChainCacheItem;
1824
1825 static void chain_cache_put(
1826 OrderedHashmap *h,
1827 ChainCacheItem *ci,
1828 uint64_t first,
1829 uint64_t array,
1830 uint64_t begin,
1831 uint64_t total,
1832 uint64_t last_index) {
1833
1834 if (!ci) {
1835 /* If the chain item to cache for this chain is the
1836 * first one it's not worth caching anything */
1837 if (array == first)
1838 return;
1839
1840 if (ordered_hashmap_size(h) >= CHAIN_CACHE_MAX) {
1841 ci = ordered_hashmap_steal_first(h);
1842 assert(ci);
1843 } else {
1844 ci = new(ChainCacheItem, 1);
1845 if (!ci)
1846 return;
1847 }
1848
1849 ci->first = first;
1850
1851 if (ordered_hashmap_put(h, &ci->first, ci) < 0) {
1852 free(ci);
1853 return;
1854 }
1855 } else
1856 assert(ci->first == first);
1857
1858 ci->array = array;
1859 ci->begin = begin;
1860 ci->total = total;
1861 ci->last_index = last_index;
1862 }
1863
1864 static int generic_array_get(
1865 JournalFile *f,
1866 uint64_t first,
1867 uint64_t i,
1868 Object **ret, uint64_t *offset) {
1869
1870 Object *o;
1871 uint64_t p = 0, a, t = 0;
1872 int r;
1873 ChainCacheItem *ci;
1874
1875 assert(f);
1876
1877 a = first;
1878
1879 /* Try the chain cache first */
1880 ci = ordered_hashmap_get(f->chain_cache, &first);
1881 if (ci && i > ci->total) {
1882 a = ci->array;
1883 i -= ci->total;
1884 t = ci->total;
1885 }
1886
1887 while (a > 0) {
1888 uint64_t k;
1889
1890 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
1891 if (r < 0)
1892 return r;
1893
1894 k = journal_file_entry_array_n_items(o);
1895 if (i < k) {
1896 p = le64toh(o->entry_array.items[i]);
1897 goto found;
1898 }
1899
1900 i -= k;
1901 t += k;
1902 a = le64toh(o->entry_array.next_entry_array_offset);
1903 }
1904
1905 return 0;
1906
1907 found:
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);
1910
1911 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
1912 if (r < 0)
1913 return r;
1914
1915 if (ret)
1916 *ret = o;
1917
1918 if (offset)
1919 *offset = p;
1920
1921 return 1;
1922 }
1923
1924 static int generic_array_get_plus_one(
1925 JournalFile *f,
1926 uint64_t extra,
1927 uint64_t first,
1928 uint64_t i,
1929 Object **ret, uint64_t *offset) {
1930
1931 Object *o;
1932
1933 assert(f);
1934
1935 if (i == 0) {
1936 int r;
1937
1938 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
1939 if (r < 0)
1940 return r;
1941
1942 if (ret)
1943 *ret = o;
1944
1945 if (offset)
1946 *offset = extra;
1947
1948 return 1;
1949 }
1950
1951 return generic_array_get(f, first, i-1, ret, offset);
1952 }
1953
1954 enum {
1955 TEST_FOUND,
1956 TEST_LEFT,
1957 TEST_RIGHT
1958 };
1959
1960 static int generic_array_bisect(
1961 JournalFile *f,
1962 uint64_t first,
1963 uint64_t n,
1964 uint64_t needle,
1965 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
1966 direction_t direction,
1967 Object **ret,
1968 uint64_t *offset,
1969 uint64_t *idx) {
1970
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;
1974 int r;
1975 ChainCacheItem *ci;
1976
1977 assert(f);
1978 assert(test_object);
1979
1980 /* Start with the first array in the chain */
1981 a = first;
1982
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
1989 * first. */
1990
1991 r = test_object(f, ci->begin, needle);
1992 if (r < 0)
1993 return r;
1994
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
1999 * chain */
2000
2001 a = ci->array;
2002 n -= ci->total;
2003 t = ci->total;
2004 last_index = ci->last_index;
2005 }
2006 }
2007
2008 while (a > 0) {
2009 uint64_t left, right, k, lp;
2010
2011 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
2012 if (r < 0)
2013 return r;
2014
2015 k = journal_file_entry_array_n_items(array);
2016 right = MIN(k, n);
2017 if (right <= 0)
2018 return 0;
2019
2020 i = right - 1;
2021 lp = p = le64toh(array->entry_array.items[i]);
2022 if (p <= 0)
2023 r = -EBADMSG;
2024 else
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)");
2028 n = i;
2029 continue;
2030 }
2031 if (r < 0)
2032 return r;
2033
2034 if (r == TEST_FOUND)
2035 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2036
2037 if (r == TEST_RIGHT) {
2038 left = 0;
2039 right -= 1;
2040
2041 if (last_index != (uint64_t) -1) {
2042 assert(last_index <= right);
2043
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. */
2050
2051 if (last_index > 0) {
2052 uint64_t x = last_index - 1;
2053
2054 p = le64toh(array->entry_array.items[x]);
2055 if (p <= 0)
2056 return -EBADMSG;
2057
2058 r = test_object(f, p, needle);
2059 if (r < 0)
2060 return r;
2061
2062 if (r == TEST_FOUND)
2063 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2064
2065 if (r == TEST_RIGHT)
2066 right = x;
2067 else
2068 left = x + 1;
2069 }
2070
2071 if (last_index < right) {
2072 uint64_t y = last_index + 1;
2073
2074 p = le64toh(array->entry_array.items[y]);
2075 if (p <= 0)
2076 return -EBADMSG;
2077
2078 r = test_object(f, p, needle);
2079 if (r < 0)
2080 return r;
2081
2082 if (r == TEST_FOUND)
2083 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2084
2085 if (r == TEST_RIGHT)
2086 right = y;
2087 else
2088 left = y + 1;
2089 }
2090 }
2091
2092 for (;;) {
2093 if (left == right) {
2094 if (direction == DIRECTION_UP)
2095 subtract_one = true;
2096
2097 i = left;
2098 goto found;
2099 }
2100
2101 assert(left < right);
2102 i = (left + right) / 2;
2103
2104 p = le64toh(array->entry_array.items[i]);
2105 if (p <= 0)
2106 r = -EBADMSG;
2107 else
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)");
2111 right = n = i;
2112 continue;
2113 }
2114 if (r < 0)
2115 return r;
2116
2117 if (r == TEST_FOUND)
2118 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2119
2120 if (r == TEST_RIGHT)
2121 right = i;
2122 else
2123 left = i + 1;
2124 }
2125 }
2126
2127 if (k >= n) {
2128 if (direction == DIRECTION_UP) {
2129 i = n;
2130 subtract_one = true;
2131 goto found;
2132 }
2133
2134 return 0;
2135 }
2136
2137 last_p = lp;
2138
2139 n -= k;
2140 t += k;
2141 last_index = (uint64_t) -1;
2142 a = le64toh(array->entry_array.next_entry_array_offset);
2143 }
2144
2145 return 0;
2146
2147 found:
2148 if (subtract_one && t == 0 && i == 0)
2149 return 0;
2150
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);
2153
2154 if (subtract_one && i == 0)
2155 p = last_p;
2156 else if (subtract_one)
2157 p = le64toh(array->entry_array.items[i-1]);
2158 else
2159 p = le64toh(array->entry_array.items[i]);
2160
2161 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2162 if (r < 0)
2163 return r;
2164
2165 if (ret)
2166 *ret = o;
2167
2168 if (offset)
2169 *offset = p;
2170
2171 if (idx)
2172 *idx = t + i + (subtract_one ? -1 : 0);
2173
2174 return 1;
2175 }
2176
2177 static int generic_array_bisect_plus_one(
2178 JournalFile *f,
2179 uint64_t extra,
2180 uint64_t first,
2181 uint64_t n,
2182 uint64_t needle,
2183 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
2184 direction_t direction,
2185 Object **ret,
2186 uint64_t *offset,
2187 uint64_t *idx) {
2188
2189 int r;
2190 bool step_back = false;
2191 Object *o;
2192
2193 assert(f);
2194 assert(test_object);
2195
2196 if (n <= 0)
2197 return 0;
2198
2199 /* This bisects the array in object 'first', but first checks
2200 * an extra */
2201 r = test_object(f, extra, needle);
2202 if (r < 0)
2203 return r;
2204
2205 if (r == TEST_FOUND)
2206 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2207
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
2212 below. */
2213 if (r == TEST_LEFT)
2214 step_back = direction == DIRECTION_UP;
2215
2216 if (r == TEST_RIGHT) {
2217 if (direction == DIRECTION_DOWN)
2218 goto found;
2219 else
2220 return 0;
2221 }
2222
2223 r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret, offset, idx);
2224
2225 if (r == 0 && step_back)
2226 goto found;
2227
2228 if (r > 0 && idx)
2229 (*idx)++;
2230
2231 return r;
2232
2233 found:
2234 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
2235 if (r < 0)
2236 return r;
2237
2238 if (ret)
2239 *ret = o;
2240
2241 if (offset)
2242 *offset = extra;
2243
2244 if (idx)
2245 *idx = 0;
2246
2247 return 1;
2248 }
2249
2250 _pure_ static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) {
2251 assert(f);
2252 assert(p > 0);
2253
2254 if (p == needle)
2255 return TEST_FOUND;
2256 else if (p < needle)
2257 return TEST_LEFT;
2258 else
2259 return TEST_RIGHT;
2260 }
2261
2262 static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) {
2263 Object *o;
2264 int r;
2265
2266 assert(f);
2267 assert(p > 0);
2268
2269 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2270 if (r < 0)
2271 return r;
2272
2273 if (le64toh(o->entry.seqnum) == needle)
2274 return TEST_FOUND;
2275 else if (le64toh(o->entry.seqnum) < needle)
2276 return TEST_LEFT;
2277 else
2278 return TEST_RIGHT;
2279 }
2280
2281 int journal_file_move_to_entry_by_seqnum(
2282 JournalFile *f,
2283 uint64_t seqnum,
2284 direction_t direction,
2285 Object **ret,
2286 uint64_t *offset) {
2287 assert(f);
2288 assert(f->header);
2289
2290 return generic_array_bisect(f,
2291 le64toh(f->header->entry_array_offset),
2292 le64toh(f->header->n_entries),
2293 seqnum,
2294 test_object_seqnum,
2295 direction,
2296 ret, offset, NULL);
2297 }
2298
2299 static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) {
2300 Object *o;
2301 int r;
2302
2303 assert(f);
2304 assert(p > 0);
2305
2306 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2307 if (r < 0)
2308 return r;
2309
2310 if (le64toh(o->entry.realtime) == needle)
2311 return TEST_FOUND;
2312 else if (le64toh(o->entry.realtime) < needle)
2313 return TEST_LEFT;
2314 else
2315 return TEST_RIGHT;
2316 }
2317
2318 int journal_file_move_to_entry_by_realtime(
2319 JournalFile *f,
2320 uint64_t realtime,
2321 direction_t direction,
2322 Object **ret,
2323 uint64_t *offset) {
2324 assert(f);
2325 assert(f->header);
2326
2327 return generic_array_bisect(f,
2328 le64toh(f->header->entry_array_offset),
2329 le64toh(f->header->n_entries),
2330 realtime,
2331 test_object_realtime,
2332 direction,
2333 ret, offset, NULL);
2334 }
2335
2336 static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) {
2337 Object *o;
2338 int r;
2339
2340 assert(f);
2341 assert(p > 0);
2342
2343 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
2344 if (r < 0)
2345 return r;
2346
2347 if (le64toh(o->entry.monotonic) == needle)
2348 return TEST_FOUND;
2349 else if (le64toh(o->entry.monotonic) < needle)
2350 return TEST_LEFT;
2351 else
2352 return TEST_RIGHT;
2353 }
2354
2355 static int find_data_object_by_boot_id(
2356 JournalFile *f,
2357 sd_id128_t boot_id,
2358 Object **o,
2359 uint64_t *b) {
2360
2361 char t[sizeof("_BOOT_ID=")-1 + 32 + 1] = "_BOOT_ID=";
2362
2363 sd_id128_to_string(boot_id, t + 9);
2364 return journal_file_find_data_object(f, t, sizeof(t) - 1, o, b);
2365 }
2366
2367 int journal_file_move_to_entry_by_monotonic(
2368 JournalFile *f,
2369 sd_id128_t boot_id,
2370 uint64_t monotonic,
2371 direction_t direction,
2372 Object **ret,
2373 uint64_t *offset) {
2374
2375 Object *o;
2376 int r;
2377
2378 assert(f);
2379
2380 r = find_data_object_by_boot_id(f, boot_id, &o, NULL);
2381 if (r < 0)
2382 return r;
2383 if (r == 0)
2384 return -ENOENT;
2385
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),
2390 monotonic,
2391 test_object_monotonic,
2392 direction,
2393 ret, offset, NULL);
2394 }
2395
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;
2404 }
2405
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);
2414 }
2415
2416 int journal_file_compare_locations(JournalFile *af, JournalFile *bf) {
2417 assert(af);
2418 assert(af->header);
2419 assert(bf);
2420 assert(bf->header);
2421 assert(af->location_type == LOCATION_SEEK);
2422 assert(bf->location_type == LOCATION_SEEK);
2423
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)
2430 return 0;
2431
2432 if (sd_id128_equal(af->header->seqnum_id, bf->header->seqnum_id)) {
2433
2434 /* If this is from the same seqnum source, compare
2435 * seqnums */
2436 if (af->current_seqnum < bf->current_seqnum)
2437 return -1;
2438 if (af->current_seqnum > bf->current_seqnum)
2439 return 1;
2440
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. */
2444 }
2445
2446 if (sd_id128_equal(af->current_boot_id, bf->current_boot_id)) {
2447
2448 /* If the boot id matches, compare monotonic time */
2449 if (af->current_monotonic < bf->current_monotonic)
2450 return -1;
2451 if (af->current_monotonic > bf->current_monotonic)
2452 return 1;
2453 }
2454
2455 /* Otherwise, compare UTC time */
2456 if (af->current_realtime < bf->current_realtime)
2457 return -1;
2458 if (af->current_realtime > bf->current_realtime)
2459 return 1;
2460
2461 /* Finally, compare by contents */
2462 if (af->current_xor_hash < bf->current_xor_hash)
2463 return -1;
2464 if (af->current_xor_hash > bf->current_xor_hash)
2465 return 1;
2466
2467 return 0;
2468 }
2469
2470 int journal_file_next_entry(
2471 JournalFile *f,
2472 uint64_t p,
2473 direction_t direction,
2474 Object **ret, uint64_t *offset) {
2475
2476 uint64_t i, n, ofs;
2477 int r;
2478
2479 assert(f);
2480 assert(f->header);
2481
2482 n = le64toh(f->header->n_entries);
2483 if (n <= 0)
2484 return 0;
2485
2486 if (p == 0)
2487 i = direction == DIRECTION_DOWN ? 0 : n - 1;
2488 else {
2489 r = generic_array_bisect(f,
2490 le64toh(f->header->entry_array_offset),
2491 le64toh(f->header->n_entries),
2492 p,
2493 test_object_offset,
2494 DIRECTION_DOWN,
2495 NULL, NULL,
2496 &i);
2497 if (r <= 0)
2498 return r;
2499
2500 if (direction == DIRECTION_DOWN) {
2501 if (i >= n - 1)
2502 return 0;
2503
2504 i++;
2505 } else {
2506 if (i <= 0)
2507 return 0;
2508
2509 i--;
2510 }
2511 }
2512
2513 /* And jump to it */
2514 r = generic_array_get(f,
2515 le64toh(f->header->entry_array_offset),
2516 i,
2517 ret, &ofs);
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.");
2522 return 0;
2523 }
2524 if (r <= 0)
2525 return r;
2526
2527 if (p > 0 &&
2528 (direction == DIRECTION_DOWN ? ofs <= p : ofs >= p)) {
2529 log_debug("%s: entry array corrupted at entry %" PRIu64, f->path, i);
2530 return -EBADMSG;
2531 }
2532
2533 if (offset)
2534 *offset = ofs;
2535
2536 return 1;
2537 }
2538
2539 int journal_file_next_entry_for_data(
2540 JournalFile *f,
2541 Object *o, uint64_t p,
2542 uint64_t data_offset,
2543 direction_t direction,
2544 Object **ret, uint64_t *offset) {
2545
2546 uint64_t n, i;
2547 int r;
2548 Object *d;
2549
2550 assert(f);
2551 assert(p > 0 || !o);
2552
2553 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
2554 if (r < 0)
2555 return r;
2556
2557 n = le64toh(d->data.n_entries);
2558 if (n <= 0)
2559 return n;
2560
2561 if (!o)
2562 i = direction == DIRECTION_DOWN ? 0 : n - 1;
2563 else {
2564 if (o->object.type != OBJECT_ENTRY)
2565 return -EINVAL;
2566
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),
2571 p,
2572 test_object_offset,
2573 DIRECTION_DOWN,
2574 NULL, NULL,
2575 &i);
2576
2577 if (r <= 0)
2578 return r;
2579
2580 if (direction == DIRECTION_DOWN) {
2581 if (i >= n - 1)
2582 return 0;
2583
2584 i++;
2585 } else {
2586 if (i <= 0)
2587 return 0;
2588
2589 i--;
2590 }
2591
2592 }
2593
2594 return generic_array_get_plus_one(f,
2595 le64toh(d->data.entry_offset),
2596 le64toh(d->data.entry_array_offset),
2597 i,
2598 ret, offset);
2599 }
2600
2601 int journal_file_move_to_entry_by_offset_for_data(
2602 JournalFile *f,
2603 uint64_t data_offset,
2604 uint64_t p,
2605 direction_t direction,
2606 Object **ret, uint64_t *offset) {
2607
2608 int r;
2609 Object *d;
2610
2611 assert(f);
2612
2613 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
2614 if (r < 0)
2615 return r;
2616
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),
2621 p,
2622 test_object_offset,
2623 direction,
2624 ret, offset, NULL);
2625 }
2626
2627 int journal_file_move_to_entry_by_monotonic_for_data(
2628 JournalFile *f,
2629 uint64_t data_offset,
2630 sd_id128_t boot_id,
2631 uint64_t monotonic,
2632 direction_t direction,
2633 Object **ret, uint64_t *offset) {
2634
2635 Object *o, *d;
2636 int r;
2637 uint64_t b, z;
2638
2639 assert(f);
2640
2641 /* First, seek by time */
2642 r = find_data_object_by_boot_id(f, boot_id, &o, &b);
2643 if (r < 0)
2644 return r;
2645 if (r == 0)
2646 return -ENOENT;
2647
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),
2652 monotonic,
2653 test_object_monotonic,
2654 direction,
2655 NULL, &z, NULL);
2656 if (r <= 0)
2657 return r;
2658
2659 /* And now, continue seeking until we find an entry that
2660 * exists in both bisection arrays */
2661
2662 for (;;) {
2663 Object *qo;
2664 uint64_t p, q;
2665
2666 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
2667 if (r < 0)
2668 return r;
2669
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),
2674 z,
2675 test_object_offset,
2676 direction,
2677 NULL, &p, NULL);
2678 if (r <= 0)
2679 return r;
2680
2681 r = journal_file_move_to_object(f, OBJECT_DATA, b, &o);
2682 if (r < 0)
2683 return r;
2684
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),
2689 p,
2690 test_object_offset,
2691 direction,
2692 &qo, &q, NULL);
2693
2694 if (r <= 0)
2695 return r;
2696
2697 if (p == q) {
2698 if (ret)
2699 *ret = qo;
2700 if (offset)
2701 *offset = q;
2702
2703 return 1;
2704 }
2705
2706 z = q;
2707 }
2708 }
2709
2710 int journal_file_move_to_entry_by_seqnum_for_data(
2711 JournalFile *f,
2712 uint64_t data_offset,
2713 uint64_t seqnum,
2714 direction_t direction,
2715 Object **ret, uint64_t *offset) {
2716
2717 Object *d;
2718 int r;
2719
2720 assert(f);
2721
2722 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
2723 if (r < 0)
2724 return r;
2725
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),
2730 seqnum,
2731 test_object_seqnum,
2732 direction,
2733 ret, offset, NULL);
2734 }
2735
2736 int journal_file_move_to_entry_by_realtime_for_data(
2737 JournalFile *f,
2738 uint64_t data_offset,
2739 uint64_t realtime,
2740 direction_t direction,
2741 Object **ret, uint64_t *offset) {
2742
2743 Object *d;
2744 int r;
2745
2746 assert(f);
2747
2748 r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
2749 if (r < 0)
2750 return r;
2751
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),
2756 realtime,
2757 test_object_realtime,
2758 direction,
2759 ret, offset, NULL);
2760 }
2761
2762 void journal_file_dump(JournalFile *f) {
2763 Object *o;
2764 int r;
2765 uint64_t p;
2766
2767 assert(f);
2768 assert(f->header);
2769
2770 journal_file_print_header(f);
2771
2772 p = le64toh(f->header->header_size);
2773 while (p != 0) {
2774 r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o);
2775 if (r < 0)
2776 goto fail;
2777
2778 switch (o->object.type) {
2779
2780 case OBJECT_UNUSED:
2781 printf("Type: OBJECT_UNUSED\n");
2782 break;
2783
2784 case OBJECT_DATA:
2785 printf("Type: OBJECT_DATA\n");
2786 break;
2787
2788 case OBJECT_FIELD:
2789 printf("Type: OBJECT_FIELD\n");
2790 break;
2791
2792 case OBJECT_ENTRY:
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));
2797 break;
2798
2799 case OBJECT_FIELD_HASH_TABLE:
2800 printf("Type: OBJECT_FIELD_HASH_TABLE\n");
2801 break;
2802
2803 case OBJECT_DATA_HASH_TABLE:
2804 printf("Type: OBJECT_DATA_HASH_TABLE\n");
2805 break;
2806
2807 case OBJECT_ENTRY_ARRAY:
2808 printf("Type: OBJECT_ENTRY_ARRAY\n");
2809 break;
2810
2811 case OBJECT_TAG:
2812 printf("Type: OBJECT_TAG seqnum=%"PRIu64" epoch=%"PRIu64"\n",
2813 le64toh(o->tag.seqnum),
2814 le64toh(o->tag.epoch));
2815 break;
2816
2817 default:
2818 printf("Type: unknown (%i)\n", o->object.type);
2819 break;
2820 }
2821
2822 if (o->object.flags & OBJECT_COMPRESSION_MASK)
2823 printf("Flags: %s\n",
2824 object_compressed_to_string(o->object.flags & OBJECT_COMPRESSION_MASK));
2825
2826 if (p == le64toh(f->header->tail_object_offset))
2827 p = 0;
2828 else
2829 p = p + ALIGN64(le64toh(o->object.size));
2830 }
2831
2832 return;
2833 fail:
2834 log_error("File corrupt");
2835 }
2836
2837 static const char* format_timestamp_safe(char *buf, size_t l, usec_t t) {
2838 const char *x;
2839
2840 x = format_timestamp(buf, l, t);
2841 if (x)
2842 return x;
2843 return " --- ";
2844 }
2845
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];
2849 struct stat st;
2850 char bytes[FORMAT_BYTES_MAX];
2851
2852 assert(f);
2853 assert(f->header);
2854
2855 printf("File Path: %s\n"
2856 "File ID: %s\n"
2857 "Machine ID: %s\n"
2858 "Boot ID: %s\n"
2859 "Sequential Number ID: %s\n"
2860 "State: %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",
2875 f->path,
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));
2900
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))));
2906
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))));
2912
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));
2919
2920 if (fstat(f->fd, &st) >= 0)
2921 printf("Disk usage: %s\n", format_bytes(bytes, sizeof(bytes), (uint64_t) st.st_blocks * 512ULL));
2922 }
2923
2924 static int journal_file_warn_btrfs(JournalFile *f) {
2925 unsigned attrs;
2926 int r;
2927
2928 assert(f);
2929
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). */
2936
2937 r = btrfs_is_filesystem(f->fd);
2938 if (r < 0)
2939 return log_warning_errno(r, "Failed to determine if journal is on btrfs: %m");
2940 if (!r)
2941 return 0;
2942
2943 r = read_attr_fd(f->fd, &attrs);
2944 if (r < 0)
2945 return log_warning_errno(r, "Failed to read file attributes: %m");
2946
2947 if (attrs & FS_NOCOW_FL) {
2948 log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
2949 return 0;
2950 }
2951
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);
2955
2956 return 1;
2957 }
2958
2959 int journal_file_open(
2960 int fd,
2961 const char *fname,
2962 int flags,
2963 mode_t mode,
2964 bool compress,
2965 bool seal,
2966 JournalMetrics *metrics,
2967 MMapCache *mmap_cache,
2968 Set *deferred_closes,
2969 JournalFile *template,
2970 JournalFile **ret) {
2971
2972 bool newly_created = false;
2973 JournalFile *f;
2974 void *h;
2975 int r;
2976
2977 assert(ret);
2978 assert(fd >= 0 || fname);
2979
2980 if ((flags & O_ACCMODE) != O_RDONLY &&
2981 (flags & O_ACCMODE) != O_RDWR)
2982 return -EINVAL;
2983
2984 if (fname) {
2985 if (!endswith(fname, ".journal") &&
2986 !endswith(fname, ".journal~"))
2987 return -EINVAL;
2988 }
2989
2990 f = new0(JournalFile, 1);
2991 if (!f)
2992 return -ENOMEM;
2993
2994 f->fd = fd;
2995 f->mode = mode;
2996
2997 f->flags = flags;
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;
3004 #endif
3005 #ifdef HAVE_GCRYPT
3006 f->seal = seal;
3007 #endif
3008
3009 if (mmap_cache)
3010 f->mmap = mmap_cache_ref(mmap_cache);
3011 else {
3012 f->mmap = mmap_cache_new();
3013 if (!f->mmap) {
3014 r = -ENOMEM;
3015 goto fail;
3016 }
3017 }
3018
3019 if (fname)
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);
3023 if (!f->path) {
3024 r = -ENOMEM;
3025 goto fail;
3026 }
3027
3028 f->chain_cache = ordered_hashmap_new(&uint64_hash_ops);
3029 if (!f->chain_cache) {
3030 r = -ENOMEM;
3031 goto fail;
3032 }
3033
3034 if (f->fd < 0) {
3035 f->fd = open(f->path, f->flags|O_CLOEXEC, f->mode);
3036 if (f->fd < 0) {
3037 r = -errno;
3038 goto fail;
3039 }
3040
3041 /* fds we opened here by us should also be closed by us. */
3042 f->close_fd = true;
3043 }
3044
3045 r = journal_file_fstat(f);
3046 if (r < 0)
3047 goto fail;
3048
3049 if (f->last_stat.st_size == 0 && f->writable) {
3050
3051 (void) journal_file_warn_btrfs(f);
3052
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. */
3062
3063 fd_setcrtime(f->fd, 0);
3064
3065 #ifdef HAVE_GCRYPT
3066 /* Try to load the FSPRG state, and if we can't, then
3067 * just don't do sealing */
3068 if (f->seal) {
3069 r = journal_file_fss_load(f);
3070 if (r < 0)
3071 f->seal = false;
3072 }
3073 #endif
3074
3075 r = journal_file_init_header(f, template);
3076 if (r < 0)
3077 goto fail;
3078
3079 r = journal_file_fstat(f);
3080 if (r < 0)
3081 goto fail;
3082
3083 newly_created = true;
3084 }
3085
3086 if (f->last_stat.st_size < (off_t) HEADER_SIZE_MIN) {
3087 r = -ENODATA;
3088 goto fail;
3089 }
3090
3091 r = mmap_cache_get(f->mmap, f->fd, f->prot, CONTEXT_HEADER, true, 0, PAGE_ALIGN(sizeof(Header)), &f->last_stat, &h);
3092 if (r < 0)
3093 goto fail;
3094
3095 f->header = h;
3096
3097 if (!newly_created) {
3098 if (deferred_closes)
3099 journal_file_close_set(deferred_closes);
3100
3101 r = journal_file_verify_header(f);
3102 if (r < 0)
3103 goto fail;
3104 }
3105
3106 #ifdef HAVE_GCRYPT
3107 if (!newly_created && f->writable) {
3108 r = journal_file_fss_load(f);
3109 if (r < 0)
3110 goto fail;
3111 }
3112 #endif
3113
3114 if (f->writable) {
3115 if (metrics) {
3116 journal_default_metrics(metrics, f->fd);
3117 f->metrics = *metrics;
3118 } else if (template)
3119 f->metrics = template->metrics;
3120
3121 r = journal_file_refresh_header(f);
3122 if (r < 0)
3123 goto fail;
3124 }
3125
3126 #ifdef HAVE_GCRYPT
3127 r = journal_file_hmac_setup(f);
3128 if (r < 0)
3129 goto fail;
3130 #endif
3131
3132 if (newly_created) {
3133 r = journal_file_setup_field_hash_table(f);
3134 if (r < 0)
3135 goto fail;
3136
3137 r = journal_file_setup_data_hash_table(f);
3138 if (r < 0)
3139 goto fail;
3140
3141 #ifdef HAVE_GCRYPT
3142 r = journal_file_append_first_tag(f);
3143 if (r < 0)
3144 goto fail;
3145 #endif
3146 }
3147
3148 if (mmap_cache_got_sigbus(f->mmap, f->fd)) {
3149 r = -EIO;
3150 goto fail;
3151 }
3152
3153 if (template && template->post_change_timer) {
3154 r = journal_file_enable_post_change_timer(
3155 f,
3156 sd_event_source_get_event(template->post_change_timer),
3157 template->post_change_timer_period);
3158
3159 if (r < 0)
3160 goto fail;
3161 }
3162
3163 /* The file is opened now successfully, thus we take possesion of any passed in fd. */
3164 f->close_fd = true;
3165
3166 *ret = f;
3167 return 0;
3168
3169 fail:
3170 if (f->fd >= 0 && mmap_cache_got_sigbus(f->mmap, f->fd))
3171 r = -EIO;
3172
3173 (void) journal_file_close(f);
3174
3175 return r;
3176 }
3177
3178 int journal_file_rotate(JournalFile **f, bool compress, bool seal, Set *deferred_closes) {
3179 _cleanup_free_ char *p = NULL;
3180 size_t l;
3181 JournalFile *old_file, *new_file = NULL;
3182 int r;
3183
3184 assert(f);
3185 assert(*f);
3186
3187 old_file = *f;
3188
3189 if (!old_file->writable)
3190 return -EINVAL;
3191
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"))
3195 return -EINVAL;
3196
3197 if (!endswith(old_file->path, ".journal"))
3198 return -EINVAL;
3199
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));
3206 if (r < 0)
3207 return -ENOMEM;
3208
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
3211 * case. */
3212 r = rename(old_file->path, p);
3213 if (r < 0 && errno != ENOENT)
3214 return -errno;
3215
3216 /* Sync the rename to disk */
3217 (void) fsync_directory_of_file(old_file->fd);
3218
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;
3226
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;
3231
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);
3233
3234 if (deferred_closes &&
3235 set_put(deferred_closes, old_file) >= 0)
3236 (void) journal_file_set_offline(old_file, false);
3237 else
3238 (void) journal_file_close(old_file);
3239
3240 *f = new_file;
3241 return r;
3242 }
3243
3244 int journal_file_open_reliably(
3245 const char *fname,
3246 int flags,
3247 mode_t mode,
3248 bool compress,
3249 bool seal,
3250 JournalMetrics *metrics,
3251 MMapCache *mmap_cache,
3252 Set *deferred_closes,
3253 JournalFile *template,
3254 JournalFile **ret) {
3255
3256 int r;
3257 size_t l;
3258 _cleanup_free_ char *p = NULL;
3259
3260 r = journal_file_open(-1, fname, flags, mode, compress, seal, metrics, mmap_cache, deferred_closes, template, ret);
3261 if (!IN_SET(r,
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 */))
3270 return r;
3271
3272 if ((flags & O_ACCMODE) == O_RDONLY)
3273 return r;
3274
3275 if (!(flags & O_CREAT))
3276 return r;
3277
3278 if (!endswith(fname, ".journal"))
3279 return r;
3280
3281 /* The file is corrupted. Rotate it away and try it again (but only once) */
3282
3283 l = strlen(fname);
3284 if (asprintf(&p, "%.*s@%016"PRIx64 "-%016"PRIx64 ".journal~",
3285 (int) l - 8, fname,
3286 now(CLOCK_REALTIME),
3287 random_u64()) < 0)
3288 return -ENOMEM;
3289
3290 if (rename(fname, p) < 0)
3291 return -errno;
3292
3293 /* btrfs doesn't cope well with our write pattern and
3294 * fragments heavily. Let's defrag all files we rotate */
3295
3296 (void) chattr_path(p, 0, FS_NOCOW_FL);
3297 (void) btrfs_defrag(p);
3298
3299 log_warning_errno(r, "File %s corrupted or uncleanly shut down, renaming and replacing.", fname);
3300
3301 return journal_file_open(-1, fname, flags, mode, compress, seal, metrics, mmap_cache, deferred_closes, template, ret);
3302 }
3303
3304 int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset) {
3305 uint64_t i, n;
3306 uint64_t q, xor_hash = 0;
3307 int r;
3308 EntryItem *items;
3309 dual_timestamp ts;
3310
3311 assert(from);
3312 assert(to);
3313 assert(o);
3314 assert(p);
3315
3316 if (!to->writable)
3317 return -EPERM;
3318
3319 ts.monotonic = le64toh(o->entry.monotonic);
3320 ts.realtime = le64toh(o->entry.realtime);
3321
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));
3325
3326 for (i = 0; i < n; i++) {
3327 uint64_t l, h;
3328 le64_t le_hash;
3329 size_t t;
3330 void *data;
3331 Object *u;
3332
3333 q = le64toh(o->entry.items[i].object_offset);
3334 le_hash = o->entry.items[i].hash;
3335
3336 r = journal_file_move_to_object(from, OBJECT_DATA, q, &o);
3337 if (r < 0)
3338 return r;
3339
3340 if (le_hash != o->data.hash)
3341 return -EBADMSG;
3342
3343 l = le64toh(o->object.size) - offsetof(Object, data.payload);
3344 t = (size_t) l;
3345
3346 /* We hit the limit on 32bit machines */
3347 if ((uint64_t) t != l)
3348 return -E2BIG;
3349
3350 if (o->object.flags & OBJECT_COMPRESSION_MASK) {
3351 #if defined(HAVE_XZ) || defined(HAVE_LZ4)
3352 size_t rsize = 0;
3353
3354 r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK,
3355 o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize, 0);
3356 if (r < 0)
3357 return r;
3358
3359 data = from->compress_buffer;
3360 l = rsize;
3361 #else
3362 return -EPROTONOSUPPORT;
3363 #endif
3364 } else
3365 data = o->data.payload;
3366
3367 r = journal_file_append_data(to, data, l, &u, &h);
3368 if (r < 0)
3369 return r;
3370
3371 xor_hash ^= le64toh(u->data.hash);
3372 items[i].object_offset = htole64(h);
3373 items[i].hash = u->data.hash;
3374
3375 r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
3376 if (r < 0)
3377 return r;
3378 }
3379
3380 r = journal_file_append_entry_internal(to, &ts, xor_hash, items, n, seqnum, ret, offset);
3381
3382 if (mmap_cache_got_sigbus(to->mmap, to->fd))
3383 return -EIO;
3384
3385 return r;
3386 }
3387
3388 void journal_reset_metrics(JournalMetrics *m) {
3389 assert(m);
3390
3391 /* Set everything to "pick automatic values". */
3392
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,
3400 };
3401 }
3402
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];
3405 struct statvfs ss;
3406 uint64_t fs_size;
3407
3408 assert(m);
3409 assert(fd >= 0);
3410
3411 if (fstatvfs(fd, &ss) >= 0)
3412 fs_size = ss.f_frsize * ss.f_blocks;
3413 else {
3414 log_debug_errno(errno, "Failed to detremine disk size: %m");
3415 fs_size = 0;
3416 }
3417
3418 if (m->max_use == (uint64_t) -1) {
3419
3420 if (fs_size > 0) {
3421 m->max_use = PAGE_ALIGN(fs_size / 10); /* 10% of file system size */
3422
3423 if (m->max_use > DEFAULT_MAX_USE_UPPER)
3424 m->max_use = DEFAULT_MAX_USE_UPPER;
3425
3426 if (m->max_use < DEFAULT_MAX_USE_LOWER)
3427 m->max_use = DEFAULT_MAX_USE_LOWER;
3428 } else
3429 m->max_use = DEFAULT_MAX_USE_LOWER;
3430 } else {
3431 m->max_use = PAGE_ALIGN(m->max_use);
3432
3433 if (m->max_use != 0 && m->max_use < JOURNAL_FILE_SIZE_MIN*2)
3434 m->max_use = JOURNAL_FILE_SIZE_MIN*2;
3435 }
3436
3437 if (m->min_use == (uint64_t) -1)
3438 m->min_use = DEFAULT_MIN_USE;
3439
3440 if (m->min_use > m->max_use)
3441 m->min_use = m->max_use;
3442
3443 if (m->max_size == (uint64_t) -1) {
3444 m->max_size = PAGE_ALIGN(m->max_use / 8); /* 8 chunks */
3445
3446 if (m->max_size > DEFAULT_MAX_SIZE_UPPER)
3447 m->max_size = DEFAULT_MAX_SIZE_UPPER;
3448 } else
3449 m->max_size = PAGE_ALIGN(m->max_size);
3450
3451 if (m->max_size != 0) {
3452 if (m->max_size < JOURNAL_FILE_SIZE_MIN)
3453 m->max_size = JOURNAL_FILE_SIZE_MIN;
3454
3455 if (m->max_use != 0 && m->max_size*2 > m->max_use)
3456 m->max_use = m->max_size*2;
3457 }
3458
3459 if (m->min_size == (uint64_t) -1)
3460 m->min_size = JOURNAL_FILE_SIZE_MIN;
3461 else {
3462 m->min_size = PAGE_ALIGN(m->min_size);
3463
3464 if (m->min_size < JOURNAL_FILE_SIZE_MIN)
3465 m->min_size = JOURNAL_FILE_SIZE_MIN;
3466
3467 if (m->max_size != 0 && m->min_size > m->max_size)
3468 m->max_size = m->min_size;
3469 }
3470
3471 if (m->keep_free == (uint64_t) -1) {
3472
3473 if (fs_size > 0) {
3474 m->keep_free = PAGE_ALIGN(fs_size * 3 / 20); /* 15% of file system size */
3475
3476 if (m->keep_free > DEFAULT_KEEP_FREE_UPPER)
3477 m->keep_free = DEFAULT_KEEP_FREE_UPPER;
3478
3479 } else
3480 m->keep_free = DEFAULT_KEEP_FREE;
3481 }
3482
3483 if (m->n_max_files == (uint64_t) -1)
3484 m->n_max_files = DEFAULT_N_MAX_FILES;
3485
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),
3492 m->n_max_files);
3493 }
3494
3495 int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *from, usec_t *to) {
3496 assert(f);
3497 assert(f->header);
3498 assert(from || to);
3499
3500 if (from) {
3501 if (f->header->head_entry_realtime == 0)
3502 return -ENOENT;
3503
3504 *from = le64toh(f->header->head_entry_realtime);
3505 }
3506
3507 if (to) {
3508 if (f->header->tail_entry_realtime == 0)
3509 return -ENOENT;
3510
3511 *to = le64toh(f->header->tail_entry_realtime);
3512 }
3513
3514 return 1;
3515 }
3516
3517 int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot_id, usec_t *from, usec_t *to) {
3518 Object *o;
3519 uint64_t p;
3520 int r;
3521
3522 assert(f);
3523 assert(from || to);
3524
3525 r = find_data_object_by_boot_id(f, boot_id, &o, &p);
3526 if (r <= 0)
3527 return r;
3528
3529 if (le64toh(o->data.n_entries) <= 0)
3530 return 0;
3531
3532 if (from) {
3533 r = journal_file_move_to_object(f, OBJECT_ENTRY, le64toh(o->data.entry_offset), &o);
3534 if (r < 0)
3535 return r;
3536
3537 *from = le64toh(o->entry.monotonic);
3538 }
3539
3540 if (to) {
3541 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
3542 if (r < 0)
3543 return r;
3544
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,
3549 &o, NULL);
3550 if (r <= 0)
3551 return r;
3552
3553 *to = le64toh(o->entry.monotonic);
3554 }
3555
3556 return 1;
3557 }
3558
3559 bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec) {
3560 assert(f);
3561 assert(f->header);
3562
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);
3567 return true;
3568 }
3569
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. */
3575
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.",
3579 f->path,
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));
3585 return true;
3586 }
3587
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.",
3591 f->path,
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));
3595 return true;
3596 }
3597
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)
3603 return true;
3604
3605 if (max_file_usec > 0) {
3606 usec_t t, h;
3607
3608 h = le64toh(f->header->head_entry_realtime);
3609 t = now(CLOCK_REALTIME);
3610
3611 if (h > 0 && t > h + max_file_usec)
3612 return true;
3613 }
3614
3615 return false;
3616 }