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