Migrates the backing memory region to a new allocator, freeing the current region. Memory allocated by the
new allocator must be accessible by the same accessor as the current one.
183358
public final void migrateTo(MemoryAllocator newMalloc) {
        baseAddress = move(baseAddress, capacity(), malloc, newMalloc);
        malloc = newMalloc;
        auxMalloc = null;
    }
1360070
public void releaseAll() {
        synchronized(this) {
            Object[] refSet = allocatedMemoryReferences.values().toArray();
            if(refSet.length != 0) {
                logger.finer("Releasing allocated memory regions");
            }
            for(Object ref : refSet) {
                release((MemoryReference) ref);
            }
        }
    }
1328361
private FileEntry allocate(int len) {
      synchronized (freeList) {
         // lookup a free entry of sufficient size
         SortedSet<FileEntry> candidates = freeList.tailSet(new FileEntry(0, len));
         for (Iterator<FileEntry> it = candidates.iterator(); it.hasNext(); ) {
            FileEntry free = it.next();
            // ignore entries that are still in use by concurrent readers
            if (free.isLocked())
               continue;

            // There's no race condition risk between locking the entry on
            // loading and checking whether it's locked (or store allocation),
            // because for the entry to be lockable, it needs to be in the
            // entries collection, in which case it's not in the free list.
            // The only way an entry can be found in the free list is if it's
            // been removed, and to remove it, lock on "entries" needs to be
            // acquired, which is also a pre-requisite for loading data.

            // found one, remove from freeList
            it.remove();
            return allocateExistingEntry(free, len);
         }

         // no appropriate free section available, append at end of file
         FileEntry fe = new FileEntry(filePos, len);
         filePos += len;
         if (trace) log.tracef("New entry allocated at %d:%d, %d free entries, file size is %d", fe.offset, fe.size, freeList.size(), filePos);
         return fe;
      }
   }
1108038
private long freeMemory() {
    updatePeakMemoryUsed();
    long memoryFreed = 0;
    for (MemoryBlock block : allocatedPages) {
      memoryFreed += block.size();
      freePage(block);
    }
    allocatedPages.clear();
    currentPage = null;
    pageCursor = 0;
    return memoryFreed;
  }
630114
@Override
    public void free(AllocationPoint point) {
        switch (point.getAllocationStatus()) {
            case HOST: {
                // cudaFreeHost call here
                long reqMem = AllocationUtils.getRequiredMemory(point.getShape());
                val nativeOps = NativeOpsHolder.getInstance().getDeviceNativeOps();

                long result = nativeOps.freeHost(point.getPointers().getHostPointer());
                if (result == 0) {
                    throw new RuntimeException("Can't deallocate [HOST] memory...");
                }

                MemoryTracker.getInstance().decrementAllocatedHostAmount(reqMem);
            }
                break;
            case DEVICE: {
                if (point.isConstant())
                    return;

                long reqMem = AllocationUtils.getRequiredMemory(point.getShape());

                val nativeOps = NativeOpsHolder.getInstance().getDeviceNativeOps();
                AllocationsTracker.getInstance().markReleased(AllocationKind.GENERAL, point.getDeviceId(), reqMem);

                val pointers = point.getPointers();

                long result = nativeOps.freeDevice(pointers.getDevicePointer(), 0);
                if (result == 0)
                    throw new RuntimeException("Can't deallocate [DEVICE] memory...");

                MemoryTracker.getInstance().decrementAllocatedAmount(point.getDeviceId(), reqMem);
            }
                break;
            default:
                throw new IllegalStateException("Can't free memory on target [" + point.getAllocationStatus() + "]");
        }
    }
864161
void discardUnusedTail()
    {
        // we guard this with the OpOrdering instead of synchronised due to potential dead-lock with CLSM.advanceAllocatingFrom()
        // this actually isn't strictly necessary, as currently all calls to discardUnusedTail occur within a block
        // already protected by this OpOrdering, but to prevent future potential mistakes, we duplicate the protection here
        // so that the contract between discardUnusedTail() and sync() is more explicit.
        try (OpOrder.Group group = appendOrder.start())
        {
            while (true)
            {
                int prev = allocatePosition.get();
                // we set allocatePosition past buffer.capacity() to make sure we always set discardedTailFrom
                int next = buffer.capacity() + 1;
                if (prev == next)
                    return;
                if (allocatePosition.compareAndSet(prev, next))
                {
                    discardedTailFrom = prev;
                    return;
                }
            }
        }
    }
885072
def copy(self):
        
        s = MemoryData(self.address, self.size, self.sort, pointer_addr=self.pointer_addr, max_size=self.max_size)
        s.content = self.content

        return s
758390
def copy(self, _):
        
        #l.debug("Copying %d bytes of memory with id %s." % (len(self.mem), self.id))
        c = SimSymbolicDbgMemory(
            mem=self.mem.branch(),
            memory_id=self.id,
            endness=self.endness,
            abstract_backer=self._abstract_backer,
            read_strategies=[ s.copy() for s in self.read_strategies ],
            write_strategies=[ s.copy() for s in self.write_strategies ],
            stack_region_map=self._stack_region_map,
            generic_region_map=self._generic_region_map
        )

        return c
813852
def copy(self, memo):
        
        am = SimAbstractMemory(
            memory_id=self._memory_id,
            endness=self.endness,
            stack_region_map=self._stack_region_map,
            generic_region_map=self._generic_region_map
        )
        for region_id, region in self._regions.items():
            am._regions[region_id] = region.copy(memo)
        am._stack_size = self._stack_size
        return am
236712
public synchronized CommsByteBuffer allocate()
   {
      if (tc.isEntryEnabled()) SibTr.entry(this, tc, "allocate");
   
      // Remove a CommsByteBuffer from the pool
      CommsByteBuffer buff = (CommsByteBuffer) pool.remove();
   
      // If the buffer is null then there was none available in the pool
      // So create a new one
      if (buff == null)
      {
         if (tc.isDebugEnabled()) SibTr.debug(this, tc, "No buffer available from pool - creating a new one");
      
         buff = createNew();
      }
   
      if (tc.isEntryEnabled()) SibTr.exit(this, tc, "allocate", buff);
      return buff;
   }
267017
public void setDiscarded()
    {
        state = state.transition(LifeCycle.DISCARDED);
        // release any memory owned by this allocator; automatically signals waiters
        onHeap.releaseAll();
        offHeap.releaseAll();
    }
886350
@Override
    public void free(AllocationPoint point) {
        if (point.getAllocationStatus() == AllocationStatus.DEVICE) {
            if (point.isConstant())
                return;

            val shape = point.getShape();
            val deviceId = point.getDeviceId();
            val address = point.getDevicePointer().address();
            val reqMemory = AllocationUtils.getRequiredMemory(shape);
            // we don't cache too big objects

            if (reqMemory > CudaEnvironment.getInstance().getConfiguration().getMaximumDeviceCacheableLength() || deviceCachedAmount.get(deviceId).get() >= CudaEnvironment.getInstance().getConfiguration().getMaximumDeviceCache()) {
                super.free(point);
                return;
            }

            ensureDeviceCacheHolder(deviceId, shape);

            val cache = deviceCache.get(deviceId).get(shape);

            if (point.getDeviceId() != deviceId)
                throw new RuntimeException("deviceId changed!");

            // memory chunks < threshold will be cached no matter what
            if (reqMemory <= FORCED_CACHE_THRESHOLD) {
                cache.put(new CudaPointer(point.getDevicePointer().address()));
                MemoryTracker.getInstance().incrementCachedAmount(deviceId, reqMemory);
                MemoryTracker.getInstance().decrementAllocatedAmount(deviceId, reqMemory);
                return;
            } else {

                cache.put(new CudaPointer(point.getDevicePointer().address()));

                MemoryTracker.getInstance().incrementCachedAmount(deviceId, reqMemory);
                MemoryTracker.getInstance().decrementAllocatedAmount(deviceId, reqMemory);
                return;
            }
        }
        super.free(point);
    }
610361
private void migrateGroups() throws Exception
   {
      Session session = service.getStorageSession();
      try
      {
         if (session.itemExists(groupsStorageOld))
         {
            NodeIterator iterator = ((ExtendedNode)session.getItem(groupsStorageOld)).getNodesLazily();
            GroupHandlerImpl gh = ((GroupHandlerImpl)service.getGroupHandler());
            while (iterator.hasNext())
            {
               Node oldGroupNode = iterator.nextNode();
               gh.migrateGroup(oldGroupNode);
               migrateGroups(oldGroupNode);
            }
         }
      }
      finally
      {
         session.logout();
      }
   }
908456
@Override
  public void relocate(final int oldPosition, final int newPosition, final ByteBuffer oldBuf, final ByteBuffer newBuf)
  {
    HllSketch sketch = sketchCache.get(oldBuf).get(oldPosition);
    final WritableMemory oldMem = getMemory(oldBuf).writableRegion(oldPosition, size);
    if (sketch.isSameResource(oldMem)) { // sketch has not moved
      final WritableMemory newMem = getMemory(newBuf).writableRegion(newPosition, size);
      sketch = HllSketch.writableWrap(newMem);
    }
    putSketchIntoCache(newBuf, newPosition, sketch);
  }
806169
def free(self):
        
        # Free the memory
        self._machine_controller.sdram_free(self._start_address,
                                            self._x, self._y)

        # Mark as freed
        self._freed = True
1232177
synchronized void cleanUp() {

        updateAccessCounts();

        int                          removeCount = size() / 2;
        int accessTarget = getAccessCountCeiling(removeCount, removeCount / 8);
        BaseHashMap.BaseHashIterator it          = new BaseHashIterator();
        int                          savecount   = 0;

        for (; it.hasNext(); ) {
            CachedObject r = (CachedObject) it.next();

            if (it.getAccessCount() <= accessTarget) {
                synchronized (r) {
                    if (!r.isKeepInMemory()) {
                        r.setInMemory(false);

                        if (r.hasChanged()) {
                            rowTable[savecount++] = r;
                        }

                        it.remove();

                        cacheBytesLength -= r.getStorageSize();

                        removeCount--;
                    }
                }
            }
        }

        if (removeCount > 50) {
            it = new BaseHashIterator();

            for (; removeCount >= 0 && it.hasNext(); ) {
                CachedObject r = (CachedObject) it.next();

                if (!r.isKeepInMemory()) {
                    r.setInMemory(false);

                    if (r.hasChanged()) {
                        rowTable[savecount++] = r;
                    }

                    it.remove();

                    cacheBytesLength -= r.getStorageSize();

                    removeCount--;
                }
            }
        }

        super.setAccessCountFloor(accessTarget);
        saveRows(savecount);
    }
484521
private boolean updateMemoryReservation()
    {
        // Operator/driver will be blocked on memory after we call localUserMemoryContext.setBytes().
        // If memory is not available, once we return, this operator will be blocked until memory is available.
        long memorySizeInBytes = groupByHash.map(GroupByHash::getEstimatedSize).orElse(0L) + partitionRowCount.sizeOf();
        localUserMemoryContext.setBytes(memorySizeInBytes);
        // If memory is not available, inform the caller that we cannot proceed for allocation.
        return operatorContext.isWaitingForMemory().isDone();
    }