blob: 44d9638ff6ec4d9d4595d085ab14b7a4065d1c41 [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:
Antoine Pitroud5aec7b2015-04-13 20:53:43 +020074 bs = 1024 * 1024
75 if size >= bs:
76 zeros = b'\0' * bs
77 for _ in range(size // bs):
78 f.write(zeros)
79 del zeros
80 f.write(b'\0' * (size % bs))
81 assert f.tell() == size
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010082 self.buffer = mmap.mmap(self.fd, self.size)
83
84 def reduce_arena(a):
85 if a.fd == -1:
86 raise ValueError('Arena is unpicklable because '
87 'forking was enabled when it was created')
88 return rebuild_arena, (a.size, reduction.DupFd(a.fd))
89
90 def rebuild_arena(size, dupfd):
91 return Arena(size, dupfd.detach())
92
93 reduction.register(Arena, reduce_arena)
Benjamin Petersone711caf2008-06-11 16:44:04 +000094
95#
96# Class allowing allocation of chunks of memory from arenas
97#
98
99class Heap(object):
100
101 _alignment = 8
102
103 def __init__(self, size=mmap.PAGESIZE):
104 self._lastpid = os.getpid()
105 self._lock = threading.Lock()
106 self._size = size
107 self._lengths = []
108 self._len_to_seq = {}
109 self._start_to_block = {}
110 self._stop_to_block = {}
111 self._allocated_blocks = set()
112 self._arenas = []
Charles-François Natali778db492011-07-02 14:35:49 +0200113 # list of pending blocks to free - see free() comment below
114 self._pending_free_blocks = []
Benjamin Petersone711caf2008-06-11 16:44:04 +0000115
116 @staticmethod
117 def _roundup(n, alignment):
118 # alignment must be a power of 2
119 mask = alignment - 1
120 return (n + mask) & ~mask
121
122 def _malloc(self, size):
123 # returns a large enough block -- it might be much larger
124 i = bisect.bisect_left(self._lengths, size)
125 if i == len(self._lengths):
126 length = self._roundup(max(self._size, size), mmap.PAGESIZE)
127 self._size *= 2
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100128 util.info('allocating a new mmap of length %d', length)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000129 arena = Arena(length)
130 self._arenas.append(arena)
131 return (arena, 0, length)
132 else:
133 length = self._lengths[i]
134 seq = self._len_to_seq[length]
135 block = seq.pop()
136 if not seq:
137 del self._len_to_seq[length], self._lengths[i]
138
139 (arena, start, stop) = block
140 del self._start_to_block[(arena, start)]
141 del self._stop_to_block[(arena, stop)]
142 return block
143
144 def _free(self, block):
145 # free location and try to merge with neighbours
146 (arena, start, stop) = block
147
148 try:
149 prev_block = self._stop_to_block[(arena, start)]
150 except KeyError:
151 pass
152 else:
153 start, _ = self._absorb(prev_block)
154
155 try:
156 next_block = self._start_to_block[(arena, stop)]
157 except KeyError:
158 pass
159 else:
160 _, stop = self._absorb(next_block)
161
162 block = (arena, start, stop)
163 length = stop - start
164
165 try:
166 self._len_to_seq[length].append(block)
167 except KeyError:
168 self._len_to_seq[length] = [block]
169 bisect.insort(self._lengths, length)
170
171 self._start_to_block[(arena, start)] = block
172 self._stop_to_block[(arena, stop)] = block
173
174 def _absorb(self, block):
175 # deregister this block so it can be merged with a neighbour
176 (arena, start, stop) = block
177 del self._start_to_block[(arena, start)]
178 del self._stop_to_block[(arena, stop)]
179
180 length = stop - start
181 seq = self._len_to_seq[length]
182 seq.remove(block)
183 if not seq:
184 del self._len_to_seq[length]
185 self._lengths.remove(length)
186
187 return start, stop
188
Charles-François Natali778db492011-07-02 14:35:49 +0200189 def _free_pending_blocks(self):
190 # Free all the blocks in the pending list - called with the lock held.
191 while True:
192 try:
193 block = self._pending_free_blocks.pop()
194 except IndexError:
195 break
Benjamin Petersone711caf2008-06-11 16:44:04 +0000196 self._allocated_blocks.remove(block)
197 self._free(block)
Charles-François Natali778db492011-07-02 14:35:49 +0200198
199 def free(self, block):
200 # free a block returned by malloc()
201 # Since free() can be called asynchronously by the GC, it could happen
202 # that it's called while self._lock is held: in that case,
203 # self._lock.acquire() would deadlock (issue #12352). To avoid that, a
204 # trylock is used instead, and if the lock can't be acquired
205 # immediately, the block is added to a list of blocks to be freed
206 # synchronously sometimes later from malloc() or free(), by calling
207 # _free_pending_blocks() (appending and retrieving from a list is not
208 # strictly thread-safe but under cPython it's atomic thanks to the GIL).
209 assert os.getpid() == self._lastpid
210 if not self._lock.acquire(False):
211 # can't acquire the lock right now, add the block to the list of
212 # pending blocks to free
213 self._pending_free_blocks.append(block)
214 else:
215 # we hold the lock
216 try:
217 self._free_pending_blocks()
218 self._allocated_blocks.remove(block)
219 self._free(block)
220 finally:
221 self._lock.release()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000222
223 def malloc(self, size):
224 # return a block of right size (possibly rounded up)
225 assert 0 <= size < sys.maxsize
226 if os.getpid() != self._lastpid:
227 self.__init__() # reinitialize after fork
Charles-François Natalia924fc72014-05-25 14:12:12 +0100228 with self._lock:
229 self._free_pending_blocks()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000230 size = self._roundup(max(size,1), self._alignment)
231 (arena, start, stop) = self._malloc(size)
232 new_stop = start + size
233 if new_stop < stop:
234 self._free((arena, new_stop, stop))
235 block = (arena, start, new_stop)
236 self._allocated_blocks.add(block)
237 return block
Benjamin Petersone711caf2008-06-11 16:44:04 +0000238
239#
Richard Oudkerk26cdf1f2012-05-26 22:09:59 +0100240# Class representing a chunk of an mmap -- can be inherited by child process
Benjamin Petersone711caf2008-06-11 16:44:04 +0000241#
242
243class BufferWrapper(object):
244
245 _heap = Heap()
246
247 def __init__(self, size):
248 assert 0 <= size < sys.maxsize
249 block = BufferWrapper._heap.malloc(size)
250 self._state = (block, size)
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100251 util.Finalize(self, BufferWrapper._heap.free, args=(block,))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000252
Richard Oudkerk26cdf1f2012-05-26 22:09:59 +0100253 def create_memoryview(self):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000254 (arena, start, stop), size = self._state
Richard Oudkerk26cdf1f2012-05-26 22:09:59 +0100255 return memoryview(arena.buffer)[start:start+size]