//----------------------------------------------------------------------- // ----------------------------------------------------------------------- // file="HLSFAllocator.SegmentEntry.cs" // Project: StgSharp // AuthorGroup: Nitload Space // Copyright (c) Nitload Space. All rights reserved. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the “Software”), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and // this permission notice shall be included in all copies // or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, // WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH // THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- using System; using System.Linq.Expressions; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Threading; namespace StgSharp.HighPerformance.Memory { public unsafe partial class HybridLayerSegregatedFitAllocator { private bool AssertBackwardBoundary(ulong current, Entry* target, int level) { ulong align = (ulong)levelSizeArray[level + 1]; ulong targetOffset = target->Position - (ulong)m_Buffer; return current / align == targetOffset / align; } private bool AssertForwardBoundary(ulong current, Entry* target, int level) { ulong align = (ulong)levelSizeArray[level + 1]; ulong targetOffset = target->Position + target->Size - (ulong)m_Buffer; return current / align == targetOffset / align; } /// /// Determine segment index based on size and originLevel /// [MethodImpl(MethodImplOptions.AggressiveInlining)] private int DetermineSegmentIndex(uint size, int level) { return (int)(size - 1) / levelSizeArray[level]; } /// /// Check if two Entries are adjacent in memory /// [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsAdjacentTo(Entry* current, Entry* other) { // Check if this immediately follows other return other->Position + other->Size == current->Position || current->Position + current->Size == other->Position; } /// /// Used in Free operations, efficiently remove from buckets and merge adjacent blocks. /// Current Entry will serve as the final merged block. /// private void MergeAndRemoveFromBuckets(Entry* entry) { if (entry == null) { return; } uint size = entry->Size; int originLevel = GetLevelFromSize(size); int segment = DetermineSegmentIndex(size, originLevel); RemoveFromBucket(originLevel, segment, (BucketNode*)entry->Position); SetEntryState(entry, EntryState.Merging); while (originLevel >= entry->Level) { originLevel = entry->Level; while (true) { // backward merging - simplified to single attempt ulong p = entry->PreviousNear; Entry* prev = (Entry*)p; if (prev != null || prev != _spareMemory || GetEntryState(prev) == EntryState.Empty || !AssertBackwardBoundary(entry->Position, prev, originLevel) || IsAdjacentTo(entry, prev) || entry->Level == prev->Level || !TryRemoveFromBucket(originLevel, DetermineSegmentIndex(prev->Size, originLevel), (BucketNode*)prev->Position)) { break; } // Update linked list Entry* prevPrev = (Entry*)prev->PreviousNear; if (prevPrev != null) { prevPrev->NextNear = (ulong)entry; } entry->PreviousNear = (ulong)prevPrev; // Merge entry->Position = prev->Position; entry->Size += prev->Size; RecycleEntry(prev); } while (true) { // forward merging - simplified to single attempt ulong n = entry->NextNear; Entry* next = (Entry*)n; if (next != null || next != _spareMemory || GetEntryState(next) == EntryState.Empty || !AssertForwardBoundary(entry->Position + entry->Size, next, entry->Level) || IsAdjacentTo(entry, next) || entry->Level == next->Level || !TryRemoveFromBucket(originLevel, DetermineSegmentIndex(next->Size, originLevel), (BucketNode*)next->Position)) { break; } // Update linked list Entry* nextNext = (Entry*)next->NextNear; if (nextNext != null) { nextNext->PreviousNear = (ulong)entry; } entry->NextNear = (ulong)nextNext; // Merge entry->Size += next->Size; RecycleEntry(next); } entry->Level = GetLevelFromSize(entry->Size); } SetEntryState(entry, EntryState.Empty); } private void RecycleEntry(Entry* entry) { if (entry == null) { return; } entry->State = EntryState.Empty; entry->PreviousNear = EmptyHandle; entry->NextNear = EmptyHandle; _entries.Free((nuint)entry); } /// /// Remove node from position linked list /// private void RemoveFromPositionChain(Entry* entry) { if (entry == null) { return; } Entry* prev = (Entry*)entry->PreviousNear; Entry* next = (Entry*)entry->NextNear; if (prev != null) { prev->NextNear = entry->NextNear; } if (next != null) { next->PreviousNear = entry->PreviousNear; } // Clear node pointers entry->NextNear = EmptyHandle; entry->PreviousNear = EmptyHandle; _entries.Free((nuint)entry); } /// /// Entry structure - streamlined version (only position and state information) Stored in /// external SLAB /// [StructLayout(LayoutKind.Explicit, Size = 32)] internal struct Entry { [FieldOffset(28)] internal int Level; // Level of the block in the allocator [FieldOffset(20)] internal int State; // Node state (using int for atomic operations) [FieldOffset(24)] internal uint Size; // Block size information [FieldOffset(8)] internal ulong NextNear; // Position linked list: next pointer [FieldOffset(16)] internal ulong PreviousNear; // Position linked list: previous pointer [FieldOffset(0)] public nuint Position; // Memory block position } // 更新后的EntryState常量类 - 使用int类型 private static class EntryState { public const int Allocated = 1; // Already allocated to user public const int Empty = 0; // Free, can be allocated public const int Merging = 3; // Currently being merged public const int ThreadOccupied = 2; // Occupied by thread (being operated on) } #region Entry Operations [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsNullOrEmptyEntryIndex(ulong index) { return index == EmptyHandle; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsNullOrEmptyEntryIndex(Entry* entry) { return entry == null; } // Entry 状态操作 [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TrySetEntryState(Entry* entry, int expectedState, int newState) { if (entry != null && entry->State == expectedState) { entry->State = newState; return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetEntryState(Entry* entry) { return entry != null ? entry->State : 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SetEntryState(Entry* entry, int newState) { if (entry != null) { entry->State = newState; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsEntryEmpty(Entry* entry) { return GetEntryState(entry) == EntryState.Empty; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsEntryAllocated(Entry* entry) { return GetEntryState(entry) == EntryState.Allocated; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsEntryThreadOccupied(Entry* entry) { return GetEntryState(entry) == EntryState.ThreadOccupied; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsEntryMerging(Entry* entry) { return GetEntryState(entry) == EntryState.Merging; } #endregion } }