xref: /freebsd/sys/contrib/openzfs/tests/zfs-tests/cmd/mmap_libaio.c (revision 61145dc2b94f12f6a47344fb9aac702321880e43)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2018 Canonical.  All rights reserved.
25  */
26 
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <sys/mman.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <libaio.h>
35 #include <err.h>
36 
37 static io_context_t io_ctx;
38 
39 static void
do_sync_io(struct iocb * iocb)40 do_sync_io(struct iocb *iocb)
41 {
42 	struct io_event event;
43 	struct iocb *iocbs[] = { iocb };
44 	struct timespec ts = { 30, 0 };
45 
46 	if (io_submit(io_ctx, 1, iocbs) != 1)
47 		err(1, "io_submit failed");
48 
49 	if (io_getevents(io_ctx, 0, 1, &event, &ts) != 1)
50 		err(1, "io_getevents failed");
51 }
52 
53 int
main(int argc,char ** argv)54 main(int argc, char **argv)
55 {
56 	(void) argc;
57 	char *buf;
58 	int page_size = getpagesize();
59 	int buf_size = strtol(argv[2], NULL, 0);
60 	int rwfd;
61 	struct iocb iocb;
62 
63 	if (io_queue_init(1024, &io_ctx))
64 		err(1, "io_queue_init failed");
65 
66 	rwfd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
67 	if (rwfd < 0)
68 		err(1, "open failed");
69 
70 	if (ftruncate(rwfd, buf_size) < 0)
71 		err(1, "ftruncate failed");
72 
73 	buf = mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_SHARED, rwfd, 0);
74 	if (buf == MAP_FAILED)
75 		err(1, "mmap failed");
76 
77 	(void) io_prep_pwrite(&iocb, rwfd, buf, buf_size, 0);
78 	do_sync_io(&iocb);
79 
80 	(void) io_prep_pread(&iocb, rwfd, buf, buf_size, 0);
81 	do_sync_io(&iocb);
82 
83 	if (close(rwfd))
84 		err(1, "close failed");
85 
86 	if (io_queue_release(io_ctx) != 0)
87 		err(1, "io_queue_release failed");
88 
89 	return (0);
90 }
91