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>
48 #include "sd-daemon.h"
50 #include "readahead-common.h"
54 * - detect ssd on btrfs/lvm...
55 * - read ahead directories
56 * - sd_readahead_cancel
59 * - does ioprio_set work with fadvise()?
62 static unsigned arg_files_max = 16*1024;
63 static off_t arg_file_size_max = READAHEAD_FILE_SIZE_MAX;
64 static usec_t arg_timeout = 2*USEC_PER_MINUTE;
66 static int btrfs_defrag(int fd) {
67 struct btrfs_ioctl_vol_args data;
72 return ioctl(fd, BTRFS_IOC_DEFRAG, &data);
75 static int pack_file(FILE *pack, const char *fn, bool on_btrfs) {
77 void *start = MAP_FAILED;
82 int r = 0, fd = -1, k;
87 if ((fd = open(fn, O_RDONLY|O_CLOEXEC|O_NOATIME|O_NOCTTY|O_NOFOLLOW)) < 0) {
88 log_warning("open(%s) failed: %m", fn);
93 if ((k = file_verify(fd, fn, arg_file_size_max, &st)) <= 0) {
101 l = PAGE_ALIGN(st.st_size);
102 if ((start = mmap(NULL, l, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
103 log_warning("mmap(%s) failed: %m", fn);
108 pages = l / PAGE_SIZE;
111 if (mincore(start, l, vec) < 0) {
112 log_warning("mincore(%s) failed: %m", fn);
121 for (c = 0; c < pages; c++) {
122 bool new_mapped = !!(vec[c] & 1);
124 if (!mapped && new_mapped)
126 else if (mapped && !new_mapped) {
127 fwrite(&b, sizeof(b), 1, pack);
128 fwrite(&c, sizeof(c), 1, pack);
130 log_debug("%s: page %u to %u", fn, b, c);
136 /* We don't write any range data if we should read the entire file */
137 if (mapped && b > 0) {
138 fwrite(&b, sizeof(b), 1, pack);
139 fwrite(&c, sizeof(c), 1, pack);
141 log_debug("%s: page %u to %u", fn, b, c);
146 fwrite(&b, sizeof(b), 1, pack);
147 fwrite(&b, sizeof(b), 1, pack);
150 if (start != MAP_FAILED)
154 close_nointr_nofail(fd);
159 static unsigned long fd_first_block(int fd) {
161 struct fiemap fiemap;
162 struct fiemap_extent extent;
166 data.fiemap.fm_length = ~0ULL;
167 data.fiemap.fm_extent_count = 1;
169 if (ioctl(fd, FS_IOC_FIEMAP, &data) < 0)
172 if (data.fiemap.fm_mapped_extents <= 0)
175 if (data.fiemap.fm_extents[0].fe_flags & FIEMAP_EXTENT_UNKNOWN)
178 return (unsigned long) data.fiemap.fm_extents[0].fe_physical;
186 static int qsort_compare(const void *a, const void *b) {
187 const struct item *i, *j;
192 if (i->block < j->block)
194 if (i->block > j->block)
197 return strcmp(i->path, j->path);
200 static int collect(const char *root) {
206 struct pollfd pollfd[_FD_MAX];
207 int fanotify_fd = -1, signal_fd = -1, r = 0;
209 Hashmap *files = NULL;
214 char *pack_fn_new = NULL, *pack_fn = NULL;
215 bool on_ssd, on_btrfs;
221 write_one_line_file("/proc/self/oom_score_adj", "1000");
223 if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) < 0)
224 log_warning("Failed to set IDLE IO priority class: %m");
226 assert_se(sigemptyset(&mask) == 0);
227 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
228 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
230 if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
231 log_error("signalfd(): %m");
236 if (!(files = hashmap_new(string_hash_func, string_compare_func))) {
237 log_error("Failed to allocate set.");
242 if ((fanotify_fd = fanotify_init(FAN_CLOEXEC|FAN_NONBLOCK, O_RDONLY|O_LARGEFILE|O_CLOEXEC|O_NOATIME)) < 0) {
243 log_error("Failed to create fanotify object: %m");
248 if (fanotify_mark(fanotify_fd, FAN_MARK_ADD|FAN_MARK_MOUNT, FAN_OPEN, AT_FDCWD, root) < 0) {
249 log_error("Failed to mark %s: %m", root);
254 not_after = now(CLOCK_MONOTONIC) + arg_timeout;
259 pollfd[FD_FANOTIFY].fd = fanotify_fd;
260 pollfd[FD_FANOTIFY].events = POLLIN;
261 pollfd[FD_SIGNAL].fd = signal_fd;
262 pollfd[FD_SIGNAL].events = POLLIN;
266 "STATUS=Collecting readahead data");
268 log_debug("Collecting...");
272 struct fanotify_event_metadata metadata;
276 struct fanotify_event_metadata *m;
280 if (hashmap_size(files) > arg_files_max) {
281 log_debug("Reached maximum number of read ahead files, ending collection.");
285 t = now(CLOCK_MONOTONIC);
286 if (t >= not_after) {
287 log_debug("Reached maximum collection time, ending collection.");
291 if ((h = poll(pollfd, _FD_MAX, (int) ((not_after - t) / USEC_PER_MSEC))) < 0) {
296 log_error("poll(): %m");
301 if (pollfd[FD_SIGNAL].revents != 0)
305 log_debug("Reached maximum collection time, ending collection.");
309 if ((n = read(fanotify_fd, &data, sizeof(data))) < 0) {
311 if (errno == EINTR || errno == EAGAIN)
314 log_error("Failed to read event: %m");
319 for (m = &data.metadata; FAN_EVENT_OK(m, n); m = FAN_EVENT_NEXT(m, n)) {
321 if (m->pid != my_pid && m->fd >= 0) {
325 snprintf(fn, sizeof(fn), "/proc/self/fd/%i", m->fd);
328 if ((k = readlink_malloc(fn, &p)) >= 0) {
330 if (startswith(p, "/tmp") ||
331 hashmap_get(files, p))
332 /* Not interesting, or
338 ul = fd_first_block(m->fd);
340 if ((k = hashmap_put(files, p, ULONG_TO_PTR(ul))) < 0) {
341 log_warning("set_put() failed: %s", strerror(-k));
347 log_warning("readlink(%s) failed: %s", fn, strerror(-k));
351 close_nointr_nofail(m->fd);
355 if (fanotify_fd >= 0) {
356 close_nointr_nofail(fanotify_fd);
360 log_debug("Writing Pack File...");
362 on_ssd = fs_on_ssd(root);
363 log_debug("On SSD: %s", yes_no(on_ssd));
365 on_btrfs = statfs(root, &sfs) >= 0 && sfs.f_type == BTRFS_SUPER_MAGIC;
366 log_debug("On btrfs: %s", yes_no(on_btrfs));
368 asprintf(&pack_fn, "%s/.readahead", root);
369 asprintf(&pack_fn_new, "%s/.readahead.new", root);
371 if (!pack_fn || !pack_fn_new) {
372 log_error("Out of memory");
377 if (!(pack = fopen(pack_fn_new, "we"))) {
378 log_error("Failed to open pack file: %m");
383 fputs(CANONICAL_HOST "\n", pack);
384 putc(on_ssd ? 'S' : 'R', pack);
386 if (on_ssd || on_btrfs) {
388 /* On SSD or on btrfs, just write things out in the
389 * order the files were accessed. */
391 HASHMAP_FOREACH_KEY(q, p, files, i)
392 pack_file(pack, p, on_btrfs);
394 struct item *ordered, *j;
397 /* On rotating media, order things by the block
400 log_debug("Ordering...");
402 n = hashmap_size(files);
403 if (!(ordered = new(struct item, n))) {
404 log_error("Out of memory");
410 HASHMAP_FOREACH_KEY(q, p, files, i) {
412 j->block = PTR_TO_ULONG(q);
416 assert(ordered + n == j);
418 qsort(ordered, n, sizeof(struct item), qsort_compare);
420 for (k = 0; k < n; k++)
421 pack_file(pack, ordered[k].path, on_btrfs);
426 log_debug("Finalizing...");
431 log_error("Failed to write pack file.");
436 if (rename(pack_fn_new, pack_fn) < 0) {
437 log_error("Failed to rename readahead file: %m");
448 if (fanotify_fd >= 0)
449 close_nointr_nofail(fanotify_fd);
452 close_nointr_nofail(signal_fd);
462 while ((p = hashmap_steal_first_key(files)))
470 static int help(void) {
472 printf("%s [OPTIONS...] [DIRECTORY]\n\n"
473 "Collect read-ahead data on early boot.\n\n"
474 " -h --help Show this help\n"
475 " --max-files=INT Maximum number of files to read ahead\n"
476 " --max-file-size=BYTES Maximum size of files to read ahead\n"
477 " --timeout=USEC Maximum time to spend collecting data\n",
478 program_invocation_short_name);
483 static int parse_argv(int argc, char *argv[]) {
486 ARG_FILES_MAX = 0x100,
491 static const struct option options[] = {
492 { "help", no_argument, NULL, 'h' },
493 { "files-max", required_argument, NULL, ARG_FILES_MAX },
494 { "file-size-max", required_argument, NULL, ARG_FILE_SIZE_MAX },
495 { "timeout", required_argument, NULL, ARG_TIMEOUT },
504 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
513 if (safe_atou(optarg, &arg_files_max) < 0 || arg_files_max <= 0) {
514 log_error("Failed to parse maximum number of files %s.", optarg);
519 case ARG_FILE_SIZE_MAX: {
520 unsigned long long ull;
522 if (safe_atollu(optarg, &ull) < 0 || ull <= 0) {
523 log_error("Failed to parse maximum file size %s.", optarg);
527 arg_file_size_max = (off_t) ull;
532 if (parse_usec(optarg, &arg_timeout) < 0 || arg_timeout <= 0) {
533 log_error("Failed to parse timeout %s.", optarg);
543 log_error("Unknown option code %c", c);
548 if (optind != argc &&
557 int main(int argc, char *argv[]) {
560 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
561 log_parse_environment();
564 if ((r = parse_argv(argc, argv)) <= 0)
565 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
568 log_info("Disabling readahead collector due to low memory.");
572 if (collect(optind < argc ? argv[optind] : "/") < 0)