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