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