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