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