2008-06-11 13:44:04 -03:00
|
|
|
#
|
|
|
|
# Module which supports allocation of memory from an mmap
|
|
|
|
#
|
|
|
|
# multiprocessing/heap.py
|
|
|
|
#
|
2010-12-13 21:41:07 -04:00
|
|
|
# Copyright (c) 2006-2008, R Oudkerk
|
2012-04-30 08:13:55 -03:00
|
|
|
# Licensed to PSF under a Contributor Agreement.
|
2008-06-11 13:44:04 -03:00
|
|
|
#
|
|
|
|
|
|
|
|
import bisect
|
2018-04-09 12:37:55 -03:00
|
|
|
from collections import defaultdict
|
2008-06-11 13:44:04 -03:00
|
|
|
import mmap
|
|
|
|
import os
|
|
|
|
import sys
|
2013-08-14 11:35:41 -03:00
|
|
|
import tempfile
|
2008-06-11 13:44:04 -03:00
|
|
|
import threading
|
2013-08-14 11:35:41 -03:00
|
|
|
|
2016-09-09 20:03:10 -03:00
|
|
|
from .context import reduction, assert_spawning
|
2013-08-14 11:35:41 -03:00
|
|
|
from . import util
|
2008-06-11 13:44:04 -03:00
|
|
|
|
|
|
|
__all__ = ['BufferWrapper']
|
|
|
|
|
|
|
|
#
|
2013-07-30 10:12:49 -03:00
|
|
|
# Inheritable class which wraps an mmap, and from which blocks can be allocated
|
2008-06-11 13:44:04 -03:00
|
|
|
#
|
|
|
|
|
|
|
|
if sys.platform == 'win32':
|
|
|
|
|
2012-04-18 15:51:15 -03:00
|
|
|
import _winapi
|
2008-06-11 13:44:04 -03:00
|
|
|
|
|
|
|
class Arena(object):
|
2018-04-09 12:37:55 -03:00
|
|
|
"""
|
|
|
|
A shared memory area backed by anonymous memory (Windows).
|
|
|
|
"""
|
2008-06-11 13:44:04 -03:00
|
|
|
|
2013-08-14 11:35:41 -03:00
|
|
|
_rand = tempfile._RandomNameSequence()
|
2008-06-11 13:44:04 -03:00
|
|
|
|
|
|
|
def __init__(self, size):
|
|
|
|
self.size = size
|
2013-08-14 11:35:41 -03:00
|
|
|
for i in range(100):
|
|
|
|
name = 'pym-%d-%s' % (os.getpid(), next(self._rand))
|
|
|
|
buf = mmap.mmap(-1, size, tagname=name)
|
|
|
|
if _winapi.GetLastError() == 0:
|
|
|
|
break
|
|
|
|
# We have reopened a preexisting mmap.
|
|
|
|
buf.close()
|
|
|
|
else:
|
|
|
|
raise FileExistsError('Cannot find name for new mmap')
|
|
|
|
self.name = name
|
|
|
|
self.buffer = buf
|
2008-06-11 13:44:04 -03:00
|
|
|
self._state = (self.size, self.name)
|
|
|
|
|
|
|
|
def __getstate__(self):
|
2016-09-09 20:03:10 -03:00
|
|
|
assert_spawning(self)
|
2008-06-11 13:44:04 -03:00
|
|
|
return self._state
|
|
|
|
|
|
|
|
def __setstate__(self, state):
|
|
|
|
self.size, self.name = self._state = state
|
2018-04-09 12:37:55 -03:00
|
|
|
# Reopen existing mmap
|
2008-06-11 13:44:04 -03:00
|
|
|
self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
|
2014-12-17 10:35:49 -04:00
|
|
|
# XXX Temporarily preventing buildbot failures while determining
|
|
|
|
# XXX the correct long-term fix. See issue 23060
|
|
|
|
#assert _winapi.GetLastError() == _winapi.ERROR_ALREADY_EXISTS
|
2008-06-11 13:44:04 -03:00
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
class Arena(object):
|
2018-04-09 12:37:55 -03:00
|
|
|
"""
|
|
|
|
A shared memory area backed by a temporary file (POSIX).
|
|
|
|
"""
|
|
|
|
|
2017-07-23 08:05:26 -03:00
|
|
|
if sys.platform == 'linux':
|
|
|
|
_dir_candidates = ['/dev/shm']
|
|
|
|
else:
|
|
|
|
_dir_candidates = []
|
2008-06-11 13:44:04 -03:00
|
|
|
|
2013-08-14 11:35:41 -03:00
|
|
|
def __init__(self, size, fd=-1):
|
2008-06-11 13:44:04 -03:00
|
|
|
self.size = size
|
2013-08-14 11:35:41 -03:00
|
|
|
self.fd = fd
|
|
|
|
if fd == -1:
|
2018-04-09 12:37:55 -03:00
|
|
|
# Arena is created anew (if fd != -1, it means we're coming
|
|
|
|
# from rebuild_arena() below)
|
2013-08-14 11:35:41 -03:00
|
|
|
self.fd, name = tempfile.mkstemp(
|
2017-07-23 08:05:26 -03:00
|
|
|
prefix='pym-%d-'%os.getpid(),
|
|
|
|
dir=self._choose_dir(size))
|
2013-08-14 11:35:41 -03:00
|
|
|
os.unlink(name)
|
|
|
|
util.Finalize(self, os.close, (self.fd,))
|
2017-07-23 08:05:26 -03:00
|
|
|
os.ftruncate(self.fd, size)
|
2013-08-14 11:35:41 -03:00
|
|
|
self.buffer = mmap.mmap(self.fd, self.size)
|
|
|
|
|
2017-07-23 08:05:26 -03:00
|
|
|
def _choose_dir(self, size):
|
|
|
|
# Choose a non-storage backed directory if possible,
|
|
|
|
# to improve performance
|
|
|
|
for d in self._dir_candidates:
|
|
|
|
st = os.statvfs(d)
|
|
|
|
if st.f_bavail * st.f_frsize >= size: # enough free space?
|
|
|
|
return d
|
|
|
|
return util.get_temp_dir()
|
|
|
|
|
2013-08-14 11:35:41 -03:00
|
|
|
def reduce_arena(a):
|
|
|
|
if a.fd == -1:
|
|
|
|
raise ValueError('Arena is unpicklable because '
|
|
|
|
'forking was enabled when it was created')
|
|
|
|
return rebuild_arena, (a.size, reduction.DupFd(a.fd))
|
|
|
|
|
|
|
|
def rebuild_arena(size, dupfd):
|
|
|
|
return Arena(size, dupfd.detach())
|
|
|
|
|
|
|
|
reduction.register(Arena, reduce_arena)
|
2008-06-11 13:44:04 -03:00
|
|
|
|
|
|
|
#
|
|
|
|
# Class allowing allocation of chunks of memory from arenas
|
|
|
|
#
|
|
|
|
|
|
|
|
class Heap(object):
|
|
|
|
|
2018-04-09 12:37:55 -03:00
|
|
|
# Minimum malloc() alignment
|
2008-06-11 13:44:04 -03:00
|
|
|
_alignment = 8
|
|
|
|
|
2018-04-09 12:37:55 -03:00
|
|
|
_DISCARD_FREE_SPACE_LARGER_THAN = 4 * 1024 ** 2 # 4 MB
|
|
|
|
_DOUBLE_ARENA_SIZE_UNTIL = 4 * 1024 ** 2
|
|
|
|
|
2008-06-11 13:44:04 -03:00
|
|
|
def __init__(self, size=mmap.PAGESIZE):
|
|
|
|
self._lastpid = os.getpid()
|
|
|
|
self._lock = threading.Lock()
|
2018-04-09 12:37:55 -03:00
|
|
|
# Current arena allocation size
|
2008-06-11 13:44:04 -03:00
|
|
|
self._size = size
|
2018-04-09 12:37:55 -03:00
|
|
|
# A sorted list of available block sizes in arenas
|
2008-06-11 13:44:04 -03:00
|
|
|
self._lengths = []
|
2018-04-09 12:37:55 -03:00
|
|
|
|
|
|
|
# Free block management:
|
|
|
|
# - map each block size to a list of `(Arena, start, stop)` blocks
|
2008-06-11 13:44:04 -03:00
|
|
|
self._len_to_seq = {}
|
2018-04-09 12:37:55 -03:00
|
|
|
# - map `(Arena, start)` tuple to the `(Arena, start, stop)` block
|
|
|
|
# starting at that offset
|
2008-06-11 13:44:04 -03:00
|
|
|
self._start_to_block = {}
|
2018-04-09 12:37:55 -03:00
|
|
|
# - map `(Arena, stop)` tuple to the `(Arena, start, stop)` block
|
|
|
|
# ending at that offset
|
2008-06-11 13:44:04 -03:00
|
|
|
self._stop_to_block = {}
|
2018-04-09 12:37:55 -03:00
|
|
|
|
|
|
|
# Map arenas to their `(Arena, start, stop)` blocks in use
|
|
|
|
self._allocated_blocks = defaultdict(set)
|
2008-06-11 13:44:04 -03:00
|
|
|
self._arenas = []
|
2018-04-09 12:37:55 -03:00
|
|
|
|
|
|
|
# List of pending blocks to free - see comment in free() below
|
2011-07-02 09:35:49 -03:00
|
|
|
self._pending_free_blocks = []
|
2008-06-11 13:44:04 -03:00
|
|
|
|
2018-04-09 12:37:55 -03:00
|
|
|
# Statistics
|
|
|
|
self._n_mallocs = 0
|
|
|
|
self._n_frees = 0
|
|
|
|
|
2008-06-11 13:44:04 -03:00
|
|
|
@staticmethod
|
|
|
|
def _roundup(n, alignment):
|
|
|
|
# alignment must be a power of 2
|
|
|
|
mask = alignment - 1
|
|
|
|
return (n + mask) & ~mask
|
|
|
|
|
2018-04-09 12:37:55 -03:00
|
|
|
def _new_arena(self, size):
|
|
|
|
# Create a new arena with at least the given *size*
|
|
|
|
length = self._roundup(max(self._size, size), mmap.PAGESIZE)
|
|
|
|
# We carve larger and larger arenas, for efficiency, until we
|
|
|
|
# reach a large-ish size (roughly L3 cache-sized)
|
|
|
|
if self._size < self._DOUBLE_ARENA_SIZE_UNTIL:
|
|
|
|
self._size *= 2
|
|
|
|
util.info('allocating a new mmap of length %d', length)
|
|
|
|
arena = Arena(length)
|
|
|
|
self._arenas.append(arena)
|
|
|
|
return (arena, 0, length)
|
|
|
|
|
|
|
|
def _discard_arena(self, arena):
|
|
|
|
# Possibly delete the given (unused) arena
|
|
|
|
length = arena.size
|
|
|
|
# Reusing an existing arena is faster than creating a new one, so
|
|
|
|
# we only reclaim space if it's large enough.
|
|
|
|
if length < self._DISCARD_FREE_SPACE_LARGER_THAN:
|
|
|
|
return
|
|
|
|
blocks = self._allocated_blocks.pop(arena)
|
|
|
|
assert not blocks
|
|
|
|
del self._start_to_block[(arena, 0)]
|
|
|
|
del self._stop_to_block[(arena, length)]
|
|
|
|
self._arenas.remove(arena)
|
|
|
|
seq = self._len_to_seq[length]
|
|
|
|
seq.remove((arena, 0, length))
|
|
|
|
if not seq:
|
|
|
|
del self._len_to_seq[length]
|
|
|
|
self._lengths.remove(length)
|
|
|
|
|
2008-06-11 13:44:04 -03:00
|
|
|
def _malloc(self, size):
|
|
|
|
# returns a large enough block -- it might be much larger
|
|
|
|
i = bisect.bisect_left(self._lengths, size)
|
|
|
|
if i == len(self._lengths):
|
2018-04-09 12:37:55 -03:00
|
|
|
return self._new_arena(size)
|
2008-06-11 13:44:04 -03:00
|
|
|
else:
|
|
|
|
length = self._lengths[i]
|
|
|
|
seq = self._len_to_seq[length]
|
|
|
|
block = seq.pop()
|
|
|
|
if not seq:
|
|
|
|
del self._len_to_seq[length], self._lengths[i]
|
|
|
|
|
|
|
|
(arena, start, stop) = block
|
|
|
|
del self._start_to_block[(arena, start)]
|
|
|
|
del self._stop_to_block[(arena, stop)]
|
|
|
|
return block
|
|
|
|
|
2018-04-09 12:37:55 -03:00
|
|
|
def _add_free_block(self, block):
|
|
|
|
# make block available and try to merge with its neighbours in the arena
|
2008-06-11 13:44:04 -03:00
|
|
|
(arena, start, stop) = block
|
|
|
|
|
|
|
|
try:
|
|
|
|
prev_block = self._stop_to_block[(arena, start)]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
start, _ = self._absorb(prev_block)
|
|
|
|
|
|
|
|
try:
|
|
|
|
next_block = self._start_to_block[(arena, stop)]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
_, stop = self._absorb(next_block)
|
|
|
|
|
|
|
|
block = (arena, start, stop)
|
|
|
|
length = stop - start
|
|
|
|
|
|
|
|
try:
|
|
|
|
self._len_to_seq[length].append(block)
|
|
|
|
except KeyError:
|
|
|
|
self._len_to_seq[length] = [block]
|
|
|
|
bisect.insort(self._lengths, length)
|
|
|
|
|
|
|
|
self._start_to_block[(arena, start)] = block
|
|
|
|
self._stop_to_block[(arena, stop)] = block
|
|
|
|
|
|
|
|
def _absorb(self, block):
|
|
|
|
# deregister this block so it can be merged with a neighbour
|
|
|
|
(arena, start, stop) = block
|
|
|
|
del self._start_to_block[(arena, start)]
|
|
|
|
del self._stop_to_block[(arena, stop)]
|
|
|
|
|
|
|
|
length = stop - start
|
|
|
|
seq = self._len_to_seq[length]
|
|
|
|
seq.remove(block)
|
|
|
|
if not seq:
|
|
|
|
del self._len_to_seq[length]
|
|
|
|
self._lengths.remove(length)
|
|
|
|
|
|
|
|
return start, stop
|
|
|
|
|
2018-04-09 12:37:55 -03:00
|
|
|
def _remove_allocated_block(self, block):
|
|
|
|
arena, start, stop = block
|
|
|
|
blocks = self._allocated_blocks[arena]
|
|
|
|
blocks.remove((start, stop))
|
|
|
|
if not blocks:
|
|
|
|
# Arena is entirely free, discard it from this process
|
|
|
|
self._discard_arena(arena)
|
|
|
|
|
2011-07-02 09:35:49 -03:00
|
|
|
def _free_pending_blocks(self):
|
|
|
|
# Free all the blocks in the pending list - called with the lock held.
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
block = self._pending_free_blocks.pop()
|
|
|
|
except IndexError:
|
|
|
|
break
|
2018-04-09 12:37:55 -03:00
|
|
|
self._add_free_block(block)
|
|
|
|
self._remove_allocated_block(block)
|
2011-07-02 09:35:49 -03:00
|
|
|
|
2008-06-11 13:44:04 -03:00
|
|
|
def free(self, block):
|
|
|
|
# free a block returned by malloc()
|
2011-07-02 09:35:49 -03:00
|
|
|
# Since free() can be called asynchronously by the GC, it could happen
|
|
|
|
# that it's called while self._lock is held: in that case,
|
|
|
|
# self._lock.acquire() would deadlock (issue #12352). To avoid that, a
|
|
|
|
# trylock is used instead, and if the lock can't be acquired
|
|
|
|
# immediately, the block is added to a list of blocks to be freed
|
|
|
|
# synchronously sometimes later from malloc() or free(), by calling
|
|
|
|
# _free_pending_blocks() (appending and retrieving from a list is not
|
2018-04-09 12:37:55 -03:00
|
|
|
# strictly thread-safe but under CPython it's atomic thanks to the GIL).
|
2017-08-29 19:52:18 -03:00
|
|
|
if os.getpid() != self._lastpid:
|
|
|
|
raise ValueError(
|
|
|
|
"My pid ({0:n}) is not last pid {1:n}".format(
|
|
|
|
os.getpid(),self._lastpid))
|
2011-07-02 09:35:49 -03:00
|
|
|
if not self._lock.acquire(False):
|
|
|
|
# can't acquire the lock right now, add the block to the list of
|
|
|
|
# pending blocks to free
|
|
|
|
self._pending_free_blocks.append(block)
|
|
|
|
else:
|
|
|
|
# we hold the lock
|
|
|
|
try:
|
2018-04-09 12:37:55 -03:00
|
|
|
self._n_frees += 1
|
2011-07-02 09:35:49 -03:00
|
|
|
self._free_pending_blocks()
|
2018-04-09 12:37:55 -03:00
|
|
|
self._add_free_block(block)
|
|
|
|
self._remove_allocated_block(block)
|
2011-07-02 09:35:49 -03:00
|
|
|
finally:
|
|
|
|
self._lock.release()
|
2008-06-11 13:44:04 -03:00
|
|
|
|
|
|
|
def malloc(self, size):
|
|
|
|
# return a block of right size (possibly rounded up)
|
2017-08-29 19:52:18 -03:00
|
|
|
if size < 0:
|
|
|
|
raise ValueError("Size {0:n} out of range".format(size))
|
|
|
|
if sys.maxsize <= size:
|
|
|
|
raise OverflowError("Size {0:n} too large".format(size))
|
2008-06-11 13:44:04 -03:00
|
|
|
if os.getpid() != self._lastpid:
|
|
|
|
self.__init__() # reinitialize after fork
|
2014-05-25 10:12:12 -03:00
|
|
|
with self._lock:
|
2018-04-09 12:37:55 -03:00
|
|
|
self._n_mallocs += 1
|
|
|
|
# allow pending blocks to be marked available
|
2014-05-25 10:12:12 -03:00
|
|
|
self._free_pending_blocks()
|
2018-04-09 12:37:55 -03:00
|
|
|
size = self._roundup(max(size, 1), self._alignment)
|
2008-06-11 13:44:04 -03:00
|
|
|
(arena, start, stop) = self._malloc(size)
|
2018-04-09 12:37:55 -03:00
|
|
|
real_stop = start + size
|
|
|
|
if real_stop < stop:
|
|
|
|
# if the returned block is larger than necessary, mark
|
|
|
|
# the remainder available
|
|
|
|
self._add_free_block((arena, real_stop, stop))
|
|
|
|
self._allocated_blocks[arena].add((start, real_stop))
|
|
|
|
return (arena, start, real_stop)
|
2008-06-11 13:44:04 -03:00
|
|
|
|
|
|
|
#
|
2018-04-09 12:37:55 -03:00
|
|
|
# Class wrapping a block allocated out of a Heap -- can be inherited by child process
|
2008-06-11 13:44:04 -03:00
|
|
|
#
|
|
|
|
|
|
|
|
class BufferWrapper(object):
|
|
|
|
|
|
|
|
_heap = Heap()
|
|
|
|
|
|
|
|
def __init__(self, size):
|
2017-08-29 19:52:18 -03:00
|
|
|
if size < 0:
|
|
|
|
raise ValueError("Size {0:n} out of range".format(size))
|
|
|
|
if sys.maxsize <= size:
|
|
|
|
raise OverflowError("Size {0:n} too large".format(size))
|
2008-06-11 13:44:04 -03:00
|
|
|
block = BufferWrapper._heap.malloc(size)
|
|
|
|
self._state = (block, size)
|
2013-08-14 11:35:41 -03:00
|
|
|
util.Finalize(self, BufferWrapper._heap.free, args=(block,))
|
2008-06-11 13:44:04 -03:00
|
|
|
|
2012-05-26 18:09:59 -03:00
|
|
|
def create_memoryview(self):
|
2008-06-11 13:44:04 -03:00
|
|
|
(arena, start, stop), size = self._state
|
2012-05-26 18:09:59 -03:00
|
|
|
return memoryview(arena.buffer)[start:start+size]
|