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