chiark / gitweb /
readahead: disable readahead in virtual machines
[elogind.git] / src / readahead-collect.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
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.
12
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.
17
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/>.
20 ***/
21
22 #include <errno.h>
23 #include <inttypes.h>
24 #include <fcntl.h>
25 #include <linux/limits.h>
26 #include <stdbool.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/select.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <unistd.h>
35 #include <linux/fanotify.h>
36 #include <sys/signalfd.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <linux/fs.h>
40 #include <linux/fiemap.h>
41 #include <sys/ioctl.h>
42 #include <sys/vfs.h>
43 #include <getopt.h>
44 #include <sys/inotify.h>
45
46 #include "missing.h"
47 #include "util.h"
48 #include "set.h"
49 #include "sd-daemon.h"
50 #include "ioprio.h"
51 #include "readahead-common.h"
52
53 /* fixme:
54  *
55  * - detect ssd on btrfs/lvm...
56  * - read ahead directories
57  * - gzip?
58  * - remount rw?
59  * - handle files where nothing is in mincore
60  * - does ioprio_set work with fadvise()?
61  */
62
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;
66
67 static ReadaheadShared *shared = NULL;
68
69 /* Avoid collisions with the NULL pointer */
70 #define SECTOR_TO_PTR(s) ULONG_TO_PTR((s)+1)
71 #define PTR_TO_SECTOR(p) (PTR_TO_ULONG(p)-1)
72
73 static int btrfs_defrag(int fd) {
74         struct btrfs_ioctl_vol_args data;
75
76         zero(data);
77         data.fd = fd;
78
79         return ioctl(fd, BTRFS_IOC_DEFRAG, &data);
80 }
81
82 static int pack_file(FILE *pack, const char *fn, bool on_btrfs) {
83         struct stat st;
84         void *start = MAP_FAILED;
85         uint8_t *vec;
86         uint32_t b, c;
87         size_t l, pages;
88         bool mapped;
89         int r = 0, fd = -1, k;
90
91         assert(pack);
92         assert(fn);
93
94         if ((fd = open(fn, O_RDONLY|O_CLOEXEC|O_NOATIME|O_NOCTTY|O_NOFOLLOW)) < 0) {
95
96                 if (errno == ENOENT)
97                         return 0;
98
99                 log_warning("open(%s) failed: %m", fn);
100                 r = -errno;
101                 goto finish;
102         }
103
104         if ((k = file_verify(fd, fn, arg_file_size_max, &st)) <= 0) {
105                 r = k;
106                 goto finish;
107         }
108
109         if (on_btrfs)
110                 btrfs_defrag(fd);
111
112         l = PAGE_ALIGN(st.st_size);
113         if ((start = mmap(NULL, l, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
114                 log_warning("mmap(%s) failed: %m", fn);
115                 r = -errno;
116                 goto finish;
117         }
118
119         pages = l / PAGE_SIZE;
120
121         vec = alloca(pages);
122         if (mincore(start, l, vec) < 0) {
123                 log_warning("mincore(%s) failed: %m", fn);
124                 r = -errno;
125                 goto finish;
126         }
127
128         fputs(fn, pack);
129         fputc('\n', pack);
130
131         mapped = false;
132         for (c = 0; c < pages; c++) {
133                 bool new_mapped = !!(vec[c] & 1);
134
135                 if (!mapped && new_mapped)
136                         b = c;
137                 else if (mapped && !new_mapped) {
138                         fwrite(&b, sizeof(b), 1, pack);
139                         fwrite(&c, sizeof(c), 1, pack);
140
141                         log_debug("%s: page %u to %u", fn, b, c);
142                 }
143
144                 mapped = new_mapped;
145         }
146
147         /* We don't write any range data if we should read the entire file */
148         if (mapped && b > 0) {
149                 fwrite(&b, sizeof(b), 1, pack);
150                 fwrite(&c, sizeof(c), 1, pack);
151
152                 log_debug("%s: page %u to %u", fn, b, c);
153         }
154
155         /* End marker */
156         b = 0;
157         fwrite(&b, sizeof(b), 1, pack);
158         fwrite(&b, sizeof(b), 1, pack);
159
160 finish:
161         if (start != MAP_FAILED)
162                 munmap(start, l);
163
164         if (fd >= 0)
165                 close_nointr_nofail(fd);
166
167         return r;
168 }
169
170 static unsigned long fd_first_block(int fd) {
171         struct {
172                 struct fiemap fiemap;
173                 struct fiemap_extent extent;
174         } data;
175
176         zero(data);
177         data.fiemap.fm_length = ~0ULL;
178         data.fiemap.fm_extent_count = 1;
179
180         if (ioctl(fd, FS_IOC_FIEMAP, &data) < 0)
181                 return 0;
182
183         if (data.fiemap.fm_mapped_extents <= 0)
184                 return 0;
185
186         if (data.fiemap.fm_extents[0].fe_flags & FIEMAP_EXTENT_UNKNOWN)
187                 return 0;
188
189         return (unsigned long) data.fiemap.fm_extents[0].fe_physical;
190 }
191
192 struct item {
193         const char *path;
194         unsigned long block;
195 };
196
197 static int qsort_compare(const void *a, const void *b) {
198         const struct item *i, *j;
199
200         i = a;
201         j = b;
202
203         if (i->block < j->block)
204                 return -1;
205         if (i->block > j->block)
206                 return 1;
207
208         return strcmp(i->path, j->path);
209 }
210
211 static int collect(const char *root) {
212         enum {
213                 FD_FANOTIFY,  /* Get the actual fs events */
214                 FD_SIGNAL,
215                 FD_INOTIFY,   /* We get notifications to quit early via this fd */
216                 _FD_MAX
217         };
218         struct pollfd pollfd[_FD_MAX];
219         int fanotify_fd = -1, signal_fd = -1, inotify_fd = -1, r = 0;
220         pid_t my_pid;
221         Hashmap *files = NULL;
222         Iterator i;
223         char *p, *q;
224         sigset_t mask;
225         FILE *pack = NULL;
226         char *pack_fn_new = NULL, *pack_fn = NULL;
227         bool on_ssd, on_btrfs;
228         struct statfs sfs;
229         usec_t not_after;
230
231         assert(root);
232
233         write_one_line_file("/proc/self/oom_score_adj", "1000");
234
235         if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) < 0)
236                 log_warning("Failed to set IDLE IO priority class: %m");
237
238         assert_se(sigemptyset(&mask) == 0);
239         sigset_add_many(&mask, SIGINT, SIGTERM, -1);
240         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
241
242         if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
243                 log_error("signalfd(): %m");
244                 r = -errno;
245                 goto finish;
246         }
247
248         if (!(files = hashmap_new(string_hash_func, string_compare_func))) {
249                 log_error("Failed to allocate set.");
250                 r = -ENOMEM;
251                 goto finish;
252         }
253
254         if ((fanotify_fd = fanotify_init(FAN_CLOEXEC|FAN_NONBLOCK, O_RDONLY|O_LARGEFILE|O_CLOEXEC|O_NOATIME)) < 0)  {
255                 log_error("Failed to create fanotify object: %m");
256                 r = -errno;
257                 goto finish;
258         }
259
260         if (fanotify_mark(fanotify_fd, FAN_MARK_ADD|FAN_MARK_MOUNT, FAN_OPEN, AT_FDCWD, root) < 0) {
261                 log_error("Failed to mark %s: %m", root);
262                 r = -errno;
263                 goto finish;
264         }
265
266         if ((inotify_fd = open_inotify()) < 0) {
267                 r = inotify_fd;
268                 goto finish;
269         }
270
271         not_after = now(CLOCK_MONOTONIC) + arg_timeout;
272
273         my_pid = getpid();
274
275         zero(pollfd);
276         pollfd[FD_FANOTIFY].fd = fanotify_fd;
277         pollfd[FD_FANOTIFY].events = POLLIN;
278         pollfd[FD_SIGNAL].fd = signal_fd;
279         pollfd[FD_SIGNAL].events = POLLIN;
280         pollfd[FD_INOTIFY].fd = inotify_fd;
281         pollfd[FD_INOTIFY].events = POLLIN;
282
283         sd_notify(0,
284                   "READY=1\n"
285                   "STATUS=Collecting readahead data");
286
287         log_debug("Collecting...");
288
289         if (access("/dev/.systemd/readahead/cancel", F_OK) >= 0) {
290                 log_debug("Collection canceled");
291                 r = -ECANCELED;
292                 goto finish;
293         }
294
295         if (access("/dev/.systemd/readahead/done", F_OK) >= 0) {
296                 log_debug("Got termination request");
297                 goto done;
298         }
299
300         for (;;) {
301                 union {
302                         struct fanotify_event_metadata metadata;
303                         char buffer[4096];
304                 } data;
305                 ssize_t n;
306                 struct fanotify_event_metadata *m;
307                 usec_t t;
308                 int h;
309
310                 if (hashmap_size(files) > arg_files_max) {
311                         log_debug("Reached maximum number of read ahead files, ending collection.");
312                         break;
313                 }
314
315                 t = now(CLOCK_MONOTONIC);
316                 if (t >= not_after) {
317                         log_debug("Reached maximum collection time, ending collection.");
318                         break;
319                 }
320
321                 if ((h = poll(pollfd, _FD_MAX, (int) ((not_after - t) / USEC_PER_MSEC))) < 0) {
322
323                         if (errno == EINTR)
324                                 continue;
325
326                         log_error("poll(): %m");
327                         r = -errno;
328                         goto finish;
329                 }
330
331                 if (h == 0) {
332                         log_debug("Reached maximum collection time, ending collection.");
333                         break;
334                 }
335
336                 if (pollfd[FD_SIGNAL].revents) {
337                         log_debug("Got signal.");
338                         break;
339                 }
340
341                 if (pollfd[FD_INOTIFY].revents) {
342                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
343                         struct inotify_event *e;
344
345                         if ((n = read(inotify_fd, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
346                                 if (errno == EINTR || errno == EAGAIN)
347                                         continue;
348
349                                 log_error("Failed to read inotify event: %m");
350                                 r = -errno;
351                                 goto finish;
352                         }
353
354                         e = (struct inotify_event*) inotify_buffer;
355                         while (n > 0) {
356                                 size_t step;
357
358                                 if ((e->mask & IN_CREATE) && streq(e->name, "cancel")) {
359                                         log_debug("Collection canceled");
360                                         r = -ECANCELED;
361                                         goto finish;
362                                 }
363
364                                 if ((e->mask & IN_CREATE) && streq(e->name, "done")) {
365                                         log_debug("Got termination request");
366                                         goto done;
367                                 }
368
369                                 step = sizeof(struct inotify_event) + e->len;
370                                 assert(step <= (size_t) n);
371
372                                 e = (struct inotify_event*) ((uint8_t*) e + step);
373                                 n -= step;
374                         }
375                 }
376
377                 if ((n = read(fanotify_fd, &data, sizeof(data))) < 0) {
378
379                         if (errno == EINTR || errno == EAGAIN)
380                                 continue;
381
382                         log_error("Failed to read event: %m");
383                         r = -errno;
384                         goto finish;
385                 }
386
387                 for (m = &data.metadata; FAN_EVENT_OK(m, n); m = FAN_EVENT_NEXT(m, n)) {
388                         char fn[PATH_MAX];
389                         int k;
390
391                         if (m->fd < 0)
392                                 goto next_iteration;
393
394                         if (m->pid == my_pid)
395                                 goto next_iteration;
396
397                         __sync_synchronize();
398                         if (m->pid == shared->replay)
399                                 goto next_iteration;
400
401                         snprintf(fn, sizeof(fn), "/proc/self/fd/%i", m->fd);
402                         char_array_0(fn);
403
404                         if ((k = readlink_malloc(fn, &p)) >= 0) {
405                                 if (startswith(p, "/tmp") ||
406                                     endswith(p, " (deleted)") ||
407                                     hashmap_get(files, p))
408                                         /* Not interesting, or
409                                          * already read */
410                                         free(p);
411                                 else {
412                                         unsigned long ul;
413
414                                         ul = fd_first_block(m->fd);
415
416                                         if ((k = hashmap_put(files, p, SECTOR_TO_PTR(ul))) < 0) {
417                                                 log_warning("set_put() failed: %s", strerror(-k));
418                                                 free(p);
419                                         }
420                                 }
421
422                         } else
423                                 log_warning("readlink(%s) failed: %s", fn, strerror(-k));
424
425                 next_iteration:
426                         if (m->fd)
427                                 close_nointr_nofail(m->fd);
428                 }
429         }
430
431 done:
432         if (fanotify_fd >= 0) {
433                 close_nointr_nofail(fanotify_fd);
434                 fanotify_fd = -1;
435         }
436
437         log_debug("Writing Pack File...");
438
439         on_ssd = fs_on_ssd(root) > 0;
440         log_debug("On SSD: %s", yes_no(on_ssd));
441
442         on_btrfs = statfs(root, &sfs) >= 0 && (long) sfs.f_type == (long) BTRFS_SUPER_MAGIC;
443         log_debug("On btrfs: %s", yes_no(on_btrfs));
444
445         asprintf(&pack_fn, "%s/.readahead", root);
446         asprintf(&pack_fn_new, "%s/.readahead.new", root);
447
448         if (!pack_fn || !pack_fn_new) {
449                 log_error("Out of memory");
450                 r = -ENOMEM;
451                 goto finish;
452         }
453
454         if (!(pack = fopen(pack_fn_new, "we"))) {
455                 log_error("Failed to open pack file: %m");
456                 r = -errno;
457                 goto finish;
458         }
459
460         fputs(CANONICAL_HOST "\n", pack);
461         putc(on_ssd ? 'S' : 'R', pack);
462
463         if (on_ssd || on_btrfs) {
464
465                 /* On SSD or on btrfs, just write things out in the
466                  * order the files were accessed. */
467
468                 HASHMAP_FOREACH_KEY(q, p, files, i)
469                         pack_file(pack, p, on_btrfs);
470         } else {
471                 struct item *ordered, *j;
472                 unsigned k, n;
473
474                 /* On rotating media, order things by the block
475                  * numbers */
476
477                 log_debug("Ordering...");
478
479                 n = hashmap_size(files);
480                 if (!(ordered = new(struct item, n))) {
481                         log_error("Out of memory");
482                         r = -ENOMEM;
483                         goto finish;
484                 }
485
486                 j = ordered;
487                 HASHMAP_FOREACH_KEY(q, p, files, i) {
488                         j->path = p;
489                         j->block = PTR_TO_SECTOR(q);
490                         j++;
491                 }
492
493                 assert(ordered + n == j);
494
495                 qsort(ordered, n, sizeof(struct item), qsort_compare);
496
497                 for (k = 0; k < n; k++)
498                         pack_file(pack, ordered[k].path, on_btrfs);
499
500                 free(ordered);
501         }
502
503         log_debug("Finalizing...");
504
505         fflush(pack);
506
507         if (ferror(pack)) {
508                 log_error("Failed to write pack file.");
509                 r = -EIO;
510                 goto finish;
511         }
512
513         if (rename(pack_fn_new, pack_fn) < 0) {
514                 log_error("Failed to rename readahead file: %m");
515                 r = -errno;
516                 goto finish;
517         }
518
519         fclose(pack);
520         pack = NULL;
521
522         log_debug("Done.");
523
524 finish:
525         if (fanotify_fd >= 0)
526                 close_nointr_nofail(fanotify_fd);
527
528         if (signal_fd >= 0)
529                 close_nointr_nofail(signal_fd);
530
531         if (inotify_fd >= 0)
532                 close_nointr_nofail(inotify_fd);
533
534         if (pack) {
535                 fclose(pack);
536                 unlink(pack_fn_new);
537         }
538
539         free(pack_fn_new);
540         free(pack_fn);
541
542         while ((p = hashmap_steal_first_key(files)))
543                 free(p);
544
545         hashmap_free(files);
546
547         return r;
548 }
549
550 static int help(void) {
551
552         printf("%s [OPTIONS...] [DIRECTORY]\n\n"
553                "Collect read-ahead data on early boot.\n\n"
554                "  -h --help                 Show this help\n"
555                "     --max-files=INT        Maximum number of files to read ahead\n"
556                "     --max-file-size=BYTES  Maximum size of files to read ahead\n"
557                "     --timeout=USEC         Maximum time to spend collecting data\n",
558                program_invocation_short_name);
559
560         return 0;
561 }
562
563 static int parse_argv(int argc, char *argv[]) {
564
565         enum {
566                 ARG_FILES_MAX = 0x100,
567                 ARG_FILE_SIZE_MAX,
568                 ARG_TIMEOUT
569         };
570
571         static const struct option options[] = {
572                 { "help",          no_argument,       NULL, 'h'                },
573                 { "files-max",     required_argument, NULL, ARG_FILES_MAX      },
574                 { "file-size-max", required_argument, NULL, ARG_FILE_SIZE_MAX  },
575                 { "timeout",       required_argument, NULL, ARG_TIMEOUT        },
576                 { NULL,            0,                 NULL, 0                  }
577         };
578
579         int c;
580
581         assert(argc >= 0);
582         assert(argv);
583
584         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
585
586                 switch (c) {
587
588                 case 'h':
589                         help();
590                         return 0;
591
592                 case ARG_FILES_MAX:
593                         if (safe_atou(optarg, &arg_files_max) < 0 || arg_files_max <= 0) {
594                                 log_error("Failed to parse maximum number of files %s.", optarg);
595                                 return -EINVAL;
596                         }
597                         break;
598
599                 case ARG_FILE_SIZE_MAX: {
600                         unsigned long long ull;
601
602                         if (safe_atollu(optarg, &ull) < 0 || ull <= 0) {
603                                 log_error("Failed to parse maximum file size %s.", optarg);
604                                 return -EINVAL;
605                         }
606
607                         arg_file_size_max = (off_t) ull;
608                         break;
609                 }
610
611                 case ARG_TIMEOUT:
612                         if (parse_usec(optarg, &arg_timeout) < 0 || arg_timeout <= 0) {
613                                 log_error("Failed to parse timeout %s.", optarg);
614                                 return -EINVAL;
615                         }
616
617                         break;
618
619                 case '?':
620                         return -EINVAL;
621
622                 default:
623                         log_error("Unknown option code %c", c);
624                         return -EINVAL;
625                 }
626         }
627
628         if (optind != argc &&
629             optind != argc-1) {
630                 help();
631                 return -EINVAL;
632         }
633
634         return 1;
635 }
636
637 int main(int argc, char *argv[]) {
638         int r;
639
640         log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
641         log_parse_environment();
642         log_open();
643
644         if ((r = parse_argv(argc, argv)) <= 0)
645                 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
646
647         if (!enough_ram()) {
648                 log_info("Disabling readahead collector due to low memory.");
649                 return 0;
650         }
651
652         if (running_in_vm()) {
653                 log_info("Disabling readahead collector due to execution in virtual machine.");
654                 return 0;
655         }
656
657         if (!(shared = shared_get()))
658                 return 1;
659
660         shared->collect = getpid();
661         __sync_synchronize();
662
663         if (collect(optind < argc ? argv[optind] : "/") < 0)
664                 return 1;
665
666         return 0;
667 }