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
62 * - are filenames from anotify normalized regards /../ and // and /./?
63 * - does ioprio_set work with fadvise()?
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;
78 uint8_t vec[MINCORE_VEC_SIZE];
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, &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 if (mincore(start, l, vec) < 0) {
109 log_warning("mincore(%s) failed: %m", fn);
117 pages = l / PAGE_SIZE;
119 for (c = 0; c < pages; c++) {
120 bool new_mapped = !!(vec[c] & 1);
122 if (!mapped && new_mapped)
124 else if (mapped && !new_mapped) {
125 fwrite(&b, sizeof(b), 1, pack);
126 fwrite(&c, sizeof(c), 1, pack);
128 log_debug("%s: page %u to %u", fn, b, c);
134 /* We don't write any range data if we should read the entire file */
135 if (mapped && b > 0) {
136 fwrite(&b, sizeof(b), 1, pack);
137 fwrite(&c, sizeof(c), 1, pack);
139 log_debug("%s: page %u to %u", fn, b, c);
144 fwrite(&b, sizeof(b), 1, pack);
145 fwrite(&b, sizeof(b), 1, pack);
148 if (start != MAP_FAILED)
152 close_nointr_nofail(fd);
157 static unsigned long fd_first_block(int fd) {
159 struct fiemap fiemap;
160 struct fiemap_extent extent;
164 data.fiemap.fm_length = ~0ULL;
165 data.fiemap.fm_extent_count = 1;
167 if (ioctl(fd, FS_IOC_FIEMAP, &data) < 0)
170 if (data.fiemap.fm_mapped_extents <= 0)
173 if (data.fiemap.fm_extents[0].fe_flags & FIEMAP_EXTENT_UNKNOWN)
176 return (unsigned long) data.fiemap.fm_extents[0].fe_physical;
184 static int qsort_compare(const void *a, const void *b) {
185 const struct item *i, *j;
190 if (i->block < j->block)
192 if (i->block > j->block)
195 return strcmp(i->path, j->path);
198 static int collect(const char *root) {
204 struct pollfd pollfd[_FD_MAX];
205 int fanotify_fd = -1, signal_fd = -1, r = 0;
207 Hashmap *files = NULL;
212 char *pack_fn_new = NULL, *pack_fn = NULL;
213 bool on_ssd, on_btrfs;
219 if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) < 0)
220 log_warning("Failed to set IDLE IO priority class: %m");
222 assert_se(sigemptyset(&mask) == 0);
223 sigset_add_many(&mask, SIGINT, SIGTERM, -1);
224 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
226 if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
227 log_error("signalfd(): %m");
232 if (!(files = hashmap_new(string_hash_func, string_compare_func))) {
233 log_error("Failed to allocate set.");
238 if ((fanotify_fd = fanotify_init(FAN_CLOEXEC|FAN_NONBLOCK, O_RDONLY|O_LARGEFILE|O_CLOEXEC|O_NOATIME)) < 0) {
239 log_error("Failed to create fanotify object: %m");
244 if (fanotify_mark(fanotify_fd, FAN_MARK_ADD|FAN_MARK_MOUNT, FAN_OPEN, AT_FDCWD, root) < 0) {
245 log_error("Failed to mark %s: %m", root);
250 not_after = now(CLOCK_MONOTONIC) + TIMEOUT_USEC;
255 pollfd[FD_FANOTIFY].fd = fanotify_fd;
256 pollfd[FD_FANOTIFY].events = POLLIN;
257 pollfd[FD_SIGNAL].fd = signal_fd;
258 pollfd[FD_SIGNAL].events = POLLIN;
262 "STATUS=Collecting readahead data");
264 log_debug("Collecting...");
268 struct fanotify_event_metadata metadata;
272 struct fanotify_event_metadata *m;
276 if (hashmap_size(files) > READAHEAD_FILES_MAX) {
277 log_debug("Reached maximum number of read ahead files, ending collection.");
281 t = now(CLOCK_MONOTONIC);
282 if (t >= not_after) {
283 log_debug("Reached maximum collection time, ending collection.");
287 if ((h = poll(pollfd, _FD_MAX, (int) ((not_after - t) / USEC_PER_MSEC))) < 0) {
292 log_error("poll(): %m");
297 if (pollfd[FD_SIGNAL].revents != 0)
301 log_debug("Reached maximum collection time, ending collection.");
305 if ((n = read(fanotify_fd, &data, sizeof(data))) < 0) {
307 if (errno == EINTR || errno == EAGAIN)
310 log_error("Failed to read event: %m");
315 for (m = &data.metadata; FAN_EVENT_OK(m, n); m = FAN_EVENT_NEXT(m, n)) {
317 if (m->pid != my_pid && m->fd >= 0) {
321 snprintf(fn, sizeof(fn), "/proc/self/fd/%i", m->fd);
324 if ((k = readlink_malloc(fn, &p)) >= 0) {
326 if (hashmap_get(files, p))
332 ul = fd_first_block(m->fd);
334 if ((k = hashmap_put(files, p, ULONG_TO_PTR(ul))) < 0) {
335 log_warning("set_put() failed: %s", strerror(-k));
341 log_warning("readlink(%s) failed: %s", fn, strerror(-k));
345 close_nointr_nofail(m->fd);
349 if (fanotify_fd >= 0) {
350 close_nointr_nofail(fanotify_fd);
354 log_debug("Writing Pack File...");
356 on_ssd = fs_on_ssd(root);
357 log_debug("On SSD: %s", yes_no(on_ssd));
359 on_btrfs = statfs(root, &sfs) >= 0 && sfs.f_type == BTRFS_SUPER_MAGIC;
360 log_debug("On btrfs: %s", yes_no(on_btrfs));
362 asprintf(&pack_fn, "%s/.readahead", root);
363 asprintf(&pack_fn_new, "%s/.readahead.new", root);
365 if (!pack_fn || !pack_fn_new) {
366 log_error("Out of memory");
371 if (!(pack = fopen(pack_fn_new, "we"))) {
372 log_error("Failed to open pack file: %m");
377 fputs(CANONICAL_HOST "\n", pack);
378 putc(on_ssd ? 'S' : 'R', pack);
380 if (on_ssd || on_btrfs) {
382 /* On SSD or on btrfs, just write things out in the
383 * order the files were accessed. */
385 HASHMAP_FOREACH_KEY(q, p, files, i)
386 pack_file(pack, p, on_btrfs);
388 struct item *ordered, *j;
391 /* On rotating media, order things by the block
394 log_debug("Ordering...");
396 n = hashmap_size(files);
397 if (!(ordered = new(struct item, n))) {
398 log_error("Out of memory");
404 HASHMAP_FOREACH_KEY(q, p, files, i) {
406 j->block = PTR_TO_ULONG(q);
410 assert(ordered + n == j);
412 qsort(ordered, n, sizeof(struct item), qsort_compare);
414 for (k = 0; k < n; k++)
415 pack_file(pack, ordered[k].path, on_btrfs);
420 log_debug("Finalizing...");
425 log_error("Failed to write pack file.");
430 if (rename(pack_fn_new, pack_fn) < 0) {
431 log_error("Failed to rename readahead file: %m");
442 if (fanotify_fd >= 0)
443 close_nointr_nofail(fanotify_fd);
446 close_nointr_nofail(signal_fd);
456 while ((p = hashmap_steal_first_key(files)))
464 int main(int argc, char *argv[]) {
466 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
467 log_parse_environment();
471 log_info("Disabling readahead collector due to low memory.");
475 if (collect(argc >= 2 ? argv[1] : "/") < 0)