xref: /freebsd/tests/sys/cddl/zfs/bin/mmapwrite.c (revision 4928135658a9d0eaee37003df6137ab363fcb0b4)
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 http://www.opensolaris.org/os/licensing.
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  * $FreeBSD$
21  */
22 
23 /*
24  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 #pragma ident	"@(#)mmapwrite.c	1.4	07/05/25 SMI"
29 
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <sys/mman.h>
35 #include <pthread.h>
36 
37 /*
38  * --------------------------------------------------------------------
39  * Bug Id: 5032643
40  *
41  * Simply writing to a file and mmaping that file at the same time can
42  * result in deadlock.  Nothing perverse like writing from the file's
43  * own mapping is required.
44  * --------------------------------------------------------------------
45  */
46 
47 static void *
48 mapper(void *fdp)
49 {
50 	void *addr;
51 	int fd = *(int *)fdp;
52 
53 	if ((addr =
54 	    mmap(0, 8192, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
55 		perror("mmap");
56 		exit(1);
57 	}
58 	for (;;) {
59 		if (mmap(addr, 8192, PROT_READ,
60 		    MAP_SHARED|MAP_FIXED, fd, 0) == MAP_FAILED) {
61 			perror("mmap");
62 			exit(1);
63 		}
64 	}
65 	/* NOTREACHED */
66 	return ((void *)1);
67 }
68 
69 int
70 main(int argc, char **argv)
71 {
72 	int fd;
73 	char buf[BUFSIZ];
74 	pthread_t pt;
75 
76 	if (argc != 2) {
77 		(void) printf("usage: %s <file name>\n", argv[0]);
78 		exit(1);
79 	}
80 
81 	if ((fd = open(argv[1], O_RDWR|O_CREAT|O_TRUNC, 0666)) == -1) {
82 		perror("open");
83 		exit(1);
84 	}
85 
86 	if (pthread_create(&pt, NULL, mapper, &fd) != 0) {
87 		perror("pthread_create");
88 		exit(1);
89 	}
90 	for (;;) {
91 		if (write(fd, buf, sizeof (buf)) == -1) {
92 			perror("write");
93 			exit(1);
94 		}
95 	}
96 
97 	/* NOTREACHED */
98 	return (0);
99 }
100