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