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