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