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