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