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