4 * Copyright (c) 2015 Red Hat, Inc.
6 * QEMU library functions on POSIX which are shared between QEMU and
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 #include "qemu/osdep.h"
31 #include <glib/gprintf.h>
35 #include "qemu/memfd.h"
38 #include <sys/memfd.h>
39 #elif defined CONFIG_LINUX
40 #include <sys/syscall.h>
41 #include <asm/unistd.h>
43 static int memfd_create(const char *name
, unsigned int flags
)
45 #ifdef __NR_memfd_create
46 return syscall(__NR_memfd_create
, name
, flags
);
54 #define MFD_CLOEXEC 0x0001U
57 #ifndef MFD_ALLOW_SEALING
58 #define MFD_ALLOW_SEALING 0x0002U
62 * This is a best-effort helper for shared memory allocation, with
63 * optional sealing. The helper will do his best to allocate using
64 * memfd with sealing, but may fallback on other methods without
67 void *qemu_memfd_alloc(const char *name
, size_t size
, unsigned int seals
,
77 mfd
= memfd_create(name
, MFD_ALLOW_SEALING
| MFD_CLOEXEC
);
81 /* some systems have memfd without sealing */
82 mfd
= memfd_create(name
, MFD_CLOEXEC
);
88 if (ftruncate(mfd
, size
) == -1) {
94 if (seals
&& fcntl(mfd
, F_ADD_SEALS
, seals
) == -1) {
100 const char *tmpdir
= g_get_tmp_dir();
103 fname
= g_strdup_printf("%s/memfd-XXXXXX", tmpdir
);
104 mfd
= mkstemp(fname
);
113 if (ftruncate(mfd
, size
) == -1) {
120 ptr
= mmap(0, size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, mfd
, 0);
121 if (ptr
== MAP_FAILED
) {
131 void qemu_memfd_free(void *ptr
, size_t size
, int fd
)
148 bool qemu_memfd_check(void)
150 static int memfd_check
= MEMFD_TODO
;
152 if (memfd_check
== MEMFD_TODO
) {
156 ptr
= qemu_memfd_alloc("test", 4096, 0, &fd
);
157 memfd_check
= ptr
? MEMFD_OK
: MEMFD_KO
;
158 qemu_memfd_free(ptr
, 4096, fd
);
161 return memfd_check
== MEMFD_OK
;