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