1 // SPDX-License-Identifier: GPL-2.0
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <errno.h>
7 #include <linux/fcntl.h>
8 #include <malloc.h>
9 
10 #include <sys/ioctl.h>
11 #include <sys/syscall.h>
12 #include <linux/memfd.h>
13 #include <linux/udmabuf.h>
14 
15 #define TEST_PREFIX	"drivers/dma-buf/udmabuf"
16 #define NUM_PAGES       4
17 
18 static int memfd_create(const char *name, unsigned int flags)
19 {
20 	return syscall(__NR_memfd_create, name, flags);
21 }
22 
23 int main(int argc, char *argv[])
24 {
25 	struct udmabuf_create create;
26 	int devfd, memfd, buf, ret;
27 	off_t size;
28 	void *mem;
29 
30 	devfd = open("/dev/udmabuf", O_RDWR);
31 	if (devfd < 0) {
32 		printf("%s: [skip,no-udmabuf]\n", TEST_PREFIX);
33 		exit(77);
34 	}
35 
36 	memfd = memfd_create("udmabuf-test", MFD_ALLOW_SEALING);
37 	if (memfd < 0) {
38 		printf("%s: [skip,no-memfd]\n", TEST_PREFIX);
39 		exit(77);
40 	}
41 
42 	ret = fcntl(memfd, F_ADD_SEALS, F_SEAL_SHRINK);
43 	if (ret < 0) {
44 		printf("%s: [skip,fcntl-add-seals]\n", TEST_PREFIX);
45 		exit(77);
46 	}
47 
48 
49 	size = getpagesize() * NUM_PAGES;
50 	ret = ftruncate(memfd, size);
51 	if (ret == -1) {
52 		printf("%s: [FAIL,memfd-truncate]\n", TEST_PREFIX);
53 		exit(1);
54 	}
55 
56 	memset(&create, 0, sizeof(create));
57 
58 	/* should fail (offset not page aligned) */
59 	create.memfd  = memfd;
60 	create.offset = getpagesize()/2;
61 	create.size   = getpagesize();
62 	buf = ioctl(devfd, UDMABUF_CREATE, &create);
63 	if (buf >= 0) {
64 		printf("%s: [FAIL,test-1]\n", TEST_PREFIX);
65 		exit(1);
66 	}
67 
68 	/* should fail (size not multiple of page) */
69 	create.memfd  = memfd;
70 	create.offset = 0;
71 	create.size   = getpagesize()/2;
72 	buf = ioctl(devfd, UDMABUF_CREATE, &create);
73 	if (buf >= 0) {
74 		printf("%s: [FAIL,test-2]\n", TEST_PREFIX);
75 		exit(1);
76 	}
77 
78 	/* should fail (not memfd) */
79 	create.memfd  = 0; /* stdin */
80 	create.offset = 0;
81 	create.size   = size;
82 	buf = ioctl(devfd, UDMABUF_CREATE, &create);
83 	if (buf >= 0) {
84 		printf("%s: [FAIL,test-3]\n", TEST_PREFIX);
85 		exit(1);
86 	}
87 
88 	/* should work */
89 	create.memfd  = memfd;
90 	create.offset = 0;
91 	create.size   = size;
92 	buf = ioctl(devfd, UDMABUF_CREATE, &create);
93 	if (buf < 0) {
94 		printf("%s: [FAIL,test-4]\n", TEST_PREFIX);
95 		exit(1);
96 	}
97 
98 	fprintf(stderr, "%s: ok\n", TEST_PREFIX);
99 	close(buf);
100 	close(memfd);
101 	close(devfd);
102 	return 0;
103 }
104