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