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