blob: 333b3baf20f43b5d88b4c9b67a790dd2c5a4ff2c [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# Module which supports allocation of memory from an mmap
3#
4# multiprocessing/heap.py
5#
R. David Murrayd3820662010-12-14 01:41:07 +00006# Copyright (c) 2006-2008, R Oudkerk
Richard Oudkerk3e268aa2012-04-30 12:13:55 +01007# Licensed to PSF under a Contributor Agreement.
Benjamin Petersone711caf2008-06-11 16:44:04 +00008#
9
10import bisect
11import mmap
Benjamin Petersone711caf2008-06-11 16:44:04 +000012import os
13import sys
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010014import tempfile
Benjamin Petersone711caf2008-06-11 16:44:04 +000015import threading
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010016
Richard Oudkerkb1694cf2013-10-16 16:41:56 +010017from . import context
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010018from . import reduction
19from . import util
Benjamin Petersone711caf2008-06-11 16:44:04 +000020
21__all__ = ['BufferWrapper']
22
23#
Eli Bendersky25f043b2013-07-30 06:12:49 -070024# Inheritable class which wraps an mmap, and from which blocks can be allocated
Benjamin Petersone711caf2008-06-11 16:44:04 +000025#
26
27if sys.platform == 'win32':
28
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020029 import _winapi
Benjamin Petersone711caf2008-06-11 16:44:04 +000030
31 class Arena(object):
32
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010033 _rand = tempfile._RandomNameSequence()
Benjamin Petersone711caf2008-06-11 16:44:04 +000034
35 def __init__(self, size):
36 self.size = size
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010037 for i in range(100):
38 name = 'pym-%d-%s' % (os.getpid(), next(self._rand))
39 buf = mmap.mmap(-1, size, tagname=name)
40 if _winapi.GetLastError() == 0:
41 break
42 # We have reopened a preexisting mmap.
43 buf.close()
44 else:
45 raise FileExistsError('Cannot find name for new mmap')
46 self.name = name
47 self.buffer = buf
Benjamin Petersone711caf2008-06-11 16:44:04 +000048 self._state = (self.size, self.name)
49
50 def __getstate__(self):
Richard Oudkerkb1694cf2013-10-16 16:41:56 +010051 context.assert_spawning(self)
Benjamin Petersone711caf2008-06-11 16:44:04 +000052 return self._state
53
54 def __setstate__(self, state):
55 self.size, self.name = self._state = state
56 self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
Steve Dower438f4ab2014-12-17 06:35:49 -080057 # XXX Temporarily preventing buildbot failures while determining
58 # XXX the correct long-term fix. See issue 23060
59 #assert _winapi.GetLastError() == _winapi.ERROR_ALREADY_EXISTS
Benjamin Petersone711caf2008-06-11 16:44:04 +000060
61else:
62
63 class Arena(object):
64
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010065 def __init__(self, size, fd=-1):
Benjamin Petersone711caf2008-06-11 16:44:04 +000066 self.size = size
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010067 self.fd = fd
68 if fd == -1:
69 self.fd, name = tempfile.mkstemp(
70 prefix='pym-%d-'%os.getpid(), dir=util.get_temp_dir())
71 os.unlink(name)
72 util.Finalize(self, os.close, (self.fd,))
73 with open(self.fd, 'wb', closefd=False) as f:
74 f.write(b'\0'*size)
75 self.buffer = mmap.mmap(self.fd, self.size)
76
77 def reduce_arena(a):
78 if a.fd == -1:
79 raise ValueError('Arena is unpicklable because '
80 'forking was enabled when it was created')
81 return rebuild_arena, (a.size, reduction.DupFd(a.fd))
82
83 def rebuild_arena(size, dupfd):
84 return Arena(size, dupfd.detach())
85
86 reduction.register(Arena, reduce_arena)
Benjamin Petersone711caf2008-06-11 16:44:04 +000087
88#
89# Class allowing allocation of chunks of memory from arenas
90#
91
92class Heap(object):
93
94 _alignment = 8
95
96 def __init__(self, size=mmap.PAGESIZE):
97 self._lastpid = os.getpid()
98 self._lock = threading.Lock()
99 self._size = size
100 self._lengths = []
101 self._len_to_seq = {}
102 self._start_to_block = {}
103 self._stop_to_block = {}
104 self._allocated_blocks = set()
105 self._arenas = []
Charles-François Natali778db492011-07-02 14:35:49 +0200106 # list of pending blocks to free - see free() comment below
107 self._pending_free_blocks = []
Benjamin Petersone711caf2008-06-11 16:44:04 +0000108
109 @staticmethod
110 def _roundup(n, alignment):
111 # alignment must be a power of 2
112 mask = alignment - 1
113 return (n + mask) & ~mask
114
115 def _malloc(self, size):
116 # returns a large enough block -- it might be much larger
117 i = bisect.bisect_left(self._lengths, size)
118 if i == len(self._lengths):
119 length = self._roundup(max(self._size, size), mmap.PAGESIZE)
120 self._size *= 2
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100121 util.info('allocating a new mmap of length %d', length)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000122 arena = Arena(length)
123 self._arenas.append(arena)
124 return (arena, 0, length)
125 else:
126 length = self._lengths[i]
127 seq = self._len_to_seq[length]
128 block = seq.pop()
129 if not seq:
130 del self._len_to_seq[length], self._lengths[i]
131
132 (arena, start, stop) = block
133 del self._start_to_block[(arena, start)]
134 del self._stop_to_block[(arena, stop)]
135 return block
136
137 def _free(self, block):
138 # free location and try to merge with neighbours
139 (arena, start, stop) = block
140
141 try:
142 prev_block = self._stop_to_block[(arena, start)]
143 except KeyError:
144 pass
145 else:
146 start, _ = self._absorb(prev_block)
147
148 try:
149 next_block = self._start_to_block[(arena, stop)]
150 except KeyError:
151 pass
152 else:
153 _, stop = self._absorb(next_block)
154
155 block = (arena, start, stop)
156 length = stop - start
157
158 try:
159 self._len_to_seq[length].append(block)
160 except KeyError:
161 self._len_to_seq[length] = [block]
162 bisect.insort(self._lengths, length)
163
164 self._start_to_block[(arena, start)] = block
165 self._stop_to_block[(arena, stop)] = block
166
167 def _absorb(self, block):
168 # deregister this block so it can be merged with a neighbour
169 (arena, start, stop) = block
170 del self._start_to_block[(arena, start)]
171 del self._stop_to_block[(arena, stop)]
172
173 length = stop - start
174 seq = self._len_to_seq[length]
175 seq.remove(block)
176 if not seq:
177 del self._len_to_seq[length]
178 self._lengths.remove(length)
179
180 return start, stop
181
Charles-François Natali778db492011-07-02 14:35:49 +0200182 def _free_pending_blocks(self):
183 # Free all the blocks in the pending list - called with the lock held.
184 while True:
185 try:
186 block = self._pending_free_blocks.pop()
187 except IndexError:
188 break
Benjamin Petersone711caf2008-06-11 16:44:04 +0000189 self._allocated_blocks.remove(block)
190 self._free(block)
Charles-François Natali778db492011-07-02 14:35:49 +0200191
192 def free(self, block):
193 # free a block returned by malloc()
194 # Since free() can be called asynchronously by the GC, it could happen
195 # that it's called while self._lock is held: in that case,
196 # self._lock.acquire() would deadlock (issue #12352). To avoid that, a
197 # trylock is used instead, and if the lock can't be acquired
198 # immediately, the block is added to a list of blocks to be freed
199 # synchronously sometimes later from malloc() or free(), by calling
200 # _free_pending_blocks() (appending and retrieving from a list is not
201 # strictly thread-safe but under cPython it's atomic thanks to the GIL).
202 assert os.getpid() == self._lastpid
203 if not self._lock.acquire(False):
204 # can't acquire the lock right now, add the block to the list of
205 # pending blocks to free
206 self._pending_free_blocks.append(block)
207 else:
208 # we hold the lock
209 try:
210 self._free_pending_blocks()
211 self._allocated_blocks.remove(block)
212 self._free(block)
213 finally:
214 self._lock.release()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000215
216 def malloc(self, size):
217 # return a block of right size (possibly rounded up)
218 assert 0 <= size < sys.maxsize
219 if os.getpid() != self._lastpid:
220 self.__init__() # reinitialize after fork
Charles-François Natalia924fc72014-05-25 14:12:12 +0100221 with self._lock:
222 self._free_pending_blocks()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000223 size = self._roundup(max(size,1), self._alignment)
224 (arena, start, stop) = self._malloc(size)
225 new_stop = start + size
226 if new_stop < stop:
227 self._free((arena, new_stop, stop))
228 block = (arena, start, new_stop)
229 self._allocated_blocks.add(block)
230 return block
Benjamin Petersone711caf2008-06-11 16:44:04 +0000231
232#
Richard Oudkerk26cdf1f2012-05-26 22:09:59 +0100233# Class representing a chunk of an mmap -- can be inherited by child process
Benjamin Petersone711caf2008-06-11 16:44:04 +0000234#
235
236class BufferWrapper(object):
237
238 _heap = Heap()
239
240 def __init__(self, size):
241 assert 0 <= size < sys.maxsize
242 block = BufferWrapper._heap.malloc(size)
243 self._state = (block, size)
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100244 util.Finalize(self, BufferWrapper._heap.free, args=(block,))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000245
Richard Oudkerk26cdf1f2012-05-26 22:09:59 +0100246 def create_memoryview(self):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000247 (arena, start, stop), size = self._state
Richard Oudkerk26cdf1f2012-05-26 22:09:59 +0100248 return memoryview(arena.buffer)[start:start+size]