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 /* Avoid collisions with the NULL pointer */
68 #define SECTOR_TO_PTR(s) ULONG_TO_PTR((s)+1)
69 #define PTR_TO_SECTOR(p) (PTR_TO_ULONG(p)-1)
71 static int btrfs_defrag(int fd) {
72 struct btrfs_ioctl_vol_args data;
77 return ioctl(fd, BTRFS_IOC_DEFRAG, &data);
80 static int pack_file(FILE *pack, const char *fn, bool on_btrfs) {
82 void *start = MAP_FAILED;
87 int r = 0, fd = -1, k;
92 if ((fd = open(fn, O_RDONLY|O_CLOEXEC|O_NOATIME|O_NOCTTY|O_NOFOLLOW)) < 0) {
93 log_warning("open(%s) failed: %m", fn);
98 if ((k = file_verify(fd, fn, arg_file_size_max, &st)) <= 0) {
106 l = PAGE_ALIGN(st.st_size);
107 if ((start = mmap(NULL, l, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
108 log_warning("mmap(%s) failed: %m", fn);
113 pages = l / PAGE_SIZE;
116 if (mincore(start, l, vec) < 0) {
117 log_warning("mincore(%s) failed: %m", fn);
126 for (c = 0; c < pages; c++) {
127 bool new_mapped = !!(vec[c] & 1);
129 if (!mapped && new_mapped)
131 else if (mapped && !new_mapped) {
132 fwrite(&b, sizeof(b), 1, pack);
133 fwrite(&c, sizeof(c), 1, pack);
135 log_debug("%s: page %u to %u", fn, b, c);
141 /* We don't write any range data if we should read the entire file */
142 if (mapped && b > 0) {
143 fwrite(&b, sizeof(b), 1, pack);
144 fwrite(&c, sizeof(c), 1, pack);
146 log_debug("%s: page %u to %u", fn, b, c);
151 fwrite(&b, sizeof(b), 1, pack);
152 fwrite(&b, sizeof(b), 1, pack);
155 if (start != MAP_FAILED)
159 close_nointr_nofail(fd);
164 static unsigned long fd_first_block(int fd) {
166 struct fiemap fiemap;
167 struct fiemap_extent extent;
171 data.fiemap.fm_length = ~0ULL;
172 data.fiemap.fm_extent_count = 1;
174 if (ioctl(fd, FS_IOC_FIEMAP, &data) < 0)
177 if (data.fiemap.fm_mapped_extents <= 0)
180 if (data.fiemap.fm_extents[0].fe_flags & FIEMAP_EXTENT_UNKNOWN)
183 return (unsigned long) data.fiemap.fm_extents[0].fe_physical;
191 static int qsort_compare(const void *a, const void *b) {
192 const struct item *i, *j;
197 if (i->block < j->block)
199 if (i->block > j->block)
202 return strcmp(i->path, j->path);
205 static int collect(const char *root) {
207 FD_FANOTIFY, /* Get the actual fs events */
209 FD_INOTIFY, /* We get notifications to quit early via this fd */
212 struct pollfd pollfd[_FD_MAX];
213 int fanotify_fd = -1, signal_fd = -1, inotify_fd = -1, r = 0;
215 Hashmap *files = NULL;
220 char *pack_fn_new = NULL, *pack_fn = NULL;
221 bool on_ssd, on_btrfs;
227 write_one_line_file("/proc/self/oom_score_adj", "1000");
229 if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) < 0)
230 log_warning("Failed to set IDLE IO priority class: %m");
232 assert_se(sigemptyset(&mask) == 0);
233 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
234 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
236 if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
237 log_error("signalfd(): %m");
242 if (!(files = hashmap_new(string_hash_func, string_compare_func))) {
243 log_error("Failed to allocate set.");
248 if ((fanotify_fd = fanotify_init(FAN_CLOEXEC|FAN_NONBLOCK, O_RDONLY|O_LARGEFILE|O_CLOEXEC|O_NOATIME)) < 0) {
249 log_error("Failed to create fanotify object: %m");
254 if (fanotify_mark(fanotify_fd, FAN_MARK_ADD|FAN_MARK_MOUNT, FAN_OPEN, AT_FDCWD, root) < 0) {
255 log_error("Failed to mark %s: %m", root);
260 if ((inotify_fd = open_inotify()) < 0) {
265 not_after = now(CLOCK_MONOTONIC) + arg_timeout;
270 pollfd[FD_FANOTIFY].fd = fanotify_fd;
271 pollfd[FD_FANOTIFY].events = POLLIN;
272 pollfd[FD_SIGNAL].fd = signal_fd;
273 pollfd[FD_SIGNAL].events = POLLIN;
274 pollfd[FD_INOTIFY].fd = inotify_fd;
275 pollfd[FD_INOTIFY].events = POLLIN;
279 "STATUS=Collecting readahead data");
281 log_debug("Collecting...");
283 if (access("/dev/.systemd/readahead/cancel", F_OK) >= 0) {
284 log_debug("Collection canceled");
289 if (access("/dev/.systemd/readahead/done", F_OK) >= 0) {
290 log_debug("Got termination request");
296 struct fanotify_event_metadata metadata;
300 struct fanotify_event_metadata *m;
304 if (hashmap_size(files) > arg_files_max) {
305 log_debug("Reached maximum number of read ahead files, ending collection.");
309 t = now(CLOCK_MONOTONIC);
310 if (t >= not_after) {
311 log_debug("Reached maximum collection time, ending collection.");
315 if ((h = poll(pollfd, _FD_MAX, (int) ((not_after - t) / USEC_PER_MSEC))) < 0) {
320 log_error("poll(): %m");
326 log_debug("Reached maximum collection time, ending collection.");
330 if (pollfd[FD_SIGNAL].revents) {
331 log_debug("Got signal.");
335 if (pollfd[FD_INOTIFY].revents) {
336 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
337 struct inotify_event *e;
339 if ((n = read(inotify_fd, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
340 if (errno == EINTR || errno == EAGAIN)
343 log_error("Failed to read inotify event: %m");
348 e = (struct inotify_event*) inotify_buffer;
352 if ((e->mask & IN_CREATE) && streq(e->name, "cancel")) {
353 log_debug("Collection canceled");
358 if ((e->mask & IN_CREATE) && streq(e->name, "done")) {
359 log_debug("Got termination request");
363 step = sizeof(struct inotify_event) + e->len;
364 assert(step <= (size_t) n);
366 e = (struct inotify_event*) ((uint8_t*) e + step);
371 if ((n = read(fanotify_fd, &data, sizeof(data))) < 0) {
373 if (errno == EINTR || errno == EAGAIN)
376 log_error("Failed to read event: %m");
381 for (m = &data.metadata; FAN_EVENT_OK(m, n); m = FAN_EVENT_NEXT(m, n)) {
383 if (m->pid != my_pid && m->fd >= 0) {
387 snprintf(fn, sizeof(fn), "/proc/self/fd/%i", m->fd);
390 if ((k = readlink_malloc(fn, &p)) >= 0) {
392 if (startswith(p, "/tmp") ||
393 hashmap_get(files, p))
394 /* Not interesting, or
400 ul = fd_first_block(m->fd);
402 if ((k = hashmap_put(files, p, SECTOR_TO_PTR(ul))) < 0) {
403 log_warning("set_put() failed: %s", strerror(-k));
409 log_warning("readlink(%s) failed: %s", fn, strerror(-k));
413 close_nointr_nofail(m->fd);
418 if (fanotify_fd >= 0) {
419 close_nointr_nofail(fanotify_fd);
423 log_debug("Writing Pack File...");
425 on_ssd = fs_on_ssd(root) == 0;
426 log_debug("On SSD: %s", yes_no(on_ssd));
428 on_btrfs = statfs(root, &sfs) >= 0 && sfs.f_type == BTRFS_SUPER_MAGIC;
429 log_debug("On btrfs: %s", yes_no(on_btrfs));
431 asprintf(&pack_fn, "%s/.readahead", root);
432 asprintf(&pack_fn_new, "%s/.readahead.new", root);
434 if (!pack_fn || !pack_fn_new) {
435 log_error("Out of memory");
440 if (!(pack = fopen(pack_fn_new, "we"))) {
441 log_error("Failed to open pack file: %m");
446 fputs(CANONICAL_HOST "\n", pack);
447 putc(on_ssd ? 'S' : 'R', pack);
449 if (on_ssd || on_btrfs) {
451 /* On SSD or on btrfs, just write things out in the
452 * order the files were accessed. */
454 HASHMAP_FOREACH_KEY(q, p, files, i)
455 pack_file(pack, p, on_btrfs);
457 struct item *ordered, *j;
460 /* On rotating media, order things by the block
463 log_debug("Ordering...");
465 n = hashmap_size(files);
466 if (!(ordered = new(struct item, n))) {
467 log_error("Out of memory");
473 HASHMAP_FOREACH_KEY(q, p, files, i) {
475 j->block = PTR_TO_SECTOR(q);
479 assert(ordered + n == j);
481 qsort(ordered, n, sizeof(struct item), qsort_compare);
483 for (k = 0; k < n; k++)
484 pack_file(pack, ordered[k].path, on_btrfs);
489 log_debug("Finalizing...");
494 log_error("Failed to write pack file.");
499 if (rename(pack_fn_new, pack_fn) < 0) {
500 log_error("Failed to rename readahead file: %m");
511 if (fanotify_fd >= 0)
512 close_nointr_nofail(fanotify_fd);
515 close_nointr_nofail(signal_fd);
518 close_nointr_nofail(inotify_fd);
528 while ((p = hashmap_steal_first_key(files)))
536 static int help(void) {
538 printf("%s [OPTIONS...] [DIRECTORY]\n\n"
539 "Collect read-ahead data on early boot.\n\n"
540 " -h --help Show this help\n"
541 " --max-files=INT Maximum number of files to read ahead\n"
542 " --max-file-size=BYTES Maximum size of files to read ahead\n"
543 " --timeout=USEC Maximum time to spend collecting data\n",
544 program_invocation_short_name);
549 static int parse_argv(int argc, char *argv[]) {
552 ARG_FILES_MAX = 0x100,
557 static const struct option options[] = {
558 { "help", no_argument, NULL, 'h' },
559 { "files-max", required_argument, NULL, ARG_FILES_MAX },
560 { "file-size-max", required_argument, NULL, ARG_FILE_SIZE_MAX },
561 { "timeout", required_argument, NULL, ARG_TIMEOUT },
570 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
579 if (safe_atou(optarg, &arg_files_max) < 0 || arg_files_max <= 0) {
580 log_error("Failed to parse maximum number of files %s.", optarg);
585 case ARG_FILE_SIZE_MAX: {
586 unsigned long long ull;
588 if (safe_atollu(optarg, &ull) < 0 || ull <= 0) {
589 log_error("Failed to parse maximum file size %s.", optarg);
593 arg_file_size_max = (off_t) ull;
598 if (parse_usec(optarg, &arg_timeout) < 0 || arg_timeout <= 0) {
599 log_error("Failed to parse timeout %s.", optarg);
609 log_error("Unknown option code %c", c);
614 if (optind != argc &&
623 int main(int argc, char *argv[]) {
626 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
627 log_parse_environment();
630 if ((r = parse_argv(argc, argv)) <= 0)
631 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
634 log_info("Disabling readahead collector due to low memory.");
638 if (collect(optind < argc ? argv[optind] : "/") < 0)