1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
25 #include <linux/limits.h>
30 #include <sys/select.h>
32 #include <sys/types.h>
35 #include <linux/fanotify.h>
36 #include <sys/signalfd.h>
40 #include <linux/fiemap.h>
41 #include <sys/ioctl.h>
44 #include <sys/inotify.h>
49 #include "sd-daemon.h"
51 #include "readahead-common.h"
55 * - detect ssd on btrfs/lvm...
56 * - read ahead directories
59 * - handle files where nothing is in mincore
60 * - does ioprio_set work with fadvise()?
63 static unsigned arg_files_max = 16*1024;
64 static off_t arg_file_size_max = READAHEAD_FILE_SIZE_MAX;
65 static usec_t arg_timeout = 2*USEC_PER_MINUTE;
67 static ReadaheadShared *shared = NULL;
69 /* Avoid collisions with the NULL pointer */
70 #define SECTOR_TO_PTR(s) ULONG_TO_PTR((s)+1)
71 #define PTR_TO_SECTOR(p) (PTR_TO_ULONG(p)-1)
73 static int btrfs_defrag(int fd) {
74 struct btrfs_ioctl_vol_args data;
79 return ioctl(fd, BTRFS_IOC_DEFRAG, &data);
82 static int pack_file(FILE *pack, const char *fn, bool on_btrfs) {
84 void *start = MAP_FAILED;
89 int r = 0, fd = -1, k;
94 if ((fd = open(fn, O_RDONLY|O_CLOEXEC|O_NOATIME|O_NOCTTY|O_NOFOLLOW)) < 0) {
99 if (errno == EPERM || errno == EACCES)
102 log_warning("open(%s) failed: %m", fn);
107 if ((k = file_verify(fd, fn, arg_file_size_max, &st)) <= 0) {
115 l = PAGE_ALIGN(st.st_size);
116 if ((start = mmap(NULL, l, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
117 log_warning("mmap(%s) failed: %m", fn);
122 pages = l / page_size();
125 memset(vec, 0, pages);
126 if (mincore(start, l, vec) < 0) {
127 log_warning("mincore(%s) failed: %m", fn);
136 for (c = 0; c < pages; c++) {
137 bool new_mapped = !!(vec[c] & 1);
139 if (!mapped && new_mapped)
141 else if (mapped && !new_mapped) {
142 fwrite(&b, sizeof(b), 1, pack);
143 fwrite(&c, sizeof(c), 1, pack);
145 log_debug("%s: page %u to %u", fn, b, c);
151 /* We don't write any range data if we should read the entire file */
152 if (mapped && b > 0) {
153 fwrite(&b, sizeof(b), 1, pack);
154 fwrite(&c, sizeof(c), 1, pack);
156 log_debug("%s: page %u to %u", fn, b, c);
161 fwrite(&b, sizeof(b), 1, pack);
162 fwrite(&b, sizeof(b), 1, pack);
165 if (start != MAP_FAILED)
169 close_nointr_nofail(fd);
174 static unsigned long fd_first_block(int fd) {
176 struct fiemap fiemap;
177 struct fiemap_extent extent;
181 data.fiemap.fm_length = ~0ULL;
182 data.fiemap.fm_extent_count = 1;
184 if (ioctl(fd, FS_IOC_FIEMAP, &data) < 0)
187 if (data.fiemap.fm_mapped_extents <= 0)
190 if (data.fiemap.fm_extents[0].fe_flags & FIEMAP_EXTENT_UNKNOWN)
193 return (unsigned long) data.fiemap.fm_extents[0].fe_physical;
201 static int qsort_compare(const void *a, const void *b) {
202 const struct item *i, *j;
207 if (i->block < j->block)
209 if (i->block > j->block)
212 return strcmp(i->path, j->path);
215 static int collect(const char *root) {
217 FD_FANOTIFY, /* Get the actual fs events */
219 FD_INOTIFY, /* We get notifications to quit early via this fd */
222 struct pollfd pollfd[_FD_MAX];
223 int fanotify_fd = -1, signal_fd = -1, inotify_fd = -1, r = 0;
225 Hashmap *files = NULL;
230 char *pack_fn_new = NULL, *pack_fn = NULL;
231 bool on_ssd, on_btrfs;
237 write_one_line_file("/proc/self/oom_score_adj", "1000");
239 if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) < 0)
240 log_warning("Failed to set IDLE IO priority class: %m");
242 assert_se(sigemptyset(&mask) == 0);
243 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
244 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
246 if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
247 log_error("signalfd(): %m");
252 if (!(files = hashmap_new(string_hash_func, string_compare_func))) {
253 log_error("Failed to allocate set.");
258 if ((fanotify_fd = fanotify_init(FAN_CLOEXEC|FAN_NONBLOCK, O_RDONLY|O_LARGEFILE|O_CLOEXEC|O_NOATIME)) < 0) {
259 log_error("Failed to create fanotify object: %m");
264 if (fanotify_mark(fanotify_fd, FAN_MARK_ADD|FAN_MARK_MOUNT, FAN_OPEN, AT_FDCWD, root) < 0) {
265 log_error("Failed to mark %s: %m", root);
270 if ((inotify_fd = open_inotify()) < 0) {
275 not_after = now(CLOCK_MONOTONIC) + arg_timeout;
280 pollfd[FD_FANOTIFY].fd = fanotify_fd;
281 pollfd[FD_FANOTIFY].events = POLLIN;
282 pollfd[FD_SIGNAL].fd = signal_fd;
283 pollfd[FD_SIGNAL].events = POLLIN;
284 pollfd[FD_INOTIFY].fd = inotify_fd;
285 pollfd[FD_INOTIFY].events = POLLIN;
289 "STATUS=Collecting readahead data");
291 log_debug("Collecting...");
293 if (access("/run/systemd/readahead/cancel", F_OK) >= 0) {
294 log_debug("Collection canceled");
299 if (access("/run/systemd/readahead/done", F_OK) >= 0) {
300 log_debug("Got termination request");
306 struct fanotify_event_metadata metadata;
310 struct fanotify_event_metadata *m;
314 if (hashmap_size(files) > arg_files_max) {
315 log_debug("Reached maximum number of read ahead files, ending collection.");
319 t = now(CLOCK_MONOTONIC);
320 if (t >= not_after) {
321 log_debug("Reached maximum collection time, ending collection.");
325 if ((h = poll(pollfd, _FD_MAX, (int) ((not_after - t) / USEC_PER_MSEC))) < 0) {
330 log_error("poll(): %m");
336 log_debug("Reached maximum collection time, ending collection.");
340 if (pollfd[FD_SIGNAL].revents) {
341 log_debug("Got signal.");
345 if (pollfd[FD_INOTIFY].revents) {
346 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
347 struct inotify_event *e;
349 if ((n = read(inotify_fd, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
350 if (errno == EINTR || errno == EAGAIN)
353 log_error("Failed to read inotify event: %m");
358 e = (struct inotify_event*) inotify_buffer;
362 if ((e->mask & IN_CREATE) && streq(e->name, "cancel")) {
363 log_debug("Collection canceled");
368 if ((e->mask & IN_CREATE) && streq(e->name, "done")) {
369 log_debug("Got termination request");
373 step = sizeof(struct inotify_event) + e->len;
374 assert(step <= (size_t) n);
376 e = (struct inotify_event*) ((uint8_t*) e + step);
381 if ((n = read(fanotify_fd, &data, sizeof(data))) < 0) {
383 if (errno == EINTR || errno == EAGAIN)
386 log_error("Failed to read event: %m");
391 for (m = &data.metadata; FAN_EVENT_OK(m, n); m = FAN_EVENT_NEXT(m, n)) {
398 if (m->pid == my_pid)
401 __sync_synchronize();
402 if (m->pid == shared->replay)
405 snprintf(fn, sizeof(fn), "/proc/self/fd/%i", m->fd);
408 if ((k = readlink_malloc(fn, &p)) >= 0) {
409 if (startswith(p, "/tmp") ||
410 endswith(p, " (deleted)") ||
411 hashmap_get(files, p))
412 /* Not interesting, or
418 ul = fd_first_block(m->fd);
420 if ((k = hashmap_put(files, p, SECTOR_TO_PTR(ul))) < 0) {
421 log_warning("set_put() failed: %s", strerror(-k));
427 log_warning("readlink(%s) failed: %s", fn, strerror(-k));
431 close_nointr_nofail(m->fd);
436 if (fanotify_fd >= 0) {
437 close_nointr_nofail(fanotify_fd);
441 log_debug("Writing Pack File...");
443 on_ssd = fs_on_ssd(root) > 0;
444 log_debug("On SSD: %s", yes_no(on_ssd));
446 on_btrfs = statfs(root, &sfs) >= 0 && (long) sfs.f_type == (long) BTRFS_SUPER_MAGIC;
447 log_debug("On btrfs: %s", yes_no(on_btrfs));
449 asprintf(&pack_fn, "%s/.readahead", root);
450 asprintf(&pack_fn_new, "%s/.readahead.new", root);
452 if (!pack_fn || !pack_fn_new) {
453 log_error("Out of memory");
458 if (!(pack = fopen(pack_fn_new, "we"))) {
459 log_error("Failed to open pack file: %m");
464 fputs(CANONICAL_HOST "\n", pack);
465 putc(on_ssd ? 'S' : 'R', pack);
467 if (on_ssd || on_btrfs) {
469 /* On SSD or on btrfs, just write things out in the
470 * order the files were accessed. */
472 HASHMAP_FOREACH_KEY(q, p, files, i)
473 pack_file(pack, p, on_btrfs);
475 struct item *ordered, *j;
478 /* On rotating media, order things by the block
481 log_debug("Ordering...");
483 n = hashmap_size(files);
484 if (!(ordered = new(struct item, n))) {
485 log_error("Out of memory");
491 HASHMAP_FOREACH_KEY(q, p, files, i) {
493 j->block = PTR_TO_SECTOR(q);
497 assert(ordered + n == j);
499 qsort(ordered, n, sizeof(struct item), qsort_compare);
501 for (k = 0; k < n; k++)
502 pack_file(pack, ordered[k].path, on_btrfs);
507 log_debug("Finalizing...");
512 log_error("Failed to write pack file.");
517 if (rename(pack_fn_new, pack_fn) < 0) {
518 log_error("Failed to rename readahead file: %m");
529 if (fanotify_fd >= 0)
530 close_nointr_nofail(fanotify_fd);
533 close_nointr_nofail(signal_fd);
536 close_nointr_nofail(inotify_fd);
546 while ((p = hashmap_steal_first_key(files)))
554 static int help(void) {
556 printf("%s [OPTIONS...] [DIRECTORY]\n\n"
557 "Collect read-ahead data on early boot.\n\n"
558 " -h --help Show this help\n"
559 " --max-files=INT Maximum number of files to read ahead\n"
560 " --max-file-size=BYTES Maximum size of files to read ahead\n"
561 " --timeout=USEC Maximum time to spend collecting data\n",
562 program_invocation_short_name);
567 static int parse_argv(int argc, char *argv[]) {
570 ARG_FILES_MAX = 0x100,
575 static const struct option options[] = {
576 { "help", no_argument, NULL, 'h' },
577 { "files-max", required_argument, NULL, ARG_FILES_MAX },
578 { "file-size-max", required_argument, NULL, ARG_FILE_SIZE_MAX },
579 { "timeout", required_argument, NULL, ARG_TIMEOUT },
588 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
597 if (safe_atou(optarg, &arg_files_max) < 0 || arg_files_max <= 0) {
598 log_error("Failed to parse maximum number of files %s.", optarg);
603 case ARG_FILE_SIZE_MAX: {
604 unsigned long long ull;
606 if (safe_atollu(optarg, &ull) < 0 || ull <= 0) {
607 log_error("Failed to parse maximum file size %s.", optarg);
611 arg_file_size_max = (off_t) ull;
616 if (parse_usec(optarg, &arg_timeout) < 0 || arg_timeout <= 0) {
617 log_error("Failed to parse timeout %s.", optarg);
627 log_error("Unknown option code %c", c);
632 if (optind != argc &&
641 int main(int argc, char *argv[]) {
645 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
646 log_parse_environment();
649 if ((r = parse_argv(argc, argv)) <= 0)
650 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
652 root = optind < argc ? argv[optind] : "/";
654 if (fs_on_read_only(root) > 0) {
655 log_info("Disabling readahead collector due to read-only media.");
660 log_info("Disabling readahead collector due to low memory.");
664 if (detect_virtualization(NULL) > 0) {
665 log_info("Disabling readahead collector due to execution in virtualized environment.");
669 if (!(shared = shared_get()))
672 shared->collect = getpid();
673 __sync_synchronize();
675 if (collect(root) < 0)