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