blob: 98bfdc8ee195282bb912c49574d2d1e8660b0bb2 [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
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010011import itertools
Benjamin Petersone711caf2008-06-11 16:44:04 +000012import mmap
Benjamin Petersone711caf2008-06-11 16:44:04 +000013import os
14import sys
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010015import tempfile
Benjamin Petersone711caf2008-06-11 16:44:04 +000016import threading
Benjamin Petersone711caf2008-06-11 16:44:04 +000017import _multiprocessing
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010018
Richard Oudkerkb1694cf2013-10-16 16:41:56 +010019from . import context
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010020from . import reduction
21from . import util
Benjamin Petersone711caf2008-06-11 16:44:04 +000022
23__all__ = ['BufferWrapper']
24
25#
Eli Bendersky25f043b2013-07-30 06:12:49 -070026# Inheritable class which wraps an mmap, and from which blocks can be allocated
Benjamin Petersone711caf2008-06-11 16:44:04 +000027#
28
29if sys.platform == 'win32':
30
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020031 import _winapi
Benjamin Petersone711caf2008-06-11 16:44:04 +000032
33 class Arena(object):
34
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010035 _rand = tempfile._RandomNameSequence()
Benjamin Petersone711caf2008-06-11 16:44:04 +000036
37 def __init__(self, size):
38 self.size = size
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010039 for i in range(100):
40 name = 'pym-%d-%s' % (os.getpid(), next(self._rand))
41 buf = mmap.mmap(-1, size, tagname=name)
42 if _winapi.GetLastError() == 0:
43 break
44 # We have reopened a preexisting mmap.
45 buf.close()
46 else:
47 raise FileExistsError('Cannot find name for new mmap')
48 self.name = name
49 self.buffer = buf
Benjamin Petersone711caf2008-06-11 16:44:04 +000050 self._state = (self.size, self.name)
51
52 def __getstate__(self):
Richard Oudkerkb1694cf2013-10-16 16:41:56 +010053 context.assert_spawning(self)
Benjamin Petersone711caf2008-06-11 16:44:04 +000054 return self._state
55
56 def __setstate__(self, state):
57 self.size, self.name = self._state = state
58 self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020059 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
221 self._lock.acquire()
Charles-François Natali778db492011-07-02 14:35:49 +0200222 self._free_pending_blocks()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000223 try:
224 size = self._roundup(max(size,1), self._alignment)
225 (arena, start, stop) = self._malloc(size)
226 new_stop = start + size
227 if new_stop < stop:
228 self._free((arena, new_stop, stop))
229 block = (arena, start, new_stop)
230 self._allocated_blocks.add(block)
231 return block
232 finally:
233 self._lock.release()
234
235#
Richard Oudkerk26cdf1f2012-05-26 22:09:59 +0100236# Class representing a chunk of an mmap -- can be inherited by child process
Benjamin Petersone711caf2008-06-11 16:44:04 +0000237#
238
239class BufferWrapper(object):
240
241 _heap = Heap()
242
243 def __init__(self, size):
244 assert 0 <= size < sys.maxsize
245 block = BufferWrapper._heap.malloc(size)
246 self._state = (block, size)
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100247 util.Finalize(self, BufferWrapper._heap.free, args=(block,))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000248
Richard Oudkerk26cdf1f2012-05-26 22:09:59 +0100249 def create_memoryview(self):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000250 (arena, start, stop), size = self._state
Richard Oudkerk26cdf1f2012-05-26 22:09:59 +0100251 return memoryview(arena.buffer)[start:start+size]