Files
stgsharp/.vs/CopilotSnapshots/F647F1E24D09C24DB19C5EC7EB5E2560/4D9BA39CF2B5784991D89E8E595FD6C4/1BFCBC1D28329246691E0D2AD2276290
T

367 lines
14 KiB
Plaintext

//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="HLSFAllocator.BucketNode.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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace StgSharp.HighPerformance.Memory
{
public unsafe partial class HybridLayerSegregatedFitAllocator
{
private TryPopLevel(int levelIndex, int sizeIndex, out BucketNode* node)
{
int index = (3 * levelIndex) + sizeIndex;
while (true)
{
ulong h = Volatile.Read(ref _bucketHeads[index]);
BucketNode* head = (BucketNode*)h;
BucketNode* next = null;
try
{
if (head == null)
{
node = null;
return false;
}
if (!TryAcquireBucketNodeSpinLock(head))
{
Thread.Sleep(0);
continue;
}
ulong n = Volatile.Read(ref head->NextLevel);
next = (BucketNode*)n;
if (!TryAcquireBucketNodeSpinLock(next))
{
Thread.Sleep(0);
continue;
}
if (Interlocked.CompareExchange(ref _bucketHeads[index], head->NextLevel, h) == h)
{
node = head;
node->Mask = false;
node->NextLevel = EmptyHandle;
next->PreviousLevel = EmptyHandle;
return true;
} else
{
Thread.Sleep(0);
continue;
}
}
finally
{
ReleaseBucketNodeSpinLock(head);
ReleaseBucketNodeSpinLock(next);
}
}
}
private static void AcquireBucketNodeSpinLock(BucketNode* node)
{
// 兼容性包装:获取两个锁
if (node != null)
{
node->AcquirePrevLock();
node->AcquireNextLock();
}
}
/// <summary>
/// Initialize bucket system (called in constructor)
/// </summary>
private void InitializeBucketSystem()
{
_bucketHeads = new ulong[levelSize.Length * 3];
}
private void PushLevel(int levelIndex, int sizeIndex, BucketNode* node)
{
if (node == null || node->EntryRef == null) {
return;
}
int index = (3 * levelIndex) + sizeIndex;
if (Interlocked.CompareExchange(ref _bucketHeads[index], (nuint)node, EmptyHandle) == EmptyHandle)
{
node->IsInBucket = true;
node->Magic = BucketNode.MAGIC_NUMBER;
return;
} else
{
while (true)
{
// 对新节点只需要获取NextLock,因为我们要设置它的NextLevel
node->AcquireNextLock();
ulong head = Volatile.Read(ref _bucketHeads[index]);
node->NextLevel = head;
BucketNode* headNode = (BucketNode*)head;
try
{
if (Interlocked.CompareExchange(ref _bucketHeads[index], (nuint)node, head) == head)
{
// 对头节点只需要获取PrevLock,因为我们要设置它的PreviousLevel
if (headNode != null && !headNode->TryAcquirePrevLock())
{
// reset state and retry
_ = Interlocked.CompareExchange(ref _bucketHeads[index], head, (nuint)node);
Thread.Sleep(0);
continue;
}
try
{
node->IsInBucket = true;
node->Magic = BucketNode.MAGIC_NUMBER;
if (headNode != null) {
headNode->PreviousLevel = (ulong)node;
}
return;
}
finally
{
if (headNode != null) {
headNode->ReleasePrevLock();
}
}
} else
{
Thread.Sleep(0);
continue;
}
}
finally
{
node->ReleaseNextLock();
}
}
}
}
private static void ReleaseBucketNodeSpinLock(BucketNode* node)
{
// 兼容性包装:释放两个锁
if (node != null)
{
node->ReleaseBothLocks();
}
}
private void RemoveFromBucket(int levelIndex, int sizeIndex, BucketNode* node)
{
int index = (3 * levelIndex) + sizeIndex;
while (true)
{
// top of stack
if ((BucketNode*)Volatile.Read(ref _bucketHeads[index]) == node && TryAcquireBucketNodeSpinLock(node))
{
_ = TryPopLevel(levelIndex, sizeIndex, out _);
} else
{
AcquireBucketNodeSpinLock(node);
ulong p = Volatile.Read(ref node->PreviousLevel), n = Volatile.Read(ref node->NextLevel);
BucketNode* previous = (BucketNode*)p, next = (BucketNode*)n;
try
{
if (next is null)
{
// bottom of stack
if (!TryAcquireBucketNodeSpinLock(previous))
{
Thread.Sleep(0);
continue;
}
previous->NextLevel = EmptyHandle;
node->PreviousLevel = EmptyHandle;
return;
}
if (!(TryAcquireBucketNodeSpinLock(previous) && TryAcquireBucketNodeSpinLock(next)))
{
// middle of stack
Thread.Sleep(0);
continue;
}
previous ->NextLevel = n;
next->PreviousLevel = p;
node->NextLevel = EmptyHandle;
node->PreviousLevel = EmptyHandle;
return;
}
finally
{
ReleaseBucketNodeSpinLock(node);
ReleaseBucketNodeSpinLock(previous);
ReleaseBucketNodeSpinLock(next);
}
}
}
}
private static bool TryAcquireBucketNodeSpinLock(BucketNode* node)
{
// 兼容性包装:尝试获取两个锁
return node == null || node->TryAcquireBothLocks();
}
/// <summary>
/// BucketNode structure - specialized node for bucket linked lists Stored in main
/// allocation area (user-overwritable region)
/// </summary>
[StructLayout(LayoutKind.Explicit, Size = 36)]
internal struct BucketNode
{
public const uint MAGIC_NUMBER = 0xBEEFCAFE; // Magic number for node integrity verification
[FieldOffset(16)] internal Entry* EntryRef; // Pointer to corresponding Entry
[FieldOffset(28)] internal bool IsInBucket; // Whether in bucket
// 双锁设计:分离前后指针操作
[FieldOffset(32)] internal int PrevLock; // 前驱指针锁(控制PreviousLevel指针操作)
[FieldOffset(34)] internal short NextLock; // 后继指针锁(控制NextLevel指针操作)
[FieldOffset(24)] internal uint Magic; // Magic number verification
// [FieldOffset(36)] 保留空间用于扩展
[FieldOffset(0)] internal ulong NextLevel; // Bucket stack linked list: next pointer
[FieldOffset(8)] internal ulong PreviousLevel; // Bucket stack linked list: previous pointer
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsNullOrEmpty(BucketNode* node)
{
return node == null || node->Magic != MAGIC_NUMBER;
}
#region Dual Lock Operations
// 前驱锁操作(控制PreviousLevel字段)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryAcquirePrevLock()
{
int thread = Environment.CurrentManagedThreadId;
return Interlocked.CompareExchange(ref PrevLock, thread, 0) == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AcquirePrevLock()
{
int thread = Environment.CurrentManagedThreadId;
if (Volatile.Read(ref PrevLock) != thread)
{
while (Interlocked.CompareExchange(ref PrevLock, thread, 0) != 0) {
Thread.Sleep(0);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReleasePrevLock()
{
int thread = Environment.CurrentManagedThreadId;
if (Volatile.Read(ref PrevLock) == thread) {
Volatile.Write(ref PrevLock, 0);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsPrevLockHeld() => Volatile.Read(ref PrevLock) != 0;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsPrevLockHeldByCurrentThread() => Volatile.Read(ref PrevLock) == Environment.CurrentManagedThreadId;
// 后继锁操作(控制NextLevel字段)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryAcquireNextLock()
{
short thread = (short)(Environment.CurrentManagedThreadId & 0x7FFF); // 使用低15位
return Interlocked.CompareExchange(ref NextLock, thread, (short)0) == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AcquireNextLock()
{
short thread = (short)(Environment.CurrentManagedThreadId & 0x7FFF);
if (Volatile.Read(ref NextLock) != thread)
{
while (Interlocked.CompareExchange(ref NextLock, thread, (short)0) != 0) {
Thread.Sleep(0);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReleaseNextLock()
{
short thread = (short)(Environment.CurrentManagedThreadId & 0x7FFF);
if (Volatile.Read(ref NextLock) == thread) {
Volatile.Write(ref NextLock, (short)0);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsNextLockHeld() => Volatile.Read(ref NextLock) != 0;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsNextLockHeldByCurrentThread() => Volatile.Read(ref NextLock) == (short)(Environment.CurrentManagedThreadId & 0x7FFF);
// 双锁组合操作
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryAcquireBothLocks()
{
if (TryAcquirePrevLock())
{
if (TryAcquireNextLock())
{
return true;
} else
{
ReleasePrevLock(); // 回滚
return false;
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReleaseBothLocks()
{
ReleasePrevLock();
ReleaseNextLock();
}
#endregion
}
private bool.
}
}