Debian Codegraph @

src/libsystemd/sd-journal/mmap-cache.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdlib.h>
4 #include <sys/mman.h>
5 #include <sys/stat.h>
6
7 #include "alloc-util.h"
8 #include "bitfield.h"
9 #include "errno-util.h"
10 #include "fd-util.h"
11 #include "hashmap.h"
12 #include "list.h"
13 #include "log.h"
14 #include "memory-util.h"
15 #include "mmap-cache.h"
16 #include "sigbus.h"
17
18 typedef struct Window Window;
19
20 typedef enum WindowFlags {
21 WINDOW_KEEP_ALWAYS = 1u << (_MMAP_CACHE_CATEGORY_MAX + 0),
22 WINDOW_IN_UNUSED = 1u << (_MMAP_CACHE_CATEGORY_MAX + 1),
23 WINDOW_INVALIDATED = 1u << (_MMAP_CACHE_CATEGORY_MAX + 2),
24
25 _WINDOW_USED_MASK = WINDOW_IN_UNUSED - 1, /* The mask contains all bits that indicate the windows
26 * is currently in use. Covers the all the object types
27 * and the additional WINDOW_KEEP_ALWAYS flag. */
28 } WindowFlags;
29
30 #define WINDOW_IS_UNUSED(w) (((w)->flags & _WINDOW_USED_MASK) == 0)
31
32 struct Window {
33 MMapFileDescriptor *fd;
34
35 WindowFlags flags;
36
37 void *ptr;
38 uint64_t offset;
39 size_t size;
40
41 LIST_FIELDS(Window, windows);
42 LIST_FIELDS(Window, unused);
43 };
44
45 struct MMapFileDescriptor {
46 MMapCache *cache;
47
48 int fd;
49 int prot;
50 bool sigbus;
51
52 LIST_HEAD(Window, windows);
53 };
54
55 struct MMapCache {
56 unsigned n_ref;
57 unsigned n_windows;
58
59 unsigned n_category_cache_hit;
60 unsigned n_window_list_hit;
61 unsigned n_missed;
62
63 Hashmap *fds;
64
65 LIST_HEAD(Window, unused);
66 Window *last_unused;
67 unsigned n_unused;
68
69 Window *windows_by_category[_MMAP_CACHE_CATEGORY_MAX];
70 };
71
72 #define WINDOWS_MIN 64
73 #define UNUSED_MIN 4
74
75 #if ENABLE_DEBUG_MMAP_CACHE
76 /* Tiny windows increase mmap activity and the chance of exposing unsafe use. */
77 # define WINDOW_SIZE (page_size())
78 #else
79 # define WINDOW_SIZE ((size_t) (UINT64_C(8) * UINT64_C(1024) * UINT64_C(1024)))
80 #endif
81
82 MMapCache* mmap_cache_new(void) {
83 MMapCache *m;
84
85 m = new(MMapCache, 1);
86 if (!m)
87 return NULL;
88
89 *m = (MMapCache) {
90 .n_ref = 1,
91 };
92
93 return m;
94 }
95
96 static Window* window_unlink(Window *w) {
97 assert(w);
98
99 MMapCache *m = mmap_cache_fd_cache(w->fd);
100
101 if (w->ptr)
102 munmap(w->ptr, w->size);
103
104 if (FLAGS_SET(w->flags, WINDOW_IN_UNUSED)) {
105 if (m->last_unused == w)
106 m->last_unused = w->unused_prev;
107 LIST_REMOVE(unused, m->unused, w);
108 m->n_unused--;
109 }
110
111 for (unsigned i = 0; i < _MMAP_CACHE_CATEGORY_MAX; i++)
112 if (BIT_SET(w->flags, i))
113 assert_se(TAKE_PTR(m->windows_by_category[i]) == w);
114
115 return LIST_REMOVE(windows, w->fd->windows, w);
116 }
117
118 static void window_invalidate(Window *w) {
119 assert(w);
120 assert(w->fd);
121
122 if (FLAGS_SET(w->flags, WINDOW_INVALIDATED))
123 return;
124
125 /* Replace the window with anonymous pages. This is useful when we hit a SIGBUS and want to make sure
126 * the file cannot trigger any further SIGBUS, possibly overrunning the sigbus queue. */
127
128 assert_se(mmap(w->ptr, w->size, w->fd->prot, MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0) == w->ptr);
129 w->flags |= WINDOW_INVALIDATED;
130 }
131
132 static Window* window_free(Window *w) {
133 if (!w)
134 return NULL;
135
136 window_unlink(w);
137 w->fd->cache->n_windows--;
138
139 return mfree(w);
140 }
141
142 static bool window_matches(Window *w, MMapFileDescriptor *f, uint64_t offset, size_t size) {
143 assert(size > 0);
144
145 return
146 w &&
147 f == w->fd &&
148 offset >= w->offset &&
149 offset + size <= w->offset + w->size;
150 }
151
152 static bool window_matches_by_addr(Window *w, MMapFileDescriptor *f, void *addr, size_t size) {
153 assert(size > 0);
154
155 return
156 w &&
157 f == w->fd &&
158 (uint8_t*) addr >= (uint8_t*) w->ptr &&
159 (uint8_t*) addr + size <= (uint8_t*) w->ptr + w->size;
160 }
161
162 static Window* window_add(MMapFileDescriptor *f, uint64_t offset, size_t size, void *ptr) {
163 MMapCache *m = mmap_cache_fd_cache(f);
164 Window *w;
165
166 if (!m->last_unused || m->n_windows < WINDOWS_MIN || m->n_unused < UNUSED_MIN) {
167 /* Allocate a new window */
168 w = new(Window, 1);
169 if (!w)
170 return NULL;
171 m->n_windows++;
172 } else
173 /* Reuse an existing one */
174 w = window_unlink(m->last_unused);
175
176 *w = (Window) {
177 .fd = f,
178 .offset = offset,
179 .size = size,
180 .ptr = ptr,
181 };
182
183 return LIST_PREPEND(windows, f->windows, w);
184 }
185
186 static void category_detach_window(MMapCache *m, MMapCacheCategory c) {
187 Window *w;
188
189 assert(m);
190 assert(c >= 0 && c < _MMAP_CACHE_CATEGORY_MAX);
191
192 w = TAKE_PTR(m->windows_by_category[c]);
193 if (!w)
194 return; /* Nothing attached. */
195
196 assert(BIT_SET(w->flags, c));
197 w->flags &= ~(1u << c);
198
199 if (WINDOW_IS_UNUSED(w)) {
200 /* Not used anymore? */
201 #if ENABLE_DEBUG_MMAP_CACHE
202 /* Unmap unused windows immediately to expose use-after-unmap by SIGSEGV. */
203 window_free(w);
204 #else
205 LIST_PREPEND(unused, m->unused, w);
206 if (!m->last_unused)
207 m->last_unused = w;
208 m->n_unused++;
209 w->flags |= WINDOW_IN_UNUSED;
210 #endif
211 }
212 }
213
214 static void category_attach_window(MMapCache *m, MMapCacheCategory c, Window *w) {
215 assert(m);
216 assert(c >= 0 && c < _MMAP_CACHE_CATEGORY_MAX);
217 assert(w);
218
219 if (m->windows_by_category[c] == w)
220 return; /* Already attached. */
221
222 category_detach_window(m, c);
223
224 if (FLAGS_SET(w->flags, WINDOW_IN_UNUSED)) {
225 /* Used again? */
226 if (m->last_unused == w)
227 m->last_unused = w->unused_prev;
228 LIST_REMOVE(unused, m->unused, w);
229 m->n_unused--;
230 w->flags &= ~WINDOW_IN_UNUSED;
231 }
232
233 m->windows_by_category[c] = w;
234 w->flags |= (1u << c);
235 }
236
237 static MMapCache* mmap_cache_free(MMapCache *m) {
238 if (!m)
239 return NULL;
240
241 /* All windows are owned by fds, and each fd takes a reference of MMapCache. So, when this is called,
242 * all fds are already freed, and hence there is no window. */
243
244 assert(hashmap_isempty(m->fds));
245 hashmap_free(m->fds);
246
247 assert(!m->unused && m->n_unused == 0);
248 assert(m->n_windows == 0);
249
250 return mfree(m);
251 }
252
253 DEFINE_TRIVIAL_REF_UNREF_FUNC(MMapCache, mmap_cache, mmap_cache_free);
254
255 static int mmap_try_harder(MMapFileDescriptor *f, void *addr, int flags, uint64_t offset, size_t size, void **ret) {
256 MMapCache *m = mmap_cache_fd_cache(f);
257
258 assert(ret);
259
260 for (;;) {
261 void *ptr;
262
263 ptr = mmap(addr, size, f->prot, flags, f->fd, offset);
264 if (ptr != MAP_FAILED) {
265 *ret = ptr;
266 return 0;
267 }
268 if (errno != ENOMEM)
269 return negative_errno();
270
271 /* When failed with ENOMEM, try again after making a room by freeing an unused window. */
272
273 if (!m->last_unused)
274 return -ENOMEM; /* no free window, propagate the original error. */
275
276 window_free(m->last_unused);
277 }
278 }
279
280 static int add_mmap(
281 MMapFileDescriptor *f,
282 uint64_t offset,
283 size_t size,
284 struct stat *st,
285 Window **ret) {
286
287 Window *w;
288 void *d;
289 int r;
290
291 assert(f);
292 assert(size > 0);
293 assert(ret);
294
295 /* overflow check */
296 if (size > SIZE_MAX - PAGE_OFFSET_U64(offset))
297 return -EADDRNOTAVAIL;
298
299 size = PAGE_ALIGN(size + PAGE_OFFSET_U64(offset));
300 offset = PAGE_ALIGN_DOWN_U64(offset);
301
302 if (size < WINDOW_SIZE) {
303 uint64_t delta;
304
305 delta = PAGE_ALIGN((WINDOW_SIZE - size) / 2);
306 offset = LESS_BY(offset, delta);
307 size = WINDOW_SIZE;
308 }
309
310 if (st) {
311 /* Memory maps that are larger then the files underneath have undefined behavior. Hence,
312 * clamp things to the file size if we know it */
313
314 if (offset >= (uint64_t) st->st_size)
315 return -EADDRNOTAVAIL;
316
317 if (size > (uint64_t) st->st_size - offset)
318 size = PAGE_ALIGN((uint64_t) st->st_size - offset);
319 }
320
321 if (size >= SIZE_MAX)
322 return -EADDRNOTAVAIL;
323
324 r = mmap_try_harder(f, NULL, MAP_SHARED, offset, size, &d);
325 if (r < 0)
326 return r;
327
328 w = window_add(f, offset, size, d);
329 if (!w) {
330 (void) munmap(d, size);
331 return -ENOMEM;
332 }
333
334 *ret = w;
335 return 0;
336 }
337
338 int mmap_cache_fd_get(
339 MMapFileDescriptor *f,
340 MMapCacheCategory c,
341 bool keep_always,
342 uint64_t offset,
343 size_t size,
344 struct stat *st,
345 void **ret) {
346
347 MMapCache *m = mmap_cache_fd_cache(f);
348 Window *w;
349 int r;
350
351 assert(size > 0);
352 assert(c >= 0 && c < _MMAP_CACHE_CATEGORY_MAX);
353 assert(ret);
354
355 if (f->sigbus)
356 return -EIO;
357
358 /* Check whether the current category is the right one already */
359 if (window_matches(m->windows_by_category[c], f, offset, size)) {
360 m->n_category_cache_hit++;
361 w = m->windows_by_category[c];
362 goto found;
363 }
364
365 /* Drop the reference to the window, since it's unnecessary now */
366 category_detach_window(m, c);
367
368 /* Search for a matching mmap */
369 LIST_FOREACH(windows, i, f->windows)
370 if (window_matches(i, f, offset, size)) {
371 m->n_window_list_hit++;
372 w = i;
373 goto found;
374 }
375
376 m->n_missed++;
377
378 /* Create a new mmap */
379 r = add_mmap(f, offset, size, st, &w);
380 if (r < 0)
381 return r;
382
383 found:
384 if (keep_always)
385 w->flags |= WINDOW_KEEP_ALWAYS;
386
387 category_attach_window(m, c, w);
388 *ret = (uint8_t*) w->ptr + (offset - w->offset);
389 return 0;
390 }
391
392 int mmap_cache_fd_pin(
393 MMapFileDescriptor *f,
394 MMapCacheCategory c,
395 void *addr,
396 size_t size) {
397
398 MMapCache *m = mmap_cache_fd_cache(f);
399 Window *w;
400
401 assert(addr);
402 assert(c >= 0 && c < _MMAP_CACHE_CATEGORY_MAX);
403 assert(size > 0);
404
405 if (f->sigbus)
406 return -EIO;
407
408 /* Check if the current category is the right one. */
409 if (window_matches_by_addr(m->windows_by_category[c], f, addr, size)) {
410 m->n_category_cache_hit++;
411 w = m->windows_by_category[c];
412 goto found;
413 }
414
415 /* Search for a matching mmap. */
416 LIST_FOREACH(windows, i, f->windows)
417 if (window_matches_by_addr(i, f, addr, size)) {
418 m->n_window_list_hit++;
419 w = i;
420 goto found;
421 }
422
423 m->n_missed++;
424 return -EADDRNOTAVAIL; /* Not found. */
425
426 found:
427 if (FLAGS_SET(w->flags, WINDOW_KEEP_ALWAYS))
428 return 0; /* The window will never unmapped. */
429
430 /* Attach the window to the 'pinning' category. */
431 category_attach_window(m, MMAP_CACHE_CATEGORY_PIN, w);
432 return 1;
433 }
434
435 void mmap_cache_stats_log_debug(MMapCache *m) {
436 assert(m);
437
438 log_debug("mmap cache statistics: %u category cache hit, %u window list hit, %u miss, %u files, %u windows, %u unused",
439 m->n_category_cache_hit, m->n_window_list_hit, m->n_missed, hashmap_size(m->fds), m->n_windows, m->n_unused);
440 }
441
442 static void mmap_cache_process_sigbus(MMapCache *m) {
443 bool found = false;
444 MMapFileDescriptor *f;
445 int r;
446
447 assert(m);
448
449 /* Iterate through all triggered pages and mark their files as invalidated. */
450 for (;;) {
451 bool ours;
452 void *addr;
453
454 r = sigbus_pop(&addr);
455 if (_likely_(r == 0))
456 break;
457 if (r < 0) {
458 log_error_errno(r, "SIGBUS handling failed: %m");
459 abort();
460 }
461
462 ours = false;
463 HASHMAP_FOREACH(f, m->fds) {
464 LIST_FOREACH(windows, w, f->windows)
465 if (window_matches_by_addr(w, f, addr, 1)) {
466 found = ours = f->sigbus = true;
467 break;
468 }
469
470 if (ours)
471 break;
472 }
473
474 /* Didn't find a matching window, give up. */
475 if (!ours) {
476 log_error("Unknown SIGBUS page, aborting.");
477 abort();
478 }
479 }
480
481 /* The list of triggered pages is now empty. Now, let's remap all windows of the triggered file to
482 * anonymous maps, so that no page of the file in question is triggered again, so that we can be sure
483 * not to hit the queue size limit. */
484 if (_likely_(!found))
485 return;
486
487 HASHMAP_FOREACH(f, m->fds) {
488 if (!f->sigbus)
489 continue;
490
491 LIST_FOREACH(windows, w, f->windows)
492 window_invalidate(w);
493 }
494 }
495
496 bool mmap_cache_fd_got_sigbus(MMapFileDescriptor *f) {
497 assert(f);
498
499 mmap_cache_process_sigbus(f->cache);
500
501 return f->sigbus;
502 }
503
504 int mmap_cache_add_fd(MMapCache *m, int fd, int prot, MMapFileDescriptor **ret) {
505 _cleanup_free_ MMapFileDescriptor *f = NULL;
506 MMapFileDescriptor *existing;
507 int r;
508
509 assert(m);
510 assert(fd >= 0);
511
512 existing = hashmap_get(m->fds, FD_TO_PTR(fd));
513 if (existing) {
514 if (existing->prot != prot)
515 return -EEXIST;
516 if (ret)
517 *ret = existing;
518 return 0;
519 }
520
521 f = new(MMapFileDescriptor, 1);
522 if (!f)
523 return -ENOMEM;
524
525 *f = (MMapFileDescriptor) {
526 .fd = fd,
527 .prot = prot,
528 };
529
530 r = hashmap_ensure_put(&m->fds, NULL, FD_TO_PTR(fd), f);
531 if (r < 0)
532 return r;
533 assert(r > 0);
534
535 f->cache = mmap_cache_ref(m);
536
537 if (ret)
538 *ret = f;
539
540 TAKE_PTR(f);
541 return 1;
542 }
543
544 MMapFileDescriptor* mmap_cache_fd_free(MMapFileDescriptor *f) {
545 if (!f)
546 return NULL;
547
548 /* Make sure that any queued SIGBUS are first dispatched, so that we don't end up with a SIGBUS entry
549 * we cannot relate to any existing memory map. */
550
551 mmap_cache_process_sigbus(f->cache);
552
553 while (f->windows)
554 window_free(f->windows);
555
556 assert_se(hashmap_remove(f->cache->fds, FD_TO_PTR(f->fd)) == f);
557
558 /* Unref the cache at the end. Otherwise, the assertions in mmap_cache_free() may be triggered. */
559 f->cache = mmap_cache_unref(f->cache);
560
561 return mfree(f);
562 }
563
564 MMapCache* mmap_cache_fd_cache(MMapFileDescriptor *f) {
565 assert(f);
566 return ASSERT_PTR(f->cache);
567 }