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