1 /* Memory allocation aligned to system page boundaries.
2 
3    Copyright (C) 2005 Free Software Foundation, Inc.
4 
5    This program is free software; you can redistribute it and/or modify it
6    under the terms of the GNU General Public License as published
7    by the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14 
15    You should have received a copy of the GNU General Public
16    License along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
18    USA.  */
19 
20 /* Written by Derek R. Price <derek@ximbiot.com>.  */
21 
22 #ifdef HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25 
26 #include "pagealign_alloc.h"
27 
28 #include <errno.h>
29 #include <stdlib.h>
30 
31 #include <fcntl.h>
32 
33 #if HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36 
37 #if HAVE_MMAP
38 # include <sys/mman.h>
39 #endif
40 
41 #include "error.h"
42 #include "exit.h"
43 #include "getpagesize.h"
44 #include "xalloc.h"
45 #include "gettext.h"
46 
47 #if HAVE_MMAP && !defined(HAVE_MAP_ANONYMOUS)
48 #include <stdio.h>
49 #endif
50 
51 __RCSID("$MirOS: src/gnu/usr.bin/cvs/lib/pagealign_alloc.c,v 1.5 2010/09/19 19:42:59 tg Exp $");
52 
53 #define _(str) gettext (str)
54 
55 #if HAVE_MMAP
56 /* Define MAP_FILE when it isn't otherwise.  */
57 # ifndef MAP_FILE
58 #  define MAP_FILE 0
59 # endif
60 /* Define MAP_FAILED for old systems which neglect to.  */
61 # ifndef MAP_FAILED
62 #  define MAP_FAILED ((void *)-1)
63 # endif
64 #endif
65 
66 
67 #if HAVE_MMAP || ! HAVE_POSIX_MEMALIGN
68 
69 # if HAVE_MMAP
70 /* For each memory region, we store its size.  */
71 typedef size_t info_t;
72 # else
73 /* For each memory region, we store the original pointer returned by
74    malloc().  */
75 typedef void * info_t;
76 # endif
77 
78 /* A simple linked list of allocated memory regions.  It is probably not the
79    most efficient way to store these, but anyway...  */
80 typedef struct memnode_s memnode_t;
81 struct memnode_s
82 {
83   void *aligned_ptr;
84   info_t info;
85   memnode_t *next;
86 };
87 
88 /* The list of currently allocated memory regions.  */
89 static memnode_t *memnode_table = NULL;
90 
91 
92 static void
new_memnode(void * aligned_ptr,info_t info)93 new_memnode (void *aligned_ptr, info_t info)
94 {
95   memnode_t *new_node = (memnode_t *) xmalloc (sizeof (memnode_t));
96   new_node->aligned_ptr = aligned_ptr;
97   new_node->info = info;
98   new_node->next = memnode_table;
99   memnode_table = new_node;
100 }
101 
102 
103 /* Dispose of the memnode containing a map for the ALIGNED_PTR in question
104    and return the content of the node's INFO field.  */
105 static info_t
get_memnode(void * aligned_ptr)106 get_memnode (void *aligned_ptr)
107 {
108   info_t ret;
109   memnode_t *c;
110   memnode_t **p_next = &memnode_table;
111 
112   for (c = *p_next; c != NULL; p_next = &c->next, c = c->next)
113     if (c->aligned_ptr == aligned_ptr)
114       break;
115 
116   if (c == NULL)
117     /* An attempt to free untracked memory.  A wrong pointer was passed
118        to pagealign_free().  */
119     abort ();
120 
121   /* Remove this entry from the list, save the return value, and free it.  */
122   *p_next = c->next;
123   ret = c->info;
124   free (c);
125 
126   return ret;
127 }
128 
129 #endif /* HAVE_MMAP || !HAVE_POSIX_MEMALIGN */
130 
131 
132 void *
pagealign_alloc(size_t size)133 pagealign_alloc (size_t size)
134 {
135   void *ret;
136 #if HAVE_MMAP
137 # ifdef HAVE_MAP_ANONYMOUS
138   const int fd = -1;
139   const int flags = MAP_ANONYMOUS | MAP_PRIVATE;
140 # else /* !HAVE_MAP_ANONYMOUS */
141   static int beenhere = 0;
142   static int fd = -1;  /* Only open /dev/zero once in order to avoid limiting
143 			  the amount of memory we may allocate based on the
144 			  number of open file descriptors.  */
145   const int flags = MAP_FILE | MAP_PRIVATE;
146   if (fd == -1)
147     {
148       fd = open ("/dev/zero", O_RDONLY, 0666);
149       if (fd < 0)
150 	{
151 	  if (!beenhere)
152 	    {
153 	      beenhere = 1;
154 	      error (EXIT_FAILURE, errno, _("Failed to open /dev/zero for read"));
155 	    }
156 	  else
157 	    {
158 	      fprintf (stderr, "Fatal in pagealign: %s\n",
159 			_("Failed to open /dev/zero for read"));
160 	      fflush (stderr);
161 	      _exit (EXIT_FAILURE);
162 	    }
163 	}
164     }
165 # endif /* HAVE_MAP_ANONYMOUS */
166   ret = mmap (NULL, size, PROT_READ | PROT_WRITE, flags, fd, 0);
167   if (ret == MAP_FAILED)
168     return NULL;
169   new_memnode (ret, size);
170 #elif HAVE_POSIX_MEMALIGN
171   int status = posix_memalign (&ret, getpagesize (), size);
172   if (status)
173     {
174       errno = status;
175       return NULL;
176     }
177 #else /* !HAVE_MMAP && !HAVE_POSIX_MEMALIGN */
178   size_t pagesize = getpagesize ();
179   void *unaligned_ptr = malloc (size + pagesize - 1);
180   if (unaligned_ptr == NULL)
181     {
182       /* Set errno.  We don't know whether malloc already set errno: some
183 	 implementations of malloc do, some don't.  */
184       errno = ENOMEM;
185       return NULL;
186     }
187   ret = (char *) unaligned_ptr
188         + ((- (unsigned long) unaligned_ptr) & (pagesize - 1));
189   new_memnode (ret, unaligned_ptr);
190 #endif /* HAVE_MMAP && HAVE_POSIX_MEMALIGN */
191   return ret;
192 }
193 
194 
195 void *
pagealign_xalloc(size_t size)196 pagealign_xalloc (size_t size)
197 {
198   void *ret;
199 
200   ret = pagealign_alloc (size);
201   if (ret == NULL)
202     xalloc_die ();
203   return ret;
204 }
205 
206 
207 void
pagealign_free(void * aligned_ptr)208 pagealign_free (void *aligned_ptr)
209 {
210 #if HAVE_MMAP
211   if (munmap (aligned_ptr, get_memnode (aligned_ptr)) < 0)
212     error (EXIT_FAILURE, errno, "Failed to unmap memory");
213 #elif HAVE_POSIX_MEMALIGN
214   free (aligned_ptr);
215 #else
216   free (get_memnode (aligned_ptr));
217 #endif
218 }
219