xref: /aosp_15_r20/external/liburing/test/eeed8b54e0df.c (revision 25da2bea747f3a93b4c30fd9708b0618ef55a0e6)
1 /* SPDX-License-Identifier: MIT */
2 /*
3  * Description: -EAGAIN handling
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 
13 #include "helpers.h"
14 #include "liburing.h"
15 
16 #define BLOCK	4096
17 
18 #ifndef RWF_NOWAIT
19 #define RWF_NOWAIT	8
20 #endif
21 
get_file_fd(void)22 static int get_file_fd(void)
23 {
24 	ssize_t ret;
25 	char *buf;
26 	int fd;
27 
28 	fd = open("testfile", O_RDWR | O_CREAT, 0644);
29 	unlink("testfile");
30 	if (fd < 0) {
31 		perror("open file");
32 		return -1;
33 	}
34 
35 	buf = t_malloc(BLOCK);
36 	ret = write(fd, buf, BLOCK);
37 	if (ret != BLOCK) {
38 		if (ret < 0)
39 			perror("write");
40 		else
41 			printf("Short write\n");
42 		goto err;
43 	}
44 	fsync(fd);
45 
46 	if (posix_fadvise(fd, 0, 4096, POSIX_FADV_DONTNEED)) {
47 		perror("fadvise");
48 err:
49 		close(fd);
50 		free(buf);
51 		return -1;
52 	}
53 
54 	free(buf);
55 	return fd;
56 }
57 
main(int argc,char * argv[])58 int main(int argc, char *argv[])
59 {
60 	struct io_uring ring;
61 	struct io_uring_sqe *sqe;
62 	struct io_uring_cqe *cqe;
63 	struct iovec iov;
64 	int ret, fd;
65 
66 	if (argc > 1)
67 		return 0;
68 
69 	iov.iov_base = t_malloc(4096);
70 	iov.iov_len = 4096;
71 
72 	ret = io_uring_queue_init(2, &ring, 0);
73 	if (ret) {
74 		printf("ring setup failed\n");
75 		return 1;
76 
77 	}
78 
79 	sqe = io_uring_get_sqe(&ring);
80 	if (!sqe) {
81 		printf("get sqe failed\n");
82 		return 1;
83 	}
84 
85 	fd = get_file_fd();
86 	if (fd < 0)
87 		return 1;
88 
89 	io_uring_prep_readv(sqe, fd, &iov, 1, 0);
90 	sqe->rw_flags = RWF_NOWAIT;
91 
92 	ret = io_uring_submit(&ring);
93 	if (ret != 1) {
94 		printf("Got submit %d, expected 1\n", ret);
95 		goto err;
96 	}
97 
98 	ret = io_uring_peek_cqe(&ring, &cqe);
99 	if (ret) {
100 		printf("Ring peek got %d\n", ret);
101 		goto err;
102 	}
103 
104 	if (cqe->res != -EAGAIN && cqe->res != 4096) {
105 		printf("cqe error: %d\n", cqe->res);
106 		goto err;
107 	}
108 
109 	close(fd);
110 	return 0;
111 err:
112 	close(fd);
113 	return 1;
114 }
115