xref: /aosp_15_r20/external/liburing/test/eventfd.c (revision 25da2bea747f3a93b4c30fd9708b0618ef55a0e6)
1 /* SPDX-License-Identifier: MIT */
2 /*
3  * Description: run various nop tests
4  *
5  */
6 #include <errno.h>
7 #include <stdio.h>
8 #include <unistd.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <fcntl.h>
12 #include <poll.h>
13 #include <sys/eventfd.h>
14 
15 #include "liburing.h"
16 
main(int argc,char * argv[])17 int main(int argc, char *argv[])
18 {
19 	struct io_uring_params p = {};
20 	struct io_uring_sqe *sqe;
21 	struct io_uring_cqe *cqe;
22 	struct io_uring ring;
23 	uint64_t ptr;
24 	struct iovec vec = {
25 		.iov_base = &ptr,
26 		.iov_len = sizeof(ptr)
27 	};
28 	int ret, evfd, i;
29 
30 	if (argc > 1)
31 		return 0;
32 
33 	ret = io_uring_queue_init_params(8, &ring, &p);
34 	if (ret) {
35 		fprintf(stderr, "ring setup failed: %d\n", ret);
36 		return 1;
37 	}
38 	if (!(p.features & IORING_FEAT_CUR_PERSONALITY)) {
39 		fprintf(stdout, "Skipping\n");
40 		return 0;
41 	}
42 
43 	evfd = eventfd(0, EFD_CLOEXEC);
44 	if (evfd < 0) {
45 		perror("eventfd");
46 		return 1;
47 	}
48 
49 	ret = io_uring_register_eventfd(&ring, evfd);
50 	if (ret) {
51 		fprintf(stderr, "failed to register evfd: %d\n", ret);
52 		return 1;
53 	}
54 
55 	sqe = io_uring_get_sqe(&ring);
56 	io_uring_prep_poll_add(sqe, evfd, POLLIN);
57 	sqe->flags |= IOSQE_IO_LINK;
58 	sqe->user_data = 1;
59 
60 	sqe = io_uring_get_sqe(&ring);
61 	io_uring_prep_readv(sqe, evfd, &vec, 1, 0);
62 	sqe->flags |= IOSQE_IO_LINK;
63 	sqe->user_data = 2;
64 
65 	ret = io_uring_submit(&ring);
66 	if (ret != 2) {
67 		fprintf(stderr, "submit: %d\n", ret);
68 		return 1;
69 	}
70 
71 	sqe = io_uring_get_sqe(&ring);
72 	io_uring_prep_nop(sqe);
73 	sqe->user_data = 3;
74 
75 	ret = io_uring_submit(&ring);
76 	if (ret != 1) {
77 		fprintf(stderr, "submit: %d\n", ret);
78 		return 1;
79 	}
80 
81 	for (i = 0; i < 3; i++) {
82 		ret = io_uring_wait_cqe(&ring, &cqe);
83 		if (ret) {
84 			fprintf(stderr, "wait: %d\n", ret);
85 			return 1;
86 		}
87 		switch (cqe->user_data) {
88 		case 1:
89 			/* POLLIN */
90 			if (cqe->res != 1) {
91 				fprintf(stderr, "poll: %d\n", cqe->res);
92 				return 1;
93 			}
94 			break;
95 		case 2:
96 			if (cqe->res != sizeof(ptr)) {
97 				fprintf(stderr, "read: %d\n", cqe->res);
98 				return 1;
99 			}
100 			break;
101 		case 3:
102 			if (cqe->res) {
103 				fprintf(stderr, "nop: %d\n", cqe->res);
104 				return 1;
105 			}
106 			break;
107 		}
108 		io_uring_cqe_seen(&ring, cqe);
109 	}
110 
111 	return 0;
112 }
113