1 /* SPDX-License-Identifier: MIT */
2 /*
3 * Description: Helpers for tests.
4 */
5 #include <stdlib.h>
6 #include <assert.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <sys/types.h>
12
13 #include "helpers.h"
14 #include "liburing.h"
15
16 /*
17 * Helper for allocating memory in tests.
18 */
t_malloc(size_t size)19 void *t_malloc(size_t size)
20 {
21 void *ret;
22 ret = malloc(size);
23 assert(ret);
24 return ret;
25 }
26
27 /*
28 * Helper for allocating size bytes aligned on a boundary.
29 */
t_posix_memalign(void ** memptr,size_t alignment,size_t size)30 void t_posix_memalign(void **memptr, size_t alignment, size_t size)
31 {
32 int ret;
33 ret = posix_memalign(memptr, alignment, size);
34 assert(!ret);
35 }
36
37 /*
38 * Helper for allocating space for an array of nmemb elements
39 * with size bytes for each element.
40 */
t_calloc(size_t nmemb,size_t size)41 void *t_calloc(size_t nmemb, size_t size)
42 {
43 void *ret;
44 ret = calloc(nmemb, size);
45 assert(ret);
46 return ret;
47 }
48
49 /*
50 * Helper for creating file and write @size byte buf with 0xaa value in the file.
51 */
t_create_file(const char * file,size_t size)52 void t_create_file(const char *file, size_t size)
53 {
54 ssize_t ret;
55 char *buf;
56 int fd;
57
58 buf = t_malloc(size);
59 memset(buf, 0xaa, size);
60
61 fd = open(file, O_WRONLY | O_CREAT, 0644);
62 assert(fd >= 0);
63
64 ret = write(fd, buf, size);
65 fsync(fd);
66 close(fd);
67 free(buf);
68 assert(ret == size);
69 }
70
71 /*
72 * Helper for creating @buf_num number of iovec
73 * with @buf_size bytes buffer of each iovec.
74 */
t_create_buffers(size_t buf_num,size_t buf_size)75 struct iovec *t_create_buffers(size_t buf_num, size_t buf_size)
76 {
77 struct iovec *vecs;
78 int i;
79
80 vecs = t_malloc(buf_num * sizeof(struct iovec));
81 for (i = 0; i < buf_num; i++) {
82 t_posix_memalign(&vecs[i].iov_base, buf_size, buf_size);
83 vecs[i].iov_len = buf_size;
84 }
85 return vecs;
86 }
87
88 /*
89 * Helper for setting up an io_uring instance, skipping if the given user isn't
90 * allowed to.
91 */
t_create_ring_params(int depth,struct io_uring * ring,struct io_uring_params * p)92 enum t_setup_ret t_create_ring_params(int depth, struct io_uring *ring,
93 struct io_uring_params *p)
94 {
95 int ret;
96
97 ret = io_uring_queue_init_params(depth, ring, p);
98 if (!ret)
99 return T_SETUP_OK;
100 if ((p->flags & IORING_SETUP_SQPOLL) && ret == -EPERM && geteuid()) {
101 fprintf(stdout, "SQPOLL skipped for regular user\n");
102 return T_SETUP_SKIP;
103 }
104
105 fprintf(stderr, "queue_init: %s\n", strerror(-ret));
106 return ret;
107 }
108
t_create_ring(int depth,struct io_uring * ring,unsigned int flags)109 enum t_setup_ret t_create_ring(int depth, struct io_uring *ring,
110 unsigned int flags)
111 {
112 struct io_uring_params p = { };
113
114 p.flags = flags;
115 return t_create_ring_params(depth, ring, &p);
116 }
117