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 int btrfs_defrag(int fd) {
68 struct btrfs_ioctl_vol_args data;
73 return ioctl(fd, BTRFS_IOC_DEFRAG, &data);
76 static int pack_file(FILE *pack, const char *fn, bool on_btrfs) {
78 void *start = MAP_FAILED;
83 int r = 0, fd = -1, k;
88 if ((fd = open(fn, O_RDONLY|O_CLOEXEC|O_NOATIME|O_NOCTTY|O_NOFOLLOW)) < 0) {
89 log_warning("open(%s) failed: %m", fn);
94 if ((k = file_verify(fd, fn, arg_file_size_max, &st)) <= 0) {
102 l = PAGE_ALIGN(st.st_size);
103 if ((start = mmap(NULL, l, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
104 log_warning("mmap(%s) failed: %m", fn);
109 pages = l / PAGE_SIZE;
112 if (mincore(start, l, vec) < 0) {
113 log_warning("mincore(%s) failed: %m", fn);
122 for (c = 0; c < pages; c++) {
123 bool new_mapped = !!(vec[c] & 1);
125 if (!mapped && new_mapped)
127 else if (mapped && !new_mapped) {
128 fwrite(&b, sizeof(b), 1, pack);
129 fwrite(&c, sizeof(c), 1, pack);
131 log_debug("%s: page %u to %u", fn, b, c);
137 /* We don't write any range data if we should read the entire file */
138 if (mapped && b > 0) {
139 fwrite(&b, sizeof(b), 1, pack);
140 fwrite(&c, sizeof(c), 1, pack);
142 log_debug("%s: page %u to %u", fn, b, c);
147 fwrite(&b, sizeof(b), 1, pack);
148 fwrite(&b, sizeof(b), 1, pack);
151 if (start != MAP_FAILED)
155 close_nointr_nofail(fd);
160 static unsigned long fd_first_block(int fd) {
162 struct fiemap fiemap;
163 struct fiemap_extent extent;
167 data.fiemap.fm_length = ~0ULL;
168 data.fiemap.fm_extent_count = 1;
170 if (ioctl(fd, FS_IOC_FIEMAP, &data) < 0)
173 if (data.fiemap.fm_mapped_extents <= 0)
176 if (data.fiemap.fm_extents[0].fe_flags & FIEMAP_EXTENT_UNKNOWN)
179 return (unsigned long) data.fiemap.fm_extents[0].fe_physical;
187 static int qsort_compare(const void *a, const void *b) {
188 const struct item *i, *j;
193 if (i->block < j->block)
195 if (i->block > j->block)
198 return strcmp(i->path, j->path);
201 static int collect(const char *root) {
203 FD_FANOTIFY, /* Get the actual fs events */
205 FD_INOTIFY, /* We get notifications to quit early via this fd */
208 struct pollfd pollfd[_FD_MAX];
209 int fanotify_fd = -1, signal_fd = -1, inotify_fd = -1, r = 0;
211 Hashmap *files = NULL;
216 char *pack_fn_new = NULL, *pack_fn = NULL;
217 bool on_ssd, on_btrfs;
223 write_one_line_file("/proc/self/oom_score_adj", "1000");
225 if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) < 0)
226 log_warning("Failed to set IDLE IO priority class: %m");
228 assert_se(sigemptyset(&mask) == 0);
229 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
230 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
232 if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
233 log_error("signalfd(): %m");
238 if (!(files = hashmap_new(string_hash_func, string_compare_func))) {
239 log_error("Failed to allocate set.");
244 if ((fanotify_fd = fanotify_init(FAN_CLOEXEC|FAN_NONBLOCK, O_RDONLY|O_LARGEFILE|O_CLOEXEC|O_NOATIME)) < 0) {
245 log_error("Failed to create fanotify object: %m");
250 if (fanotify_mark(fanotify_fd, FAN_MARK_ADD|FAN_MARK_MOUNT, FAN_OPEN, AT_FDCWD, root) < 0) {
251 log_error("Failed to mark %s: %m", root);
256 if ((inotify_fd = open_inotify()) < 0) {
261 not_after = now(CLOCK_MONOTONIC) + arg_timeout;
266 pollfd[FD_FANOTIFY].fd = fanotify_fd;
267 pollfd[FD_FANOTIFY].events = POLLIN;
268 pollfd[FD_SIGNAL].fd = signal_fd;
269 pollfd[FD_SIGNAL].events = POLLIN;
270 pollfd[FD_INOTIFY].fd = inotify_fd;
271 pollfd[FD_INOTIFY].events = POLLIN;
275 "STATUS=Collecting readahead data");
277 log_debug("Collecting...");
279 if (access("/dev/.systemd/readahead/cancel", F_OK) >= 0) {
280 log_debug("Collection canceled");
285 if (access("/dev/.systemd/readahead/done", F_OK) >= 0) {
286 log_debug("Got termination request");
292 struct fanotify_event_metadata metadata;
296 struct fanotify_event_metadata *m;
300 if (hashmap_size(files) > arg_files_max) {
301 log_debug("Reached maximum number of read ahead files, ending collection.");
305 t = now(CLOCK_MONOTONIC);
306 if (t >= not_after) {
307 log_debug("Reached maximum collection time, ending collection.");
311 if ((h = poll(pollfd, _FD_MAX, (int) ((not_after - t) / USEC_PER_MSEC))) < 0) {
316 log_error("poll(): %m");
322 log_debug("Reached maximum collection time, ending collection.");
326 if (pollfd[FD_SIGNAL].revents) {
327 log_debug("Got signal.");
331 if (pollfd[FD_INOTIFY].revents) {
332 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
333 struct inotify_event *e;
335 if ((n = read(inotify_fd, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
336 if (errno == EINTR || errno == EAGAIN)
339 log_error("Failed to read inotify event: %m");
344 e = (struct inotify_event*) inotify_buffer;
348 if ((e->mask & IN_CREATE) && streq(e->name, "cancel")) {
349 log_debug("Collection canceled");
354 if ((e->mask & IN_CREATE) && streq(e->name, "done")) {
355 log_debug("Got termination request");
359 step = sizeof(struct inotify_event) + e->len;
360 assert(step <= (size_t) n);
362 e = (struct inotify_event*) ((uint8_t*) e + step);
367 if ((n = read(fanotify_fd, &data, sizeof(data))) < 0) {
369 if (errno == EINTR || errno == EAGAIN)
372 log_error("Failed to read event: %m");
377 for (m = &data.metadata; FAN_EVENT_OK(m, n); m = FAN_EVENT_NEXT(m, n)) {
379 if (m->pid != my_pid && m->fd >= 0) {
383 snprintf(fn, sizeof(fn), "/proc/self/fd/%i", m->fd);
386 if ((k = readlink_malloc(fn, &p)) >= 0) {
388 if (startswith(p, "/tmp") ||
389 hashmap_get(files, p))
390 /* Not interesting, or
396 ul = fd_first_block(m->fd);
398 if ((k = hashmap_put(files, p, ULONG_TO_PTR(ul))) < 0) {
399 log_warning("set_put() failed: %s", strerror(-k));
405 log_warning("readlink(%s) failed: %s", fn, strerror(-k));
409 close_nointr_nofail(m->fd);
414 if (fanotify_fd >= 0) {
415 close_nointr_nofail(fanotify_fd);
419 log_debug("Writing Pack File...");
421 on_ssd = fs_on_ssd(root) == 0;
422 log_debug("On SSD: %s", yes_no(on_ssd));
424 on_btrfs = statfs(root, &sfs) >= 0 && sfs.f_type == BTRFS_SUPER_MAGIC;
425 log_debug("On btrfs: %s", yes_no(on_btrfs));
427 asprintf(&pack_fn, "%s/.readahead", root);
428 asprintf(&pack_fn_new, "%s/.readahead.new", root);
430 if (!pack_fn || !pack_fn_new) {
431 log_error("Out of memory");
436 if (!(pack = fopen(pack_fn_new, "we"))) {
437 log_error("Failed to open pack file: %m");
442 fputs(CANONICAL_HOST "\n", pack);
443 putc(on_ssd ? 'S' : 'R', pack);
445 if (on_ssd || on_btrfs) {
447 /* On SSD or on btrfs, just write things out in the
448 * order the files were accessed. */
450 HASHMAP_FOREACH_KEY(q, p, files, i)
451 pack_file(pack, p, on_btrfs);
453 struct item *ordered, *j;
456 /* On rotating media, order things by the block
459 log_debug("Ordering...");
461 n = hashmap_size(files);
462 if (!(ordered = new(struct item, n))) {
463 log_error("Out of memory");
469 HASHMAP_FOREACH_KEY(q, p, files, i) {
471 j->block = PTR_TO_ULONG(q);
475 assert(ordered + n == j);
477 qsort(ordered, n, sizeof(struct item), qsort_compare);
479 for (k = 0; k < n; k++)
480 pack_file(pack, ordered[k].path, on_btrfs);
485 log_debug("Finalizing...");
490 log_error("Failed to write pack file.");
495 if (rename(pack_fn_new, pack_fn) < 0) {
496 log_error("Failed to rename readahead file: %m");
507 if (fanotify_fd >= 0)
508 close_nointr_nofail(fanotify_fd);
511 close_nointr_nofail(signal_fd);
514 close_nointr_nofail(inotify_fd);
524 while ((p = hashmap_steal_first_key(files)))
532 static int help(void) {
534 printf("%s [OPTIONS...] [DIRECTORY]\n\n"
535 "Collect read-ahead data on early boot.\n\n"
536 " -h --help Show this help\n"
537 " --max-files=INT Maximum number of files to read ahead\n"
538 " --max-file-size=BYTES Maximum size of files to read ahead\n"
539 " --timeout=USEC Maximum time to spend collecting data\n",
540 program_invocation_short_name);
545 static int parse_argv(int argc, char *argv[]) {
548 ARG_FILES_MAX = 0x100,
553 static const struct option options[] = {
554 { "help", no_argument, NULL, 'h' },
555 { "files-max", required_argument, NULL, ARG_FILES_MAX },
556 { "file-size-max", required_argument, NULL, ARG_FILE_SIZE_MAX },
557 { "timeout", required_argument, NULL, ARG_TIMEOUT },
566 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
575 if (safe_atou(optarg, &arg_files_max) < 0 || arg_files_max <= 0) {
576 log_error("Failed to parse maximum number of files %s.", optarg);
581 case ARG_FILE_SIZE_MAX: {
582 unsigned long long ull;
584 if (safe_atollu(optarg, &ull) < 0 || ull <= 0) {
585 log_error("Failed to parse maximum file size %s.", optarg);
589 arg_file_size_max = (off_t) ull;
594 if (parse_usec(optarg, &arg_timeout) < 0 || arg_timeout <= 0) {
595 log_error("Failed to parse timeout %s.", optarg);
605 log_error("Unknown option code %c", c);
610 if (optind != argc &&
619 int main(int argc, char *argv[]) {
622 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
623 log_parse_environment();
626 if ((r = parse_argv(argc, argv)) <= 0)
627 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
630 log_info("Disabling readahead collector due to low memory.");
634 if (collect(optind < argc ? argv[optind] : "/") < 0)