chiark / gitweb /
88c7a219a8dd5fa04e4ebd353d4818c2883943ea
[elogind.git] / src / readahead / readahead-replay.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 <getopt.h>
36 #include <sys/inotify.h>
37
38 #include <systemd/sd-daemon.h>
39
40 #include "missing.h"
41 #include "util.h"
42 #include "set.h"
43 #include "ioprio.h"
44 #include "readahead-common.h"
45 #include "virt.h"
46
47 static off_t arg_file_size_max = READAHEAD_FILE_SIZE_MAX;
48
49 static ReadaheadShared *shared = NULL;
50
51 static int unpack_file(FILE *pack) {
52         char fn[PATH_MAX];
53         int r = 0, fd = -1;
54         bool any = false;
55         struct stat st;
56
57         assert(pack);
58
59         if (!fgets(fn, sizeof(fn), pack))
60                 return 0;
61
62         char_array_0(fn);
63         truncate_nl(fn);
64
65         if ((fd = open(fn, O_RDONLY|O_CLOEXEC|O_NOATIME|O_NOCTTY|O_NOFOLLOW)) < 0) {
66
67                 if (errno != ENOENT && errno != EPERM && errno != EACCES)
68                         log_warning("open(%s) failed: %m", fn);
69
70         } else if (file_verify(fd, fn, arg_file_size_max, &st) <= 0) {
71                 close_nointr_nofail(fd);
72                 fd = -1;
73         }
74
75         for (;;) {
76                 uint32_t b, c;
77
78                 if (fread(&b, sizeof(b), 1, pack) != 1 ||
79                     fread(&c, sizeof(c), 1, pack) != 1) {
80                         log_error("Premature end of pack file.");
81                         r = -EIO;
82                         goto finish;
83                 }
84
85                 if (b == 0 && c == 0)
86                         break;
87
88                 if (c <= b) {
89                         log_error("Invalid pack file.");
90                         r = -EIO;
91                         goto finish;
92                 }
93
94                 log_debug("%s: page %u to %u", fn, b, c);
95
96                 any = true;
97
98                 if (fd >= 0)
99                         if (posix_fadvise(fd, b * page_size(), (c - b) * page_size(), POSIX_FADV_WILLNEED) < 0) {
100                                 log_warning("posix_fadvise() failed: %m");
101                                 goto finish;
102                         }
103         }
104
105         if (!any && fd >= 0) {
106                 /* if no range is encoded in the pack file this is
107                  * intended to mean that the whole file shall be
108                  * read */
109
110                 if (posix_fadvise(fd, 0, st.st_size, POSIX_FADV_WILLNEED) < 0) {
111                         log_warning("posix_fadvise() failed: %m");
112                         goto finish;
113                 }
114         }
115
116 finish:
117         if (fd >= 0)
118                 close_nointr_nofail(fd);
119
120         return r;
121 }
122
123 static int replay(const char *root) {
124         FILE *pack = NULL;
125         char line[LINE_MAX];
126         int r = 0;
127         char *pack_fn = NULL;
128         int c;
129         bool on_ssd, ready = false;
130         int prio;
131         int inotify_fd = -1;
132
133         assert(root);
134
135         write_one_line_file("/proc/self/oom_score_adj", "1000");
136         bump_request_nr(root);
137
138         if (asprintf(&pack_fn, "%s/.readahead", root) < 0) {
139                 log_error("Out of memory");
140                 r = -ENOMEM;
141                 goto finish;
142         }
143
144         if ((!(pack = fopen(pack_fn, "re")))) {
145                 if (errno == ENOENT)
146                         log_debug("No pack file found.");
147                 else {
148                         log_error("Failed to open pack file: %m");
149                         r = -errno;
150                 }
151
152                 goto finish;
153         }
154
155         posix_fadvise(fileno(pack), 0, 0, POSIX_FADV_WILLNEED);
156
157         if ((inotify_fd = open_inotify()) < 0) {
158                 r = inotify_fd;
159                 goto finish;
160         }
161
162         if (!(fgets(line, sizeof(line), pack))) {
163                 log_error("Premature end of pack file.");
164                 r = -EIO;
165                 goto finish;
166         }
167
168         char_array_0(line);
169
170         if (!streq(line, CANONICAL_HOST "\n")) {
171                 log_debug("Pack file host type mismatch.");
172                 goto finish;
173         }
174
175         if ((c = getc(pack)) == EOF) {
176                 log_debug("Premature end of pack file.");
177                 r = -EIO;
178                 goto finish;
179         }
180
181         /* We do not retest SSD here, so that we can start replaying
182          * before udev is up.*/
183         on_ssd = c == 'S';
184         log_debug("On SSD: %s", yes_no(on_ssd));
185
186         if (on_ssd)
187                 prio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0);
188         else
189                 prio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_RT, 7);
190
191         if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), prio) < 0)
192                 log_warning("Failed to set IDLE IO priority class: %m");
193
194         sd_notify(0, "STATUS=Replaying readahead data");
195
196         log_debug("Replaying...");
197
198         if (access("/run/systemd/readahead/noreplay", F_OK) >= 0) {
199                 log_debug("Got termination request");
200                 goto done;
201         }
202
203         while (!feof(pack) && !ferror(pack)) {
204                 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
205                 int k;
206                 ssize_t n;
207
208                 if ((n = read(inotify_fd, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
209                         if (errno != EINTR && errno != EAGAIN) {
210                                 log_error("Failed to read inotify event: %m");
211                                 r = -errno;
212                                 goto finish;
213                         }
214                 } else {
215                         struct inotify_event *e = (struct inotify_event*) inotify_buffer;
216
217                         while (n > 0) {
218                                 size_t step;
219
220                                 if ((e->mask & IN_CREATE) && streq(e->name, "noreplay")) {
221                                         log_debug("Got termination request");
222                                         goto done;
223                                 }
224
225                                 step = sizeof(struct inotify_event) + e->len;
226                                 assert(step <= (size_t) n);
227
228                                 e = (struct inotify_event*) ((uint8_t*) e + step);
229                                 n -= step;
230                         }
231                 }
232
233                 if ((k = unpack_file(pack)) < 0) {
234                         r = k;
235                         goto finish;
236                 }
237
238                 if (!ready) {
239                         /* We delay the ready notification until we
240                          * queued at least one read */
241                         sd_notify(0, "READY=1");
242                         ready = true;
243                 }
244         }
245
246 done:
247         if (!ready)
248                 sd_notify(0, "READY=1");
249
250         if (ferror(pack)) {
251                 log_error("Failed to read pack file.");
252                 r = -EIO;
253                 goto finish;
254         }
255
256         log_debug("Done.");
257
258 finish:
259         if (pack)
260                 fclose(pack);
261
262         if (inotify_fd >= 0)
263                 close_nointr_nofail(inotify_fd);
264
265         free(pack_fn);
266
267         return r;
268 }
269
270
271 static int help(void) {
272
273         printf("%s [OPTIONS...] [DIRECTORY]\n\n"
274                "Replay collected read-ahead data on early boot.\n\n"
275                "  -h --help                 Show this help\n"
276                "     --max-file-size=BYTES  Maximum size of files to read ahead\n",
277                program_invocation_short_name);
278
279         return 0;
280 }
281
282 static int parse_argv(int argc, char *argv[]) {
283
284         enum {
285                 ARG_FILE_SIZE_MAX
286         };
287
288         static const struct option options[] = {
289                 { "help",          no_argument,       NULL, 'h'                },
290                 { "file-size-max", required_argument, NULL, ARG_FILE_SIZE_MAX  },
291                 { NULL,            0,                 NULL, 0                  }
292         };
293
294         int c;
295
296         assert(argc >= 0);
297         assert(argv);
298
299         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
300
301                 switch (c) {
302
303                 case 'h':
304                         help();
305                         return 0;
306
307                 case ARG_FILE_SIZE_MAX: {
308                         unsigned long long ull;
309
310                         if (safe_atollu(optarg, &ull) < 0 || ull <= 0) {
311                                 log_error("Failed to parse maximum file size %s.", optarg);
312                                 return -EINVAL;
313                         }
314
315                         arg_file_size_max = (off_t) ull;
316                         break;
317                 }
318
319                 case '?':
320                         return -EINVAL;
321
322                 default:
323                         log_error("Unknown option code %c", c);
324                         return -EINVAL;
325                 }
326         }
327
328         if (optind != argc &&
329             optind != argc-1) {
330                 help();
331                 return -EINVAL;
332         }
333
334         return 1;
335 }
336
337 int main(int argc, char*argv[]) {
338         int r;
339         const char *root;
340
341         log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
342         log_parse_environment();
343         log_open();
344
345         umask(0022);
346
347         if ((r = parse_argv(argc, argv)) <= 0)
348                 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
349
350         root = optind < argc ? argv[optind] : "/";
351
352         if (!enough_ram()) {
353                 log_info("Disabling readahead replay due to low memory.");
354                 return 0;
355         }
356
357         if (detect_virtualization(NULL) > 0) {
358                 log_info("Disabling readahead replay due to execution in virtualized environment.");
359                 return 0;
360         }
361
362         if (!(shared = shared_get()))
363                 return 1;
364
365         shared->replay = getpid();
366         __sync_synchronize();
367
368         if (replay(root) < 0)
369                 return 1;
370
371         return 0;
372 }