jpayne@69
|
1 #
|
jpayne@69
|
2 # Module which supports allocation of memory from an mmap
|
jpayne@69
|
3 #
|
jpayne@69
|
4 # multiprocessing/heap.py
|
jpayne@69
|
5 #
|
jpayne@69
|
6 # Copyright (c) 2006-2008, R Oudkerk
|
jpayne@69
|
7 # Licensed to PSF under a Contributor Agreement.
|
jpayne@69
|
8 #
|
jpayne@69
|
9
|
jpayne@69
|
10 import bisect
|
jpayne@69
|
11 from collections import defaultdict
|
jpayne@69
|
12 import mmap
|
jpayne@69
|
13 import os
|
jpayne@69
|
14 import sys
|
jpayne@69
|
15 import tempfile
|
jpayne@69
|
16 import threading
|
jpayne@69
|
17
|
jpayne@69
|
18 from .context import reduction, assert_spawning
|
jpayne@69
|
19 from . import util
|
jpayne@69
|
20
|
jpayne@69
|
21 __all__ = ['BufferWrapper']
|
jpayne@69
|
22
|
jpayne@69
|
23 #
|
jpayne@69
|
24 # Inheritable class which wraps an mmap, and from which blocks can be allocated
|
jpayne@69
|
25 #
|
jpayne@69
|
26
|
jpayne@69
|
27 if sys.platform == 'win32':
|
jpayne@69
|
28
|
jpayne@69
|
29 import _winapi
|
jpayne@69
|
30
|
jpayne@69
|
31 class Arena(object):
|
jpayne@69
|
32 """
|
jpayne@69
|
33 A shared memory area backed by anonymous memory (Windows).
|
jpayne@69
|
34 """
|
jpayne@69
|
35
|
jpayne@69
|
36 _rand = tempfile._RandomNameSequence()
|
jpayne@69
|
37
|
jpayne@69
|
38 def __init__(self, size):
|
jpayne@69
|
39 self.size = size
|
jpayne@69
|
40 for i in range(100):
|
jpayne@69
|
41 name = 'pym-%d-%s' % (os.getpid(), next(self._rand))
|
jpayne@69
|
42 buf = mmap.mmap(-1, size, tagname=name)
|
jpayne@69
|
43 if _winapi.GetLastError() == 0:
|
jpayne@69
|
44 break
|
jpayne@69
|
45 # We have reopened a preexisting mmap.
|
jpayne@69
|
46 buf.close()
|
jpayne@69
|
47 else:
|
jpayne@69
|
48 raise FileExistsError('Cannot find name for new mmap')
|
jpayne@69
|
49 self.name = name
|
jpayne@69
|
50 self.buffer = buf
|
jpayne@69
|
51 self._state = (self.size, self.name)
|
jpayne@69
|
52
|
jpayne@69
|
53 def __getstate__(self):
|
jpayne@69
|
54 assert_spawning(self)
|
jpayne@69
|
55 return self._state
|
jpayne@69
|
56
|
jpayne@69
|
57 def __setstate__(self, state):
|
jpayne@69
|
58 self.size, self.name = self._state = state
|
jpayne@69
|
59 # Reopen existing mmap
|
jpayne@69
|
60 self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
|
jpayne@69
|
61 # XXX Temporarily preventing buildbot failures while determining
|
jpayne@69
|
62 # XXX the correct long-term fix. See issue 23060
|
jpayne@69
|
63 #assert _winapi.GetLastError() == _winapi.ERROR_ALREADY_EXISTS
|
jpayne@69
|
64
|
jpayne@69
|
65 else:
|
jpayne@69
|
66
|
jpayne@69
|
67 class Arena(object):
|
jpayne@69
|
68 """
|
jpayne@69
|
69 A shared memory area backed by a temporary file (POSIX).
|
jpayne@69
|
70 """
|
jpayne@69
|
71
|
jpayne@69
|
72 if sys.platform == 'linux':
|
jpayne@69
|
73 _dir_candidates = ['/dev/shm']
|
jpayne@69
|
74 else:
|
jpayne@69
|
75 _dir_candidates = []
|
jpayne@69
|
76
|
jpayne@69
|
77 def __init__(self, size, fd=-1):
|
jpayne@69
|
78 self.size = size
|
jpayne@69
|
79 self.fd = fd
|
jpayne@69
|
80 if fd == -1:
|
jpayne@69
|
81 # Arena is created anew (if fd != -1, it means we're coming
|
jpayne@69
|
82 # from rebuild_arena() below)
|
jpayne@69
|
83 self.fd, name = tempfile.mkstemp(
|
jpayne@69
|
84 prefix='pym-%d-'%os.getpid(),
|
jpayne@69
|
85 dir=self._choose_dir(size))
|
jpayne@69
|
86 os.unlink(name)
|
jpayne@69
|
87 util.Finalize(self, os.close, (self.fd,))
|
jpayne@69
|
88 os.ftruncate(self.fd, size)
|
jpayne@69
|
89 self.buffer = mmap.mmap(self.fd, self.size)
|
jpayne@69
|
90
|
jpayne@69
|
91 def _choose_dir(self, size):
|
jpayne@69
|
92 # Choose a non-storage backed directory if possible,
|
jpayne@69
|
93 # to improve performance
|
jpayne@69
|
94 for d in self._dir_candidates:
|
jpayne@69
|
95 st = os.statvfs(d)
|
jpayne@69
|
96 if st.f_bavail * st.f_frsize >= size: # enough free space?
|
jpayne@69
|
97 return d
|
jpayne@69
|
98 return util.get_temp_dir()
|
jpayne@69
|
99
|
jpayne@69
|
100 def reduce_arena(a):
|
jpayne@69
|
101 if a.fd == -1:
|
jpayne@69
|
102 raise ValueError('Arena is unpicklable because '
|
jpayne@69
|
103 'forking was enabled when it was created')
|
jpayne@69
|
104 return rebuild_arena, (a.size, reduction.DupFd(a.fd))
|
jpayne@69
|
105
|
jpayne@69
|
106 def rebuild_arena(size, dupfd):
|
jpayne@69
|
107 return Arena(size, dupfd.detach())
|
jpayne@69
|
108
|
jpayne@69
|
109 reduction.register(Arena, reduce_arena)
|
jpayne@69
|
110
|
jpayne@69
|
111 #
|
jpayne@69
|
112 # Class allowing allocation of chunks of memory from arenas
|
jpayne@69
|
113 #
|
jpayne@69
|
114
|
jpayne@69
|
115 class Heap(object):
|
jpayne@69
|
116
|
jpayne@69
|
117 # Minimum malloc() alignment
|
jpayne@69
|
118 _alignment = 8
|
jpayne@69
|
119
|
jpayne@69
|
120 _DISCARD_FREE_SPACE_LARGER_THAN = 4 * 1024 ** 2 # 4 MB
|
jpayne@69
|
121 _DOUBLE_ARENA_SIZE_UNTIL = 4 * 1024 ** 2
|
jpayne@69
|
122
|
jpayne@69
|
123 def __init__(self, size=mmap.PAGESIZE):
|
jpayne@69
|
124 self._lastpid = os.getpid()
|
jpayne@69
|
125 self._lock = threading.Lock()
|
jpayne@69
|
126 # Current arena allocation size
|
jpayne@69
|
127 self._size = size
|
jpayne@69
|
128 # A sorted list of available block sizes in arenas
|
jpayne@69
|
129 self._lengths = []
|
jpayne@69
|
130
|
jpayne@69
|
131 # Free block management:
|
jpayne@69
|
132 # - map each block size to a list of `(Arena, start, stop)` blocks
|
jpayne@69
|
133 self._len_to_seq = {}
|
jpayne@69
|
134 # - map `(Arena, start)` tuple to the `(Arena, start, stop)` block
|
jpayne@69
|
135 # starting at that offset
|
jpayne@69
|
136 self._start_to_block = {}
|
jpayne@69
|
137 # - map `(Arena, stop)` tuple to the `(Arena, start, stop)` block
|
jpayne@69
|
138 # ending at that offset
|
jpayne@69
|
139 self._stop_to_block = {}
|
jpayne@69
|
140
|
jpayne@69
|
141 # Map arenas to their `(Arena, start, stop)` blocks in use
|
jpayne@69
|
142 self._allocated_blocks = defaultdict(set)
|
jpayne@69
|
143 self._arenas = []
|
jpayne@69
|
144
|
jpayne@69
|
145 # List of pending blocks to free - see comment in free() below
|
jpayne@69
|
146 self._pending_free_blocks = []
|
jpayne@69
|
147
|
jpayne@69
|
148 # Statistics
|
jpayne@69
|
149 self._n_mallocs = 0
|
jpayne@69
|
150 self._n_frees = 0
|
jpayne@69
|
151
|
jpayne@69
|
152 @staticmethod
|
jpayne@69
|
153 def _roundup(n, alignment):
|
jpayne@69
|
154 # alignment must be a power of 2
|
jpayne@69
|
155 mask = alignment - 1
|
jpayne@69
|
156 return (n + mask) & ~mask
|
jpayne@69
|
157
|
jpayne@69
|
158 def _new_arena(self, size):
|
jpayne@69
|
159 # Create a new arena with at least the given *size*
|
jpayne@69
|
160 length = self._roundup(max(self._size, size), mmap.PAGESIZE)
|
jpayne@69
|
161 # We carve larger and larger arenas, for efficiency, until we
|
jpayne@69
|
162 # reach a large-ish size (roughly L3 cache-sized)
|
jpayne@69
|
163 if self._size < self._DOUBLE_ARENA_SIZE_UNTIL:
|
jpayne@69
|
164 self._size *= 2
|
jpayne@69
|
165 util.info('allocating a new mmap of length %d', length)
|
jpayne@69
|
166 arena = Arena(length)
|
jpayne@69
|
167 self._arenas.append(arena)
|
jpayne@69
|
168 return (arena, 0, length)
|
jpayne@69
|
169
|
jpayne@69
|
170 def _discard_arena(self, arena):
|
jpayne@69
|
171 # Possibly delete the given (unused) arena
|
jpayne@69
|
172 length = arena.size
|
jpayne@69
|
173 # Reusing an existing arena is faster than creating a new one, so
|
jpayne@69
|
174 # we only reclaim space if it's large enough.
|
jpayne@69
|
175 if length < self._DISCARD_FREE_SPACE_LARGER_THAN:
|
jpayne@69
|
176 return
|
jpayne@69
|
177 blocks = self._allocated_blocks.pop(arena)
|
jpayne@69
|
178 assert not blocks
|
jpayne@69
|
179 del self._start_to_block[(arena, 0)]
|
jpayne@69
|
180 del self._stop_to_block[(arena, length)]
|
jpayne@69
|
181 self._arenas.remove(arena)
|
jpayne@69
|
182 seq = self._len_to_seq[length]
|
jpayne@69
|
183 seq.remove((arena, 0, length))
|
jpayne@69
|
184 if not seq:
|
jpayne@69
|
185 del self._len_to_seq[length]
|
jpayne@69
|
186 self._lengths.remove(length)
|
jpayne@69
|
187
|
jpayne@69
|
188 def _malloc(self, size):
|
jpayne@69
|
189 # returns a large enough block -- it might be much larger
|
jpayne@69
|
190 i = bisect.bisect_left(self._lengths, size)
|
jpayne@69
|
191 if i == len(self._lengths):
|
jpayne@69
|
192 return self._new_arena(size)
|
jpayne@69
|
193 else:
|
jpayne@69
|
194 length = self._lengths[i]
|
jpayne@69
|
195 seq = self._len_to_seq[length]
|
jpayne@69
|
196 block = seq.pop()
|
jpayne@69
|
197 if not seq:
|
jpayne@69
|
198 del self._len_to_seq[length], self._lengths[i]
|
jpayne@69
|
199
|
jpayne@69
|
200 (arena, start, stop) = block
|
jpayne@69
|
201 del self._start_to_block[(arena, start)]
|
jpayne@69
|
202 del self._stop_to_block[(arena, stop)]
|
jpayne@69
|
203 return block
|
jpayne@69
|
204
|
jpayne@69
|
205 def _add_free_block(self, block):
|
jpayne@69
|
206 # make block available and try to merge with its neighbours in the arena
|
jpayne@69
|
207 (arena, start, stop) = block
|
jpayne@69
|
208
|
jpayne@69
|
209 try:
|
jpayne@69
|
210 prev_block = self._stop_to_block[(arena, start)]
|
jpayne@69
|
211 except KeyError:
|
jpayne@69
|
212 pass
|
jpayne@69
|
213 else:
|
jpayne@69
|
214 start, _ = self._absorb(prev_block)
|
jpayne@69
|
215
|
jpayne@69
|
216 try:
|
jpayne@69
|
217 next_block = self._start_to_block[(arena, stop)]
|
jpayne@69
|
218 except KeyError:
|
jpayne@69
|
219 pass
|
jpayne@69
|
220 else:
|
jpayne@69
|
221 _, stop = self._absorb(next_block)
|
jpayne@69
|
222
|
jpayne@69
|
223 block = (arena, start, stop)
|
jpayne@69
|
224 length = stop - start
|
jpayne@69
|
225
|
jpayne@69
|
226 try:
|
jpayne@69
|
227 self._len_to_seq[length].append(block)
|
jpayne@69
|
228 except KeyError:
|
jpayne@69
|
229 self._len_to_seq[length] = [block]
|
jpayne@69
|
230 bisect.insort(self._lengths, length)
|
jpayne@69
|
231
|
jpayne@69
|
232 self._start_to_block[(arena, start)] = block
|
jpayne@69
|
233 self._stop_to_block[(arena, stop)] = block
|
jpayne@69
|
234
|
jpayne@69
|
235 def _absorb(self, block):
|
jpayne@69
|
236 # deregister this block so it can be merged with a neighbour
|
jpayne@69
|
237 (arena, start, stop) = block
|
jpayne@69
|
238 del self._start_to_block[(arena, start)]
|
jpayne@69
|
239 del self._stop_to_block[(arena, stop)]
|
jpayne@69
|
240
|
jpayne@69
|
241 length = stop - start
|
jpayne@69
|
242 seq = self._len_to_seq[length]
|
jpayne@69
|
243 seq.remove(block)
|
jpayne@69
|
244 if not seq:
|
jpayne@69
|
245 del self._len_to_seq[length]
|
jpayne@69
|
246 self._lengths.remove(length)
|
jpayne@69
|
247
|
jpayne@69
|
248 return start, stop
|
jpayne@69
|
249
|
jpayne@69
|
250 def _remove_allocated_block(self, block):
|
jpayne@69
|
251 arena, start, stop = block
|
jpayne@69
|
252 blocks = self._allocated_blocks[arena]
|
jpayne@69
|
253 blocks.remove((start, stop))
|
jpayne@69
|
254 if not blocks:
|
jpayne@69
|
255 # Arena is entirely free, discard it from this process
|
jpayne@69
|
256 self._discard_arena(arena)
|
jpayne@69
|
257
|
jpayne@69
|
258 def _free_pending_blocks(self):
|
jpayne@69
|
259 # Free all the blocks in the pending list - called with the lock held.
|
jpayne@69
|
260 while True:
|
jpayne@69
|
261 try:
|
jpayne@69
|
262 block = self._pending_free_blocks.pop()
|
jpayne@69
|
263 except IndexError:
|
jpayne@69
|
264 break
|
jpayne@69
|
265 self._add_free_block(block)
|
jpayne@69
|
266 self._remove_allocated_block(block)
|
jpayne@69
|
267
|
jpayne@69
|
268 def free(self, block):
|
jpayne@69
|
269 # free a block returned by malloc()
|
jpayne@69
|
270 # Since free() can be called asynchronously by the GC, it could happen
|
jpayne@69
|
271 # that it's called while self._lock is held: in that case,
|
jpayne@69
|
272 # self._lock.acquire() would deadlock (issue #12352). To avoid that, a
|
jpayne@69
|
273 # trylock is used instead, and if the lock can't be acquired
|
jpayne@69
|
274 # immediately, the block is added to a list of blocks to be freed
|
jpayne@69
|
275 # synchronously sometimes later from malloc() or free(), by calling
|
jpayne@69
|
276 # _free_pending_blocks() (appending and retrieving from a list is not
|
jpayne@69
|
277 # strictly thread-safe but under CPython it's atomic thanks to the GIL).
|
jpayne@69
|
278 if os.getpid() != self._lastpid:
|
jpayne@69
|
279 raise ValueError(
|
jpayne@69
|
280 "My pid ({0:n}) is not last pid {1:n}".format(
|
jpayne@69
|
281 os.getpid(),self._lastpid))
|
jpayne@69
|
282 if not self._lock.acquire(False):
|
jpayne@69
|
283 # can't acquire the lock right now, add the block to the list of
|
jpayne@69
|
284 # pending blocks to free
|
jpayne@69
|
285 self._pending_free_blocks.append(block)
|
jpayne@69
|
286 else:
|
jpayne@69
|
287 # we hold the lock
|
jpayne@69
|
288 try:
|
jpayne@69
|
289 self._n_frees += 1
|
jpayne@69
|
290 self._free_pending_blocks()
|
jpayne@69
|
291 self._add_free_block(block)
|
jpayne@69
|
292 self._remove_allocated_block(block)
|
jpayne@69
|
293 finally:
|
jpayne@69
|
294 self._lock.release()
|
jpayne@69
|
295
|
jpayne@69
|
296 def malloc(self, size):
|
jpayne@69
|
297 # return a block of right size (possibly rounded up)
|
jpayne@69
|
298 if size < 0:
|
jpayne@69
|
299 raise ValueError("Size {0:n} out of range".format(size))
|
jpayne@69
|
300 if sys.maxsize <= size:
|
jpayne@69
|
301 raise OverflowError("Size {0:n} too large".format(size))
|
jpayne@69
|
302 if os.getpid() != self._lastpid:
|
jpayne@69
|
303 self.__init__() # reinitialize after fork
|
jpayne@69
|
304 with self._lock:
|
jpayne@69
|
305 self._n_mallocs += 1
|
jpayne@69
|
306 # allow pending blocks to be marked available
|
jpayne@69
|
307 self._free_pending_blocks()
|
jpayne@69
|
308 size = self._roundup(max(size, 1), self._alignment)
|
jpayne@69
|
309 (arena, start, stop) = self._malloc(size)
|
jpayne@69
|
310 real_stop = start + size
|
jpayne@69
|
311 if real_stop < stop:
|
jpayne@69
|
312 # if the returned block is larger than necessary, mark
|
jpayne@69
|
313 # the remainder available
|
jpayne@69
|
314 self._add_free_block((arena, real_stop, stop))
|
jpayne@69
|
315 self._allocated_blocks[arena].add((start, real_stop))
|
jpayne@69
|
316 return (arena, start, real_stop)
|
jpayne@69
|
317
|
jpayne@69
|
318 #
|
jpayne@69
|
319 # Class wrapping a block allocated out of a Heap -- can be inherited by child process
|
jpayne@69
|
320 #
|
jpayne@69
|
321
|
jpayne@69
|
322 class BufferWrapper(object):
|
jpayne@69
|
323
|
jpayne@69
|
324 _heap = Heap()
|
jpayne@69
|
325
|
jpayne@69
|
326 def __init__(self, size):
|
jpayne@69
|
327 if size < 0:
|
jpayne@69
|
328 raise ValueError("Size {0:n} out of range".format(size))
|
jpayne@69
|
329 if sys.maxsize <= size:
|
jpayne@69
|
330 raise OverflowError("Size {0:n} too large".format(size))
|
jpayne@69
|
331 block = BufferWrapper._heap.malloc(size)
|
jpayne@69
|
332 self._state = (block, size)
|
jpayne@69
|
333 util.Finalize(self, BufferWrapper._heap.free, args=(block,))
|
jpayne@69
|
334
|
jpayne@69
|
335 def create_memoryview(self):
|
jpayne@69
|
336 (arena, start, stop), size = self._state
|
jpayne@69
|
337 return memoryview(arena.buffer)[start:start+size]
|