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