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