summaryrefslogtreecommitdiff
path: root/src/shm.c
blob: 9658a758d0b816d363b4b9ca3ac06024a6d1633d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
#include "shm.h"

/* These two functions aren't used on linux. */
#ifndef __linux__
static void randname(char *buf)
{
	struct timespec ts;
	clock_gettime(CLOCK_REALTIME, &ts);
	long r = ts.tv_nsec;
	for (int i = 0; i < 6; ++i) {
		buf[i] = 'A'+(r&15)+(r&16)*2;
		r >>= 5;
	}
}

static int create_shm_file(void)
{
	int retries = 100;
	do {
		char name[] = "/wl_shm-XXXXXX";
		randname(name + sizeof(name) - 7);
		--retries;
		int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
		if (fd >= 0) {
			shm_unlink(name);
			return fd;
		}
	} while (retries > 0 && errno == EEXIST);
	return -1;
}
#endif

int shm_allocate_file(size_t size)
{
#ifdef __linux__
	/*
	 * On linux, we can just use memfd_create(). This is both simpler and
	 * potentially allows usage of Transparent HugePages, which speed up
	 * the first paint of a large screen buffer.
	 *
	 * This isn't available on *BSD, which we could conceivably be running
	 * on.
	 */
	int fd = memfd_create("wl_shm", 0);
#else
	int fd = create_shm_file();
#endif
	if (fd < 0)
		return -1;
	int ret;
	do {
		ret = ftruncate(fd, size);
	} while (ret < 0 && errno == EINTR);
	if (ret < 0) {
		close(fd);
		return -1;
	}
	return fd;
}