[PATCH] Use linux 3.17 memfd_create syscall when available

Keith Packard keithp at keithp.com
Thu Oct 9 05:02:32 PDT 2014


Linux 3.17 introduces a new anonymous memory allocation that returns a
file descriptor which we can pass around. Use this in preference to
creating a file in the filesystem where available.

Signed-off-by: Keith Packard <keithp at keithp.com>
---
 configure.ac          |  6 ++++++
 src/xshmfence_alloc.c | 50 ++++++++++++++++++++++++++++++++++++++++++--------
 2 files changed, 48 insertions(+), 8 deletions(-)

diff --git a/configure.ac b/configure.ac
index ddf63dc..84b49de 100644
--- a/configure.ac
+++ b/configure.ac
@@ -89,6 +89,12 @@ AC_SUBST([XPROTO_CFLAGS])
 
 CFLAGS="$CFLAGS $XPROTO_CFLAGS"
 
+AC_CHECK_FUNCS(memfd_create)
+
+AC_CHECK_DECLS([__NR_memfd_create], [], [], [[#include <asm/unistd.h>]])
+
+AC_CHECK_HEADERS([sys/memfd.h], [AC_DEFINE([HAVE_MEMFD_H], 1, [Has sys/memfd.h header])])
+
 AC_ARG_ENABLE(visibility,     AC_HELP_STRING([--enable-visibility], [Enable symbol visibility (default: auto)]),
 				[SYMBOL_VISIBILITY=$enableval],
 				[SYMBOL_VISIBILITY=auto])
diff --git a/src/xshmfence_alloc.c b/src/xshmfence_alloc.c
index 58416cd..afa6b16 100644
--- a/src/xshmfence_alloc.c
+++ b/src/xshmfence_alloc.c
@@ -26,6 +26,34 @@
 
 #include "xshmfenceint.h"
 
+#if !HAVE_MEMFD_CREATE
+#if HAVE_DECL___NR_MEMFD_CREATE
+#include <asm/unistd.h>
+static int memfd_create(const char *name,
+			    unsigned int flags)
+{
+	return syscall(__NR_memfd_create, name, flags);
+}
+#define HAVE_MEMFD_CREATE	1
+#endif
+#endif
+
+#if HAVE_MEMFD_CREATE
+
+/* Get defines for the memfd_create syscall, using the
+ * header if available, or just defining the constants otherwise
+ */
+
+#if HAVE_MEMFD_H
+#include <sys/memfd.h>
+#else
+/* flags for memfd_create(2) (unsigned int) */
+#define MFD_CLOEXEC		0x0001U
+#define MFD_ALLOW_SEALING	0x0002U
+#endif
+
+#endif
+
 /**
  * xshmfence_alloc_shm:
  *
@@ -41,16 +69,22 @@ xshmfence_alloc_shm(void)
 	char	template[] = SHMDIR "/shmfd-XXXXXX";
 	int	fd;
 
-#ifdef O_TMPFILE
-	fd = open(SHMDIR, O_TMPFILE|O_RDWR|O_CLOEXEC|O_EXCL, 0666);
+#if HAVE_DECL___NR_MEMFD_CREATE
+	fd = memfd_create("xshmfence", MFD_CLOEXEC|MFD_ALLOW_SEALING);
 	if (fd < 0)
 #endif
-        {
-            fd = mkstemp(template);
-            if (fd < 0)
-		return fd;
-            unlink(template);
-        }
+	{
+#ifdef O_TMPFILE
+		fd = open(SHMDIR, O_TMPFILE|O_RDWR|O_CLOEXEC|O_EXCL, 0666);
+		if (fd < 0)
+#endif
+		{
+			fd = mkstemp(template);
+			if (fd < 0)
+				return fd;
+			unlink(template);
+		}
+	}
 	if (ftruncate(fd, sizeof (struct xshmfence)) < 0) {
             close(fd);
             return -1;
-- 
2.1.1



More information about the xorg-devel mailing list