chiark / gitweb /
cryptsetup: lock ourselves into memory as long as we deal with passwords
[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         bump_request_nr(root);
131
132         if (asprintf(&pack_fn, "%s/.readahead", root) < 0) {
133                 log_error("Out of memory");
134                 r = -ENOMEM;
135                 goto finish;
136         }
137
138         if ((!(pack = fopen(pack_fn, "re")))) {
139                 if (errno == -ENOENT)
140                         log_debug("No pack file found.");
141                 else {
142                         log_error("Failed to open pack file: %m");
143                         r = -errno;
144                 }
145
146                 goto finish;
147         }
148
149         posix_fadvise(fileno(pack), 0, 0, POSIX_FADV_WILLNEED);
150
151         if ((inotify_fd = open_inotify()) < 0) {
152                 r = inotify_fd;
153                 goto finish;
154         }
155
156         if (!(fgets(line, sizeof(line), pack))) {
157                 log_error("Premature end of pack file.");
158                 r = -EIO;
159                 goto finish;
160         }
161
162         char_array_0(line);
163
164         if (!streq(line, CANONICAL_HOST "\n")) {
165                 log_debug("Pack file host type mismatch.");
166                 goto finish;
167         }
168
169         if ((c = getc(pack)) == EOF) {
170                 log_debug("Premature end of pack file.");
171                 r = -EIO;
172                 goto finish;
173         }
174
175         /* We do not retest SSD here, so that we can start replaying
176          * before udev is up.*/
177         on_ssd = c == 'S';
178         log_debug("On SSD: %s", yes_no(on_ssd));
179
180         if (on_ssd)
181                 prio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0);
182         else
183                 prio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_RT, 7);
184
185         if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), prio) < 0)
186                 log_warning("Failed to set IDLE IO priority class: %m");
187
188         sd_notify(0, "STATUS=Replaying readahead data");
189
190         log_debug("Replaying...");
191
192         if (access("/dev/.systemd/readahead/noreplay", F_OK) >= 0) {
193                 log_debug("Got termination request");
194                 goto done;
195         }
196
197         while (!feof(pack) && !ferror(pack)) {
198                 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
199                 int k;
200                 ssize_t n;
201
202                 if ((n = read(inotify_fd, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
203                         if (errno != EINTR && errno != EAGAIN) {
204                                 log_error("Failed to read inotify event: %m");
205                                 r = -errno;
206                                 goto finish;
207                         }
208                 } else {
209                         struct inotify_event *e = (struct inotify_event*) inotify_buffer;
210
211                         while (n > 0) {
212                                 size_t step;
213
214                                 if ((e->mask & IN_CREATE) && streq(e->name, "noreplay")) {
215                                         log_debug("Got termination request");
216                                         goto done;
217                                 }
218
219                                 step = sizeof(struct inotify_event) + e->len;
220                                 assert(step <= (size_t) n);
221
222                                 e = (struct inotify_event*) ((uint8_t*) e + step);
223                                 n -= step;
224                         }
225                 }
226
227                 if ((k = unpack_file(pack)) < 0) {
228                         r = k;
229                         goto finish;
230                 }
231
232                 if (!ready) {
233                         /* We delay the ready notification until we
234                          * queued at least one read */
235                         sd_notify(0, "READY=1");
236                         ready = true;
237                 }
238         }
239
240 done:
241         if (!ready)
242                 sd_notify(0, "READY=1");
243
244         if (ferror(pack)) {
245                 log_error("Failed to read pack file.");
246                 r = -EIO;
247                 goto finish;
248         }
249
250         log_debug("Done.");
251
252 finish:
253         if (pack)
254                 fclose(pack);
255
256         if (inotify_fd >= 0)
257                 close_nointr_nofail(inotify_fd);
258
259         free(pack_fn);
260
261         return r;
262 }
263
264
265 static int help(void) {
266
267         printf("%s [OPTIONS...] [DIRECTORY]\n\n"
268                "Replay collected read-ahead data on early boot.\n\n"
269                "  -h --help                 Show this help\n"
270                "     --max-file-size=BYTES  Maximum size of files to read ahead\n",
271                program_invocation_short_name);
272
273         return 0;
274 }
275
276 static int parse_argv(int argc, char *argv[]) {
277
278         enum {
279                 ARG_FILE_SIZE_MAX
280         };
281
282         static const struct option options[] = {
283                 { "help",          no_argument,       NULL, 'h'                },
284                 { "file-size-max", required_argument, NULL, ARG_FILE_SIZE_MAX  },
285                 { NULL,            0,                 NULL, 0                  }
286         };
287
288         int c;
289
290         assert(argc >= 0);
291         assert(argv);
292
293         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
294
295                 switch (c) {
296
297                 case 'h':
298                         help();
299                         return 0;
300
301                 case ARG_FILE_SIZE_MAX: {
302                         unsigned long long ull;
303
304                         if (safe_atollu(optarg, &ull) < 0 || ull <= 0) {
305                                 log_error("Failed to parse maximum file size %s.", optarg);
306                                 return -EINVAL;
307                         }
308
309                         arg_file_size_max = (off_t) ull;
310                         break;
311                 }
312
313                 case '?':
314                         return -EINVAL;
315
316                 default:
317                         log_error("Unknown option code %c", c);
318                         return -EINVAL;
319                 }
320         }
321
322         if (optind != argc &&
323             optind != argc-1) {
324                 help();
325                 return -EINVAL;
326         }
327
328         return 1;
329 }
330
331 int main(int argc, char*argv[]) {
332         int r;
333
334         log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
335         log_parse_environment();
336         log_open();
337
338         if ((r = parse_argv(argc, argv)) <= 0)
339                 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
340
341         if (!enough_ram()) {
342                 log_info("Disabling readahead replay due to low memory.");
343                 return 0;
344         }
345
346         if (!(shared = shared_get()))
347                 return 1;
348
349         shared->replay = getpid();
350         __sync_synchronize();
351
352         if (replay(optind < argc ? argv[optind] : "/") < 0)
353                 return 1;
354
355         return 0;
356 }