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