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>
47 #include "sd-daemon.h"
49 #include "readahead-common.h"
51 #define MINCORE_VEC_SIZE (READAHEAD_FILE_SIZE_MAX/PAGE_SIZE)
52 #define TIMEOUT_USEC (2*USEC_PER_MINUTE)
56 * - detect ssd on btrfs/lvm...
57 * - read ahead directories
58 * - sd_readahead_cancel
61 * - are filenames from anotify normalized regards /../ and // and /./?
62 * - does ioprio_set work with fadvise()?
65 static int btrfs_defrag(int fd) {
66 struct btrfs_ioctl_vol_args data;
71 return ioctl(fd, BTRFS_IOC_DEFRAG, &data);
74 static int pack_file(FILE *pack, const char *fn, bool on_btrfs) {
76 void *start = MAP_FAILED;
77 uint8_t vec[MINCORE_VEC_SIZE];
81 int r = 0, fd = -1, k;
86 if ((fd = open(fn, O_RDONLY|O_CLOEXEC|O_NOATIME|O_NOCTTY|O_NOFOLLOW)) < 0) {
87 log_warning("open(%s) failed: %m", fn);
92 if ((k = file_verify(fd, fn, &st)) <= 0) {
100 l = PAGE_ALIGN(st.st_size);
101 if ((start = mmap(NULL, l, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
102 log_warning("mmap(%s) failed: %m", fn);
107 if (mincore(start, l, vec) < 0) {
108 log_warning("mincore(%s) failed: %m", fn);
116 pages = l / PAGE_SIZE;
118 for (c = 0; c < pages; c++) {
119 bool new_mapped = !!(vec[c] & 1);
121 if (!mapped && new_mapped)
123 else if (mapped && !new_mapped) {
124 fwrite(&b, sizeof(b), 1, pack);
125 fwrite(&c, sizeof(c), 1, pack);
127 log_debug("%s: page %u to %u", fn, b, c);
133 /* We don't write any range data if we should read the entire file */
134 if (mapped && b > 0) {
135 fwrite(&b, sizeof(b), 1, pack);
136 fwrite(&c, sizeof(c), 1, pack);
138 log_debug("%s: page %u to %u", fn, b, c);
143 fwrite(&b, sizeof(b), 1, pack);
144 fwrite(&b, sizeof(b), 1, pack);
147 if (start != MAP_FAILED)
151 close_nointr_nofail(fd);
156 static unsigned long fd_first_block(int fd) {
158 struct fiemap fiemap;
159 struct fiemap_extent extent;
163 data.fiemap.fm_length = ~0ULL;
164 data.fiemap.fm_extent_count = 1;
166 if (ioctl(fd, FS_IOC_FIEMAP, &data) < 0)
169 if (data.fiemap.fm_mapped_extents <= 0)
172 if (data.fiemap.fm_extents[0].fe_flags & FIEMAP_EXTENT_UNKNOWN)
175 return (unsigned long) data.fiemap.fm_extents[0].fe_physical;
183 static int qsort_compare(const void *a, const void *b) {
184 const struct item *i, *j;
189 if (i->block < j->block)
191 if (i->block > j->block)
194 return strcmp(i->path, j->path);
197 static int collect(const char *root) {
203 struct pollfd pollfd[_FD_MAX];
204 int fanotify_fd = -1, signal_fd = -1, r = 0;
206 Hashmap *files = NULL;
211 char *pack_fn_new = NULL, *pack_fn = NULL;
212 bool on_ssd, on_btrfs;
218 write_one_line_file("/proc/self/oom_score_adj", "1000");
220 if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) < 0)
221 log_warning("Failed to set IDLE IO priority class: %m");
223 assert_se(sigemptyset(&mask) == 0);
224 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
225 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
227 if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
228 log_error("signalfd(): %m");
233 if (!(files = hashmap_new(string_hash_func, string_compare_func))) {
234 log_error("Failed to allocate set.");
239 if ((fanotify_fd = fanotify_init(FAN_CLOEXEC|FAN_NONBLOCK, O_RDONLY|O_LARGEFILE|O_CLOEXEC|O_NOATIME)) < 0) {
240 log_error("Failed to create fanotify object: %m");
245 if (fanotify_mark(fanotify_fd, FAN_MARK_ADD|FAN_MARK_MOUNT, FAN_OPEN, AT_FDCWD, root) < 0) {
246 log_error("Failed to mark %s: %m", root);
251 not_after = now(CLOCK_MONOTONIC) + TIMEOUT_USEC;
256 pollfd[FD_FANOTIFY].fd = fanotify_fd;
257 pollfd[FD_FANOTIFY].events = POLLIN;
258 pollfd[FD_SIGNAL].fd = signal_fd;
259 pollfd[FD_SIGNAL].events = POLLIN;
263 "STATUS=Collecting readahead data");
265 log_debug("Collecting...");
269 struct fanotify_event_metadata metadata;
273 struct fanotify_event_metadata *m;
277 if (hashmap_size(files) > READAHEAD_FILES_MAX) {
278 log_debug("Reached maximum number of read ahead files, ending collection.");
282 t = now(CLOCK_MONOTONIC);
283 if (t >= not_after) {
284 log_debug("Reached maximum collection time, ending collection.");
288 if ((h = poll(pollfd, _FD_MAX, (int) ((not_after - t) / USEC_PER_MSEC))) < 0) {
293 log_error("poll(): %m");
298 if (pollfd[FD_SIGNAL].revents != 0)
302 log_debug("Reached maximum collection time, ending collection.");
306 if ((n = read(fanotify_fd, &data, sizeof(data))) < 0) {
308 if (errno == EINTR || errno == EAGAIN)
311 log_error("Failed to read event: %m");
316 for (m = &data.metadata; FAN_EVENT_OK(m, n); m = FAN_EVENT_NEXT(m, n)) {
318 if (m->pid != my_pid && m->fd >= 0) {
322 snprintf(fn, sizeof(fn), "/proc/self/fd/%i", m->fd);
325 if ((k = readlink_malloc(fn, &p)) >= 0) {
327 if (startswith(p, "/tmp") ||
328 hashmap_get(files, p))
329 /* Not interesting, or
335 ul = fd_first_block(m->fd);
337 if ((k = hashmap_put(files, p, ULONG_TO_PTR(ul))) < 0) {
338 log_warning("set_put() failed: %s", strerror(-k));
344 log_warning("readlink(%s) failed: %s", fn, strerror(-k));
348 close_nointr_nofail(m->fd);
352 if (fanotify_fd >= 0) {
353 close_nointr_nofail(fanotify_fd);
357 log_debug("Writing Pack File...");
359 on_ssd = fs_on_ssd(root);
360 log_debug("On SSD: %s", yes_no(on_ssd));
362 on_btrfs = statfs(root, &sfs) >= 0 && sfs.f_type == BTRFS_SUPER_MAGIC;
363 log_debug("On btrfs: %s", yes_no(on_btrfs));
365 asprintf(&pack_fn, "%s/.readahead", root);
366 asprintf(&pack_fn_new, "%s/.readahead.new", root);
368 if (!pack_fn || !pack_fn_new) {
369 log_error("Out of memory");
374 if (!(pack = fopen(pack_fn_new, "we"))) {
375 log_error("Failed to open pack file: %m");
380 fputs(CANONICAL_HOST "\n", pack);
381 putc(on_ssd ? 'S' : 'R', pack);
383 if (on_ssd || on_btrfs) {
385 /* On SSD or on btrfs, just write things out in the
386 * order the files were accessed. */
388 HASHMAP_FOREACH_KEY(q, p, files, i)
389 pack_file(pack, p, on_btrfs);
391 struct item *ordered, *j;
394 /* On rotating media, order things by the block
397 log_debug("Ordering...");
399 n = hashmap_size(files);
400 if (!(ordered = new(struct item, n))) {
401 log_error("Out of memory");
407 HASHMAP_FOREACH_KEY(q, p, files, i) {
409 j->block = PTR_TO_ULONG(q);
413 assert(ordered + n == j);
415 qsort(ordered, n, sizeof(struct item), qsort_compare);
417 for (k = 0; k < n; k++)
418 pack_file(pack, ordered[k].path, on_btrfs);
423 log_debug("Finalizing...");
428 log_error("Failed to write pack file.");
433 if (rename(pack_fn_new, pack_fn) < 0) {
434 log_error("Failed to rename readahead file: %m");
445 if (fanotify_fd >= 0)
446 close_nointr_nofail(fanotify_fd);
449 close_nointr_nofail(signal_fd);
459 while ((p = hashmap_steal_first_key(files)))
467 int main(int argc, char *argv[]) {
469 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
470 log_parse_environment();
474 log_info("Disabling readahead collector due to low memory.");
478 if (collect(argc >= 2 ? argv[1] : "/") < 0)