tizen 2.4 release
[framework/uifw/xorg/lib/libxshmfence.git] / src / xshmfence_alloc.c
1 /*
2  * Copyright © 2013 Keith Packard
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that copyright
7  * notice and this permission notice appear in supporting documentation, and
8  * that the name of the copyright holders not be used in advertising or
9  * publicity pertaining to distribution of the software without specific,
10  * written prior permission.  The copyright holders make no representations
11  * about the suitability of this software for any purpose.  It is provided "as
12  * is" without express or implied warranty.
13  *
14  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
16  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
18  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
19  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
20  * OF THIS SOFTWARE.
21  */
22
23 #if HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include "xshmfenceint.h"
28
29 /**
30  * xshmfence_alloc_shm:
31  *
32  * Allocates a shared memory object large enough to hold a single
33  * fence.
34  *
35  * Return value: the file descriptor of the object, or -1 on failure
36  * (in which case, errno will be set as appropriate).
37  **/
38 int
39 xshmfence_alloc_shm(void)
40 {
41         char    template[] = SHMDIR "/shmfd-XXXXXX";
42         int     fd;
43
44 #ifdef O_TMPFILE
45         fd = open(SHMDIR, O_TMPFILE|O_RDWR|O_CLOEXEC|O_EXCL, 0666);
46         if (fd < 0)
47 #endif
48         {
49             fd = mkstemp(template);
50             if (fd < 0)
51                 return fd;
52             unlink(template);
53         }
54         ftruncate(fd, sizeof (struct xshmfence));
55         xshmfence_init(fd);
56         return fd;
57 }
58
59 /**
60  * xshmfence_map_shm:
61  *
62  * Map a shared memory fence referenced by @fd.
63  *
64  * Return value: the fence or NULL (in which case, errno will be set
65  * as appropriate).
66  **/
67 struct xshmfence *
68 xshmfence_map_shm(int fd)
69 {
70         struct xshmfence *addr;
71         addr = mmap (NULL, sizeof (struct xshmfence) , PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
72         if (addr == MAP_FAILED) {
73                 close (fd);
74                 return 0;
75         }
76         return addr;
77 }
78
79 /**
80  * xshmfence_unmap_shm:
81  *
82  * Unap a shared memory fence @f.
83  **/
84 void
85 xshmfence_unmap_shm(struct xshmfence *f)
86 {
87         munmap(f, sizeof (struct xshmfence));
88 }